Repository: p0dalirius/ExtractBitlockerKeys Branch: main Commit: 54730e4564b7 Files: 12 Total size: 66.1 KB Directory structure: gitextract_n3ndlvo3/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md ├── go/ │ ├── Dockerfile │ ├── Makefile │ └── src/ │ ├── ExtractBitlockerKeys.go │ ├── go.mod │ └── go.sum ├── powershell/ │ └── ExtractBitlockerKeys.ps1 ├── python/ │ └── ExtractBitlockerKeys.py └── requirements.txt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: p0dalirius patreon: Podalirius ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # poetry # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. # This is especially recommended for binary packages to ensure reproducibility, and is more # commonly ignored for libraries. # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control #poetry.lock # pdm # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. #pdm.lock # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it # in version control. # https://pdm.fming.dev/#use-with-ide .pdm.toml # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ # PyCharm # JetBrains specific template is maintained in a separate JetBrains.gitignore that can # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: README.md ================================================ ![](./.github/banner.png)

A system administration or post-exploitation script to automatically extract the bitlocker recovery keys from a domain.
GitHub release (latest by date) YouTube Channel Subscribers

## Features - [x] Automatically gets the list of all computers from the domain controller's LDAP. - [x] Multithreaded connections to extract Bitlocker keys from LDAP. - [x] Iterate on LDAP result pages to get every computer of the domain, no matter the size. > [!WARNING] > 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. - [x] Export results in JSON with Computer FQDN, Domain, Recovery Key, Volume GUID, Created At and Organizational Units. - [x] Export results in XLSX with Computer FQDN, Domain, Recovery Key, Volume GUID, Created At and Organizational Units. - [x] Export results in SQLITE3 with Computer FQDN, Domain, Recovery Key, Volume GUID, Created At and Organizational Units. --- ## Demonstration from Linux in Python To extract Bitlocker recovery keys from all the computers of the domain `domain.local` you can use this command: ``` ./ExtractBitlockerKeys.py -d 'domain.local' -u 'Administrator' -p 'Podalirius123!' --dc-ip 192.168.1.101 ``` You will get the following output: ![](./.github/example_python.png) --- ## Demonstration from Windows in Powershell To extract Bitlocker recovery keys from all the computers of the domain `domain.local` you can use this command: ``` .\ExtractBitlockerKeys.ps1 -dcip 192.168.1.101 -ExportToCSV ./keys.csv -ExportToJSON ./keys.json ``` You will get the following output: ![](./.github/example_powershell.png) --- ## Usage ``` $ ./ExtractBitlockerKeys.py -h ExtractBitlockerKeys.py v1.1 - by Remi GASCOU (Podalirius) usage: 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] [--no-pass | -p PASSWORD | -H [LMHASH:]NTHASH | --aes-key hex key] [-k] options: -h, --help show this help message and exit -v, --verbose Verbose mode. (default: False) -q, --quiet Show no information at all. -t THREADS, --threads THREADS Number of threads (default: 4). Output files: --export-xlsx EXPORT_XLSX Output XLSX file to store the results in. --export-json EXPORT_JSON Output JSON file to store the results in. --export-sqlite EXPORT_SQLITE Output SQLITE3 file to store the results in. Authentication & connection: --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 -d DOMAIN, --domain DOMAIN (FQDN) domain to authenticate to -u USER, --user USER user to authenticate with Credentials: --no-pass Don't ask for password (useful for -k) -p PASSWORD, --password PASSWORD Password to authenticate with -H [LMHASH:]NTHASH, --hashes [LMHASH:]NTHASH NT/LM hashes, format is LMhash:NThash --aes-key hex key AES key to use for Kerberos Authentication (128 or 256 bits) -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. ``` ## Contributing Pull requests are welcome. Feel free to open an issue if you want to add other features. ## References - [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) - [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) - [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) - [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) ================================================ FILE: go/Dockerfile ================================================ FROM debian:latest RUN apt-get -y -q update \ && apt-get -y -q install nano git wget build-essential librust-gobject-sys-dev libnss3 libnss3-dev RUN wget https://go.dev/dl/go1.22.1.linux-amd64.tar.gz -O /tmp/go.tar.gz \ && rm -rf /usr/local/go \ && tar -C /usr/local -xzf /tmp/go.tar.gz \ && echo 'export PATH=$PATH:/usr/local/go/bin' >> /root/.bashrc \ && echo 'export PATH=$PATH:/root/go/bin' >> /root/.bashrc RUN echo "go clean; go build -v" >> /root/.bash_history RUN echo '#!/bin/bash' > /entrypoint.sh \ && echo 'mkdir -p /workspace/bin/' >> /entrypoint.sh \ && echo 'cd /workspace/src/' >> /entrypoint.sh \ && echo '/usr/local/go/bin/go clean' >> /entrypoint.sh \ && echo 'echo "[+] Building"' >> /entrypoint.sh \ && echo 'echo " ├──[>] Building for linux i386"' >> /entrypoint.sh \ && echo 'mkdir -p /workspace/bin/linux/x86/' >> /entrypoint.sh >> /entrypoint.sh \ && echo 'GOOS=linux GOARCH=386 /usr/local/go/bin/go build -o /workspace/bin/linux/x86/ ExtractBitlockerKeys.go' >> /entrypoint.sh \ && echo 'echo " ├──[>] Building for linux amd64"' >> /entrypoint.sh \ && echo 'mkdir -p /workspace/bin/linux/x64/' >> /entrypoint.sh >> /entrypoint.sh \ && echo 'GOOS=linux GOARCH=amd64 /usr/local/go/bin/go build -o /workspace/bin/linux/x64/ ExtractBitlockerKeys.go' >> /entrypoint.sh \ && echo 'echo " ├──[>] Building for Windows i386"' >> /entrypoint.sh \ && echo 'mkdir -p /workspace/bin/windows/x86/' >> /entrypoint.sh >> /entrypoint.sh \ && echo 'GOOS=windows GOARCH=386 /usr/local/go/bin/go build -o /workspace/bin/windows/x86/ ExtractBitlockerKeys.go' >> /entrypoint.sh \ && echo 'echo " └──[>] Building for Windows amd64"' >> /entrypoint.sh \ && echo 'mkdir -p /workspace/bin/windows/x64/' >> /entrypoint.sh >> /entrypoint.sh \ && echo 'GOOS=windows GOARCH=amd64 /usr/local/go/bin/go build -o /workspace/bin/windows/x64/ ExtractBitlockerKeys.go' >> /entrypoint.sh \ && chmod +x /entrypoint.sh # Prepare workspace volume RUN mkdir -p /workspace/ VOLUME /workspace/ WORKDIR /workspace/ CMD ["/bin/bash", "/entrypoint.sh"] ================================================ FILE: go/Makefile ================================================ .PHONY: all build_docker compile IMGNAME := build_go all: build_docker compile build_docker: docker build -t $(IMGNAME):latest -f Dockerfile . compile: build_docker docker run --rm -v "$(shell pwd):/workspace" -it $(IMGNAME) ================================================ FILE: go/src/ExtractBitlockerKeys.go ================================================ package main import ( "errors" "flag" "fmt" "os" "regexp" "strings" "github.com/go-ldap/ldap/v3" "github.com/xuri/excelize/v2" ) func banner() { fmt.Printf("ExtractBitlockerKeys v%s - by Remi GASCOU (Podalirius)\n", "1.3") fmt.Println("") } func ldap_init_connection(host string, port int, username string, domain string, password string) (*ldap.Conn, error) { // Check if TCP port is valid if port < 1 || port > 65535 { fmt.Println("[!] Invalid port number. Port must be in the range 1-65535.") return nil, errors.New("invalid port number") } // Set up LDAP connection ldapSession, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", host, port)) if err != nil { fmt.Println("[!] Error connecting to LDAP server:", err) return nil, nil } // Bind with credentials if provided bindDN := "" if username != "" { bindDN = fmt.Sprintf("%s@%s", username, domain) } if bindDN != "" && password != "" { err = ldapSession.Bind(bindDN, password) if err != nil { fmt.Println("[!] Error binding:", err) return nil, nil } } return ldapSession, nil } func ldap_get_rootdse(ldapSession *ldap.Conn) *ldap.Entry { // Specify LDAP search parameters // https://pkg.go.dev/gopkg.in/ldap.v3#NewSearchRequest searchRequest := ldap.NewSearchRequest( // Base DN blank "", // Scope Base ldap.ScopeBaseObject, // DerefAliases ldap.NeverDerefAliases, // SizeLimit 1, // TimeLimit 0, // TypesOnly false, // Search filter "(objectClass=*)", // Attributes to retrieve []string{"*"}, // Controls nil, ) // Perform LDAP search searchResult, err := ldapSession.Search(searchRequest) if err != nil { fmt.Println("[!] Error searching LDAP:", err) return nil } return searchResult.Entries[0] } func getDomainFromDistinguishedName(distinguishedName string) string { domain := "" if strings.Contains(strings.ToLower(distinguishedName), "dc=") { dnParts := strings.Split(strings.ToLower(distinguishedName), ",") for _, part := range dnParts { if strings.HasPrefix(part, "dc=") { dcValue := strings.SplitN(part, "=", 2)[1] if domain == "" { domain = dcValue } else { domain = domain + "." + dcValue } } } } return domain } func getOUPathFromDistinguishedName(distinguishedName string) string { ouPath := "" if strings.Contains(strings.ToLower(distinguishedName), "ou=") { dnParts := strings.Split(strings.ToLower(distinguishedName), ",") // Reverse dnParts slice for i, j := 0, len(dnParts)-1; i < j; i, j = i+1, j-1 { dnParts[i], dnParts[j] = dnParts[j], dnParts[i] } // Skip domain for len(dnParts) > 0 && strings.HasPrefix(dnParts[0], "dc=") { dnParts = dnParts[1:] } for len(dnParts) > 0 && strings.HasPrefix(dnParts[0], "ou=") { ouValue := strings.SplitN(dnParts[0], "=", 2)[1] if ouPath == "" { ouPath = ouValue } else { ouPath = ouPath + " --> " + ouValue } dnParts = dnParts[1:] } } return ouPath } func parseFVE(distinguishedName string, ldapEntry *ldap.Entry) map[string]string { entry := make(map[string]string) entry["distinguishedName"] = distinguishedName entry["domain"] = getDomainFromDistinguishedName(distinguishedName) entry["organizationalUnits"] = getOUPathFromDistinguishedName(distinguishedName) entry["createdAt"] = "" entry["volumeGuid"] = "" // Parse CN of key re := 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\-]+}),`) matched := re.FindStringSubmatch(distinguishedName) if matched != nil { createdAt, guid := matched[2], matched[3] entry["createdAt"] = createdAt entry["volumeGuid"] = strings.Trim(guid, "{}") } // Parse computer name entry["computerName"] = "" if strings.Contains(distinguishedName, ",") { splitDN := strings.Split(distinguishedName, ",") if strings.ToUpper(splitDN[1][:3]) == "CN=" { entry["computerName"] = strings.SplitN(splitDN[1], "=", 2)[1] } } // Add recovery key entry["recoveryKey"] = ldapEntry.GetAttributeValue("msFVE-RecoveryPassword") return entry } var ( useLdaps bool quiet bool debug bool ldapHost string ldapPort int authDomain string authUsername string // noPass bool authPassword string authHashes string // authKey string // useKerberos bool xlsx string ) func parseArgs() { flag.BoolVar(&useLdaps, "use-ldaps", false, "Use LDAPS instead of LDAP.") flag.BoolVar(&quiet, "quiet", false, "Show no information at all.") flag.BoolVar(&debug, "debug", false, "Debug mode") flag.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.") flag.IntVar(&ldapPort, "port", 0, "Port number to connect to LDAP server.") flag.StringVar(&authDomain, "domain", "", "(FQDN) domain to authenticate to.") flag.StringVar(&authUsername, "username", "", "User to authenticate as.") //flag.BoolVar(&noPass, "no-pass", false, "don't ask for password (useful for -k)") flag.StringVar(&authPassword, "password", "", "password to authenticate with.") flag.StringVar(&authHashes, "hashes", "", "NT/LM hashes, format is LMhash:NThash.") //flag.StringVar(&authKey, "aes-key", "", "AES key to use for Kerberos Authentication (128 or 256 bits)") //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") flag.StringVar(&xlsx, "xlsx", "", "Output results in a XLSX Excel file.") flag.Parse() if ldapHost == "" { fmt.Println("[!] Option -host is required.") flag.Usage() os.Exit(1) } if ldapPort == 0 { if useLdaps { ldapPort = 636 } else { ldapPort = 389 } } } func main() { banner() parseArgs() if debug { if !useLdaps { fmt.Printf("[debug] Connecting to remote ldap://%s:%d ...\n", ldapHost, ldapPort) } else { fmt.Printf("[debug] Connecting to remote ldaps://%s:%d ...\n", ldapHost, ldapPort) } } // Init the LDAP connection ldapSession, err := ldap_init_connection(ldapHost, ldapPort, authUsername, authDomain, authPassword) if err != nil { fmt.Println("[!] Error searching LDAP:", err) return } rootDSE := ldap_get_rootdse(ldapSession) if debug { fmt.Printf("[debug] Using defaultNamingContext %s ...\n", rootDSE.GetAttributeValue("defaultNamingContext")) } // Specify LDAP search parameters // https://pkg.go.dev/gopkg.in/ldap.v3#NewSearchRequest searchRequest := ldap.NewSearchRequest( // Base DN rootDSE.GetAttributeValue("defaultNamingContext"), // Scope ldap.ScopeWholeSubtree, // DerefAliases ldap.NeverDerefAliases, // SizeLimit 0, // TimeLimit 0, // TypesOnly false, // Search filter "(objectClass=msFVE-RecoveryInformation)", // Attributes to retrieve []string{ "msFVE-KeyPackage", // https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-keypackage "msFVE-RecoveryGuid", // https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoveryguid "msFVE-RecoveryPassword", // https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoverypassword "msFVE-VolumeGuid", // https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-volumeguid "distinguishedName", }, // Controls nil, ) // Perform LDAP search fmt.Println("[+] Extracting LAPS passwords of all computers ... ") searchResult, err := ldapSession.Search(searchRequest) if err != nil { fmt.Println("[!] Error searching LDAP:", err) return } // Print search results var resultsList []map[string]string for _, entry := range searchResult.Entries { result := parseFVE(entry.GetAttributeValue("distinguishedName"), entry) resultsList = append(resultsList, result) } fmt.Printf("[+] Total BitLocker recovery keys found: %d\n", len(resultsList)) // Export BitLocker Recovery Keys to an Excel if xlsx != "" { f := excelize.NewFile() // Create a new sheet. index, err := f.NewSheet("Sheet1") // Set value of a cell. f.SetCellValue("Sheet1", "A1", "Domain") f.SetCellValue("Sheet1", "B1", "Computer Name") f.SetCellValue("Sheet1", "C1", "BitLocker Recovery Key") for i, result := range resultsList { f.SetCellValue("Sheet1", fmt.Sprintf("A%d", i+2), result["domain"]) f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i+2), result["computerName"]) f.SetCellValue("Sheet1", fmt.Sprintf("C%d", i+2), result["recoveryKey"]) } // Set active sheet of the workbook. f.SetActiveSheet(index) // Save xlsx file by the given path. if err := f.SaveAs(xlsx); err != nil { fmt.Println(err) } fmt.Printf("[+] Exported BitLocker recovery keys to: %s\n", xlsx) } else { // Print the keys in the console for _, result := range resultsList { fmt.Printf("| %-20s | %-20s | %s |\n", result["domain"], result["computerName"], result["recoveryKey"]) } } fmt.Println("[+] All done!") } ================================================ FILE: go/src/go.mod ================================================ module ExtractBitlockerKeys go 1.22.1 require github.com/go-ldap/ldap/v3 v3.4.6 require ( github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect github.com/google/uuid v1.3.1 // indirect github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect github.com/richardlehane/mscfb v1.0.4 // indirect github.com/richardlehane/msoleps v1.0.3 // indirect github.com/xuri/efp v0.0.0-20231025114914-d1ff6096ae53 // indirect github.com/xuri/excelize/v2 v2.8.1 // indirect github.com/xuri/nfp v0.0.0-20230919160717-d98342af3f05 // indirect golang.org/x/crypto v0.19.0 // indirect golang.org/x/net v0.21.0 // indirect golang.org/x/text v0.14.0 // indirect ) ================================================ FILE: go/src/go.sum ================================================ github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8= github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA= github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= github.com/go-ldap/ldap/v3 v3.4.6 h1:ert95MdbiG7aWo/oPYp9btL3KJlMPKnP58r09rI8T+A= github.com/go-ldap/ldap/v3 v3.4.6/go.mod h1:IGMQANNtxpsOzj7uUAMjpGBaOVTC4DYyIy8VsTdxmtc= github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM= github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk= github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= github.com/richardlehane/msoleps v1.0.3 h1:aznSZzrwYRl3rLKRT3gUk9am7T/mLNSnJINvN0AQoVM= github.com/richardlehane/msoleps v1.0.3/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/xuri/efp v0.0.0-20231025114914-d1ff6096ae53 h1:Chd9DkqERQQuHpXjR/HSV1jLZA6uaoiwwH3vSuF3IW0= github.com/xuri/efp v0.0.0-20231025114914-d1ff6096ae53/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI= github.com/xuri/excelize/v2 v2.8.1 h1:pZLMEwK8ep+CLIUWpWmvW8IWE/yxqG0I1xcN6cVMGuQ= github.com/xuri/excelize/v2 v2.8.1/go.mod h1:oli1E4C3Pa5RXg1TBXn4ENCXDV5JUMlBluUhG7c+CEE= github.com/xuri/nfp v0.0.0-20230919160717-d98342af3f05 h1:qhbILQo1K3mphbwKh1vNm4oGezE1eF9fQWmNiIpSfI4= github.com/xuri/nfp v0.0.0-20230919160717-d98342af3f05/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck= golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: powershell/ExtractBitlockerKeys.ps1 ================================================ # File name : ExtractBitLockerKeys.ps1 # Author : Podalirius (@podalirius_) # Date created : 21 September 2023 Param ( [parameter(Mandatory=$true)][string]$dcip = $null, [parameter(Mandatory=$false,ParameterSetName="Credentials")][System.Management.Automation.PSCredential]$Credentials, [parameter(Mandatory=$false,ParameterSetName="Credentials")][Switch]$UseCredentials, [parameter(Mandatory=$false)][string]$LogFile = $null, [parameter(Mandatory=$false)][switch]$Quiet, [parameter(Mandatory=$false)][string]$ExportToCSV = $null, [parameter(Mandatory=$false)][string]$ExportToJSON = $null, [parameter(Mandatory=$false)][int]$PageSize = 5000, [parameter(Mandatory=$false)][string]$SearchBase = $null, [parameter(Mandatory=$false)][switch]$LDAPS, [parameter(Mandatory=$false)][switch]$Help ) If ($Help) { Write-Host "[+]========================================================" Write-Host "[+] Powershell ExtractBitLockerKeys v1.3 @podalirius_ " Write-Host "[+]========================================================" Write-Host "" Write-Host "Required arguments:" Write-Host " -dcip : LDAP host to target, most likely the domain controller." Write-Host "" Write-Host "Optional arguments:" Write-Host " -Help : Displays this help message" Write-Host " -Quiet : Do not print keys, only export them." Write-Host " -UseCredentials : Flag for asking for credentials to authentication" Write-Host " -Credentials : Providing PSCredentialObject for authentication" Write-Host " -PageSize : Sets the LDAP page size to use in queries (default: 5000)." Write-Host " -LDAPS : Use LDAPS instead of LDAP." Write-Host " -LogFile : Log file to save output to." Write-Host " -ExportToCSV : Export Bitlocker Keys in a CSV file." Write-Host " -ExportToJSON : Export Bitlocker Keys in a JSON file." exit 0 } If ($LogFile.Length -ne 0) { # Init log file $Stream = [System.IO.StreamWriter]::new($LogFile) $Stream.Close() } if($UseCredentials -and ([string]::IsNullOrEmpty($Credentials))){ $Credentials = Get-Credential } Function Write-Logger { [CmdletBinding()] [OutputType([Nullable])] Param ( [Parameter(Mandatory=$true)] $Logfile, [Parameter(Mandatory=$true)] $Message ) Begin { Write-Host $Message If ($LogFile.Length -ne 0) { $Stream = [System.IO.StreamWriter]::new($LogFile, $true) $Stream.WriteLine($Message) $Stream.Close() } } } Function Get-ComputerNameFromLDAPDN { [CmdletBinding()] [OutputType([Nullable])] param ([string]$ldapDN) Begin { $ldapDNParts = $ldapDN -split ',' if ($ldapDNParts[1] -match '^CN=([^,]+)$') { return $matches[1] } else { return "" } } } Function Get-DomainFromLDAPDN { [CmdletBinding()] [OutputType([Nullable])] param ([string]$ldapDN) Begin { $domain = "" [System.Collections.ArrayList]$ldapDNParts = @(); foreach ($part in ($ldapDN -split ',')) { $ldapDNParts.Add($part) | Out-Null } $ldapDNParts.Reverse() | Out-Null foreach ($part in $ldapDNParts) { if ($part -match '^DC=([^,]+)$') { $domain = $matches[1] + "." + $domain } else { # Check if the domain ends with a period if ($domain.EndsWith('.')) { # Remove the trailing period $domain = $domain.TrimEnd('.') } return $domain } } return $domain } } Function Get-VolumeGuidFromLDAPDN { [CmdletBinding()] [OutputType([Nullable])] param ([string]$ldapDN) Begin { $ldapDNParts = $ldapDN -split '/' $ldapDNParts = $ldapDNParts[3] -split ',' if ($ldapDNParts[0] -match '^CN=([^,]+){([^,]+)}$') { return $matches[2] } else { return "" } } } Function Get-CreatedAtFromLDAPDN { [CmdletBinding()] [OutputType([Nullable])] param ([string]$ldapDN) Begin { $ldapDNParts = $ldapDN -split '/' $ldapDNParts = $ldapDNParts[3] -split ',' if ($ldapDNParts[0] -match '^CN=([^,]+)$') { $createdAt = ($matches[1] -split '{') return $createdAt[0] } else { return "" } } } Function Invoke-LDAPQuery { [CmdletBinding()] [OutputType([Nullable])] Param ( [Parameter(Mandatory=$true)] $connectionString, [parameter(Mandatory=$false,ParameterSetName="Credentials")][System.Management.Automation.PSCredential] $Credentials, [Parameter(Mandatory=$false)] $PageSize ) Begin { $rootDSE = New-Object System.DirectoryServices.DirectoryEntry("{0}/RootDSE" -f $connectionString); $defaultNamingContext = $rootDSE.Properties["defaultNamingContext"].ToString(); Write-Logger -Logfile $Logfile -Message "[+] Authentication successful!"; Write-Logger -Logfile $Logfile -Message "[+] Targeting defaultNamingContext: $defaultNamingContext"; $ldapSearcher = New-Object System.DirectoryServices.DirectorySearcher if ($Credentials.UserName) { # Connect to Domain with credentials Write-Logger -Logfile $Logfile -Message ("[+] Connecting to {0}/{1} with specified account" -f $connectionString, $defaultNamingContext) $ldapSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry(("{0}/{1}" -f $connectionString, $defaultNamingContext), $Credentials.UserName, $($Credentials.Password | ConvertFrom-Securestring -AsPlaintext)) } else { # Connect to Domain with current session Write-Logger -Logfile $Logfile -Message ("[+] Connecting to {0}/{1} using current session" -f $connectionString, $defaultNamingContext) $ldapSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry(("{0}/{1}" -f $connectionString, $defaultNamingContext)) } $ldapSearcher.SearchScope = "Subtree" if ($PageSize) { $ldapSearcher.PageSize = $PageSize } else { Write-Logger -Logfile $Logfile -Message "[+] Setting PageSize to $PageSize"; $ldapSearcher.PageSize = 5000 } Write-Logger -Logfile $Logfile -Message "[+] Extracting BitLocker recovery keys ..."; $ldapSearcher.Filter = "(objectClass=msFVE-RecoveryInformation)" $ldapSearcher.PropertiesToLoad.Add("msFVE-KeyPackage") | Out-Null ; # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-keypackage $ldapSearcher.PropertiesToLoad.Add("msFVE-RecoveryGuid") | Out-Null ; # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoveryguid $ldapSearcher.PropertiesToLoad.Add("msFVE-RecoveryPassword") | Out-Null ; # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoverypassword $ldapSearcher.PropertiesToLoad.Add("msFVE-VolumeGuid") | Out-Null ; # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-volumeguid $results = [ordered]@{}; Foreach ($item in $ldapSearcher.FindAll()) { if (!($results.Keys -contains $item.Path)) { $results[$item.Path] = $item.Properties; } else { Write-Logger -Logfile $Logfile -Message "[debug] key already exists: $key (this shouldn't be possible)" } } $bitlocker_keys = Foreach ($distinguishedName in $results.Keys) { Foreach ($recoveryKey in $results[$distinguishedName]["msFVE-RecoveryPassword"]) { $domainName = (Get-DomainFromLDAPDN $distinguishedName) $createdAt = (Get-CreatedAtFromLDAPDN $distinguishedName) $volumeGuid = (Get-VolumeGuidFromLDAPDN $distinguishedName) $computerName = (Get-ComputerNameFromLDAPDN $distinguishedName) [PSCustomObject]@{ domainName = $domainName computerName = $computerName recoveryKey = $recoveryKey volumeGuid = $volumeGuid createdAt = $createdAt distinguishedName = $distinguishedName } } } return $bitlocker_keys } } #=============================================================================== Write-Logger -Logfile $Logfile -Message "[+]========================================================" Write-Logger -Logfile $Logfile -Message "[+] Powershell ExtractBitLockerKeys v1.3 @podalirius_ " Write-Logger -Logfile $Logfile -Message "[+]========================================================" Write-Logger -Logfile $Logfile -Message "" # Handle LDAPS connection $connectionString = "LDAP://{0}:{1}"; If ($LDAPS) { $connectionString = ($connectionString -f $dcip, "636"); } else { $connectionString = ($connectionString -f $dcip, "389"); } Write-Verbose "Using connectionString: $connectionString" # Connect to LDAP try { $bitlocker_keys = Invoke-LDAPQuery -connectionString $connectionString -Credentials $Credentials -PageSize $PageSize If (!($Quiet)) { Foreach ($entry in $bitlocker_keys) { $domainName = $entry.domainName.PadRight(20," ") $computerName = $entry.computerName.PadRight(20," ") $recoveryKey = $entry.recoveryKey.PadRight(20," ") $createdAt = $entry.createdAt Write-Logger -Logfile $Logfile -Message ("| {0} | {1} | {2} | {3} " -f $domainName, $computerName, $recoveryKey, $createdAt) } } Write-Logger -Logfile $Logfile -Message ("[>] Extracted {0} BitLocker recovery keys!" -f $bitlocker_keys.Length) If ($ExportToCSV) { Write-Logger -Logfile $Logfile -Message "[>] Exporting Bitlocker recovery keys in CSV in $ExportToCSV ..." $bitlocker_keys | Export-CSV -Path $ExportToCSV -NoTypeInformation } If ($ExportToJSON) { Write-Logger -Logfile $Logfile -Message "[>] Exporting Bitlocker recovery keys in JSON in $ExportToJSON ..." $bitlocker_keys | ConvertTo-Json -Depth 100 -Compress | Out-File -FilePath $ExportToJSON } } catch { Write-Verbose $_.Exception Write-Logger -Logfile $Logfile -Message -Logfile $Logfile -Message ("[!] (0x{0:X8}) {1}" -f $_.Exception.HResult, $_.Exception.InnerException.Message) exit -1 } ================================================ FILE: python/ExtractBitlockerKeys.py ================================================ #!/usr/bin/env python3 # -*- coding: utf-8 -*- # File name : ExtractBitlockerKeys.py # Author : Podalirius (@podalirius_) # Date created : 19 Sep 2023 import argparse from sectools.windows.ldap.ldap import raw_ldap_query, init_ldap_session from sectools.windows.crypto import nt_hash, parse_lm_nt_hashes import os import sys import sqlite3 import json import xlsxwriter import re VERSION = "1.3" def export_json(options, results): print("[>] Exporting results to %s ... " % options.export_json, end="") sys.stdout.flush() basepath = os.path.dirname(options.export_json) filename = os.path.basename(options.export_json) if basepath not in [".", ""]: if not os.path.exists(basepath): os.makedirs(basepath) path_to_file = basepath + os.path.sep + filename else: path_to_file = filename f = open(path_to_file, "w") f.write(json.dumps(results, indent=4) + "\n") f.close() print("done.") def export_xlsx(options, results): print("[>] Exporting results to %s ... " % options.export_xlsx, end="") sys.stdout.flush() basepath = os.path.dirname(options.export_xlsx) filename = os.path.basename(options.export_xlsx) if basepath not in [".", ""]: if not os.path.exists(basepath): os.makedirs(basepath) path_to_file = basepath + os.path.sep + filename else: path_to_file = filename workbook = xlsxwriter.Workbook(path_to_file) worksheet = workbook.add_worksheet() header_format = workbook.add_format({'bold': 1}) header_fields = ["Computer FQDN", "Domain", "Recovery Key", "Volume GUID", "Created At", "Organizational Units"] for k in range(len(header_fields)): worksheet.set_column(k, k + 1, len(header_fields[k]) + 3) worksheet.set_row(0, 20, header_format) worksheet.write_row(0, 0, header_fields) row_id = 1 for computerfqdn in results.keys(): data = [ computerfqdn, results[computerfqdn]["domain"], results[computerfqdn]["recoveryKey"], results[computerfqdn]["volumeGuid"], results[computerfqdn]["createdAt"], results[computerfqdn]["organizationalUnits"], ] worksheet.write_row(row_id, 0, data) row_id += 1 worksheet.autofilter(0, 0, row_id, len(header_fields) - 1) workbook.close() print("done.") def export_sqlite(options, results): print("[>] Exporting results to %s ... " % options.export_sqlite, end="") sys.stdout.flush() basepath = os.path.dirname(options.export_sqlite) filename = os.path.basename(options.export_sqlite) if basepath not in [".", ""]: if not os.path.exists(basepath): os.makedirs(basepath) path_to_file = basepath + os.path.sep + filename else: path_to_file = filename conn = sqlite3.connect(path_to_file) cursor = conn.cursor() 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));") for computerfqdn in results.keys(): cursor.execute("INSERT INTO shares VALUES (?, ?, ?, ?, ?, ?)", ( computerfqdn, results[computerfqdn][0]["domain"], results[computerfqdn][0]["recoveryKey"], results[computerfqdn][0]["volumeGuid"], results[computerfqdn][0]["createdAt"], results[computerfqdn][0]["organizationalUnits"], ) ) conn.commit() conn.close() print("done.") def get_domain_from_distinguished_name(distinguishedName): domain = None if "dc=" in distinguishedName.lower(): distinguishedName = distinguishedName.lower().split(',')[::-1] while distinguishedName[0].startswith("dc="): if domain is None: domain = distinguishedName[0].split('=',1)[1] else: domain = distinguishedName[0].split('=', 1)[1] + "." + domain distinguishedName = distinguishedName[1:] return domain def get_ou_path_from_distinguished_name(distinguishedName): ou_path = None if "ou=" in distinguishedName.lower(): distinguishedName = distinguishedName.lower().split(',')[::-1] # Skip domain while distinguishedName[0].startswith("dc="): distinguishedName = distinguishedName[1:] while distinguishedName[0].startswith("ou="): if ou_path is None: ou_path = distinguishedName[0].split('=',1)[1] else: ou_path = ou_path + " --> " + distinguishedName[0].split('=',1)[1] distinguishedName = distinguishedName[1:] return ou_path else: return ou_path def parse_fve(distinguishedName, bitlocker_keys): entry = { "distinguishedName": distinguishedName, "domain": get_domain_from_distinguished_name(distinguishedName), "organizationalUnits": get_ou_path_from_distinguished_name(distinguishedName), "createdAt": None, "volumeGuid": None } # Parse CN of key 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) if matched is not None: _, created_at, guid = matched.groups() entry["createdAt"] = created_at entry["volumeGuid"] = guid.strip('{}').lower() # Parse computer name entry["computerName"] = None if ',' in distinguishedName: if distinguishedName.split(',')[1].upper().startswith("CN="): entry["computerName"] = distinguishedName.split(',')[1].split('=',1)[1] # Add recovery key entry["recoveryKey"] = bitlocker_keys["msFVE-RecoveryPassword"] return entry def parseArgs(): print("ExtractBitlockerKeys.py v%s - by Remi GASCOU (Podalirius)\n" % VERSION) parser = argparse.ArgumentParser(description="") parser.add_argument("-v", "--verbose", default=False, action="store_true", help='Verbose mode. (default: False)') parser.add_argument("-q", "--quiet", dest="quiet", action="store_true", default=False, help="Show no information at all.") parser.add_argument("-t", "--threads", dest="threads", action="store", type=int, default=4, required=False, help="Number of threads (default: 4).") output = parser.add_argument_group('Output files') output.add_argument("--export-xlsx", dest="export_xlsx", type=str, default=None, required=False, help="Output XLSX file to store the results in.") output.add_argument("--export-json", dest="export_json", type=str, default=None, required=False, help="Output JSON file to store the results in.") output.add_argument("--export-sqlite", dest="export_sqlite", type=str, default=None, required=False, help="Output SQLITE3 file to store the results in.") authconn = parser.add_argument_group('Authentication & connection') 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') authconn.add_argument('--kdcHost', dest="kdcHost", action='store', metavar="FQDN KDC", help='FQDN of KDC for Kerberos.') authconn.add_argument("-d", "--domain", dest="auth_domain", metavar="DOMAIN", action="store", default="", help="(FQDN) domain to authenticate to") authconn.add_argument("-u", "--user", dest="auth_username", metavar="USER", action="store", default="", help="user to authenticate with") secret = parser.add_argument_group("Credentials") cred = secret.add_mutually_exclusive_group() cred.add_argument("--no-pass", default=False, action="store_true", help="Don't ask for password (useful for -k)") cred.add_argument("-p", "--password", dest="auth_password", metavar="PASSWORD", action="store", default=None, help="Password to authenticate with") cred.add_argument("-H", "--hashes", dest="auth_hashes", action="store", metavar="[LMHASH:]NTHASH", help='NT/LM hashes, format is LMhash:NThash') 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)') 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') return parser.parse_args() if __name__ == '__main__': options = parseArgs() if options.auth_hashes is not None: if ":" not in options.auth_hashes: options.auth_hashes = ":" + options.auth_hashes auth_lm_hash, auth_nt_hash = parse_lm_nt_hashes(options.auth_hashes) if options.auth_key is not None: options.use_kerberos = True if options.use_kerberos is True and options.kdcHost is None: print("[!] Specify KDC's Hostname of FQDN using the argument --kdcHost") exit() if not options.quiet: print("[>] Extracting BitLocker recovery keys of all computers ...") computer_keys = raw_ldap_query( auth_domain=options.auth_domain, auth_dc_ip=options.dc_ip, auth_username=options.auth_username, auth_password=options.auth_password, auth_hashes=options.auth_hashes, auth_key=options.auth_key, query="(objectClass=msFVE-RecoveryInformation)", attributes=[ "msFVE-KeyPackage", # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-keypackage "msFVE-RecoveryGuid", # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoveryguid "msFVE-RecoveryPassword", # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-recoverypassword "msFVE-VolumeGuid" # https://learn.microsoft.com/en-us/windows/win32/adschema/a-msfve-volumeguid ], use_kerberos=options.use_kerberos, kdcHost=options.kdcHost ) if not options.quiet: print("[>] Found %d BitLocker recovery keys!" % len(computer_keys.keys())) results = {} if len(computer_keys.keys()) != 0: for dn, fve_entry in computer_keys.items(): if len(fve_entry.keys()) != 0: if dn not in results.keys(): results[dn] = [] result = parse_fve(dn, fve_entry) print("| %-20s | %-20s | %s |" % (result["domain"], result["computerName"], result["recoveryKey"])) results[dn].append(result) print("[>] Extracted %d BitLocker recovery keys!" % len(computer_keys.keys())) # Export results if options.export_json is not None: export_json(options, results) if options.export_xlsx is not None: export_xlsx(options, results) if options.export_sqlite is not None: export_sqlite(options, results) else: print("[!] No computers in the domain found matching filter (objectClass=msFVE-RecoveryInformation)") print("[+] Bye Bye!") ================================================ FILE: requirements.txt ================================================ sectools>=1.5.0 xlsxwriter ldap3