[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: p0dalirius\npatreon: Podalirius"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\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.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n#poetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n#.idea/\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  <signature of Ty Coon>, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "README.md",
    "content": "![](./.github/banner.png)\n\n<p align=\"center\">\n    A system administration or post-exploitation script to automatically extract the bitlocker recovery keys from a domain.\n    <br>\n    <img alt=\"GitHub release (latest by date)\" src=\"https://img.shields.io/github/v/release/p0dalirius/ExtractBitlockerKeys\">\n    <a href=\"https://twitter.com/intent/follow?screen_name=podalirius_\" title=\"Follow\"><img src=\"https://img.shields.io/twitter/follow/podalirius_?label=Podalirius&style=social\"></a>\n    <a href=\"https://www.youtube.com/c/Podalirius_?sub_confirmation=1\" title=\"Subscribe\"><img alt=\"YouTube Channel Subscribers\" src=\"https://img.shields.io/youtube/channel/subscribers/UCF_x5O7CSfr82AfNVTKOv_A?style=social\"></a>\n    <br>\n</p>\n\n## Features\n\n - [x] Automatically gets the list of all computers from the domain controller's LDAP.\n - [x] Multithreaded connections to extract Bitlocker keys from LDAP.\n - [x] Iterate on LDAP result pages to get every computer of the domain, no matter the size.\n\n> [!WARNING]\n> Please do not store this backup in an online SMB share of the domain. You should prefer to print it and store it physically in a locked safe.\n - [x] Export results in JSON with Computer FQDN, Domain, Recovery Key, Volume GUID, Created At and Organizational Units.\n - [x] Export results in XLSX with Computer FQDN, Domain, Recovery Key, Volume GUID, Created At and Organizational Units.\n - [x] Export results in SQLITE3 with Computer FQDN, Domain, Recovery Key, Volume GUID, Created At and Organizational Units.\n\n---\n\n## Demonstration from Linux in Python\n\nTo extract Bitlocker recovery keys from all the computers of the domain `domain.local` you can use this command:\n\n```\n./ExtractBitlockerKeys.py -d 'domain.local' -u 'Administrator' -p 'Podalirius123!' --dc-ip 192.168.1.101\n```\n\nYou will get the following output:\n\n![](./.github/example_python.png)\n\n---\n\n## Demonstration from Windows in Powershell\n\nTo extract Bitlocker recovery keys from all the computers of the domain `domain.local` you can use this command:\n\n```\n.\\ExtractBitlockerKeys.ps1 -dcip 192.168.1.101 -ExportToCSV ./keys.csv -ExportToJSON ./keys.json\n```\n\nYou will get the following output:\n\n![](./.github/example_powershell.png)\n\n---\n\n## Usage\n\n```\n$ ./ExtractBitlockerKeys.py -h\nExtractBitlockerKeys.py v1.1 - by Remi GASCOU (Podalirius)\n\nusage: ExtractBitlockerKeys.py [-h] [-v] [-q] [-t THREADS] [--export-xlsx EXPORT_XLSX] [--export-json EXPORT_JSON] [--export-sqlite EXPORT_SQLITE] --dc-ip ip address [-d DOMAIN] [-u USER]\n                               [--no-pass | -p PASSWORD | -H [LMHASH:]NTHASH | --aes-key hex key] [-k]\n\noptions:\n  -h, --help            show this help message and exit\n  -v, --verbose         Verbose mode. (default: False)\n  -q, --quiet           Show no information at all.\n  -t THREADS, --threads THREADS\n                        Number of threads (default: 4).\n\nOutput files:\n  --export-xlsx EXPORT_XLSX\n                        Output XLSX file to store the results in.\n  --export-json EXPORT_JSON\n                        Output JSON file to store the results in.\n  --export-sqlite EXPORT_SQLITE\n                        Output SQLITE3 file to store the results in.\n\nAuthentication & connection:\n  --dc-ip ip address    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  -d DOMAIN, --domain DOMAIN\n                        (FQDN) domain to authenticate to\n  -u USER, --user USER  user to authenticate with\n\nCredentials:\n  --no-pass             Don't ask for password (useful for -k)\n  -p PASSWORD, --password PASSWORD\n                        Password to authenticate with\n  -H [LMHASH:]NTHASH, --hashes [LMHASH:]NTHASH\n                        NT/LM hashes, format is LMhash:NThash\n  --aes-key hex key     AES key to use for Kerberos Authentication (128 or 256 bits)\n  -k, --kerberos        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```\n\n## Contributing\n\nPull requests are welcome. Feel free to open an issue if you want to add other features.\n\n## References\n\n - [https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-keypackage](https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-keypackage?wt.mc_id=SEC-MVP-5005286)\n - [https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoveryguid](https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoveryguid?wt.mc_id=SEC-MVP-5005286)\n - [https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoverypassword](https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoverypassword?wt.mc_id=SEC-MVP-5005286)\n - [https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-volumeguid](https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-volumeguid?wt.mc_id=SEC-MVP-5005286)\n"
  },
  {
    "path": "go/Dockerfile",
    "content": "FROM debian:latest\n\nRUN apt-get -y -q update \\\n    && apt-get -y -q install nano git wget build-essential librust-gobject-sys-dev libnss3 libnss3-dev\n\nRUN wget https://go.dev/dl/go1.22.1.linux-amd64.tar.gz -O /tmp/go.tar.gz \\\n    && rm -rf /usr/local/go \\\n    && tar -C /usr/local -xzf /tmp/go.tar.gz \\\n    && echo 'export PATH=$PATH:/usr/local/go/bin' >> /root/.bashrc \\\n    && echo 'export PATH=$PATH:/root/go/bin' >> /root/.bashrc\n\nRUN echo \"go clean; go build -v\"  >> /root/.bash_history\n\nRUN echo '#!/bin/bash' > /entrypoint.sh \\\n    && echo 'mkdir -p /workspace/bin/' >> /entrypoint.sh \\\n    && echo 'cd /workspace/src/' >> /entrypoint.sh \\\n    && echo '/usr/local/go/bin/go clean' >> /entrypoint.sh \\\n    && echo 'echo \"[+] Building\"' >> /entrypoint.sh \\\n    && echo 'echo \" ├──[>] Building for linux i386\"' >> /entrypoint.sh \\\n    && echo 'mkdir -p /workspace/bin/linux/x86/' >> /entrypoint.sh >> /entrypoint.sh \\\n    && echo 'GOOS=linux GOARCH=386 /usr/local/go/bin/go build -o /workspace/bin/linux/x86/ ExtractBitlockerKeys.go' >> /entrypoint.sh \\\n    && echo 'echo \" ├──[>] Building for linux amd64\"' >> /entrypoint.sh \\\n    && echo 'mkdir -p /workspace/bin/linux/x64/' >> /entrypoint.sh >> /entrypoint.sh \\\n    && echo 'GOOS=linux GOARCH=amd64 /usr/local/go/bin/go build -o /workspace/bin/linux/x64/ ExtractBitlockerKeys.go' >> /entrypoint.sh \\\n    && echo 'echo \" ├──[>] Building for Windows i386\"' >> /entrypoint.sh \\\n    && echo 'mkdir -p /workspace/bin/windows/x86/' >> /entrypoint.sh >> /entrypoint.sh \\\n    && echo 'GOOS=windows GOARCH=386 /usr/local/go/bin/go build -o /workspace/bin/windows/x86/ ExtractBitlockerKeys.go' >> /entrypoint.sh \\\n    && echo 'echo \" └──[>] Building for Windows amd64\"' >> /entrypoint.sh \\\n    && echo 'mkdir -p /workspace/bin/windows/x64/' >> /entrypoint.sh >> /entrypoint.sh \\\n    && echo 'GOOS=windows GOARCH=amd64 /usr/local/go/bin/go build -o /workspace/bin/windows/x64/ ExtractBitlockerKeys.go' >> /entrypoint.sh \\\n    && chmod +x /entrypoint.sh\n\n# Prepare workspace volume\nRUN mkdir -p /workspace/\nVOLUME /workspace/\nWORKDIR /workspace/\n\nCMD [\"/bin/bash\", \"/entrypoint.sh\"]\n"
  },
  {
    "path": "go/Makefile",
    "content": ".PHONY: all build_docker compile\n\nIMGNAME := build_go\n\nall: build_docker compile\n\nbuild_docker:\n\tdocker build -t $(IMGNAME):latest -f Dockerfile .\n\ncompile: build_docker\n\tdocker run --rm -v \"$(shell pwd):/workspace\" -it $(IMGNAME)\n"
  },
  {
    "path": "go/src/ExtractBitlockerKeys.go",
    "content": "package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/go-ldap/ldap/v3\"\n\t\"github.com/xuri/excelize/v2\"\n)\n\nfunc banner() {\n\tfmt.Printf(\"ExtractBitlockerKeys v%s - by Remi GASCOU (Podalirius)\\n\", \"1.3\")\n\tfmt.Println(\"\")\n}\n\nfunc ldap_init_connection(host string, port int, username string, domain string, password string) (*ldap.Conn, error) {\n\t// Check if TCP port is valid\n\tif port < 1 || port > 65535 {\n\t\tfmt.Println(\"[!] Invalid port number. Port must be in the range 1-65535.\")\n\t\treturn nil, errors.New(\"invalid port number\")\n\t}\n\n\t// Set up LDAP connection\n\tldapSession, err := ldap.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", host, port))\n\tif err != nil {\n\t\tfmt.Println(\"[!] Error connecting to LDAP server:\", err)\n\t\treturn nil, nil\n\t}\n\n\t// Bind with credentials if provided\n\tbindDN := \"\"\n\tif username != \"\" {\n\t\tbindDN = fmt.Sprintf(\"%s@%s\", username, domain)\n\t}\n\tif bindDN != \"\" && password != \"\" {\n\t\terr = ldapSession.Bind(bindDN, password)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[!] Error binding:\", err)\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\n\treturn ldapSession, nil\n}\n\nfunc ldap_get_rootdse(ldapSession *ldap.Conn) *ldap.Entry {\n\t// Specify LDAP search parameters\n\t// https://pkg.go.dev/gopkg.in/ldap.v3#NewSearchRequest\n\tsearchRequest := ldap.NewSearchRequest(\n\t\t// Base DN blank\n\t\t\"\",\n\t\t// Scope Base\n\t\tldap.ScopeBaseObject,\n\t\t// DerefAliases\n\t\tldap.NeverDerefAliases,\n\t\t// SizeLimit\n\t\t1,\n\t\t// TimeLimit\n\t\t0,\n\t\t// TypesOnly\n\t\tfalse,\n\t\t// Search filter\n\t\t\"(objectClass=*)\",\n\t\t// Attributes to retrieve\n\t\t[]string{\"*\"},\n\t\t// Controls\n\t\tnil,\n\t)\n\n\t// Perform LDAP search\n\tsearchResult, err := ldapSession.Search(searchRequest)\n\tif err != nil {\n\t\tfmt.Println(\"[!] Error searching LDAP:\", err)\n\t\treturn nil\n\t}\n\n\treturn searchResult.Entries[0]\n}\n\nfunc getDomainFromDistinguishedName(distinguishedName string) string {\n\tdomain := \"\"\n\tif strings.Contains(strings.ToLower(distinguishedName), \"dc=\") {\n\t\tdnParts := strings.Split(strings.ToLower(distinguishedName), \",\")\n\t\tfor _, part := range dnParts {\n\t\t\tif strings.HasPrefix(part, \"dc=\") {\n\t\t\t\tdcValue := strings.SplitN(part, \"=\", 2)[1]\n\t\t\t\tif domain == \"\" {\n\t\t\t\t\tdomain = dcValue\n\t\t\t\t} else {\n\t\t\t\t\tdomain = domain + \".\" + dcValue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn domain\n}\n\nfunc getOUPathFromDistinguishedName(distinguishedName string) string {\n\touPath := \"\"\n\tif strings.Contains(strings.ToLower(distinguishedName), \"ou=\") {\n\t\tdnParts := strings.Split(strings.ToLower(distinguishedName), \",\")\n\t\t// Reverse dnParts slice\n\t\tfor i, j := 0, len(dnParts)-1; i < j; i, j = i+1, j-1 {\n\t\t\tdnParts[i], dnParts[j] = dnParts[j], dnParts[i]\n\t\t}\n\n\t\t// Skip domain\n\t\tfor len(dnParts) > 0 && strings.HasPrefix(dnParts[0], \"dc=\") {\n\t\t\tdnParts = dnParts[1:]\n\t\t}\n\n\t\tfor len(dnParts) > 0 && strings.HasPrefix(dnParts[0], \"ou=\") {\n\t\t\touValue := strings.SplitN(dnParts[0], \"=\", 2)[1]\n\t\t\tif ouPath == \"\" {\n\t\t\t\touPath = ouValue\n\t\t\t} else {\n\t\t\t\touPath = ouPath + \" --> \" + ouValue\n\t\t\t}\n\t\t\tdnParts = dnParts[1:]\n\t\t}\n\t}\n\treturn ouPath\n}\n\nfunc parseFVE(distinguishedName string, ldapEntry *ldap.Entry) map[string]string {\n\tentry := make(map[string]string)\n\tentry[\"distinguishedName\"] = distinguishedName\n\tentry[\"domain\"] = getDomainFromDistinguishedName(distinguishedName)\n\tentry[\"organizationalUnits\"] = getOUPathFromDistinguishedName(distinguishedName)\n\tentry[\"createdAt\"] = \"\"\n\tentry[\"volumeGuid\"] = \"\"\n\n\t// Parse CN of key\n\tre := regexp.MustCompile(`^(CN=)([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}-[0-9]{2}:[0-9]{2})({[0-9A-F\\-]+}),`)\n\tmatched := re.FindStringSubmatch(distinguishedName)\n\tif matched != nil {\n\t\tcreatedAt, guid := matched[2], matched[3]\n\t\tentry[\"createdAt\"] = createdAt\n\t\tentry[\"volumeGuid\"] = strings.Trim(guid, \"{}\")\n\t}\n\n\t// Parse computer name\n\tentry[\"computerName\"] = \"\"\n\tif strings.Contains(distinguishedName, \",\") {\n\t\tsplitDN := strings.Split(distinguishedName, \",\")\n\t\tif strings.ToUpper(splitDN[1][:3]) == \"CN=\" {\n\t\t\tentry[\"computerName\"] = strings.SplitN(splitDN[1], \"=\", 2)[1]\n\t\t}\n\t}\n\n\t// Add recovery key\n\tentry[\"recoveryKey\"] = ldapEntry.GetAttributeValue(\"msFVE-RecoveryPassword\")\n\n\treturn entry\n}\n\n\nvar (\n\tuseLdaps     bool\n\tquiet        bool\n\tdebug        bool\n\tldapHost     string\n\tldapPort     int\n\tauthDomain   string\n\tauthUsername string\n\t// noPass         bool\n\tauthPassword string\n\tauthHashes   string\n\t// authKey        string\n\t// useKerberos    bool\n\txlsx         string\n)\n\nfunc parseArgs() {\n\tflag.BoolVar(&useLdaps, \"use-ldaps\", false, \"Use LDAPS instead of LDAP.\")\n\tflag.BoolVar(&quiet, \"quiet\", false, \"Show no information at all.\")\n\tflag.BoolVar(&debug, \"debug\", false, \"Debug mode\")\n\n\tflag.StringVar(&ldapHost, \"host\", \"\", \"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\tflag.IntVar(&ldapPort, \"port\", 0, \"Port number to connect to LDAP server.\")\n\n\tflag.StringVar(&authDomain, \"domain\", \"\", \"(FQDN) domain to authenticate to.\")\n\tflag.StringVar(&authUsername, \"username\", \"\", \"User to authenticate as.\")\n\t//flag.BoolVar(&noPass, \"no-pass\", false, \"don't ask for password (useful for -k)\")\n\tflag.StringVar(&authPassword, \"password\", \"\", \"password to authenticate with.\")\n\tflag.StringVar(&authHashes, \"hashes\", \"\", \"NT/LM hashes, format is LMhash:NThash.\")\n\t//flag.StringVar(&authKey, \"aes-key\", \"\", \"AES key to use for Kerberos Authentication (128 or 256 bits)\")\n\t//flag.BoolVar(&useKerberos, \"k\", false, \"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\n\tflag.StringVar(&xlsx, \"xlsx\", \"\", \"Output results in a XLSX Excel file.\")\n\n\tflag.Parse()\n\n\tif ldapHost == \"\" {\n\t\tfmt.Println(\"[!] Option -host <host> is required.\")\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tif ldapPort == 0 {\n\t\tif useLdaps {\n\t\t\tldapPort = 636\n\t\t} else {\n\t\t\tldapPort = 389\n\t\t}\n\t}\n}\n\nfunc main() {\n\tbanner()\n\tparseArgs()\n\n\tif debug {\n\t\tif !useLdaps {\n\t\t\tfmt.Printf(\"[debug] Connecting to remote ldap://%s:%d ...\\n\", ldapHost, ldapPort)\n\t\t} else {\n\t\t\tfmt.Printf(\"[debug] Connecting to remote ldaps://%s:%d ...\\n\", ldapHost, ldapPort)\n\t\t}\n\t}\n\n\t// Init the LDAP connection\n\tldapSession, err := ldap_init_connection(ldapHost, ldapPort, authUsername, authDomain, authPassword)\n\tif err != nil {\n\t\tfmt.Println(\"[!] Error searching LDAP:\", err)\n\t\treturn\n\t}\n\n\trootDSE := ldap_get_rootdse(ldapSession)\n\tif debug {\n\t\tfmt.Printf(\"[debug] Using defaultNamingContext %s ...\\n\", rootDSE.GetAttributeValue(\"defaultNamingContext\"))\n\t}\n\n\t// Specify LDAP search parameters\n\t// https://pkg.go.dev/gopkg.in/ldap.v3#NewSearchRequest\n\tsearchRequest := ldap.NewSearchRequest(\n\t\t// Base DN\n\t\trootDSE.GetAttributeValue(\"defaultNamingContext\"),\n\t\t// Scope\n\t\tldap.ScopeWholeSubtree,\n\t\t// DerefAliases\n\t\tldap.NeverDerefAliases,\n\t\t// SizeLimit\n\t\t0,\n\t\t// TimeLimit\n\t\t0,\n\t\t// TypesOnly\n\t\tfalse,\n\t\t// Search filter\n\t\t\"(objectClass=msFVE-RecoveryInformation)\",\n\t\t// Attributes to retrieve\n\t\t[]string{\n\t\t\t\"msFVE-KeyPackage\",        // https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-keypackage\n\t\t\t\"msFVE-RecoveryGuid\",      // https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoveryguid\n\t\t\t\"msFVE-RecoveryPassword\",  // https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoverypassword\n\t\t\t\"msFVE-VolumeGuid\",        // https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-volumeguid\n\t\t\t\"distinguishedName\",\n\t\t},\n\t\t// Controls\n\t\tnil,\n\t)\n\n\t// Perform LDAP search\n\tfmt.Println(\"[+] Extracting LAPS passwords of all computers ... \")\n\tsearchResult, err := ldapSession.Search(searchRequest)\n\tif err != nil {\n\t\tfmt.Println(\"[!] Error searching LDAP:\", err)\n\t\treturn\n\t}\n\t\n\t// Print search results\n\tvar resultsList []map[string]string\n\tfor _, entry := range searchResult.Entries {\n\t\tresult := parseFVE(entry.GetAttributeValue(\"distinguishedName\"), entry)\n\t\tresultsList = append(resultsList, result)\n\t}\n\tfmt.Printf(\"[+] Total BitLocker recovery keys found: %d\\n\", len(resultsList))\n\t\n\t// Export BitLocker Recovery Keys to an Excel\n\tif xlsx != \"\" {\n\t\tf := excelize.NewFile()\n\t\t// Create a new sheet.\n\t\tindex, err := f.NewSheet(\"Sheet1\")\n\t\t// Set value of a cell.\n\t\tf.SetCellValue(\"Sheet1\", \"A1\", \"Domain\")\n\t\tf.SetCellValue(\"Sheet1\", \"B1\", \"Computer Name\")\n\t\tf.SetCellValue(\"Sheet1\", \"C1\", \"BitLocker Recovery Key\")\n\t\tfor i, result := range resultsList {\n\t\t\tf.SetCellValue(\"Sheet1\", fmt.Sprintf(\"A%d\", i+2), result[\"domain\"])\n\t\t\tf.SetCellValue(\"Sheet1\", fmt.Sprintf(\"B%d\", i+2), result[\"computerName\"])\n\t\t\tf.SetCellValue(\"Sheet1\", fmt.Sprintf(\"C%d\", i+2), result[\"recoveryKey\"])\n\t\t}\n\t\t// Set active sheet of the workbook.\n\t\tf.SetActiveSheet(index)\n\t\t// Save xlsx file by the given path.\n\t\tif err := f.SaveAs(xlsx); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tfmt.Printf(\"[+] Exported BitLocker recovery keys to: %s\\n\", xlsx)\n\t} else {\n\t\t// Print the keys in the console\n\t\tfor _, result := range resultsList {\n\t\t\tfmt.Printf(\"| %-20s | %-20s | %s |\\n\", result[\"domain\"], result[\"computerName\"], result[\"recoveryKey\"])\n\t\t}\n\t}\n\n\tfmt.Println(\"[+] All done!\")\n}\n"
  },
  {
    "path": "go/src/go.mod",
    "content": "module ExtractBitlockerKeys\n\ngo 1.22.1\n\nrequire github.com/go-ldap/ldap/v3 v3.4.6\n\nrequire (\n\tgithub.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect\n\tgithub.com/go-asn1-ber/asn1-ber v1.5.5 // indirect\n\tgithub.com/google/uuid v1.3.1 // indirect\n\tgithub.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect\n\tgithub.com/richardlehane/mscfb v1.0.4 // indirect\n\tgithub.com/richardlehane/msoleps v1.0.3 // indirect\n\tgithub.com/xuri/efp v0.0.0-20231025114914-d1ff6096ae53 // indirect\n\tgithub.com/xuri/excelize/v2 v2.8.1 // indirect\n\tgithub.com/xuri/nfp v0.0.0-20230919160717-d98342af3f05 // indirect\n\tgolang.org/x/crypto v0.19.0 // indirect\n\tgolang.org/x/net v0.21.0 // indirect\n\tgolang.org/x/text v0.14.0 // indirect\n)\n"
  },
  {
    "path": "go/src/go.sum",
    "content": "github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=\ngithub.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=\ngithub.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA=\ngithub.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=\ngithub.com/go-ldap/ldap/v3 v3.4.6 h1:ert95MdbiG7aWo/oPYp9btL3KJlMPKnP58r09rI8T+A=\ngithub.com/go-ldap/ldap/v3 v3.4.6/go.mod h1:IGMQANNtxpsOzj7uUAMjpGBaOVTC4DYyIy8VsTdxmtc=\ngithub.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=\ngithub.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=\ngithub.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM=\ngithub.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk=\ngithub.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=\ngithub.com/richardlehane/msoleps v1.0.3 h1:aznSZzrwYRl3rLKRT3gUk9am7T/mLNSnJINvN0AQoVM=\ngithub.com/richardlehane/msoleps v1.0.3/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=\ngithub.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=\ngithub.com/xuri/efp v0.0.0-20231025114914-d1ff6096ae53 h1:Chd9DkqERQQuHpXjR/HSV1jLZA6uaoiwwH3vSuF3IW0=\ngithub.com/xuri/efp v0.0.0-20231025114914-d1ff6096ae53/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=\ngithub.com/xuri/excelize/v2 v2.8.1 h1:pZLMEwK8ep+CLIUWpWmvW8IWE/yxqG0I1xcN6cVMGuQ=\ngithub.com/xuri/excelize/v2 v2.8.1/go.mod h1:oli1E4C3Pa5RXg1TBXn4ENCXDV5JUMlBluUhG7c+CEE=\ngithub.com/xuri/nfp v0.0.0-20230919160717-d98342af3f05 h1:qhbILQo1K3mphbwKh1vNm4oGezE1eF9fQWmNiIpSfI4=\ngithub.com/xuri/nfp v0.0.0-20230919160717-d98342af3f05/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=\ngithub.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=\ngolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=\ngolang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=\ngolang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=\ngolang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=\ngolang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=\ngolang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=\ngolang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=\ngolang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=\ngolang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=\ngolang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=\ngolang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=\ngolang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=\ngolang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=\ngolang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=\ngolang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=\ngolang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=\ngolang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=\ngolang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=\ngolang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=\ngolang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\ngolang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=\ngolang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=\ngolang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=\ngolang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=\ngolang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=\ngolang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=\ngolang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=\ngolang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=\ngolang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=\ngolang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=\ngolang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "powershell/ExtractBitlockerKeys.ps1",
    "content": "# File name          : ExtractBitLockerKeys.ps1\n# Author             : Podalirius (@podalirius_)\n# Date created       : 21 September 2023\n\nParam (\n    [parameter(Mandatory=$true)][string]$dcip = $null,\n    [parameter(Mandatory=$false,ParameterSetName=\"Credentials\")][System.Management.Automation.PSCredential]$Credentials,\n    [parameter(Mandatory=$false,ParameterSetName=\"Credentials\")][Switch]$UseCredentials,\n    [parameter(Mandatory=$false)][string]$LogFile = $null,\n    [parameter(Mandatory=$false)][switch]$Quiet,\n    [parameter(Mandatory=$false)][string]$ExportToCSV = $null,\n    [parameter(Mandatory=$false)][string]$ExportToJSON = $null,\n    [parameter(Mandatory=$false)][int]$PageSize = 5000,\n    [parameter(Mandatory=$false)][string]$SearchBase = $null,\n    [parameter(Mandatory=$false)][switch]$LDAPS,\n    [parameter(Mandatory=$false)][switch]$Help\n)\n\nIf ($Help) {\n    Write-Host \"[+]========================================================\"\n    Write-Host \"[+] Powershell ExtractBitLockerKeys v1.3     @podalirius_  \"\n    Write-Host \"[+]========================================================\"\n    Write-Host \"\"\n\n    Write-Host \"Required arguments:\"\n    Write-Host \"  -dcip             : LDAP host to target, most likely the domain controller.\"\n    Write-Host \"\"\n    Write-Host \"Optional arguments:\"\n    Write-Host \"  -Help             : Displays this help message\"\n    Write-Host \"  -Quiet            : Do not print keys, only export them.\"\n    Write-Host \"  -UseCredentials   : Flag for asking for credentials to authentication\"\n    Write-Host \"  -Credentials      : Providing PSCredentialObject for authentication\"\n    Write-Host \"  -PageSize         : Sets the LDAP page size to use in queries (default: 5000).\"\n    Write-Host \"  -LDAPS            : Use LDAPS instead of LDAP.\"\n    Write-Host \"  -LogFile          : Log file to save output to.\"\n    Write-Host \"  -ExportToCSV      : Export Bitlocker Keys in a CSV file.\"\n    Write-Host \"  -ExportToJSON     : Export Bitlocker Keys in a JSON file.\"\n    exit 0\n}\n\nIf ($LogFile.Length -ne 0) {\n    # Init log file\n    $Stream = [System.IO.StreamWriter]::new($LogFile)\n    $Stream.Close()\n}\n\nif($UseCredentials -and ([string]::IsNullOrEmpty($Credentials))){\n    $Credentials = Get-Credential\n}\n\n\n\nFunction Write-Logger {\n    [CmdletBinding()]\n    [OutputType([Nullable])]\n    Param\n    (\n        [Parameter(Mandatory=$true)] $Logfile,\n        [Parameter(Mandatory=$true)] $Message\n    )\n    Begin\n    {\n        Write-Host $Message\n        If ($LogFile.Length -ne 0) {\n            $Stream = [System.IO.StreamWriter]::new($LogFile, $true)\n            $Stream.WriteLine($Message)\n            $Stream.Close()\n        }\n    }\n}\n\nFunction Get-ComputerNameFromLDAPDN {\n    [CmdletBinding()]\n    [OutputType([Nullable])]\n    param ([string]$ldapDN)\n\n    Begin\n    {\n        $ldapDNParts = $ldapDN -split ','\n        if ($ldapDNParts[1] -match '^CN=([^,]+)$') {\n            return $matches[1]\n        } else {\n             return \"\"\n        }\n    }\n}\n\nFunction Get-DomainFromLDAPDN {\n    [CmdletBinding()]\n    [OutputType([Nullable])]\n    param ([string]$ldapDN)\n\n    Begin\n    {\n        $domain = \"\"\n\n        [System.Collections.ArrayList]$ldapDNParts = @();\n        foreach ($part in ($ldapDN -split ',')) { $ldapDNParts.Add($part) | Out-Null }\n        $ldapDNParts.Reverse() | Out-Null\n\n        foreach ($part in $ldapDNParts) {\n            if ($part -match '^DC=([^,]+)$') {\n                $domain = $matches[1] + \".\" + $domain\n            } else {\n                # Check if the domain ends with a period\n                if ($domain.EndsWith('.')) {\n                    # Remove the trailing period\n                    $domain = $domain.TrimEnd('.')\n                }\n\n                return $domain\n            }\n        }\n        return $domain\n    }\n}\n\n\nFunction Get-VolumeGuidFromLDAPDN {\n    [CmdletBinding()]\n    [OutputType([Nullable])]\n    param ([string]$ldapDN)\n\n    Begin\n    {\n        $ldapDNParts = $ldapDN -split '/'\n        $ldapDNParts = $ldapDNParts[3] -split ','\n        if ($ldapDNParts[0] -match '^CN=([^,]+){([^,]+)}$') {\n            return $matches[2]\n        } else {\n             return \"\"\n        }\n    }\n}\n\n\nFunction Get-CreatedAtFromLDAPDN {\n    [CmdletBinding()]\n    [OutputType([Nullable])]\n    param ([string]$ldapDN)\n\n    Begin\n    {\n        $ldapDNParts = $ldapDN -split '/'\n        $ldapDNParts = $ldapDNParts[3] -split ','\n        if ($ldapDNParts[0] -match '^CN=([^,]+)$') {\n            $createdAt = ($matches[1] -split '{')\n            return $createdAt[0]\n        } else {\n             return \"\"\n        }\n    }\n}\n\n\nFunction Invoke-LDAPQuery {\n    [CmdletBinding()]\n    [OutputType([Nullable])]\n    Param\n    (\n        [Parameter(Mandatory=$true)] $connectionString,\n        [parameter(Mandatory=$false,ParameterSetName=\"Credentials\")][System.Management.Automation.PSCredential] $Credentials,\n        [Parameter(Mandatory=$false)] $PageSize\n    )\n    Begin\n    {\n        $rootDSE = New-Object System.DirectoryServices.DirectoryEntry(\"{0}/RootDSE\" -f $connectionString);\n        $defaultNamingContext = $rootDSE.Properties[\"defaultNamingContext\"].ToString();\n        Write-Logger -Logfile $Logfile -Message \"[+] Authentication successful!\";\n        Write-Logger -Logfile $Logfile -Message \"[+] Targeting defaultNamingContext: $defaultNamingContext\";\n        $ldapSearcher = New-Object System.DirectoryServices.DirectorySearcher\n        if ($Credentials.UserName) {\n            # Connect to Domain with credentials\n            Write-Logger -Logfile $Logfile -Message (\"[+] Connecting to {0}/{1} with specified account\" -f $connectionString, $defaultNamingContext)\n            $ldapSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry((\"{0}/{1}\" -f $connectionString, $defaultNamingContext), $Credentials.UserName, $($Credentials.Password | ConvertFrom-Securestring -AsPlaintext))\n        } else {\n            # Connect to Domain with current session\n            Write-Logger -Logfile $Logfile -Message (\"[+] Connecting to {0}/{1} using current session\" -f $connectionString, $defaultNamingContext)\n            $ldapSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry((\"{0}/{1}\" -f $connectionString, $defaultNamingContext))\n        }\n        $ldapSearcher.SearchScope = \"Subtree\"\n        if ($PageSize) {\n            $ldapSearcher.PageSize = $PageSize\n        } else {\n            Write-Logger -Logfile $Logfile -Message \"[+] Setting PageSize to $PageSize\";\n            $ldapSearcher.PageSize = 5000\n        }\n\n        Write-Logger -Logfile $Logfile -Message \"[+] Extracting BitLocker recovery keys ...\";\n        $ldapSearcher.Filter = \"(objectClass=msFVE-RecoveryInformation)\"\n        $ldapSearcher.PropertiesToLoad.Add(\"msFVE-KeyPackage\") | Out-Null ;  # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-keypackage\n        $ldapSearcher.PropertiesToLoad.Add(\"msFVE-RecoveryGuid\") | Out-Null ;  # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoveryguid\n        $ldapSearcher.PropertiesToLoad.Add(\"msFVE-RecoveryPassword\") | Out-Null ;  # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoverypassword\n        $ldapSearcher.PropertiesToLoad.Add(\"msFVE-VolumeGuid\") | Out-Null ;  # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-volumeguid\n        $results = [ordered]@{};\n        Foreach ($item in $ldapSearcher.FindAll()) {\n            if (!($results.Keys -contains $item.Path)) {\n                $results[$item.Path] = $item.Properties;\n            } else {\n                Write-Logger -Logfile $Logfile -Message \"[debug] key already exists: $key (this shouldn't be possible)\"\n            }\n        }\n\n        $bitlocker_keys = Foreach ($distinguishedName in $results.Keys) {\n            Foreach ($recoveryKey in $results[$distinguishedName][\"msFVE-RecoveryPassword\"]) {\n                $domainName = (Get-DomainFromLDAPDN $distinguishedName)\n                $createdAt = (Get-CreatedAtFromLDAPDN $distinguishedName)\n                $volumeGuid = (Get-VolumeGuidFromLDAPDN $distinguishedName)\n                $computerName = (Get-ComputerNameFromLDAPDN $distinguishedName)\n                [PSCustomObject]@{\n                    domainName = $domainName\n                    computerName = $computerName\n                    recoveryKey = $recoveryKey\n                    volumeGuid = $volumeGuid\n                    createdAt = $createdAt\n                    distinguishedName = $distinguishedName\n                }\n            }\n        }\n        return $bitlocker_keys\n    }\n}\n\n#===============================================================================\n\nWrite-Logger -Logfile $Logfile -Message  \"[+]========================================================\"\nWrite-Logger -Logfile $Logfile -Message  \"[+] Powershell ExtractBitLockerKeys v1.3     @podalirius_  \"\nWrite-Logger -Logfile $Logfile -Message  \"[+]========================================================\"\nWrite-Logger -Logfile $Logfile -Message  \"\"\n\n# Handle LDAPS connection\n$connectionString = \"LDAP://{0}:{1}\";\nIf ($LDAPS) {\n    $connectionString = ($connectionString -f $dcip, \"636\");\n} else {\n    $connectionString = ($connectionString -f $dcip, \"389\");\n}\nWrite-Verbose \"Using connectionString: $connectionString\"\n\n# Connect to LDAP\ntry {\n    $bitlocker_keys = Invoke-LDAPQuery -connectionString $connectionString -Credentials $Credentials -PageSize $PageSize\n\n    If (!($Quiet)) {\n        Foreach ($entry in $bitlocker_keys) {\n            $domainName = $entry.domainName.PadRight(20,\" \")\n            $computerName = $entry.computerName.PadRight(20,\" \")\n            $recoveryKey = $entry.recoveryKey.PadRight(20,\" \")\n            $createdAt = $entry.createdAt\n            Write-Logger -Logfile $Logfile -Message (\"| {0} | {1} | {2} | {3} \" -f $domainName, $computerName, $recoveryKey, $createdAt)\n        }\n    }\n    Write-Logger -Logfile $Logfile -Message (\"[>] Extracted {0} BitLocker recovery keys!\" -f $bitlocker_keys.Length)\n    If ($ExportToCSV) {\n        Write-Logger -Logfile $Logfile -Message \"[>] Exporting Bitlocker recovery keys in CSV in $ExportToCSV ...\"\n        $bitlocker_keys | Export-CSV -Path $ExportToCSV -NoTypeInformation\n    }\n    If ($ExportToJSON) {\n        Write-Logger -Logfile $Logfile -Message \"[>] Exporting Bitlocker recovery keys in JSON in $ExportToJSON ...\"\n        $bitlocker_keys | ConvertTo-Json -Depth 100 -Compress | Out-File -FilePath $ExportToJSON\n    }\n\n} catch {\n    Write-Verbose $_.Exception\n    Write-Logger -Logfile $Logfile -Message -Logfile $Logfile -Message (\"[!] (0x{0:X8}) {1}\" -f $_.Exception.HResult, $_.Exception.InnerException.Message)\n    exit -1\n}"
  },
  {
    "path": "python/ExtractBitlockerKeys.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# File name          : ExtractBitlockerKeys.py\n# Author             : Podalirius (@podalirius_)\n# Date created       : 19 Sep 2023\n\n\nimport argparse\nfrom sectools.windows.ldap.ldap import raw_ldap_query, init_ldap_session\nfrom sectools.windows.crypto import nt_hash, parse_lm_nt_hashes\nimport os\nimport sys\nimport sqlite3\nimport json\nimport xlsxwriter\nimport re\n\n\nVERSION = \"1.3\"\n\n\ndef export_json(options, results):\n    print(\"[>] Exporting results to %s ... \" % options.export_json, end=\"\")\n    sys.stdout.flush()\n    basepath = os.path.dirname(options.export_json)\n    filename = os.path.basename(options.export_json)\n    if basepath not in [\".\", \"\"]:\n        if not os.path.exists(basepath):\n            os.makedirs(basepath)\n        path_to_file = basepath + os.path.sep + filename\n    else:\n        path_to_file = filename\n    f = open(path_to_file, \"w\")\n    f.write(json.dumps(results, indent=4) + \"\\n\")\n    f.close()\n    print(\"done.\")\n\n\ndef export_xlsx(options, results):\n    print(\"[>] Exporting results to %s ... \" % options.export_xlsx, end=\"\")\n    sys.stdout.flush()\n    basepath = os.path.dirname(options.export_xlsx)\n    filename = os.path.basename(options.export_xlsx)\n    if basepath not in [\".\", \"\"]:\n        if not os.path.exists(basepath):\n            os.makedirs(basepath)\n        path_to_file = basepath + os.path.sep + filename\n    else:\n        path_to_file = filename\n    workbook = xlsxwriter.Workbook(path_to_file)\n    worksheet = workbook.add_worksheet()\n\n    header_format = workbook.add_format({'bold': 1})\n    header_fields = [\"Computer FQDN\", \"Domain\", \"Recovery Key\", \"Volume GUID\", \"Created At\", \"Organizational Units\"]\n    for k in range(len(header_fields)):\n        worksheet.set_column(k, k + 1, len(header_fields[k]) + 3)\n    worksheet.set_row(0, 20, header_format)\n    worksheet.write_row(0, 0, header_fields)\n\n    row_id = 1\n    for computerfqdn in results.keys():\n        data = [\n            computerfqdn,\n            results[computerfqdn][\"domain\"],\n            results[computerfqdn][\"recoveryKey\"],\n            results[computerfqdn][\"volumeGuid\"],\n            results[computerfqdn][\"createdAt\"],\n            results[computerfqdn][\"organizationalUnits\"],\n        ]\n        worksheet.write_row(row_id, 0, data)\n        row_id += 1\n    worksheet.autofilter(0, 0, row_id, len(header_fields) - 1)\n    workbook.close()\n    print(\"done.\")\n\n\ndef export_sqlite(options, results):\n    print(\"[>] Exporting results to %s ... \" % options.export_sqlite, end=\"\")\n    sys.stdout.flush()\n    basepath = os.path.dirname(options.export_sqlite)\n    filename = os.path.basename(options.export_sqlite)\n    if basepath not in [\".\", \"\"]:\n        if not os.path.exists(basepath):\n            os.makedirs(basepath)\n        path_to_file = basepath + os.path.sep + filename\n    else:\n        path_to_file = filename\n\n    conn = sqlite3.connect(path_to_file)\n    cursor = conn.cursor()\n    cursor.execute(\"CREATE TABLE IF NOT EXISTS bitlocker_keys(fqdn VARCHAR(255), domain VARCHAR(255), recoveryKey VARCHAR(255), volumeGuid VARCHAR(255), createdAt VARCHAR(255), organizationalUnits VARCHAR(1024));\")\n    for computerfqdn in results.keys():\n        cursor.execute(\"INSERT INTO shares VALUES (?, ?, ?, ?, ?, ?)\", (\n                computerfqdn,\n                results[computerfqdn][0][\"domain\"],\n                results[computerfqdn][0][\"recoveryKey\"],\n                results[computerfqdn][0][\"volumeGuid\"],\n                results[computerfqdn][0][\"createdAt\"],\n                results[computerfqdn][0][\"organizationalUnits\"],\n            )\n        )\n    conn.commit()\n    conn.close()\n    print(\"done.\")\n\n\ndef get_domain_from_distinguished_name(distinguishedName):\n    domain = None\n    if \"dc=\" in distinguishedName.lower():\n        distinguishedName = distinguishedName.lower().split(',')[::-1]\n\n        while distinguishedName[0].startswith(\"dc=\"):\n            if domain is None:\n                domain = distinguishedName[0].split('=',1)[1]\n            else:\n                domain = distinguishedName[0].split('=', 1)[1] + \".\" + domain\n            distinguishedName = distinguishedName[1:]\n\n    return domain\n\n\ndef get_ou_path_from_distinguished_name(distinguishedName):\n    ou_path = None\n    if \"ou=\" in distinguishedName.lower():\n        distinguishedName = distinguishedName.lower().split(',')[::-1]\n\n        # Skip domain\n        while distinguishedName[0].startswith(\"dc=\"):\n            distinguishedName = distinguishedName[1:]\n\n        while distinguishedName[0].startswith(\"ou=\"):\n            if ou_path is None:\n                ou_path = distinguishedName[0].split('=',1)[1]\n            else:\n                ou_path = ou_path + \" --> \" + distinguishedName[0].split('=',1)[1]\n            distinguishedName = distinguishedName[1:]\n\n        return ou_path\n    else:\n        return ou_path\n\n\ndef parse_fve(distinguishedName, bitlocker_keys):\n    entry = {\n        \"distinguishedName\": distinguishedName,\n        \"domain\": get_domain_from_distinguished_name(distinguishedName),\n        \"organizationalUnits\": get_ou_path_from_distinguished_name(distinguishedName),\n        \"createdAt\": None,\n        \"volumeGuid\": None\n    }\n    # Parse CN of key\n    matched = re.match(r\"^(CN=)([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]-[0-9][0-9]:[0-9][0-9])({[0-9A-F\\-]+}),\", distinguishedName, re.IGNORECASE)\n    if matched is not None:\n        _, created_at, guid = matched.groups()\n        entry[\"createdAt\"] = created_at\n        entry[\"volumeGuid\"] = guid.strip('{}').lower()\n    # Parse computer name\n    entry[\"computerName\"] = None\n    if ',' in distinguishedName:\n        if distinguishedName.split(',')[1].upper().startswith(\"CN=\"):\n            entry[\"computerName\"] = distinguishedName.split(',')[1].split('=',1)[1]\n    # Add recovery key\n    entry[\"recoveryKey\"] = bitlocker_keys[\"msFVE-RecoveryPassword\"]\n\n    return entry\n\n\ndef parseArgs():\n    print(\"ExtractBitlockerKeys.py v%s - by Remi GASCOU (Podalirius)\\n\" % VERSION)\n\n    parser = argparse.ArgumentParser(description=\"\")\n\n    parser.add_argument(\"-v\", \"--verbose\", default=False, action=\"store_true\", help='Verbose mode. (default: False)')\n    parser.add_argument(\"-q\", \"--quiet\", dest=\"quiet\", action=\"store_true\", default=False, help=\"Show no information at all.\")\n    parser.add_argument(\"-t\", \"--threads\", dest=\"threads\", action=\"store\", type=int, default=4, required=False, help=\"Number of threads (default: 4).\")\n\n    output = parser.add_argument_group('Output files')\n    output.add_argument(\"--export-xlsx\", dest=\"export_xlsx\", type=str, default=None, required=False, help=\"Output XLSX file to store the results in.\")\n    output.add_argument(\"--export-json\", dest=\"export_json\", type=str, default=None, required=False, help=\"Output JSON file to store the results in.\")\n    output.add_argument(\"--export-sqlite\", dest=\"export_sqlite\", type=str, default=None, required=False, help=\"Output SQLITE3 file to store the results in.\")\n\n    authconn = parser.add_argument_group('Authentication & connection')\n    authconn.add_argument('--dc-ip', required=True, 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    authconn.add_argument('--kdcHost', dest=\"kdcHost\", action='store', metavar=\"FQDN KDC\", help='FQDN of KDC for Kerberos.')\n    authconn.add_argument(\"-d\", \"--domain\", dest=\"auth_domain\", metavar=\"DOMAIN\", action=\"store\", default=\"\", help=\"(FQDN) domain to authenticate to\")\n    authconn.add_argument(\"-u\", \"--user\", dest=\"auth_username\", metavar=\"USER\", action=\"store\", default=\"\", help=\"user to authenticate with\")\n\n    secret = parser.add_argument_group(\"Credentials\")\n    cred = secret.add_mutually_exclusive_group()\n    cred.add_argument(\"--no-pass\", default=False, action=\"store_true\", help=\"Don't ask for password (useful for -k)\")\n    cred.add_argument(\"-p\", \"--password\", dest=\"auth_password\", metavar=\"PASSWORD\", action=\"store\", default=None, help=\"Password to authenticate with\")\n    cred.add_argument(\"-H\", \"--hashes\", dest=\"auth_hashes\", action=\"store\", metavar=\"[LMHASH:]NTHASH\", help='NT/LM hashes, format is LMhash:NThash')\n    cred.add_argument(\"--aes-key\", dest=\"auth_key\", action=\"store\", metavar=\"hex key\", help='AES key to use for Kerberos Authentication (128 or 256 bits)')\n    secret.add_argument(\"-k\", \"--kerberos\", dest=\"use_kerberos\", 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\n    return parser.parse_args()\n\n\nif __name__ == '__main__':\n    options = parseArgs()\n    if options.auth_hashes is not None:\n        if \":\" not in options.auth_hashes:\n            options.auth_hashes = \":\" + options.auth_hashes\n    auth_lm_hash, auth_nt_hash = parse_lm_nt_hashes(options.auth_hashes)\n\n    if options.auth_key is not None:\n        options.use_kerberos = True\n\n    if options.use_kerberos is True and options.kdcHost is None:\n        print(\"[!] Specify KDC's Hostname of FQDN using the argument --kdcHost\")\n        exit()\n\n    if not options.quiet:\n        print(\"[>] Extracting BitLocker recovery keys of all computers ...\")\n\n    computer_keys = raw_ldap_query(\n        auth_domain=options.auth_domain,\n        auth_dc_ip=options.dc_ip,\n        auth_username=options.auth_username,\n        auth_password=options.auth_password,\n        auth_hashes=options.auth_hashes,\n        auth_key=options.auth_key,\n        query=\"(objectClass=msFVE-RecoveryInformation)\",\n        attributes=[\n            \"msFVE-KeyPackage\",  # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-keypackage\n            \"msFVE-RecoveryGuid\",  # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoveryguid\n            \"msFVE-RecoveryPassword\",  # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoverypassword\n            \"msFVE-VolumeGuid\"  # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-volumeguid\n        ],\n        use_kerberos=options.use_kerberos,\n        kdcHost=options.kdcHost\n    )\n\n    if not options.quiet:\n        print(\"[>] Found %d BitLocker recovery keys!\" % len(computer_keys.keys()))\n\n    results = {}\n\n    if len(computer_keys.keys()) != 0:\n        for dn, fve_entry in computer_keys.items():\n            if len(fve_entry.keys()) != 0:\n                if dn not in results.keys():\n                    results[dn] = []\n                result = parse_fve(dn, fve_entry)\n                print(\"| %-20s | %-20s | %s |\" % (result[\"domain\"], result[\"computerName\"], result[\"recoveryKey\"]))\n                results[dn].append(result)\n\n        print(\"[>] Extracted %d BitLocker recovery keys!\" % len(computer_keys.keys()))\n\n        # Export results\n        if options.export_json is not None:\n            export_json(options, results)\n\n        if options.export_xlsx is not None:\n            export_xlsx(options, results)\n\n        if options.export_sqlite is not None:\n            export_sqlite(options, results)\n    else:\n        print(\"[!] No computers in the domain found matching filter (objectClass=msFVE-RecoveryInformation)\")\n\n\n    print(\"[+] Bye Bye!\")\n"
  },
  {
    "path": "requirements.txt",
    "content": "sectools>=1.5.0\nxlsxwriter\nldap3\n"
  }
]