commit e46b0aa8f699de4d76a847c378acc12da5c65c7a
Author: Abdullah Ansari <shehzade@users.noreply.github.com>
Date: Wed, 11 Nov 2026 23:27:02 +0100
feat: offline Active Directory ntds.dit parser and BloodHound graph reconstructor
Diffstat:
21 files changed, 3721 insertions(+), 0 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -0,0 +1,44 @@
+# Binaries and build artifacts
+bin/
+dist/
+ntds-to-bloodhound
+ntds-to-bloodhound-*
+*.exe
+*.dll
+*.so
+*.dylib
+
+# Test outputs and BloodHound JSON/ZIP files
+output/
+output-*/
+BloodHound_*.zip
+*.json.gz
+
+# Sensitive Active Directory databases and hives (CRITICAL)
+*.dit
+*.DIT
+ntds.dit
+SYSTEM
+SYSTEM.*
+SAM
+SECURITY
+*.hiv
+*.hive
+
+# Ground truth & dumped credentials
+ground-truth.txt
+expected_hashes.txt
+*.hashes
+*.ntds
+*.secrets
+
+# OS and IDE files
+.DS_Store
+.vscode/
+.idea/
+*.swp
+*~
+hashes.txt
+test-run/
+*.log
+*.json
diff --git a/LICENSE b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or exemplary damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 Abdullah Ansari
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/Makefile b/Makefile
@@ -0,0 +1,19 @@
+BINARY_NAME=ntds-to-bloodhound
+SRC=cmd/ntds-to-bloodhound/main.go
+
+.PHONY: all build build-all clean
+
+all: build
+
+build:
+ go build -ldflags="-s -w" -o $(BINARY_NAME) $(SRC)
+
+build-all:
+ GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY_NAME)-linux-amd64 $(SRC)
+ GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o $(BINARY_NAME)-linux-arm64 $(SRC)
+ GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY_NAME).exe $(SRC)
+ GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY_NAME)-darwin-amd64 $(SRC)
+ GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -o $(BINARY_NAME)-darwin-arm64 $(SRC)
+
+clean:
+ rm -f $(BINARY_NAME) $(BINARY_NAME).exe $(BINARY_NAME)-*
diff --git a/README.md b/README.md
@@ -0,0 +1,164 @@
+# ntds-to-bloodhound
+
+Offline Active Directory database (`ntds.dit`) parser and BloodHound graph reconstructor. Extracts directory objects, group memberships, domain trust topology, and binary Security Descriptors (ACEs) directly from dead-disk database pages and registry hives without LDAP queries, RSAT, or a live Domain Controller.
+
+
+
+## Table of Contents
+
+- [Why / The Gap This Fills](#why--the-gap-this-fills)
+- [Internal Pipeline](#internal-pipeline)
+- [Required Files](#required-files)
+- [Build](#build)
+- [Usage](#usage)
+ - [BloodHound Community Edition (v5)](#bloodhound-community-edition-v5)
+ - [BloodHound Legacy (v4)](#bloodhound-legacy-v4)
+ - [Export Hashes and Graph Simultaneously](#export-hashes-and-graph-simultaneously)
+- [Ingestion into BloodHound](#ingestion-into-bloodhound)
+ - [BloodHound CE (v5)](#bloodhound-ce-v5)
+ - [BloodHound Legacy (v4)](#bloodhound-legacy-v4-1)
+ - [Querying Decrypted Hashes in BloodHound](#querying-decrypted-hashes-in-bloodhound)
+- [License](#license)
+
+## Why / The Gap This Fills
+
+Active Directory collectors (SharpHound, BloodHound.py, adalanche) rely on live network enumeration over LDAP, SAMR, and SMB. In red team engagements involving volume shadow copies, offline disk images, isolated backups, or heavily monitored environments where LDAP querying is restricted or triggers behavioral alerts, running live collectors is not an option.
+
+Existing offline workflows typically run `secretsdump.py` against `ntds.dit` to dump password hashes. While effective for credential harvesting, `secretsdump.py` discards all structural Active Directory metadata: nested group memberships, OU containment hierarchies, domain trusts, and Windows NT Security Descriptors (ACLs). Reconstructing the BloodHound attack graph previously required restoring the database into an isolated Windows Server VM or chaining disparate Python and C scripts dependent on external libraries like `libesedb`.
+
+`ntds-to-bloodhound` solves this with a standalone Go binary with zero Cgo and zero external dependencies. It parses raw Extensible Storage Engine (ESE) database pages, decrypts PEK-wrapped account secrets, reconstructs the directory tree, decodes binary DACLs into BloodHound attack relationships, and outputs ready-to-ingest BloodHound CE (v5) and legacy (v4) packages.
+
+## Internal Pipeline
+
+The extraction engine operates entirely offline in memory through five stages:
+
+### SysKey & PEK Recovery
+The parser reads the offline `SYSTEM` registry hive, extracts permutation vectors across `JD`, `Skew1`, `GBG`, and `Data` under `Control\Lsa`, and reconstructs the 16-byte BootKey (SysKey). It streams `ntds.dit` to locate the domain PEK record (`ATTk590689`) and decrypts the active encryption keys using RC4 or AES.
+
+### Directory Assembly
+Using a native pure-Go ESE database reader, the engine traverses the directory `datatable` and resolves fixed, variable, and tagged columns against schema definitions. It reconstructs organizational unit containment hierarchies, resolves primary group IDs, and indexes direct and nested group memberships.
+
+### Credential Decryption
+For accounts containing encrypted password attributes (`unicodePwd`), the engine decrypts the ciphertext using the matching PEK key and strips the final RID-based DES obfuscation layer. Decrypted values are attached as `nthash` node properties on User and Computer objects.
+
+### Security Descriptor Translation
+Binary Windows NT Security Descriptors (`nTSecurityDescriptor`) are retrieved from `sd_table` and parsed into owner and discretionary access control entries. Trustee SIDs, access masks, and schema GUIDs are resolved into typed BloodHound relationship edges including `Owns`, `GenericAll`, `WriteDacl`, `WriteOwner`, `GenericWrite`, `AllExtendedRights`, `ForceChangePassword`, `AddMember`, `AddSelf`, `GetChanges`, and `GetChangesAll`.
+
+### Output Serialization
+Validated graph models are written to disk. In Community Edition mode, the output is formatted as JSON arrays and packaged into a timestamped ingestion ZIP file. In legacy mode, individual v4 JSON files are exported.
+
+## Required Files
+
+| File | Source Path | Description |
+|---|---|---|
+| `ntds.dit` | `C:\Windows\NTDS\ntds.dit` | Active Directory database |
+| `SYSTEM` | `C:\Windows\System32\config\SYSTEM` | Registry hive containing the syskey |
+
+## Build
+
+Requires Go 1.21+.
+
+```bash
+make build
+```
+
+Cross-compile for Linux, Windows, and macOS:
+
+```bash
+make build-all
+```
+
+Compiled binaries are output to the repository root (`./ntds-to-bloodhound`).
+
+## Usage
+
+```text
+Usage: ntds-to-bloodhound [OPTIONS]
+
+Required Flags:
+ -n, -ntds string
+ Path to offline ntds.dit database file
+ -s, -system string
+ Path to offline SYSTEM registry hive file
+
+Optional Flags:
+ -o, -out string
+ Output directory for generated files (default: "./output")
+ -f, -format string
+ Output format: "v4" (Legacy), "v5" (Community Edition), or "all" (default: "all")
+ -d, -dump-hashes string
+ Path to write secretsdump-compatible credential file
+ -domain string
+ Override Active Directory domain FQDN if not auto-detected
+ -zip
+ Package v5 output into BloodHound ingestion ZIP archive (default: true)
+ -v, -verbose
+ Enable detailed debug logging
+ -h, -help
+ Show help information
+```
+
+### BloodHound Community Edition (v5)
+
+Generate a timestamped ZIP archive ready for BloodHound CE:
+
+```bash
+./ntds-to-bloodhound -ntds /path/to/ntds.dit -system /path/to/SYSTEM -format v5 -out ./output
+```
+
+```text
+[*] [1/5] Extracting BootKey from SYSTEM hive: /path/to/SYSTEM
+[+] SysKey / BootKey derived: 0x429b3bce************************
+[*] [2/5] Opening ESE database: /path/to/ntds.dit
+[*] [3/5] Locating and decrypting Password Encryption Keys (PEK)...
+[+] PEK # 0 found and decrypted: d6a3bd48************************
+[*] [4/5] Reconstructing Active Directory hierarchy, group memberships, and ACLs...
+[+] Processed 15 users, 53 groups, 4 computers, 1 OUs, 1 domains
+[*] [5/5] Exporting BloodHound files (format: v5) to ./output...
+[+] BloodHound Community Edition (v5) JSON files written to ./output
+[+] BloodHound CE Ingestion Archive created: ./output/BloodHound_20261111230000.zip
+```
+
+### BloodHound Legacy (v4)
+
+Generate individual JSON files formatted for legacy BloodHound:
+
+```bash
+./ntds-to-bloodhound -ntds /path/to/ntds.dit -system /path/to/SYSTEM -format v4 -out ./output/v4
+```
+
+### Export Hashes and Graph Simultaneously
+
+Dump credentials in `secretsdump.py` format (`user:RID:LM:NT:::`) while generating the graph:
+
+```bash
+./ntds-to-bloodhound \
+ -ntds /path/to/ntds.dit \
+ -system /path/to/SYSTEM \
+ -dump-hashes ./output/hashes.txt \
+ -out ./output
+```
+
+## Ingestion into BloodHound
+
+### BloodHound CE (v5)
+
+Upload the generated `BloodHound_<timestamp>.zip` archive directly through the BloodHound Community Edition interface under **Administration** → **File Ingest**, or post the archive to the CE ingestion REST endpoint.
+
+### BloodHound Legacy (v4)
+
+Drag and drop the generated JSON files (`users.json`, `groups.json`, `computers.json`, `ous.json`, `domains.json`) into the legacy BloodHound desktop GUI window.
+
+### Querying Decrypted Hashes in BloodHound
+
+`ntds-to-bloodhound` injects decrypted NT password hashes directly into the BloodHound node properties under the `nthash` key. You can query them in the Cypher console:
+
+```cypher
+MATCH (u:User) WHERE u.nthash IS NOT NULL RETURN u.name, u.nthash
+```
+
+Or view them in the node properties panel under the **Node Info** sidebar for any User or Computer object.
+
+## License
+
+Apache License 2.0
diff --git a/cmd/ntds-to-bloodhound/main.go b/cmd/ntds-to-bloodhound/main.go
@@ -0,0 +1,322 @@
+package main
+
+import (
+ "encoding/hex"
+ "flag"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/Velocidex/ordereddict"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/acl"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/ad"
+ bhv4 "github.com/shehzade/ntds-to-bloodhound/pkg/bloodhound/v4"
+ bhv5 "github.com/shehzade/ntds-to-bloodhound/pkg/bloodhound/v5"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/crypto"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/ese"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/registry"
+)
+
+const banner = `
+======================================================================
+ ntds-to-bloodhound - Fast Offline AD NTDS.DIT to BloodHound Parser
+ Version: 1.0.0 (Pure Go | Zero Cgo | Ultra-Fast ESE Engine)
+======================================================================`
+
+func printUsage() {
+ fmt.Println(banner)
+ fmt.Print(`
+USAGE:
+ ntds-to-bloodhound [OPTIONS]
+
+REQUIRED FLAGS:
+ -n, --ntds PATH Path to the offline ntds.dit database file
+ -s, --system PATH Path to the offline SYSTEM registry hive file
+
+OPTIONAL FLAGS:
+ -o, --out PATH Output directory for generated BloodHound files (default: "./output")
+ -f, --format FORMAT Output format: "v4" (Legacy), "v5" (Community Edition), or "all" (default: "all")
+ -d, --dump-hashes PATH Optional path to write a secretsdump-compatible credential file
+ --domain FQDN Override Active Directory domain FQDN if not auto-detected
+ --zip Package v5 output into standard BloodHound ingestion ZIP archive (default: true)
+ -v, --verbose Enable detailed debug logging and object parsing metrics
+ -h, --help Show help information
+`)
+}
+
+func main() {
+ var (
+ ntdsPath string
+ sysPath string
+ outDir string
+ format string
+ dumpHashesPath string
+ domainOverride string
+ zipPackage bool
+ verbose bool
+ help bool
+ )
+
+ flag.StringVar(&ntdsPath, "ntds", "", "Path to the offline ntds.dit database file")
+ flag.StringVar(&ntdsPath, "n", "", "Path to the offline ntds.dit database file (shorthand)")
+
+ flag.StringVar(&sysPath, "system", "", "Path to the offline SYSTEM registry hive file")
+ flag.StringVar(&sysPath, "s", "", "Path to the offline SYSTEM registry hive file (shorthand)")
+
+ flag.StringVar(&outDir, "out", "./output", "Output directory for generated BloodHound files")
+ flag.StringVar(&outDir, "o", "./output", "Output directory (shorthand)")
+
+ flag.StringVar(&format, "format", "all", "Output format: v4, v5, or all")
+ flag.StringVar(&format, "f", "all", "Output format (shorthand)")
+
+ flag.StringVar(&dumpHashesPath, "dump-hashes", "", "Path to write secretsdump-compatible credential file")
+ flag.StringVar(&dumpHashesPath, "d", "", "Path to write credential file (shorthand)")
+
+ flag.StringVar(&domainOverride, "domain", "", "Override Active Directory domain FQDN")
+ flag.BoolVar(&zipPackage, "zip", true, "Package v5 output into BloodHound ZIP archive")
+
+ flag.BoolVar(&verbose, "verbose", false, "Enable verbose logging")
+ flag.BoolVar(&verbose, "v", false, "Enable verbose logging (shorthand)")
+
+ flag.BoolVar(&help, "help", false, "Show help information")
+ flag.BoolVar(&help, "h", false, "Show help information (shorthand)")
+
+ flag.Parse()
+
+ if help || ntdsPath == "" || sysPath == "" {
+ printUsage()
+ if help {
+ os.Exit(0)
+ }
+ os.Exit(1)
+ }
+
+ formatLower := strings.ToLower(strings.TrimSpace(format))
+ if formatLower != "v4" && formatLower != "v5" && formatLower != "all" {
+ fmt.Printf("[-] Error: unsupported format %q (must be \"v4\", \"v5\", or \"all\")\n", format)
+ os.Exit(1)
+ }
+
+ startTime := time.Now()
+ fmt.Println(banner)
+ fmt.Println()
+
+ if _, err := os.Stat(ntdsPath); os.IsNotExist(err) {
+ fmt.Printf("[-] Error: ntds.dit file not found: %s\n", ntdsPath)
+ os.Exit(1)
+ }
+ if _, err := os.Stat(sysPath); os.IsNotExist(err) {
+ fmt.Printf("[-] Error: SYSTEM hive file not found: %s\n", sysPath)
+ os.Exit(1)
+ }
+
+ fmt.Printf("[*] [1/5] Extracting BootKey from SYSTEM hive: %s\n", sysPath)
+ bootKey, err := registry.ExtractBootKey(sysPath)
+ if err != nil {
+ fmt.Printf("[-] Failed to extract BootKey: %v\n", err)
+ os.Exit(1)
+ }
+ bootKeyHex := hex.EncodeToString(bootKey)
+ fmt.Printf("[+] SysKey / BootKey derived: 0x%s\n", bootKeyHex)
+
+ fmt.Printf("[*] [2/5] Opening ESE database: %s\n", ntdsPath)
+ db, err := ese.OpenDB(ntdsPath)
+ if err != nil {
+ fmt.Printf("[-] Failed to open ESE database: %v\n", err)
+ os.Exit(1)
+ }
+ defer db.Close()
+
+ fmt.Println("[*] [3/5] Locating and decrypting Password Encryption Keys (PEK)...")
+ cryptoEngine := crypto.NewCryptoEngine(bootKey)
+
+ pekFound := false
+ err = db.StreamTable("datatable", func(row *ordereddict.Dict) error {
+ if pekFound {
+ return nil
+ }
+ if val, ok := row.Get("ATTk590689"); ok && val != nil {
+ if rawHex, ok := val.(string); ok && len(rawHex) > 0 {
+ if b, err := hex.DecodeString(rawHex); err == nil {
+ if err := cryptoEngine.ParsePekList(b); err == nil {
+ pekFound = true
+ }
+ }
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ fmt.Printf("[-] Error scanning for pekList: %v\n", err)
+ os.Exit(1)
+ }
+ if !pekFound || len(cryptoEngine.PEKList) == 0 {
+ fmt.Println("[-] Warning: No valid pekList found or decrypted! Account hashes will not be decrypted.")
+ } else {
+ for keyID, keyBytes := range cryptoEngine.PEKList {
+ pekHex := hex.EncodeToString(keyBytes)
+ fmt.Printf("[+] PEK # %d found and decrypted: %s\n", keyID, pekHex)
+ }
+ }
+
+ if verbose {
+ fmt.Println("[*] Initializing Security Descriptor cache from sd_table...")
+ }
+ secEngine, err := acl.NewSecurityEngine(db)
+ if err != nil {
+ fmt.Printf("[-] Failed to load security descriptors: %v\n", err)
+ os.Exit(1)
+ }
+ if verbose {
+ fmt.Printf("[+] Cached %d binary security descriptors\n", secEngine.Count())
+ }
+
+ fmt.Println("[*] [4/5] Reconstructing Active Directory hierarchy, group memberships, and ACLs...")
+ assembler := ad.NewAssembler(db, cryptoEngine, secEngine, domainOverride)
+ if err := assembler.Assemble(); err != nil {
+ fmt.Printf("[-] Assembly failed: %v\n", err)
+ os.Exit(1)
+ }
+ snap := assembler.Snapshot
+
+ userCount := len(snap.Users)
+ groupCount := len(snap.Groups)
+ computerCount := len(snap.Computers)
+ ouCount := len(snap.OUs)
+ domainCount := len(snap.Domains)
+
+ var credsDecrypted int
+ for _, u := range snap.Users {
+ if u.NTHash != "" {
+ credsDecrypted++
+ }
+ }
+
+ var totalMemberships int
+ for _, g := range snap.Groups {
+ totalMemberships += len(g.Members)
+ }
+
+ var totalAces int
+ for _, u := range snap.Users {
+ totalAces += len(u.Aces)
+ }
+ for _, g := range snap.Groups {
+ totalAces += len(g.Aces)
+ }
+ for _, c := range snap.Computers {
+ totalAces += len(c.Aces)
+ }
+ for _, d := range snap.Domains {
+ totalAces += len(d.Aces)
+ }
+ for _, o := range snap.OUs {
+ totalAces += len(o.Aces)
+ }
+
+ if dumpHashesPath != "" {
+ fmt.Printf("[*] Writing decrypted credentials to %s...\n", dumpHashesPath)
+ if dir := filepath.Dir(dumpHashesPath); dir != "" {
+ _ = os.MkdirAll(dir, 0755)
+ }
+ var sb strings.Builder
+ for _, u := range snap.Users {
+ sam := u.Properties["samaccountname"].(string)
+ rid := 0
+ parts := strings.Split(u.ObjectIdentifier, "-")
+ if len(parts) > 0 {
+ fmt.Sscanf(parts[len(parts)-1], "%d", &rid)
+ }
+ nthash := u.NTHash
+ if nthash == "" {
+ nthash = crypto.EmptyNTHash
+ }
+ sb.WriteString(fmt.Sprintf("%s:%d:%s:%s:::\n",
+ sam, rid, crypto.EmptyLMHash, nthash))
+ }
+ for _, c := range snap.Computers {
+ sam := c.Properties["samaccountname"].(string)
+ rid := 0
+ parts := strings.Split(c.ObjectIdentifier, "-")
+ if len(parts) > 0 {
+ fmt.Sscanf(parts[len(parts)-1], "%d", &rid)
+ }
+ nthash := c.NTHash
+ if nthash == "" {
+ nthash = crypto.EmptyNTHash
+ }
+ sb.WriteString(fmt.Sprintf("%s:%d:%s:%s:::\n",
+ sam, rid, crypto.EmptyLMHash, nthash))
+ }
+ totalCreds := len(snap.Users) + len(snap.Computers)
+ if err := os.WriteFile(dumpHashesPath, []byte(sb.String()), 0600); err != nil {
+ fmt.Printf("[-] Failed to write credentials file: %v\n", err)
+ } else {
+ fmt.Printf("[+] Successfully wrote %d credentials to %s\n", totalCreds, dumpHashesPath)
+ }
+ }
+
+ fmt.Printf("[*] [5/5] Exporting BloodHound files (format: %s) to %s...\n", formatLower, outDir)
+
+ var createdFiles []string
+
+ if formatLower == "v4" || formatLower == "all" {
+ targetV4Dir := outDir
+ if formatLower == "all" {
+ targetV4Dir = filepath.Join(outDir, "v4")
+ }
+ v4Writer := bhv4.NewWriter(targetV4Dir)
+ if err := v4Writer.WriteSnapshot(snap); err != nil {
+ fmt.Printf("[-] Error writing v4 files: %v\n", err)
+ os.Exit(1)
+ }
+ createdFiles = append(createdFiles, filepath.Join(targetV4Dir, "{users,groups,computers,domains,ous}.json"))
+ fmt.Printf("[+] BloodHound Legacy (v4) JSON files written to %s\n", targetV4Dir)
+ }
+
+ if formatLower == "v5" || formatLower == "all" {
+ targetV5Dir := outDir
+ if formatLower == "all" {
+ targetV5Dir = filepath.Join(outDir, "v5")
+ }
+ v5Writer := bhv5.NewWriter(targetV5Dir)
+ if err := v5Writer.WriteSnapshot(snap); err != nil {
+ fmt.Printf("[-] Error writing v5 files: %v\n", err)
+ os.Exit(1)
+ }
+ createdFiles = append(createdFiles, filepath.Join(targetV5Dir, "{users,groups,computers,domains,ous}.json"))
+ fmt.Printf("[+] BloodHound Community Edition (v5) JSON files written to %s\n", targetV5Dir)
+
+ if zipPackage {
+ zipPath := filepath.Join(targetV5Dir, bhv5.GenerateZipFilename())
+ if err := bhv5.CreateZipArchive(snap, zipPath); err != nil {
+ fmt.Printf("[-] Error creating ZIP archive: %v\n", err)
+ } else {
+ createdFiles = append(createdFiles, zipPath)
+ fmt.Printf("[+] BloodHound CE Ingestion Archive created: %s\n", zipPath)
+ }
+ }
+ }
+
+ elapsed := time.Since(startTime)
+
+ fmt.Println()
+ fmt.Println("======================================================================")
+ fmt.Println(" EXTRACTION METRICS & SUMMARY ")
+ fmt.Println("======================================================================")
+ fmt.Printf(" Target Domain Name : %s\n", snap.DomainName)
+ fmt.Printf(" Target Domain SID : %s\n", snap.DomainSID)
+ fmt.Printf(" Total Users Extracted : %d\n", userCount)
+ fmt.Printf(" Total Groups Extracted : %d\n", groupCount)
+ fmt.Printf(" Total Computers Extracted: %d\n", computerCount)
+ fmt.Printf(" Total OUs Extracted : %d\n", ouCount)
+ fmt.Printf(" Domains Extracted : %d\n", domainCount)
+ fmt.Printf(" Decrypted NT Hashes : %d / %d\n", credsDecrypted, userCount)
+ fmt.Printf(" Group Memberships Linked : %d\n", totalMemberships)
+ fmt.Printf(" BloodHound Edges (ACEs) : %d\n", totalAces)
+ fmt.Printf(" Total Elapsed Processing : %s\n", elapsed)
+ fmt.Println("======================================================================")
+ fmt.Println("[+] Done! BloodHound collection complete.")
+}
diff --git a/docs/images/ntds-to-bloodhound-demo.png b/docs/images/ntds-to-bloodhound-demo.png
Binary files differ.
diff --git a/go.mod b/go.mod
@@ -0,0 +1,15 @@
+module github.com/shehzade/ntds-to-bloodhound
+
+go 1.21
+
+require (
+ github.com/Velocidex/ordereddict v0.0.0-20261028034010-6857b08b4dab
+ www.velocidex.com/golang/go-ese v0.2.0
+ www.velocidex.com/golang/regparser v0.0.0-20250203141505-31e704a67ef7
+)
+
+require (
+ github.com/Velocidex/json v0.0.0-20220224052537-92f3c0326e5a // indirect
+ github.com/Velocidex/yaml/v2 v2.2.8 // indirect
+ github.com/davecgh/go-spew v1.1.1 // indirect
+)
diff --git a/go.sum b/go.sum
@@ -0,0 +1,53 @@
+github.com/Velocidex/json v0.0.0-20220224052537-92f3c0326e5a h1:AeXPUzhU0yhID/v5JJEIkjaE85ASe+Vh4Kuv1RSLL+4=
+github.com/Velocidex/json v0.0.0-20220224052537-92f3c0326e5a/go.mod h1:ukJBuruT9b24pdgZwWDvOaCYHeS03B7oQPCUWh25bwM=
+github.com/Velocidex/ordereddict v0.0.0-20220107075049-3dbe58412844/go.mod h1:Y5Tfx5SKGOzkulpqfonrdILSPIuNg+GqKE/DhVJgnpg=
+github.com/Velocidex/ordereddict v0.0.0-20261028034010-6857b08b4dab h1:IhCSLiVMsRmBuGsjsgUW5PelPrYJxHztRIZ3teL6efc=
+github.com/Velocidex/ordereddict v0.0.0-20261028034010-6857b08b4dab/go.mod h1:+MqO5UMBemyFSm+yRXslbpFTwPUDhFHUf7HPV92twg4=
+github.com/Velocidex/yaml/v2 v2.2.8 h1:GUrSy4SBJ6RjGt43k6MeBKtw2z/27gh4A3hfFmFY3No=
+github.com/Velocidex/yaml/v2 v2.2.8/go.mod h1:PlXIg/Pxmoja48C1vMHo7C5pauAZvLq/UEPOQ3DsjS4=
+github.com/alecthomas/assert v1.0.0/go.mod h1:va/d2JC+M7F6s+80kl/R3G7FUiW6JzUO+hPhLyJ36ZY=
+github.com/alecthomas/colour v0.1.0/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0=
+github.com/alecthomas/repr v0.0.0-20210801044451-80ca428c5142/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8=
+github.com/alecthomas/repr v0.1.1 h1:87P60cSmareLAxMc4Hro0r2RBY4ROm0dYwkJNpS4pPs=
+github.com/alecthomas/repr v0.1.1/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
+github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
+github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
+github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
+github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
+github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/sebdah/goldie v1.0.0/go.mod h1:jXP4hmWywNEwZzhMuv2ccnqTSFpuq8iyQhtQdkkZBH4=
+github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
+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/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+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/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+www.velocidex.com/golang/go-ese v0.2.0 h1:8/hzEMupfqEF0oMi1/EzsMN1xLN0GBFcB3GqxqRnb9s=
+www.velocidex.com/golang/go-ese v0.2.0/go.mod h1:6fC9T6UGLbM7icuA0ugomU5HbFC5XA5I30zlWtZT8YE=
+www.velocidex.com/golang/regparser v0.0.0-20250203141505-31e704a67ef7 h1:BMX/37sYwX+8JhHt+YNbPfbx7dXG1w1L1mXonNBtjt0=
+www.velocidex.com/golang/regparser v0.0.0-20250203141505-31e704a67ef7/go.mod h1:pxSECT5mWM3goJ4sxB4HCJNKnKqiAlpyT8XnvBwkLGU=
diff --git a/pkg/acl/engine.go b/pkg/acl/engine.go
@@ -0,0 +1,134 @@
+package acl
+
+import (
+ "encoding/binary"
+ "encoding/hex"
+
+ "github.com/Velocidex/ordereddict"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/ese"
+)
+
+type cacheKey struct {
+ sdID uint64
+ objType string
+ hasLAPS bool
+}
+
+type cachedSD struct {
+ aces []Ace
+ isProtected bool
+}
+
+type SecurityEngine struct {
+ RawSDs map[uint64][]byte
+ AclCache map[cacheKey]cachedSD
+ LapsGUIDs map[string]bool
+}
+
+func NewSecurityEngine(db *ese.DB) (*SecurityEngine, error) {
+ engine := &SecurityEngine{
+ RawSDs: make(map[uint64][]byte),
+ AclCache: make(map[cacheKey]cachedSD),
+ LapsGUIDs: make(map[string]bool),
+ }
+
+ aliases := make(map[uint64]uint64)
+
+ err := db.StreamTable("sd_table", func(row *ordereddict.Dict) error {
+ idVal, ok := row.Get("sd_id")
+ if !ok || idVal == nil {
+ return nil
+ }
+
+ var id uint64
+ switch v := idVal.(type) {
+ case uint64:
+ id = v
+ case int64:
+ id = uint64(v)
+ case uint32:
+ id = uint64(v)
+ case int32:
+ id = uint64(v)
+ case int:
+ id = uint64(v)
+ }
+
+ val, _ := row.Get("sd_value")
+ hexStr, ok := val.(string)
+ if !ok || len(hexStr) == 0 {
+ return nil
+ }
+
+ b, err := hex.DecodeString(hexStr)
+ if err != nil {
+ return nil
+ }
+
+ if len(b) >= 20 {
+ engine.RawSDs[id] = b
+ } else if len(b) == 4 {
+ targetID := uint64(binary.LittleEndian.Uint32(b))
+ aliases[id] = targetID
+ }
+
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ for srcID := range aliases {
+ curr := srcID
+ visited := make(map[uint64]bool)
+ for {
+ if visited[curr] {
+ break
+ }
+ visited[curr] = true
+ if target, ok := aliases[curr]; ok {
+ curr = target
+ } else {
+ break
+ }
+ }
+ if rawSD, exists := engine.RawSDs[curr]; exists {
+ engine.RawSDs[srcID] = rawSD
+ }
+ }
+
+ return engine, nil
+}
+
+func (e *SecurityEngine) Count() int {
+ return len(e.RawSDs)
+}
+
+func (e *SecurityEngine) GetAces(sdID uint64) []Ace {
+ aces, _ := e.GetAcesForObject(sdID, "", false)
+ return aces
+}
+
+func (e *SecurityEngine) GetAcesForObject(sdID uint64, objectType string, hasLAPS bool) ([]Ace, bool) {
+ key := cacheKey{sdID: sdID, objType: objectType, hasLAPS: hasLAPS}
+ if cached, exists := e.AclCache[key]; exists {
+ out := make([]Ace, len(cached.aces))
+ copy(out, cached.aces)
+ return out, cached.isProtected
+ }
+
+ rawSD, exists := e.RawSDs[sdID]
+ if !exists {
+ return nil, false
+ }
+
+ aces, isProtected, err := ParseSecurityDescriptorForType(rawSD, objectType, hasLAPS, e.LapsGUIDs)
+ if err != nil {
+ return nil, false
+ }
+
+ e.AclCache[key] = cachedSD{aces: aces, isProtected: isProtected}
+ out := make([]Ace, len(aces))
+ copy(out, aces)
+ return out, isProtected
+}
diff --git a/pkg/acl/sd.go b/pkg/acl/sd.go
@@ -0,0 +1,381 @@
+package acl
+
+import (
+ "encoding/binary"
+ "fmt"
+ "strings"
+
+ "github.com/shehzade/ntds-to-bloodhound/pkg/crypto"
+)
+
+type Ace struct {
+ PrincipalSID string `json:"PrincipalSID"`
+ PrincipalType string `json:"PrincipalType"`
+ RightName string `json:"RightName"`
+ IsInherited bool `json:"IsInherited"`
+}
+
+const (
+ EdgeOwns = "Owns"
+ EdgeGenericAll = "GenericAll"
+ EdgeWriteDacl = "WriteDacl"
+ EdgeWriteOwner = "WriteOwner"
+ EdgeGenericWrite = "GenericWrite"
+ EdgeAllExtendedRights = "AllExtendedRights"
+ EdgeForceChangePassword = "ForceChangePassword"
+ EdgeGetChanges = "GetChanges"
+ EdgeGetChangesAll = "GetChangesAll"
+ EdgeGetChangesInFilteredSet = "GetChangesInFilteredSet"
+ EdgeAddMember = "AddMember"
+ EdgeAddSelf = "AddSelf"
+ EdgeAddAllowedToAct = "AddAllowedToAct"
+ EdgeAddKeyCredentialLink = "AddKeyCredentialLink"
+ EdgeWriteSPN = "WriteSPN"
+ EdgeWriteAccountRestrictions = "WriteAccountRestrictions"
+ EdgeWriteGPLink = "WriteGPLink"
+ EdgeReadLAPSPassword = "ReadLAPSPassword"
+ EdgeReadGMSAPassword = "ReadGMSAPassword"
+)
+
+const (
+ GUIDAllZero = "00000000-0000-0000-0000-000000000000"
+ GUIDUserForceChangePassword = "00299570-246d-11d0-a768-00aa006e0529"
+ GUIDReplicationGetChanges = "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2"
+ GUIDReplicationGetChangesAll = "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2"
+ GUIDReplicationFiltered = "89e95b76-444d-4c62-991a-0facbeda640c"
+ GUIDGroupMemberAttr = "bf9679c0-0de6-11d0-a285-00aa003049e2"
+ GUIDMembershipPropertySet = "bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
+ GUIDAllowedToAct = "3f78c3e5-f79a-46bd-a0b8-9d18116ddc79"
+ GUIDKeyCredentialLink = "5b47d60f-6090-40b2-9f37-2a4de88f3063"
+ GUIDServicePrincipalName = "f3a64788-5306-11d1-a9c5-0000f80367c1"
+ GUIDUserAccountRestrictions = "4c164200-20c0-11d0-a768-00aa006e0529"
+ GUIDWriteGPLink = "f30e3bbe-9ff0-11d1-b603-0000f80367c1"
+
+ GUIDClassUser = "bf967aba-0de6-11d0-a285-00aa003049e2"
+ GUIDClassInetOrg = "ce206244-5827-4a86-ba1c-1c0c386c1b64"
+ GUIDClassGMSA = "7b8b558a-93a5-4af7-adca-c017e67f1057"
+ GUIDClassMSA = "febc6632-080d-422c-a779-c22712b713b0"
+ GUIDClassComputer = "bf967a86-0de6-11d0-a285-00aa003049e2"
+ GUIDClassGroup = "bf967a9c-0de6-11d0-a285-00aa003049e2"
+ GUIDClassDomain = "19195a5a-6da0-11d0-afd3-00c04fd930c9"
+ GUIDClassOU = "bf967aa5-0de6-11d0-a285-00aa003049e2"
+)
+
+func isIgnoredSID(sid string) bool {
+ return sid == "S-1-3-0" || sid == "S-1-5-18" || sid == "S-1-5-10"
+}
+
+func formatGUID(b []byte) string {
+ if len(b) < 16 {
+ return ""
+ }
+ d1 := binary.LittleEndian.Uint32(b[0:4])
+ d2 := binary.LittleEndian.Uint16(b[4:6])
+ d3 := binary.LittleEndian.Uint16(b[6:8])
+ return fmt.Sprintf("%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+ d1, d2, d3, b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15])
+}
+
+func inheritedGUIDApplies(inheritedGUID, objectType string) bool {
+ if inheritedGUID == "" || inheritedGUID == GUIDAllZero || objectType == "" {
+ return true
+ }
+ g := strings.ToLower(inheritedGUID)
+ switch strings.ToLower(objectType) {
+ case "user":
+ return g == GUIDClassUser || g == GUIDClassInetOrg || g == GUIDClassGMSA || g == GUIDClassMSA
+ case "computer":
+ return g == GUIDClassComputer || g == GUIDClassGMSA
+ case "group":
+ return g == GUIDClassGroup
+ case "domain":
+ return g == GUIDClassDomain
+ case "ou":
+ return g == GUIDClassOU
+ default:
+ return true
+ }
+}
+
+func ParseSecurityDescriptor(sdBytes []byte) ([]Ace, error) {
+ aces, _, err := ParseSecurityDescriptorForType(sdBytes, "", false, nil)
+ return aces, err
+}
+
+func ParseSecurityDescriptorForType(sdBytes []byte, objectType string, hasLAPS bool, lapsGUIDs map[string]bool) ([]Ace, bool, error) {
+ if len(sdBytes) < 20 {
+ return nil, false, nil
+ }
+
+ control := binary.LittleEndian.Uint16(sdBytes[2:4])
+ isACLProtected := (control & 0x1000) != 0
+
+ type seenKey struct {
+ sid string
+ right string
+ inherited bool
+ }
+ seen := make(map[seenKey]bool)
+ var results []Ace
+
+ addAce := func(sid, right string, inherited bool) {
+ if sid == "" || right == "" {
+ return
+ }
+ k := seenKey{sid: sid, right: right, inherited: inherited}
+ if seen[k] {
+ return
+ }
+ seen[k] = true
+ results = append(results, Ace{
+ PrincipalSID: sid,
+ PrincipalType: "Base",
+ RightName: right,
+ IsInherited: inherited,
+ })
+ }
+
+ objLower := strings.ToLower(objectType)
+
+ ownerOffset := int(binary.LittleEndian.Uint32(sdBytes[4:8]))
+ if objLower != "rbcd" && objLower != "gmsa" && ownerOffset >= 20 && ownerOffset+8 <= len(sdBytes) {
+ ownerSID, _, err := crypto.ParseBinarySID(sdBytes[ownerOffset:])
+ if err == nil && ownerSID != "" && !isIgnoredSID(ownerSID) {
+ addAce(ownerSID, EdgeOwns, false)
+ }
+ }
+
+ if control&0x0004 == 0 {
+ return results, isACLProtected, nil
+ }
+
+ daclOffset := int(binary.LittleEndian.Uint32(sdBytes[16:20]))
+ if daclOffset == 0 || daclOffset >= len(sdBytes) || daclOffset+8 > len(sdBytes) {
+ return results, isACLProtected, nil
+ }
+
+ daclBytes := sdBytes[daclOffset:]
+ aclSize := int(binary.LittleEndian.Uint16(daclBytes[2:4]))
+ aceCount := int(binary.LittleEndian.Uint16(daclBytes[4:6]))
+ if aclSize > len(daclBytes) {
+ aclSize = len(daclBytes)
+ }
+
+ offset := 8
+ for i := 0; i < aceCount && offset+4 <= aclSize; i++ {
+ aceType := daclBytes[offset]
+ aceFlags := daclBytes[offset+1]
+ aceSize := int(binary.LittleEndian.Uint16(daclBytes[offset+2 : offset+4]))
+ if aceSize <= 0 || offset+aceSize > aclSize {
+ break
+ }
+
+ isInherited := (aceFlags & 0x10) != 0
+ isInheritOnly := (aceFlags & 0x08) != 0
+
+ if isInheritOnly {
+ offset += aceSize
+ continue
+ }
+
+ if aceType == 0x00 && aceSize >= 12 {
+ mask := binary.LittleEndian.Uint32(daclBytes[offset+4 : offset+8])
+ sidBytes := daclBytes[offset+8 : offset+aceSize]
+ principalSID, _, err := crypto.ParseBinarySID(sidBytes)
+ if err == nil && principalSID != "" {
+ if objLower == "rbcd" {
+ if mask != 0 {
+ addAce(principalSID, EdgeGenericAll, isInherited)
+ }
+ } else if objLower == "gmsa" {
+ if mask&0x00000100 != 0 || mask&0x10000000 != 0 || mask&0x00020014 != 0 {
+ addAce(principalSID, EdgeReadGMSAPassword, isInherited)
+ }
+ } else if !isIgnoredSID(principalSID) {
+ for _, edge := range mapStandardMaskToEdges(mask, objLower, principalSID) {
+ addAce(principalSID, edge, isInherited)
+ }
+ }
+ }
+ } else if aceType == 0x05 && aceSize >= 12 {
+ mask := binary.LittleEndian.Uint32(daclBytes[offset+4 : offset+8])
+ objFlags := binary.LittleEndian.Uint32(daclBytes[offset+8 : offset+12])
+ sidOffset := offset + 12
+ var objectTypeGUID string
+ var inheritedTypeGUID string
+
+ if objFlags&0x00000001 != 0 {
+ if sidOffset+16 <= offset+aceSize {
+ objectTypeGUID = formatGUID(daclBytes[sidOffset : sidOffset+16])
+ sidOffset += 16
+ }
+ }
+ if objFlags&0x00000002 != 0 {
+ if sidOffset+16 <= offset+aceSize {
+ inheritedTypeGUID = formatGUID(daclBytes[sidOffset : sidOffset+16])
+ sidOffset += 16
+ }
+ }
+
+ if isInherited && (objFlags&0x00000002 != 0) && !inheritedGUIDApplies(inheritedTypeGUID, objLower) {
+ offset += aceSize
+ continue
+ }
+
+ if sidOffset < offset+aceSize {
+ sidBytes := daclBytes[sidOffset : offset+aceSize]
+ principalSID, _, err := crypto.ParseBinarySID(sidBytes)
+ if err == nil && principalSID != "" {
+ if objLower == "rbcd" {
+ if mask != 0 {
+ addAce(principalSID, EdgeGenericAll, isInherited)
+ }
+ } else if objLower == "gmsa" {
+ if mask&0x00000100 != 0 || mask&0x10000000 != 0 || mask&0x00020014 != 0 {
+ addAce(principalSID, EdgeReadGMSAPassword, isInherited)
+ }
+ } else if !isIgnoredSID(principalSID) {
+ for _, edge := range mapObjectMaskToEdges(mask, objFlags, objectTypeGUID, objLower, principalSID, hasLAPS, lapsGUIDs) {
+ addAce(principalSID, edge, isInherited)
+ }
+ }
+ }
+ }
+ }
+
+ offset += aceSize
+ }
+
+ return results, isACLProtected, nil
+}
+
+func hasGenericAll(mask uint32) bool {
+ return mask&0x10000000 != 0 || (mask&0x000F01FF == 0x000F01FF) || (mask&0x001F01FF == 0x001F01FF)
+}
+
+func hasGenericWrite(mask uint32) bool {
+ return mask&0x40000000 != 0 || (mask&0x00020028 == 0x00020028) || mask&0x00000020 != 0
+}
+
+func mapStandardMaskToEdges(mask uint32, objType, principalSID string) []string {
+ var edges []string
+
+ if hasGenericAll(mask) {
+ return []string{EdgeGenericAll}
+ }
+
+ if hasGenericWrite(mask) && objType != "domain" {
+ edges = append(edges, EdgeGenericWrite)
+ }
+ if mask&0x00080000 != 0 {
+ edges = append(edges, EdgeWriteOwner)
+ }
+ if mask&0x00040000 != 0 {
+ edges = append(edges, EdgeWriteDacl)
+ }
+ if mask&0x00000100 != 0 {
+ switch objType {
+ case "", "user", "domain":
+ edges = append(edges, EdgeAllExtendedRights)
+ case "computer":
+ if principalSID != "S-1-5-32-544" && !strings.HasSuffix(principalSID, "-512") {
+ edges = append(edges, EdgeAllExtendedRights)
+ }
+ }
+ }
+
+ return edges
+}
+
+func mapObjectMaskToEdges(mask, objFlags uint32, objectGUID, objType, principalSID string, hasLAPS bool, lapsGUIDs map[string]bool) []string {
+ var edges []string
+
+ objTypePresent := (objFlags & 0x00000001) != 0
+ guidLower := strings.ToLower(objectGUID)
+ genericApplicable := !objTypePresent || guidLower == "" || guidLower == GUIDAllZero
+
+ if genericApplicable {
+ if hasGenericAll(mask) {
+ return []string{EdgeGenericAll}
+ }
+ if hasGenericWrite(mask) {
+ edges = append(edges, EdgeGenericWrite)
+ }
+ if mask&0x00040000 != 0 {
+ edges = append(edges, EdgeWriteDacl)
+ }
+ if mask&0x00080000 != 0 {
+ edges = append(edges, EdgeWriteOwner)
+ }
+ if mask&0x00000100 != 0 {
+ switch objType {
+ case "", "user", "domain":
+ edges = append(edges, EdgeAllExtendedRights)
+ case "computer":
+ if hasLAPS {
+ edges = append(edges, EdgeAllExtendedRights)
+ }
+ }
+ }
+ if (objType == "" || objType == "group") && mask&0x00000008 != 0 {
+ edges = append(edges, EdgeAddSelf)
+ }
+ return edges
+ }
+
+ canWriteProp := mask&0x00000020 != 0 || hasGenericAll(mask) || mask&0x40000000 != 0
+ hasExtRight := mask&0x00000100 != 0 || hasGenericAll(mask)
+
+ switch guidLower {
+ case GUIDGroupMemberAttr, GUIDMembershipPropertySet:
+ if objType == "" || objType == "group" {
+ if canWriteProp {
+ edges = append(edges, EdgeAddMember)
+ } else if mask&0x00000008 != 0 {
+ edges = append(edges, EdgeAddSelf)
+ }
+ }
+ case GUIDUserForceChangePassword:
+ if (objType == "" || objType == "user" || objType == "computer") && hasExtRight {
+ edges = append(edges, EdgeForceChangePassword)
+ }
+ case GUIDReplicationGetChanges:
+ if (objType == "" || objType == "domain") && hasExtRight {
+ edges = append(edges, EdgeGetChanges)
+ }
+ case GUIDReplicationGetChangesAll:
+ if (objType == "" || objType == "domain") && hasExtRight {
+ edges = append(edges, EdgeGetChangesAll)
+ }
+ case GUIDReplicationFiltered:
+ if (objType == "" || objType == "domain") && hasExtRight {
+ edges = append(edges, EdgeGetChangesInFilteredSet)
+ }
+ case GUIDAllowedToAct:
+ if (objType == "" || objType == "computer") && canWriteProp {
+ edges = append(edges, EdgeAddAllowedToAct)
+ }
+ case GUIDKeyCredentialLink:
+ if (objType == "" || objType == "user" || objType == "computer") && canWriteProp {
+ edges = append(edges, EdgeAddKeyCredentialLink)
+ }
+ case GUIDServicePrincipalName:
+ if (objType == "" || objType == "user" || objType == "computer") && canWriteProp {
+ edges = append(edges, EdgeWriteSPN)
+ }
+ case GUIDUserAccountRestrictions:
+ if (objType == "" || objType == "user" || objType == "computer") && canWriteProp && !strings.HasSuffix(principalSID, "-512") {
+ edges = append(edges, EdgeWriteAccountRestrictions)
+ }
+ case GUIDWriteGPLink:
+ if (objType == "" || objType == "ou" || objType == "domain") && canWriteProp {
+ edges = append(edges, EdgeWriteGPLink)
+ }
+ default:
+ if objType == "computer" && hasLAPS && lapsGUIDs != nil && lapsGUIDs[guidLower] && (hasExtRight || mask&0x00000010 != 0) {
+ edges = append(edges, EdgeReadLAPSPassword)
+ }
+ }
+
+ return edges
+}
diff --git a/pkg/ad/assembler.go b/pkg/ad/assembler.go
@@ -0,0 +1,952 @@
+package ad
+
+import (
+ "encoding/binary"
+ "encoding/hex"
+ "fmt"
+ "strings"
+
+ "github.com/Velocidex/ordereddict"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/acl"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/crypto"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/ese"
+)
+
+type Assembler struct {
+ db *ese.DB
+ cryptoEngine *crypto.CryptoEngine
+ secEngine *acl.SecurityEngine
+ tree *Tree
+ Snapshot *ADSnapshot
+ domainOverride string
+
+ groupsByDNT map[uint64]*GroupObject
+ ousByDNT map[uint64]*OUObject
+ deletedDNTs map[uint64]bool
+ domainDNT uint64
+ domainAces []acl.Ace
+ domainACLProtect bool
+ domainFuncLevel string
+ domainDescription interface{}
+ domainTrusts []DomainTrust
+}
+
+func NewAssembler(db *ese.DB, cryptoEngine *crypto.CryptoEngine, secEngine *acl.SecurityEngine, domainOverride string) *Assembler {
+ return &Assembler{
+ db: db,
+ cryptoEngine: cryptoEngine,
+ secEngine: secEngine,
+ tree: NewTree(),
+ Snapshot: NewADSnapshot(),
+ domainOverride: strings.TrimSpace(domainOverride),
+ groupsByDNT: make(map[uint64]*GroupObject),
+ ousByDNT: make(map[uint64]*OUObject),
+ deletedDNTs: make(map[uint64]bool),
+ domainFuncLevel: "2016",
+ domainTrusts: make([]DomainTrust, 0),
+ }
+}
+
+func (a *Assembler) Assemble() error {
+ if err := a.buildTreeAndDomain(); err != nil {
+ return fmt.Errorf("failed to build tree and domain: %w", err)
+ }
+
+ if err := a.extractObjects(); err != nil {
+ return fmt.Errorf("failed to extract objects: %w", err)
+ }
+
+ if err := a.processLinks(); err != nil {
+ return fmt.Errorf("failed to process links: %w", err)
+ }
+
+ a.processPrimaryGroups()
+
+ a.synthesizeWellKnownGroups()
+
+ a.resolvePrincipalsAndAces()
+
+ a.linkContainment()
+
+ return nil
+}
+
+func (a *Assembler) buildTreeAndDomain() error {
+ var fallbackDomainSID string
+ var dcCandidateDNTs []uint64
+
+ err := a.db.StreamTable("datatable", func(row *ordereddict.Dict) error {
+ dnt, ok := readUint64(row, "DNT_col")
+ if !ok || dnt == 0 {
+ return nil
+ }
+ pdnt, _ := readUint64(row, "PDNT_col")
+ a.Snapshot.PDNTByDNT[dnt] = pdnt
+
+ if a.secEngine != nil {
+ ldapName := strings.ToLower(readString(row, "ATTm131532"))
+ if ldapName == "ms-mcs-admpwd" || ldapName == "mslaps-password" || ldapName == "mslaps-encryptedpassword" {
+ if guidHex := readString(row, "ATTk589972"); len(guidHex) == 32 {
+ if gb, err := hex.DecodeString(guidHex); err == nil && len(gb) == 16 {
+ a.secEngine.LapsGUIDs[formatGUIDLower(gb)] = true
+ }
+ }
+ }
+ }
+
+ var rdnCol string = "ATTm3"
+ rdnTyp, hasRDNTyp := readInt64(row, "RDNtyp_col")
+ if !hasRDNTyp {
+ rdnTyp = 3
+ } else {
+ rdnCol = fmt.Sprintf("ATTm%d", rdnTyp)
+ }
+
+ rdn := readString(row, rdnCol)
+ if rdn == "" {
+ rdn = readString(row, "ATTm3")
+ }
+ if rdn == "" {
+ rdn = readString(row, "ATTm589825")
+ }
+ if rdn == "" {
+ rdn = readString(row, "ATTm1376281")
+ }
+ if rdn == "" {
+ rdn = readString(row, "ATTm1376280")
+ }
+
+ if isRowDeleted(row, rdn) {
+ a.deletedDNTs[dnt] = true
+ }
+
+ if sidHex := readString(row, "ATTr589970"); sidHex != "" {
+ if sidBytes, err := hex.DecodeString(sidHex); err == nil {
+ if sidStr, _, err := crypto.ParseSID(sidBytes); err == nil && strings.HasPrefix(sidStr, "S-1-5-21-") {
+ parts := strings.Split(sidStr, "-")
+ if len(parts) == 7 {
+ a.Snapshot.DomainSID = sidStr
+ a.domainDNT = dnt
+ if lvl, hasLvl := readInt64(row, "ATTj591540"); hasLvl {
+ a.domainFuncLevel = functionalLevelName(lvl)
+ }
+ a.domainDescription = readOptionalDescription(row)
+ } else if len(parts) >= 8 && fallbackDomainSID == "" {
+ fallbackDomainSID = strings.Join(parts[:7], "-")
+ }
+ }
+ }
+ }
+
+ if rdn == "" {
+ return nil
+ }
+
+ prefix := "CN="
+ if rdnTyp == 1376281 || strings.HasPrefix(strings.ToLower(rdn), "dc=") {
+ prefix = "DC="
+ dcCandidateDNTs = append(dcCandidateDNTs, dnt)
+ } else if rdnTyp == 1376280 || rdnTyp == 11 || strings.HasPrefix(strings.ToLower(rdn), "ou=") {
+ prefix = "OU="
+ }
+
+ cleanRDN := rdn
+ if strings.HasPrefix(strings.ToUpper(cleanRDN), prefix) {
+ cleanRDN = cleanRDN[len(prefix):]
+ }
+
+ a.tree.AddNode(dnt, pdnt, cleanRDN, prefix)
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ if a.Snapshot.DomainSID == "" && fallbackDomainSID != "" {
+ a.Snapshot.DomainSID = fallbackDomainSID
+ }
+
+ if a.domainDNT != 0 {
+ if dom := domainFromDN(a.tree.ResolveDN(a.domainDNT)); dom != "" {
+ a.Snapshot.DomainName = dom
+ }
+ }
+ if a.Snapshot.DomainName == "" {
+ for _, candDNT := range dcCandidateDNTs {
+ if dom := domainFromDN(a.tree.ResolveDN(candDNT)); dom != "" {
+ a.Snapshot.DomainName = dom
+ if a.domainDNT == 0 {
+ a.domainDNT = candDNT
+ }
+ break
+ }
+ }
+ }
+
+ if a.domainOverride != "" {
+ a.Snapshot.DomainName = strings.ToUpper(a.domainOverride)
+ }
+
+ return nil
+}
+
+func (a *Assembler) extractSDID(row *ordereddict.Dict) (uint64, bool) {
+ if sdVal := readString(row, "ATTp131353"); len(sdVal) == 16 {
+ if b, err := hex.DecodeString(sdVal); err == nil && len(b) == 8 {
+ return binary.LittleEndian.Uint64(b), true
+ }
+ }
+ for _, colName := range []string{"ATTb590606", "ATTb49"} {
+ if v, ok := row.Get(colName); ok && v != nil {
+ switch val := v.(type) {
+ case uint64:
+ return val, true
+ case int64:
+ return uint64(val), true
+ case uint32:
+ return uint64(val), true
+ case int32:
+ return uint64(val), true
+ case string:
+ if len(val) == 16 {
+ if b, err := hex.DecodeString(val); err == nil && len(b) == 8 {
+ return binary.LittleEndian.Uint64(b), true
+ }
+ }
+ }
+ }
+ }
+ return 0, false
+}
+
+func (a *Assembler) resolveObjectSD(sdID uint64, foundSD bool, objType string, hasLAPS bool) ([]acl.Ace, bool) {
+ if a.secEngine == nil || !foundSD {
+ return make([]acl.Ace, 0), false
+ }
+ aces, isProtected := a.secEngine.GetAcesForObject(sdID, objType, hasLAPS)
+ if aces == nil {
+ aces = make([]acl.Ace, 0)
+ }
+ return aces, isProtected
+}
+
+func (a *Assembler) extractObjects() error {
+ return a.db.StreamTable("datatable", func(row *ordereddict.Dict) error {
+ dnt, ok := readUint64(row, "DNT_col")
+ if !ok || dnt == 0 || a.deletedDNTs[dnt] {
+ return nil
+ }
+
+ pdnt, _ := readUint64(row, "PDNT_col")
+ a.Snapshot.PDNTByDNT[dnt] = pdnt
+
+ dn := a.tree.ResolveDN(dnt)
+ dnUpper := strings.ToUpper(dn)
+ if isRowDeleted(row, a.tree.GetRDN(dnt)) || isNonDomainPartitionDN(dnUpper) {
+ return nil
+ }
+
+ var sidStr string
+ var rid uint32
+ if sidHex := readString(row, "ATTr589970"); sidHex != "" {
+ if sidBytes, err := hex.DecodeString(sidHex); err == nil {
+ if s, r, err := crypto.ParseSID(sidBytes); err == nil {
+ sidStr = s
+ rid = r
+ }
+ }
+ }
+
+ sdID, foundSD := a.extractSDID(row)
+
+ if dnt == a.domainDNT || (sidStr != "" && sidStr == a.Snapshot.DomainSID) {
+ a.domainDNT = dnt
+ a.domainAces, a.domainACLProtect = a.resolveObjectSD(sdID, foundSD, "domain", false)
+ }
+
+ if trust, isTrust := extractTrustFromRow(row, a.tree.GetRDN(dnt)); isTrust {
+ a.domainTrusts = append(a.domainTrusts, trust)
+ return nil
+ }
+
+ samVal, _ := row.Get("ATTm590045")
+ if samVal == nil {
+ rdnTyp, hasRDN := readInt64(row, "RDNtyp_col")
+ if !hasRDN {
+ rdnTyp = 3
+ }
+
+ var guidStr string
+ if guidHex := readString(row, "ATTk589826"); len(guidHex) == 32 {
+ if gb, err := hex.DecodeString(guidHex); err == nil && len(gb) == 16 {
+ guidStr = formatGUIDUpper(gb)
+ }
+ }
+
+ if rdnTyp == 1376280 || rdnTyp == 11 || (dnUpper != "" && strings.HasPrefix(dnUpper, "OU=")) {
+ ouName := readString(row, "ATTm11")
+ if ouName == "" {
+ ouName = readString(row, "ATTm1376280")
+ }
+ if ouName == "" {
+ ouName = a.tree.GetRDN(dnt)
+ }
+ if guidStr == "" {
+ guidStr = fmt.Sprintf("OU-%d", dnt)
+ }
+
+ blocksInheritance := false
+ if gpOpt, hasGP := readInt64(row, "ATTj589846"); hasGP && (gpOpt&1) != 0 {
+ blocksInheritance = true
+ } else if readString(row, "ATTm589846") == "1" {
+ blocksInheritance = true
+ }
+
+ aces, isACLProtected := a.resolveObjectSD(sdID, foundSD, "ou", false)
+
+ ouObj := &OUObject{
+ ObjectIdentifier: guidStr,
+ ChildObjects: make([]TypedPrincipal, 0),
+ Links: make([]interface{}, 0),
+ Aces: aces,
+ IsACLProtected: isACLProtected,
+ DNT: dnt,
+ PDNT: pdnt,
+ Properties: map[string]interface{}{
+ "domain": a.Snapshot.DomainName,
+ "name": fmt.Sprintf("%s@%s", strings.ToUpper(ouName), a.Snapshot.DomainName),
+ "distinguishedname": dnUpper,
+ "domainsid": a.Snapshot.DomainSID,
+ "highvalue": false,
+ "objectid": guidStr,
+ "blocksinheritance": blocksInheritance,
+ "isaclprotected": isACLProtected,
+ "description": readOptionalDescription(row),
+ },
+ }
+ a.Snapshot.OUs = append(a.Snapshot.OUs, ouObj)
+ a.Snapshot.OUsByGUID[guidStr] = ouObj
+ a.ousByDNT[dnt] = ouObj
+ a.Snapshot.ObjectsByDNT[dnt] = TypedPrincipal{ObjectIdentifier: guidStr, ObjectType: "OU"}
+ }
+ return nil
+ }
+
+ sam, ok := samVal.(string)
+ if !ok || len(sam) == 0 || sidStr == "" {
+ return nil
+ }
+
+ uacVal, _ := readInt64(row, "ATTj589832")
+ uac := uint32(uacVal)
+
+ samAccountType, _ := readInt64(row, "ATTj590126")
+ if samAccountType == 805306370 || (uac&0x0800) != 0 {
+ return nil
+ }
+
+ var primaryGroupID uint32 = 513
+ pgInt, hasPG := readInt64(row, "ATTj589922")
+ if hasPG {
+ primaryGroupID = uint32(pgInt)
+ }
+
+ acInt, _ := readInt64(row, "ATTj589842")
+ isAdmin := acInt > 0
+
+ var pwdLastSet int64 = -1
+ if plsInt, hasPLS := readInt64(row, "ATTq589983"); hasPLS {
+ pwdLastSet = filetimeToUnix(plsInt)
+ }
+
+ var lastLogonTS int64 = -1
+ if llTSInt, hasLLTS := readInt64(row, "ATTq590204"); hasLLTS {
+ lastLogonTS = filetimeToUnix(llTSInt)
+ }
+
+ var lastLogon int64 = -1
+ if llInt, hasLL := readInt64(row, "ATTq589876"); hasLL {
+ lastLogon = filetimeToUnix(llInt)
+ }
+
+ var ntHashHex string
+ if a.cryptoEngine != nil && len(a.cryptoEngine.PEKList) > 0 && rid > 0 {
+ if pwdVal, ok := row.Get("ATTk589914"); ok && pwdVal != nil {
+ if pwdHex, ok := pwdVal.(string); ok && len(pwdHex) > 0 {
+ if encBytes, err := hex.DecodeString(pwdHex); err == nil {
+ if decHash, err := a.cryptoEngine.DecryptHash(encBytes, rid); err == nil {
+ ntHashHex = hex.EncodeToString(decHash)
+ }
+ }
+ }
+ }
+ }
+
+ spns := readStringSlice(row, "ATTm590595")
+ delegateTargets := readStringSlice(row, "ATTm591788")
+ sidHistory := readESESIDSlice(row, "ATTr590433")
+ if sidHistory == nil {
+ sidHistory = make([]string, 0)
+ }
+ desc := readOptionalDescription(row)
+ gmsaHex := readString(row, "ATTk592202")
+ rbcdHex := readString(row, "ATTk592023")
+
+ _, hasLegacyLAPSExp := readInt64(row, "ATTq591790")
+ _, hasWinLAPSExp := readInt64(row, "ATTq592270")
+ hasLAPS := hasLegacyLAPSExp || hasWinLAPSExp || readString(row, "ATTm591789") != ""
+
+ isGroup := samAccountType == 268435456 || samAccountType == 268435457 ||
+ samAccountType == 536870912 || samAccountType == 536870913 ||
+ (samAccountType == 0 && uac == 0 && !hasPG && ntHashHex == "" && !strings.HasSuffix(sam, "$"))
+
+ isComputer := !isGroup && gmsaHex == "" &&
+ (samAccountType == 805306369 || (samAccountType == 0 && strings.HasSuffix(sam, "$")))
+
+ if isComputer {
+ dnsName := readString(row, "ATTm590443")
+ if dnsName == "" {
+ baseHost := strings.TrimSuffix(sam, "$")
+ dnsName = fmt.Sprintf("%s.%s", baseHost, a.Snapshot.DomainName)
+ }
+
+ osName := readString(row, "ATTm590187")
+ osVer := readString(row, "ATTm590188")
+ isDC := (uac&0x2000) != 0 || primaryGroupID == 516 || strings.Contains(dnUpper, "OU=DOMAIN CONTROLLERS,")
+
+ aces, isACLProtected := a.resolveObjectSD(sdID, foundSD, "computer", hasLAPS)
+
+ var rawAllowedToAct []string
+ if rbcdHex != "" {
+ if rbcdBytes, err := hex.DecodeString(rbcdHex); err == nil {
+ rbcdAces, _, _ := acl.ParseSecurityDescriptorForType(rbcdBytes, "rbcd", false, nil)
+ for _, ra := range rbcdAces {
+ rawAllowedToAct = append(rawAllowedToAct, ra.PrincipalSID)
+ }
+ }
+ }
+
+ comp := &ComputerObject{
+ ObjectIdentifier: sidStr,
+ PrimaryGroupSID: fmt.Sprintf("%s-%d", a.Snapshot.DomainSID, primaryGroupID),
+ AllowedToDelegate: make([]TypedPrincipal, 0),
+ AllowedToAct: make([]TypedPrincipal, 0),
+ HasSIDHistory: make([]TypedPrincipal, 0),
+ DumpSMSAPassword: make([]TypedPrincipal, 0),
+ Sessions: EmptySessionCollection(),
+ PrivilegedSessions: EmptySessionCollection(),
+ RegistrySessions: EmptySessionCollection(),
+ LocalGroups: make([]interface{}, 0),
+ UserRights: make([]interface{}, 0),
+ Aces: aces,
+ IsACLProtected: isACLProtected,
+ IsDC: isDC,
+ DNT: dnt,
+ PDNT: pdnt,
+ NTHash: ntHashHex,
+ RawDelegateTargets: delegateTargets,
+ RawAllowedToAct: rawAllowedToAct,
+ RawSIDHistory: sidHistory,
+ Properties: map[string]interface{}{
+ "domain": a.Snapshot.DomainName,
+ "name": strings.ToUpper(dnsName),
+ "distinguishedname": dnUpper,
+ "domainsid": a.Snapshot.DomainSID,
+ "highvalue": isDC,
+ "objectid": sidStr,
+ "samaccountname": sam,
+ "enabled": (uac & 2) == 0,
+ "haslaps": hasLAPS,
+ "isaclprotected": isACLProtected,
+ "isdc": isDC,
+ "operatingsystem": osName,
+ "operatingsystemversion": osVer,
+ "pwdlastset": pwdLastSet,
+ "lastlogon": lastLogon,
+ "lastlogontimestamp": lastLogonTS,
+ "unconstraineddelegation": (uac & 0x80000) != 0,
+ "trustedtoauth": (uac & 0x1000000) != 0,
+ "serviceprincipalnames": spns,
+ "sidhistory": sidHistory,
+ "description": desc,
+ "nthash": ntHashHex,
+ },
+ }
+ a.Snapshot.Computers = append(a.Snapshot.Computers, comp)
+ a.Snapshot.ComputersBySID[sidStr] = comp
+ a.Snapshot.ObjectsByDNT[dnt] = TypedPrincipal{ObjectIdentifier: sidStr, ObjectType: "Computer"}
+
+ } else if !isGroup {
+ upn := readString(row, "ATTm590480")
+ aces, isACLProtected := a.resolveObjectSD(sdID, foundSD, "user", false)
+
+ if gmsaHex != "" {
+ if gmsaBytes, err := hex.DecodeString(gmsaHex); err == nil {
+ gmsaAces, _, _ := acl.ParseSecurityDescriptorForType(gmsaBytes, "gmsa", false, nil)
+ aces = append(aces, gmsaAces...)
+ }
+ }
+
+ userName := fmt.Sprintf("%s@%s", strings.ToUpper(sam), a.Snapshot.DomainName)
+ user := &UserObject{
+ ObjectIdentifier: sidStr,
+ PrimaryGroupSID: fmt.Sprintf("%s-%d", a.Snapshot.DomainSID, primaryGroupID),
+ AllowedToDelegate: make([]TypedPrincipal, 0),
+ SPNTargets: make([]interface{}, 0),
+ HasSIDHistory: make([]TypedPrincipal, 0),
+ Aces: aces,
+ IsACLProtected: isACLProtected,
+ DNT: dnt,
+ PDNT: pdnt,
+ NTHash: ntHashHex,
+ RawDelegateTargets: delegateTargets,
+ RawSIDHistory: sidHistory,
+ Properties: map[string]interface{}{
+ "domain": a.Snapshot.DomainName,
+ "name": userName,
+ "distinguishedname": dnUpper,
+ "domainsid": a.Snapshot.DomainSID,
+ "highvalue": isAdmin || rid == 500,
+ "objectid": sidStr,
+ "samaccountname": sam,
+ "enabled": (uac & 2) == 0,
+ "pwdlastset": pwdLastSet,
+ "lastlogon": lastLogon,
+ "lastlogontimestamp": lastLogonTS,
+ "userprincipalname": upn,
+ "admincount": isAdmin,
+ "dontreqpreauth": (uac & 0x400000) != 0,
+ "passwordnotreqd": (uac & 0x20) != 0,
+ "pwdneverexpires": (uac & 0x10000) != 0,
+ "sensitive": (uac & 0x100000) != 0,
+ "unconstraineddelegation": (uac & 0x80000) != 0,
+ "trustedtoauth": (uac & 0x1000000) != 0,
+ "isaclprotected": isACLProtected,
+ "hasspn": len(spns) > 0,
+ "serviceprincipalnames": spns,
+ "sidhistory": sidHistory,
+ "haslaps": false,
+ "description": desc,
+ "nthash": ntHashHex,
+ },
+ }
+ a.Snapshot.Users = append(a.Snapshot.Users, user)
+ a.Snapshot.UsersBySID[sidStr] = user
+ a.Snapshot.ObjectsByDNT[dnt] = TypedPrincipal{ObjectIdentifier: sidStr, ObjectType: "User"}
+
+ } else {
+ aces, isACLProtected := a.resolveObjectSD(sdID, foundSD, "group", false)
+ objID := sidStr
+ if _, isWK := wellKnownSIDs[sidStr]; isWK && a.Snapshot.DomainName != "" {
+ objID = fmt.Sprintf("%s-%s", a.Snapshot.DomainName, sidStr)
+ }
+
+ groupName := fmt.Sprintf("%s@%s", strings.ToUpper(sam), a.Snapshot.DomainName)
+ grp := &GroupObject{
+ ObjectIdentifier: objID,
+ Members: make([]MemberReference, 0),
+ Aces: aces,
+ IsACLProtected: isACLProtected,
+ DNT: dnt,
+ PDNT: pdnt,
+ Properties: map[string]interface{}{
+ "domain": a.Snapshot.DomainName,
+ "name": groupName,
+ "distinguishedname": dnUpper,
+ "domainsid": a.Snapshot.DomainSID,
+ "highvalue": isAdmin || isHighValueGroupSID(sidStr, rid),
+ "objectid": objID,
+ "samaccountname": sam,
+ "admincount": isAdmin,
+ "isaclprotected": isACLProtected,
+ "description": desc,
+ },
+ }
+ a.Snapshot.Groups = append(a.Snapshot.Groups, grp)
+ a.Snapshot.GroupsBySID[objID] = grp
+ if objID != sidStr {
+ a.Snapshot.GroupsBySID[sidStr] = grp
+ }
+ a.groupsByDNT[dnt] = grp
+ a.Snapshot.ObjectsByDNT[dnt] = TypedPrincipal{ObjectIdentifier: objID, ObjectType: "Group"}
+ }
+
+ return nil
+ })
+}
+
+func (a *Assembler) processLinks() error {
+ return a.db.StreamTable("link_table", func(row *ordereddict.Dict) error {
+ linkBaseVal, ok := row.Get("link_base")
+ if !ok || linkBaseVal == nil {
+ return nil
+ }
+
+ var linkBase uint32
+ switch v := linkBaseVal.(type) {
+ case int32:
+ linkBase = uint32(v)
+ case uint32:
+ linkBase = v
+ case int64:
+ linkBase = uint32(v)
+ case uint64:
+ linkBase = uint32(v)
+ }
+ if linkBase != 1 {
+ return nil
+ }
+
+ linkDNTVal, _ := row.Get("link_DNT")
+ backlinkDNTVal, _ := row.Get("backlink_DNT")
+ if linkDNTVal == nil || backlinkDNTVal == nil {
+ return nil
+ }
+
+ var groupDNT, memberDNT uint64
+ switch v := linkDNTVal.(type) {
+ case uint64:
+ groupDNT = v
+ case int64:
+ groupDNT = uint64(v)
+ case int32:
+ groupDNT = uint64(v)
+ case uint32:
+ groupDNT = uint64(v)
+ }
+ switch v := backlinkDNTVal.(type) {
+ case uint64:
+ memberDNT = v
+ case int64:
+ memberDNT = uint64(v)
+ case int32:
+ memberDNT = uint64(v)
+ case uint32:
+ memberDNT = uint64(v)
+ }
+
+ grp, exists := a.groupsByDNT[groupDNT]
+ if !exists {
+ return nil
+ }
+
+ targetPrincipal, exists := a.Snapshot.ObjectsByDNT[memberDNT]
+ if !exists || targetPrincipal.ObjectIdentifier == "" {
+ return nil
+ }
+
+ for _, m := range grp.Members {
+ if m.ObjectIdentifier == targetPrincipal.ObjectIdentifier {
+ return nil
+ }
+ }
+
+ grp.Members = append(grp.Members, MemberReference{
+ ObjectIdentifier: targetPrincipal.ObjectIdentifier,
+ ObjectType: targetPrincipal.ObjectType,
+ })
+
+ return nil
+ })
+}
+
+func (a *Assembler) processPrimaryGroups() {
+ for _, u := range a.Snapshot.Users {
+ if grp, exists := a.Snapshot.GroupsBySID[u.PrimaryGroupSID]; exists {
+ alreadyMember := false
+ for _, m := range grp.Members {
+ if m.ObjectIdentifier == u.ObjectIdentifier {
+ alreadyMember = true
+ break
+ }
+ }
+ if !alreadyMember {
+ grp.Members = append(grp.Members, MemberReference{
+ ObjectIdentifier: u.ObjectIdentifier,
+ ObjectType: "User",
+ })
+ }
+ }
+ }
+
+ for _, c := range a.Snapshot.Computers {
+ if grp, exists := a.Snapshot.GroupsBySID[c.PrimaryGroupSID]; exists {
+ alreadyMember := false
+ for _, m := range grp.Members {
+ if m.ObjectIdentifier == c.ObjectIdentifier {
+ alreadyMember = true
+ break
+ }
+ }
+ if !alreadyMember {
+ grp.Members = append(grp.Members, MemberReference{
+ ObjectIdentifier: c.ObjectIdentifier,
+ ObjectType: "Computer",
+ })
+ }
+ }
+ }
+
+ if a.Snapshot.DomainSID != "" {
+ if a.domainAces == nil {
+ a.domainAces = make([]acl.Ace, 0)
+ }
+ domDN := fmt.Sprintf("DC=%s", strings.ReplaceAll(strings.ToUpper(a.Snapshot.DomainName), ".", ",DC="))
+ domObj := &DomainObject{
+ ObjectIdentifier: a.Snapshot.DomainSID,
+ ChildObjects: make([]TypedPrincipal, 0),
+ Trusts: a.domainTrusts,
+ Links: make([]interface{}, 0),
+ Aces: a.domainAces,
+ IsACLProtected: a.domainACLProtect,
+ DNT: a.domainDNT,
+ Properties: map[string]interface{}{
+ "domain": a.Snapshot.DomainName,
+ "name": a.Snapshot.DomainName,
+ "distinguishedname": domDN,
+ "domainsid": a.Snapshot.DomainSID,
+ "highvalue": true,
+ "objectid": a.Snapshot.DomainSID,
+ "functionallevel": a.domainFuncLevel,
+ "isaclprotected": a.domainACLProtect,
+ "collected": true,
+ "description": a.domainDescription,
+ },
+ }
+ a.Snapshot.Domains = append(a.Snapshot.Domains, domObj)
+ }
+}
+
+func (a *Assembler) synthesizeWellKnownGroups() {
+ if a.Snapshot.DomainName == "" {
+ return
+ }
+
+ defaults := []struct {
+ rawSID string
+ name string
+ }{
+ {rawSID: "S-1-1-0", name: "EVERYONE"},
+ {rawSID: "S-1-5-11", name: "AUTHENTICATED USERS"},
+ {rawSID: "S-1-5-4", name: "INTERACTIVE"},
+ {rawSID: "S-1-5-9", name: "ENTERPRISE DOMAIN CONTROLLERS"},
+ }
+
+ for _, def := range defaults {
+ prefixedID := fmt.Sprintf("%s-%s", a.Snapshot.DomainName, def.rawSID)
+ if _, exists := a.Snapshot.GroupsBySID[prefixedID]; exists {
+ continue
+ }
+ if _, exists := a.Snapshot.GroupsBySID[def.rawSID]; exists {
+ continue
+ }
+
+ members := make([]MemberReference, 0)
+ if def.rawSID == "S-1-5-9" {
+ for _, comp := range a.Snapshot.Computers {
+ if comp.IsDC {
+ members = append(members, MemberReference{
+ ObjectIdentifier: comp.ObjectIdentifier,
+ ObjectType: "Computer",
+ })
+ }
+ }
+ }
+
+ grp := &GroupObject{
+ ObjectIdentifier: prefixedID,
+ Members: members,
+ Aces: make([]acl.Ace, 0),
+ Synthetic: true,
+ Properties: map[string]interface{}{
+ "domain": a.Snapshot.DomainName,
+ "domainsid": a.Snapshot.DomainSID,
+ "name": fmt.Sprintf("%s@%s", def.name, a.Snapshot.DomainName),
+ "objectid": prefixedID,
+ "highvalue": false,
+ },
+ }
+ a.Snapshot.Groups = append(a.Snapshot.Groups, grp)
+ a.Snapshot.GroupsBySID[prefixedID] = grp
+ a.Snapshot.GroupsBySID[def.rawSID] = grp
+ }
+}
+
+func (a *Assembler) resolveSID(rawSID string) (string, string) {
+ if rawSID == "" {
+ return "", "Base"
+ }
+ if rawSID == a.Snapshot.DomainSID {
+ return rawSID, "Domain"
+ }
+ if u, ok := a.Snapshot.UsersBySID[rawSID]; ok {
+ return u.ObjectIdentifier, "User"
+ }
+ if c, ok := a.Snapshot.ComputersBySID[rawSID]; ok {
+ return c.ObjectIdentifier, "Computer"
+ }
+ if g, ok := a.Snapshot.GroupsBySID[rawSID]; ok {
+ return g.ObjectIdentifier, "Group"
+ }
+ if wk, ok := wellKnownSIDs[rawSID]; ok && a.Snapshot.DomainName != "" {
+ return fmt.Sprintf("%s-%s", a.Snapshot.DomainName, rawSID), wk.Type
+ }
+ return rawSID, "Base"
+}
+
+func (a *Assembler) resolveDelegateSPNs(spns []string) []TypedPrincipal {
+ out := make([]TypedPrincipal, 0)
+ if len(spns) == 0 {
+ return out
+ }
+
+ compByHost := make(map[string]*ComputerObject)
+ for _, c := range a.Snapshot.Computers {
+ if nameStr, ok := c.Properties["name"].(string); ok && nameStr != "" {
+ upper := strings.ToUpper(nameStr)
+ compByHost[upper] = c
+ if idx := strings.IndexByte(upper, '.'); idx > 0 {
+ compByHost[upper[:idx]] = c
+ }
+ }
+ if samStr, ok := c.Properties["samaccountname"].(string); ok && samStr != "" {
+ short := strings.ToUpper(strings.TrimSuffix(samStr, "$"))
+ compByHost[short] = c
+ }
+ }
+
+ seen := make(map[string]bool)
+ for _, spn := range spns {
+ parts := strings.SplitN(spn, "/", 2)
+ if len(parts) < 2 {
+ continue
+ }
+ host := strings.ToUpper(parts[1])
+ if idx := strings.IndexByte(host, ':'); idx > 0 {
+ host = host[:idx]
+ }
+ if idx := strings.IndexByte(host, '/'); idx > 0 {
+ host = host[:idx]
+ }
+ comp, ok := compByHost[host]
+ if !ok {
+ if dot := strings.IndexByte(host, '.'); dot > 0 {
+ comp, ok = compByHost[host[:dot]]
+ }
+ }
+ if ok && comp != nil && !seen[comp.ObjectIdentifier] {
+ seen[comp.ObjectIdentifier] = true
+ out = append(out, TypedPrincipal{
+ ObjectIdentifier: comp.ObjectIdentifier,
+ ObjectType: "Computer",
+ })
+ }
+ }
+ return out
+}
+
+func (a *Assembler) resolveSIDList(rawSIDs []string) []TypedPrincipal {
+ out := make([]TypedPrincipal, 0, len(rawSIDs))
+ seen := make(map[string]bool)
+ for _, s := range rawSIDs {
+ id, pType := a.resolveSID(s)
+ if id != "" && !seen[id] {
+ seen[id] = true
+ out = append(out, TypedPrincipal{
+ ObjectIdentifier: id,
+ ObjectType: pType,
+ })
+ }
+ }
+ return out
+}
+
+func (a *Assembler) rewriteAces(aces []acl.Ace) {
+ for i := range aces {
+ aces[i].PrincipalSID, aces[i].PrincipalType = a.resolveSID(aces[i].PrincipalSID)
+ }
+}
+
+func (a *Assembler) resolvePrincipalsAndAces() {
+ for _, u := range a.Snapshot.Users {
+ a.rewriteAces(u.Aces)
+ u.AllowedToDelegate = a.resolveDelegateSPNs(u.RawDelegateTargets)
+ u.HasSIDHistory = a.resolveSIDList(u.RawSIDHistory)
+ }
+ for _, g := range a.Snapshot.Groups {
+ a.rewriteAces(g.Aces)
+ }
+ for _, c := range a.Snapshot.Computers {
+ a.rewriteAces(c.Aces)
+ c.AllowedToDelegate = a.resolveDelegateSPNs(c.RawDelegateTargets)
+ c.AllowedToAct = a.resolveSIDList(c.RawAllowedToAct)
+ c.HasSIDHistory = a.resolveSIDList(c.RawSIDHistory)
+ }
+ for _, d := range a.Snapshot.Domains {
+ a.rewriteAces(d.Aces)
+ }
+ for _, o := range a.Snapshot.OUs {
+ a.rewriteAces(o.Aces)
+ }
+}
+
+func (a *Assembler) linkContainment() {
+ var rootDom *DomainObject
+ if len(a.Snapshot.Domains) > 0 {
+ rootDom = a.Snapshot.Domains[0]
+ }
+
+ addChild := func(pdnt uint64, childID string, childType string) {
+ if childID == "" {
+ return
+ }
+ tp := TypedPrincipal{
+ ObjectIdentifier: childID,
+ ObjectType: childType,
+ }
+
+ curr := pdnt
+ visited := make(map[uint64]bool)
+ for curr != 0 && !visited[curr] {
+ visited[curr] = true
+ if ou, ok := a.ousByDNT[curr]; ok {
+ ou.ChildObjects = append(ou.ChildObjects, tp)
+ return
+ }
+ if a.domainDNT != 0 && curr == a.domainDNT {
+ if rootDom != nil {
+ rootDom.ChildObjects = append(rootDom.ChildObjects, tp)
+ }
+ return
+ }
+ next, exists := a.Snapshot.PDNTByDNT[curr]
+ if !exists || next == curr {
+ break
+ }
+ curr = next
+ }
+
+ if a.domainDNT == 0 && rootDom != nil {
+ rootDom.ChildObjects = append(rootDom.ChildObjects, tp)
+ }
+ }
+
+ for _, ou := range a.Snapshot.OUs {
+ addChild(ou.PDNT, ou.ObjectIdentifier, "OU")
+ }
+
+ for _, u := range a.Snapshot.Users {
+ addChild(u.PDNT, u.ObjectIdentifier, "User")
+ }
+
+ for _, c := range a.Snapshot.Computers {
+ addChild(c.PDNT, c.ObjectIdentifier, "Computer")
+ }
+
+ for _, g := range a.Snapshot.Groups {
+ if g.Synthetic {
+ continue
+ }
+ addChild(g.PDNT, g.ObjectIdentifier, "Group")
+ }
+}
diff --git a/pkg/ad/helpers.go b/pkg/ad/helpers.go
@@ -0,0 +1,355 @@
+package ad
+
+import (
+ "encoding/binary"
+ "encoding/hex"
+ "fmt"
+ "strings"
+
+ "github.com/Velocidex/ordereddict"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/crypto"
+)
+
+type wellKnownDef struct {
+ Name string
+ Type string
+}
+
+var wellKnownSIDs = map[string]wellKnownDef{
+ "S-1-0": {Name: "Null Authority", Type: "User"},
+ "S-1-0-0": {Name: "Nobody", Type: "User"},
+ "S-1-1": {Name: "World Authority", Type: "User"},
+ "S-1-1-0": {Name: "Everyone", Type: "Group"},
+ "S-1-2": {Name: "Local Authority", Type: "User"},
+ "S-1-2-0": {Name: "Local", Type: "Group"},
+ "S-1-2-1": {Name: "Console Logon", Type: "Group"},
+ "S-1-3": {Name: "Creator Authority", Type: "User"},
+ "S-1-3-0": {Name: "Creator Owner", Type: "User"},
+ "S-1-3-1": {Name: "Creator Group", Type: "Group"},
+ "S-1-3-2": {Name: "Creator Owner Server", Type: "Computer"},
+ "S-1-3-3": {Name: "Creator Group Server", Type: "Computer"},
+ "S-1-3-4": {Name: "Owner Rights", Type: "Group"},
+ "S-1-4": {Name: "Non-unique Authority", Type: "User"},
+ "S-1-5": {Name: "NT Authority", Type: "User"},
+ "S-1-5-1": {Name: "Dialup", Type: "Group"},
+ "S-1-5-2": {Name: "Network", Type: "Group"},
+ "S-1-5-3": {Name: "Batch", Type: "Group"},
+ "S-1-5-4": {Name: "Interactive", Type: "Group"},
+ "S-1-5-6": {Name: "Service", Type: "Group"},
+ "S-1-5-7": {Name: "Anonymous", Type: "Group"},
+ "S-1-5-8": {Name: "Proxy", Type: "Group"},
+ "S-1-5-9": {Name: "Enterprise Domain Controllers", Type: "Group"},
+ "S-1-5-10": {Name: "Principal Self", Type: "User"},
+ "S-1-5-11": {Name: "Authenticated Users", Type: "Group"},
+ "S-1-5-12": {Name: "Restricted Code", Type: "Group"},
+ "S-1-5-13": {Name: "Terminal Server Users", Type: "Group"},
+ "S-1-5-14": {Name: "Remote Interactive Logon", Type: "Group"},
+ "S-1-5-15": {Name: "This Organization", Type: "Group"},
+ "S-1-5-17": {Name: "IUSR", Type: "User"},
+ "S-1-5-18": {Name: "Local System", Type: "User"},
+ "S-1-5-19": {Name: "NT Authority", Type: "User"},
+ "S-1-5-20": {Name: "Network Service", Type: "User"},
+ "S-1-5-80-0": {Name: "All Services", Type: "Group"},
+ "S-1-5-32-544": {Name: "Administrators", Type: "Group"},
+ "S-1-5-32-545": {Name: "Users", Type: "Group"},
+ "S-1-5-32-546": {Name: "Guests", Type: "Group"},
+ "S-1-5-32-547": {Name: "Power Users", Type: "Group"},
+ "S-1-5-32-548": {Name: "Account Operators", Type: "Group"},
+ "S-1-5-32-549": {Name: "Server Operators", Type: "Group"},
+ "S-1-5-32-550": {Name: "Print Operators", Type: "Group"},
+ "S-1-5-32-551": {Name: "Backup Operators", Type: "Group"},
+ "S-1-5-32-552": {Name: "Replicators", Type: "Group"},
+ "S-1-5-32-554": {Name: "Pre-Windows 2000 Compatible Access", Type: "Group"},
+ "S-1-5-32-555": {Name: "Remote Desktop Users", Type: "Group"},
+ "S-1-5-32-556": {Name: "Network Configuration Operators", Type: "Group"},
+ "S-1-5-32-557": {Name: "Incoming Forest Trust Builders", Type: "Group"},
+ "S-1-5-32-558": {Name: "Performance Monitor Users", Type: "Group"},
+ "S-1-5-32-559": {Name: "Performance Log Users", Type: "Group"},
+ "S-1-5-32-560": {Name: "Windows Authorization Access Group", Type: "Group"},
+ "S-1-5-32-561": {Name: "Terminal Server License Servers", Type: "Group"},
+ "S-1-5-32-562": {Name: "Distributed COM Users", Type: "Group"},
+ "S-1-5-32-568": {Name: "IIS_IUSRS", Type: "Group"},
+ "S-1-5-32-569": {Name: "Cryptographic Operators", Type: "Group"},
+ "S-1-5-32-573": {Name: "Event Log Readers", Type: "Group"},
+ "S-1-5-32-574": {Name: "Certificate Service DCOM Access", Type: "Group"},
+ "S-1-5-32-575": {Name: "RDS Remote Access Servers", Type: "Group"},
+ "S-1-5-32-576": {Name: "RDS Endpoint Servers", Type: "Group"},
+ "S-1-5-32-577": {Name: "RDS Management Servers", Type: "Group"},
+ "S-1-5-32-578": {Name: "Hyper-V Administrators", Type: "Group"},
+ "S-1-5-32-579": {Name: "Access Control Assistance Operators", Type: "Group"},
+ "S-1-5-32-580": {Name: "Remote Management Users", Type: "Group"},
+ "S-1-5-32-582": {Name: "Storage Replica Administrators", Type: "Group"},
+}
+
+func functionalLevelName(level int64) string {
+ switch level {
+ case 0:
+ return "2000 Mixed/Native"
+ case 1:
+ return "2003 Interim"
+ case 2:
+ return "2003"
+ case 3:
+ return "2008"
+ case 4:
+ return "2008 R2"
+ case 5:
+ return "2012"
+ case 6:
+ return "2012 R2"
+ case 7:
+ return "2016"
+ default:
+ if level > 7 {
+ return "2016"
+ }
+ return "Unknown"
+ }
+}
+
+func isHighValueGroupSID(rawSID string, rid uint32) bool {
+ if rid == 512 || rid == 516 || rid == 519 {
+ return true
+ }
+ switch rawSID {
+ case "S-1-5-32-544", "S-1-5-32-548", "S-1-5-32-549", "S-1-5-32-550", "S-1-5-32-551":
+ return true
+ }
+ return false
+}
+
+func filetimeToUnix(ft int64) int64 {
+ if ft <= 0 || ft == 0x7FFFFFFFFFFFFFFF {
+ if ft == 0 {
+ return 0
+ }
+ return -1
+ }
+ const epochDiff = int64(116444736000000000)
+ if ft < epochDiff {
+ return ft
+ }
+ return (ft - epochDiff) / 10000000
+}
+
+func readInt64(row *ordereddict.Dict, col string) (int64, bool) {
+ val, ok := row.Get(col)
+ if !ok || val == nil {
+ return 0, false
+ }
+ switch v := val.(type) {
+ case int64:
+ return v, true
+ case uint64:
+ return int64(v), true
+ case int32:
+ return int64(v), true
+ case uint32:
+ return int64(v), true
+ case int:
+ return int64(v), true
+ case bool:
+ if v {
+ return 1, true
+ }
+ return 0, true
+ }
+ return 0, false
+}
+
+func readUint64(row *ordereddict.Dict, col string) (uint64, bool) {
+ v, ok := readInt64(row, col)
+ if !ok {
+ return 0, false
+ }
+ return uint64(v), true
+}
+
+func readString(row *ordereddict.Dict, col string) string {
+ val, ok := row.Get(col)
+ if !ok || val == nil {
+ return ""
+ }
+ if s, ok := val.(string); ok {
+ return s
+ }
+ return ""
+}
+
+func readOptionalDescription(row *ordereddict.Dict) interface{} {
+ s := readString(row, "ATTm13")
+ if s == "" {
+ return nil
+ }
+ return s
+}
+
+func readStringSlice(row *ordereddict.Dict, col string) []string {
+ val, ok := row.Get(col)
+ if !ok || val == nil {
+ return make([]string, 0)
+ }
+ switch v := val.(type) {
+ case string:
+ if v == "" {
+ return make([]string, 0)
+ }
+ return []string{v}
+ case []string:
+ out := make([]string, 0, len(v))
+ for _, item := range v {
+ if item != "" {
+ out = append(out, item)
+ }
+ }
+ return out
+ case []interface{}:
+ out := make([]string, 0, len(v))
+ for _, item := range v {
+ if s, ok := item.(string); ok && s != "" {
+ out = append(out, s)
+ }
+ }
+ return out
+ }
+ return make([]string, 0)
+}
+
+func readESESIDSlice(row *ordereddict.Dict, col string) []string {
+ rawVals := readStringSlice(row, col)
+ if len(rawVals) == 0 {
+ return nil
+ }
+ var out []string
+ for _, hexStr := range rawVals {
+ if b, err := hex.DecodeString(hexStr); err == nil {
+ if s, _, err := crypto.ParseSID(b); err == nil && s != "" {
+ out = append(out, s)
+ }
+ }
+ }
+ return out
+}
+
+func isRowDeleted(row *ordereddict.Dict, rdn string) bool {
+ if delVal, ok := readInt64(row, "ATTb589872"); ok && delVal != 0 {
+ return true
+ }
+ if strings.Contains(rdn, "\nDEL:") || strings.Contains(rdn, "\\0ADEL:") {
+ return true
+ }
+ return false
+}
+
+func isNonDomainPartitionDN(dnUpper string) bool {
+ if dnUpper == "" {
+ return false
+ }
+ return strings.Contains(dnUpper, "CN=DELETED OBJECTS,") ||
+ strings.Contains(dnUpper, "\nDEL:") ||
+ strings.Contains(dnUpper, "CN=SCHEMA,") ||
+ strings.Contains(dnUpper, "CN=CONFIGURATION,") ||
+ strings.Contains(dnUpper, "DC=DOMAINDNSZONES,") ||
+ strings.Contains(dnUpper, "DC=FORESTDNSZONES,")
+}
+
+func domainFromDN(dn string) string {
+ var dcParts []string
+ for _, part := range strings.Split(dn, ",") {
+ p := strings.TrimSpace(part)
+ if len(p) > 3 && strings.EqualFold(p[:3], "DC=") {
+ comp := p[3:]
+ if strings.EqualFold(comp, "DomainDnsZones") || strings.EqualFold(comp, "ForestDnsZones") {
+ return ""
+ }
+ dcParts = append(dcParts, comp)
+ }
+ }
+ if len(dcParts) == 0 {
+ return ""
+ }
+ return strings.ToUpper(strings.Join(dcParts, "."))
+}
+
+func formatGUIDUpper(b []byte) string {
+ if len(b) < 16 {
+ return ""
+ }
+ return fmt.Sprintf("%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
+ binary.LittleEndian.Uint32(b[0:4]),
+ binary.LittleEndian.Uint16(b[4:6]),
+ binary.LittleEndian.Uint16(b[6:8]),
+ b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15])
+}
+
+func formatGUIDLower(b []byte) string {
+ return strings.ToLower(formatGUIDUpper(b))
+}
+
+func extractTrustFromRow(row *ordereddict.Dict, fallbackName string) (DomainTrust, bool) {
+ partner := readString(row, "ATTm590362")
+ dirVal, hasDir := readInt64(row, "ATTj589956")
+ typeVal, hasType := readInt64(row, "ATTj589960")
+ if partner == "" && (!hasDir || !hasType) {
+ return DomainTrust{}, false
+ }
+ if partner == "" {
+ partner = readString(row, "ATTm590359")
+ }
+ if partner == "" {
+ partner = fallbackName
+ }
+ if partner == "" {
+ return DomainTrust{}, false
+ }
+
+ attrVal, _ := readInt64(row, "ATTj590294")
+ var targetSID string
+ if sidHex := readString(row, "ATTr589953"); sidHex != "" {
+ if sb, err := hex.DecodeString(sidHex); err == nil {
+ if s, _, err := crypto.ParseSID(sb); err == nil {
+ targetSID = s
+ }
+ }
+ }
+
+ nonTransitive := (attrVal & 0x00000001) != 0
+ quarantined := (attrVal & 0x00000004) != 0
+ forestTransitive := (attrVal & 0x00000008) != 0
+ crossOrg := (attrVal & 0x00000010) != 0
+ withinForest := (attrVal & 0x00000020) != 0
+ treatAsExternal := (attrVal & 0x00000040) != 0
+
+ bhType := 4
+ isTransitive := false
+ sidFiltering := true
+
+ if withinForest {
+ bhType = 0
+ isTransitive = true
+ sidFiltering = quarantined
+ } else if forestTransitive {
+ bhType = 2
+ isTransitive = true
+ sidFiltering = !treatAsExternal
+ } else if treatAsExternal || crossOrg || quarantined {
+ bhType = 3
+ isTransitive = false
+ sidFiltering = true
+ } else {
+ if typeVal == 1 || typeVal == 2 {
+ bhType = 3
+ }
+ isTransitive = !nonTransitive
+ sidFiltering = true
+ }
+
+ return DomainTrust{
+ TargetDomainName: strings.ToUpper(partner),
+ TargetDomainSid: targetSID,
+ IsTransitive: isTransitive,
+ TrustDirection: int(dirVal),
+ TrustType: bhType,
+ SidFilteringEnabled: sidFiltering,
+ }, true
+}
diff --git a/pkg/ad/model.go b/pkg/ad/model.go
@@ -0,0 +1,276 @@
+package ad
+
+import "github.com/shehzade/ntds-to-bloodhound/pkg/acl"
+
+type MemberReference struct {
+ ObjectIdentifier string `json:"ObjectIdentifier"`
+ ObjectType string `json:"ObjectType"`
+}
+
+type TypedPrincipal struct {
+ ObjectIdentifier string `json:"ObjectIdentifier"`
+ ObjectType string `json:"ObjectType"`
+}
+
+type SessionCollection struct {
+ Collected bool `json:"Collected"`
+ FailureReason *string `json:"FailureReason"`
+ Results []interface{} `json:"Results"`
+}
+
+func EmptySessionCollection() SessionCollection {
+ return SessionCollection{
+ Collected: false,
+ FailureReason: nil,
+ Results: make([]interface{}, 0),
+ }
+}
+
+type DomainTrust struct {
+ TargetDomainName string
+ TargetDomainSid string
+ IsTransitive bool
+ TrustDirection int
+ TrustType int
+ SidFilteringEnabled bool
+}
+
+type DomainTrustV4 struct {
+ TargetDomainName string `json:"TargetDomainName"`
+ TargetDomainSid string `json:"TargetDomainSid"`
+ IsTransitive bool `json:"IsTransitive"`
+ TrustDirection int `json:"TrustDirection"`
+ TrustType int `json:"TrustType"`
+ SidFilteringEnabled bool `json:"SidFilteringEnabled"`
+}
+
+type DomainTrustV5 struct {
+ TargetDomainName string `json:"TargetDomainName"`
+ TargetDomainSid string `json:"TargetDomainSid"`
+ IsTransitive bool `json:"IsTransitive"`
+ TrustDirection string `json:"TrustDirection"`
+ TrustType string `json:"TrustType"`
+ SidFilteringEnabled bool `json:"SidFilteringEnabled"`
+}
+
+func (t DomainTrust) DirectionString() string {
+ switch t.TrustDirection {
+ case 0:
+ return "Disabled"
+ case 1:
+ return "Inbound"
+ case 2:
+ return "Outbound"
+ case 3:
+ return "Bidirectional"
+ default:
+ return "Disabled"
+ }
+}
+
+func (t DomainTrust) TypeString() string {
+ switch t.TrustType {
+ case 0:
+ return "ParentChild"
+ case 1:
+ return "CrossLink"
+ case 2:
+ return "Forest"
+ case 3:
+ return "External"
+ default:
+ return "Unknown"
+ }
+}
+
+func (t DomainTrust) ToV4() DomainTrustV4 {
+ return DomainTrustV4{
+ TargetDomainName: t.TargetDomainName,
+ TargetDomainSid: t.TargetDomainSid,
+ IsTransitive: t.IsTransitive,
+ TrustDirection: t.TrustDirection,
+ TrustType: t.TrustType,
+ SidFilteringEnabled: t.SidFilteringEnabled,
+ }
+}
+
+func (t DomainTrust) ToV5() DomainTrustV5 {
+ return DomainTrustV5{
+ TargetDomainName: t.TargetDomainName,
+ TargetDomainSid: t.TargetDomainSid,
+ IsTransitive: t.IsTransitive,
+ TrustDirection: t.DirectionString(),
+ TrustType: t.TypeString(),
+ SidFilteringEnabled: t.SidFilteringEnabled,
+ }
+}
+
+type UserObject struct {
+ ObjectIdentifier string `json:"ObjectIdentifier"`
+ PrimaryGroupSID string `json:"PrimaryGroupSID,omitempty"`
+ AllowedToDelegate []TypedPrincipal `json:"AllowedToDelegate"`
+ SPNTargets []interface{} `json:"SPNTargets"`
+ HasSIDHistory []TypedPrincipal `json:"HasSIDHistory"`
+ Aces []acl.Ace `json:"Aces"`
+ IsACLProtected bool `json:"IsACLProtected"`
+ IsDeleted bool `json:"IsDeleted"`
+ Properties map[string]interface{} `json:"Properties"`
+ DNT uint64 `json:"-"`
+ PDNT uint64 `json:"-"`
+ NTHash string `json:"-"`
+ LMHash string `json:"-"`
+ RawDelegateTargets []string `json:"-"`
+ RawSIDHistory []string `json:"-"`
+}
+
+type GroupObject struct {
+ ObjectIdentifier string `json:"ObjectIdentifier"`
+ Members []MemberReference `json:"Members"`
+ Aces []acl.Ace `json:"Aces"`
+ IsACLProtected bool `json:"IsACLProtected"`
+ IsDeleted bool `json:"IsDeleted"`
+ Properties map[string]interface{} `json:"Properties"`
+ DNT uint64 `json:"-"`
+ PDNT uint64 `json:"-"`
+ Synthetic bool `json:"-"`
+}
+
+type ComputerObject struct {
+ ObjectIdentifier string `json:"ObjectIdentifier"`
+ PrimaryGroupSID string `json:"PrimaryGroupSID,omitempty"`
+ AllowedToDelegate []TypedPrincipal `json:"AllowedToDelegate"`
+ AllowedToAct []TypedPrincipal `json:"AllowedToAct"`
+ HasSIDHistory []TypedPrincipal `json:"HasSIDHistory"`
+ DumpSMSAPassword []TypedPrincipal `json:"DumpSMSAPassword"`
+ Sessions SessionCollection `json:"Sessions"`
+ PrivilegedSessions SessionCollection `json:"PrivilegedSessions"`
+ RegistrySessions SessionCollection `json:"RegistrySessions"`
+ LocalGroups []interface{} `json:"LocalGroups"`
+ UserRights []interface{} `json:"UserRights"`
+ Aces []acl.Ace `json:"Aces"`
+ IsACLProtected bool `json:"IsACLProtected"`
+ IsDeleted bool `json:"IsDeleted"`
+ IsDC bool `json:"IsDC"`
+ Status *string `json:"Status"`
+ Properties map[string]interface{} `json:"Properties"`
+ NTHash string `json:"-"`
+ LMHash string `json:"-"`
+ DNT uint64 `json:"-"`
+ PDNT uint64 `json:"-"`
+ RawDelegateTargets []string `json:"-"`
+ RawAllowedToAct []string `json:"-"`
+ RawSIDHistory []string `json:"-"`
+}
+
+type DomainObject struct {
+ ObjectIdentifier string `json:"ObjectIdentifier"`
+ ChildObjects []TypedPrincipal `json:"ChildObjects"`
+ Trusts []DomainTrust `json:"Trusts"`
+ Links []interface{} `json:"Links"`
+ Aces []acl.Ace `json:"Aces"`
+ IsACLProtected bool `json:"IsACLProtected"`
+ IsDeleted bool `json:"IsDeleted"`
+ Properties map[string]interface{} `json:"Properties"`
+ DNT uint64 `json:"-"`
+}
+
+type DomainObjectV4 struct {
+ ObjectIdentifier string `json:"ObjectIdentifier"`
+ ChildObjects []TypedPrincipal `json:"ChildObjects"`
+ Trusts []DomainTrustV4 `json:"Trusts"`
+ Links []interface{} `json:"Links"`
+ Aces []acl.Ace `json:"Aces"`
+ IsACLProtected bool `json:"IsACLProtected"`
+ IsDeleted bool `json:"IsDeleted"`
+ Properties map[string]interface{} `json:"Properties"`
+}
+
+type DomainObjectV5 struct {
+ ObjectIdentifier string `json:"ObjectIdentifier"`
+ ChildObjects []TypedPrincipal `json:"ChildObjects"`
+ Trusts []DomainTrustV5 `json:"Trusts"`
+ Links []interface{} `json:"Links"`
+ Aces []acl.Ace `json:"Aces"`
+ IsACLProtected bool `json:"IsACLProtected"`
+ IsDeleted bool `json:"IsDeleted"`
+ Properties map[string]interface{} `json:"Properties"`
+}
+
+func (d *DomainObject) ToV4() DomainObjectV4 {
+ trusts := make([]DomainTrustV4, len(d.Trusts))
+ for i, t := range d.Trusts {
+ trusts[i] = t.ToV4()
+ }
+ return DomainObjectV4{
+ ObjectIdentifier: d.ObjectIdentifier,
+ ChildObjects: d.ChildObjects,
+ Trusts: trusts,
+ Links: d.Links,
+ Aces: d.Aces,
+ IsACLProtected: d.IsACLProtected,
+ IsDeleted: d.IsDeleted,
+ Properties: d.Properties,
+ }
+}
+
+func (d *DomainObject) ToV5() DomainObjectV5 {
+ trusts := make([]DomainTrustV5, len(d.Trusts))
+ for i, t := range d.Trusts {
+ trusts[i] = t.ToV5()
+ }
+ return DomainObjectV5{
+ ObjectIdentifier: d.ObjectIdentifier,
+ ChildObjects: d.ChildObjects,
+ Trusts: trusts,
+ Links: d.Links,
+ Aces: d.Aces,
+ IsACLProtected: d.IsACLProtected,
+ IsDeleted: d.IsDeleted,
+ Properties: d.Properties,
+ }
+}
+
+type OUObject struct {
+ ObjectIdentifier string `json:"ObjectIdentifier"`
+ ChildObjects []TypedPrincipal `json:"ChildObjects"`
+ Links []interface{} `json:"Links"`
+ Aces []acl.Ace `json:"Aces"`
+ IsACLProtected bool `json:"IsACLProtected"`
+ IsDeleted bool `json:"IsDeleted"`
+ Properties map[string]interface{} `json:"Properties"`
+ DNT uint64 `json:"-"`
+ PDNT uint64 `json:"-"`
+}
+
+type ADSnapshot struct {
+ DomainName string
+ DomainSID string
+ Users []*UserObject
+ Groups []*GroupObject
+ Computers []*ComputerObject
+ Domains []*DomainObject
+ OUs []*OUObject
+
+ UsersBySID map[string]*UserObject
+ GroupsBySID map[string]*GroupObject
+ ComputersBySID map[string]*ComputerObject
+ OUsByGUID map[string]*OUObject
+ ObjectsByDNT map[uint64]TypedPrincipal
+ PDNTByDNT map[uint64]uint64
+}
+
+func NewADSnapshot() *ADSnapshot {
+ return &ADSnapshot{
+ Users: make([]*UserObject, 0),
+ Groups: make([]*GroupObject, 0),
+ Computers: make([]*ComputerObject, 0),
+ Domains: make([]*DomainObject, 0),
+ OUs: make([]*OUObject, 0),
+ UsersBySID: make(map[string]*UserObject),
+ GroupsBySID: make(map[string]*GroupObject),
+ ComputersBySID: make(map[string]*ComputerObject),
+ OUsByGUID: make(map[string]*OUObject),
+ ObjectsByDNT: make(map[uint64]TypedPrincipal),
+ PDNTByDNT: make(map[uint64]uint64),
+ }
+}
diff --git a/pkg/ad/tree.go b/pkg/ad/tree.go
@@ -0,0 +1,68 @@
+package ad
+
+import (
+ "fmt"
+ "strings"
+)
+
+type TreeNode struct {
+ DNT uint64
+ PDNT uint64
+ RDN string
+ Prefix string
+}
+
+type Tree struct {
+ nodes map[uint64]*TreeNode
+}
+
+func NewTree() *Tree {
+ return &Tree{
+ nodes: make(map[uint64]*TreeNode),
+ }
+}
+
+func (t *Tree) AddNode(dnt, pdnt uint64, rdn, prefix string) {
+ if prefix == "" {
+ prefix = "CN="
+ }
+ t.nodes[dnt] = &TreeNode{
+ DNT: dnt,
+ PDNT: pdnt,
+ RDN: rdn,
+ Prefix: prefix,
+ }
+}
+
+func (t *Tree) GetRDN(dnt uint64) string {
+ if n, ok := t.nodes[dnt]; ok {
+ return n.RDN
+ }
+ return ""
+}
+
+func (t *Tree) ResolveDN(startDNT uint64) string {
+ curr := startDNT
+ var parts []string
+ visited := make(map[uint64]bool)
+
+ for curr != 0 && curr != 2 {
+ if visited[curr] {
+ break
+ }
+ visited[curr] = true
+
+ node, exists := t.nodes[curr]
+ if !exists || node.RDN == "" {
+ break
+ }
+
+ parts = append(parts, fmt.Sprintf("%s%s", node.Prefix, node.RDN))
+ if node.PDNT == 0 || node.PDNT == curr {
+ break
+ }
+ curr = node.PDNT
+ }
+
+ return strings.Join(parts, ",")
+}
diff --git a/pkg/bloodhound/types.go b/pkg/bloodhound/types.go
@@ -0,0 +1,20 @@
+package bloodhound
+
+type Meta struct {
+ Methods int `json:"methods"`
+ Type string `json:"type"`
+ Count int `json:"count"`
+ Version int `json:"version"`
+}
+
+type Container struct {
+ Data []interface{} `json:"data"`
+ Meta Meta `json:"meta"`
+}
+
+type FormatVersion int
+
+const (
+ Version4 FormatVersion = 4
+ Version5 FormatVersion = 5
+)
diff --git a/pkg/bloodhound/v4/writer.go b/pkg/bloodhound/v4/writer.go
@@ -0,0 +1,91 @@
+package v4
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/shehzade/ntds-to-bloodhound/pkg/ad"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/bloodhound"
+)
+
+type Writer struct {
+ outDir string
+}
+
+func NewWriter(outDir string) *Writer {
+ return &Writer{outDir: outDir}
+}
+
+func (w *Writer) WriteSnapshot(snap *ad.ADSnapshot) error {
+ if err := os.MkdirAll(w.outDir, 0755); err != nil {
+ return fmt.Errorf("failed to create output directory %s: %w", w.outDir, err)
+ }
+
+ usersData := make([]interface{}, len(snap.Users))
+ for i, u := range snap.Users {
+ usersData[i] = u
+ }
+ if err := w.writeFile("users.json", "users", usersData); err != nil {
+ return err
+ }
+
+ groupsData := make([]interface{}, len(snap.Groups))
+ for i, g := range snap.Groups {
+ groupsData[i] = g
+ }
+ if err := w.writeFile("groups.json", "groups", groupsData); err != nil {
+ return err
+ }
+
+ computersData := make([]interface{}, len(snap.Computers))
+ for i, c := range snap.Computers {
+ computersData[i] = c
+ }
+ if err := w.writeFile("computers.json", "computers", computersData); err != nil {
+ return err
+ }
+
+ domainsData := make([]interface{}, len(snap.Domains))
+ for i, d := range snap.Domains {
+ domainsData[i] = d.ToV4()
+ }
+ if err := w.writeFile("domains.json", "domains", domainsData); err != nil {
+ return err
+ }
+
+ ousData := make([]interface{}, len(snap.OUs))
+ for i, o := range snap.OUs {
+ ousData[i] = o
+ }
+ if err := w.writeFile("ous.json", "ous", ousData); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (w *Writer) writeFile(filename, objType string, data []interface{}) error {
+ container := bloodhound.Container{
+ Data: data,
+ Meta: bloodhound.Meta{
+ Methods: 0,
+ Type: objType,
+ Count: len(data),
+ Version: 4,
+ },
+ }
+
+ bytes, err := json.MarshalIndent(container, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal %s: %w", filename, err)
+ }
+
+ filePath := filepath.Join(w.outDir, filename)
+ if err := os.WriteFile(filePath, bytes, 0644); err != nil {
+ return fmt.Errorf("failed to write %s: %w", filePath, err)
+ }
+
+ return nil
+}
diff --git a/pkg/bloodhound/v5/writer.go b/pkg/bloodhound/v5/writer.go
@@ -0,0 +1,91 @@
+package v5
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/shehzade/ntds-to-bloodhound/pkg/ad"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/bloodhound"
+)
+
+type Writer struct {
+ outDir string
+}
+
+func NewWriter(outDir string) *Writer {
+ return &Writer{outDir: outDir}
+}
+
+func (w *Writer) WriteSnapshot(snap *ad.ADSnapshot) error {
+ if err := os.MkdirAll(w.outDir, 0755); err != nil {
+ return fmt.Errorf("failed to create output directory %s: %w", w.outDir, err)
+ }
+
+ usersData := make([]interface{}, len(snap.Users))
+ for i, u := range snap.Users {
+ usersData[i] = u
+ }
+ if err := w.writeFile("users.json", "users", usersData); err != nil {
+ return err
+ }
+
+ groupsData := make([]interface{}, len(snap.Groups))
+ for i, g := range snap.Groups {
+ groupsData[i] = g
+ }
+ if err := w.writeFile("groups.json", "groups", groupsData); err != nil {
+ return err
+ }
+
+ computersData := make([]interface{}, len(snap.Computers))
+ for i, c := range snap.Computers {
+ computersData[i] = c
+ }
+ if err := w.writeFile("computers.json", "computers", computersData); err != nil {
+ return err
+ }
+
+ domainsData := make([]interface{}, len(snap.Domains))
+ for i, d := range snap.Domains {
+ domainsData[i] = d.ToV5()
+ }
+ if err := w.writeFile("domains.json", "domains", domainsData); err != nil {
+ return err
+ }
+
+ ousData := make([]interface{}, len(snap.OUs))
+ for i, o := range snap.OUs {
+ ousData[i] = o
+ }
+ if err := w.writeFile("ous.json", "ous", ousData); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (w *Writer) writeFile(filename, objType string, data []interface{}) error {
+ container := bloodhound.Container{
+ Data: data,
+ Meta: bloodhound.Meta{
+ Methods: 0,
+ Type: objType,
+ Count: len(data),
+ Version: 5,
+ },
+ }
+
+ bytes, err := json.MarshalIndent(container, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal %s: %w", filename, err)
+ }
+
+ filePath := filepath.Join(w.outDir, filename)
+ if err := os.WriteFile(filePath, bytes, 0644); err != nil {
+ return fmt.Errorf("failed to write %s: %w", filePath, err)
+ }
+
+ return nil
+}
diff --git a/pkg/bloodhound/v5/zip.go b/pkg/bloodhound/v5/zip.go
@@ -0,0 +1,104 @@
+package v5
+
+import (
+ "archive/zip"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/shehzade/ntds-to-bloodhound/pkg/ad"
+ "github.com/shehzade/ntds-to-bloodhound/pkg/bloodhound"
+)
+
+func GenerateZipFilename() string {
+ now := time.Now().UTC()
+ return fmt.Sprintf("BloodHound_%s.zip", now.Format("20060102150405"))
+}
+
+func CreateZipArchive(snap *ad.ADSnapshot, targetZipPath string) error {
+ dir := filepath.Dir(targetZipPath)
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return fmt.Errorf("failed to create directory %s: %w", dir, err)
+ }
+
+ zipFile, err := os.Create(targetZipPath)
+ if err != nil {
+ return fmt.Errorf("failed to create zip file %s: %w", targetZipPath, err)
+ }
+ defer zipFile.Close()
+
+ zipWriter := zip.NewWriter(zipFile)
+ defer zipWriter.Close()
+
+ writeEntry := func(filename, objType string, data []interface{}) error {
+ container := bloodhound.Container{
+ Data: data,
+ Meta: bloodhound.Meta{
+ Methods: 0,
+ Type: objType,
+ Count: len(data),
+ Version: 5,
+ },
+ }
+
+ bytes, err := json.MarshalIndent(container, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal %s: %w", filename, err)
+ }
+
+ w, err := zipWriter.Create(filename)
+ if err != nil {
+ return fmt.Errorf("failed to create zip entry %s: %w", filename, err)
+ }
+
+ if _, err := w.Write(bytes); err != nil {
+ return fmt.Errorf("failed to write zip entry %s: %w", filename, err)
+ }
+
+ return nil
+ }
+
+ usersData := make([]interface{}, len(snap.Users))
+ for i, u := range snap.Users {
+ usersData[i] = u
+ }
+ if err := writeEntry("users.json", "users", usersData); err != nil {
+ return err
+ }
+
+ groupsData := make([]interface{}, len(snap.Groups))
+ for i, g := range snap.Groups {
+ groupsData[i] = g
+ }
+ if err := writeEntry("groups.json", "groups", groupsData); err != nil {
+ return err
+ }
+
+ computersData := make([]interface{}, len(snap.Computers))
+ for i, c := range snap.Computers {
+ computersData[i] = c
+ }
+ if err := writeEntry("computers.json", "computers", computersData); err != nil {
+ return err
+ }
+
+ domainsData := make([]interface{}, len(snap.Domains))
+ for i, d := range snap.Domains {
+ domainsData[i] = d.ToV5()
+ }
+ if err := writeEntry("domains.json", "domains", domainsData); err != nil {
+ return err
+ }
+
+ ousData := make([]interface{}, len(snap.OUs))
+ for i, o := range snap.OUs {
+ ousData[i] = o
+ }
+ if err := writeEntry("ous.json", "ous", ousData); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/pkg/crypto/crypto.go b/pkg/crypto/crypto.go
@@ -0,0 +1,269 @@
+package crypto
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/des"
+ "crypto/md5"
+ "crypto/rc4"
+ "encoding/binary"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "strings"
+)
+
+const (
+ EmptyLMHash = "aad3b435b51404eeaad3b435b51404ee"
+ EmptyNTHash = "31d6cfe0d16ae931b73c59d7e0c089c0"
+)
+
+type CryptoEngine struct {
+ BootKey []byte
+ PEKList [][]byte
+}
+
+func NewCryptoEngine(bootKey []byte) *CryptoEngine {
+ return &CryptoEngine{
+ BootKey: bootKey,
+ PEKList: make([][]byte, 0),
+ }
+}
+
+func (c *CryptoEngine) ParsePekList(pekListRaw []byte) error {
+ if len(pekListRaw) < 24 {
+ return errors.New("pekList blob too short")
+ }
+
+ header := pekListRaw[:8]
+ keyMaterial := pekListRaw[8:24]
+ encryptedPek := pekListRaw[24:]
+
+ var decryptedPekList []byte
+
+ if binary.LittleEndian.Uint32(header[:4]) == 0x02 {
+ h := md5.New()
+ h.Write(c.BootKey)
+ for i := 0; i < 1000; i++ {
+ h.Write(keyMaterial)
+ }
+ tmpKey := h.Sum(nil)
+ rc4Cipher, err := rc4.NewCipher(tmpKey)
+ if err != nil {
+ return fmt.Errorf("failed to create RC4 cipher for PEK: %w", err)
+ }
+ decryptedPekList = make([]byte, len(encryptedPek))
+ rc4Cipher.XORKeyStream(decryptedPekList, encryptedPek)
+ } else if binary.LittleEndian.Uint32(header[:4]) == 0x03 {
+ block, err := aes.NewCipher(c.BootKey)
+ if err != nil {
+ return fmt.Errorf("failed to create AES cipher for PEK: %w", err)
+ }
+ if len(encryptedPek)%aes.BlockSize != 0 {
+ return fmt.Errorf("encrypted PEK size %d is not a multiple of block size", len(encryptedPek))
+ }
+ mode := cipher.NewCBCDecrypter(block, keyMaterial)
+ decryptedPekList = make([]byte, len(encryptedPek))
+ mode.CryptBlocks(decryptedPekList, encryptedPek)
+ } else {
+ return fmt.Errorf("unsupported PEK header version: %x", header[:4])
+ }
+
+ if len(decryptedPekList) < 32 {
+ return errors.New("decrypted PEK list too short")
+ }
+
+ plainEntries := decryptedPekList[32:]
+ pos := 0
+ curIndex := uint32(0)
+
+ for pos+20 <= len(plainEntries) {
+ index := binary.LittleEndian.Uint32(plainEntries[pos : pos+4])
+ pekKey := make([]byte, 16)
+ copy(pekKey, plainEntries[pos+4:pos+20])
+
+ if index != curIndex {
+ break
+ }
+ c.PEKList = append(c.PEKList, pekKey)
+ curIndex++
+ pos += 20
+ }
+
+ if len(c.PEKList) == 0 {
+ return errors.New("no valid PEK keys found in pekList")
+ }
+
+ return nil
+}
+
+func transformKey(in []byte) []byte {
+ out := make([]byte, 8)
+ out[0] = in[0] >> 1
+ out[1] = ((in[0] & 0x01) << 6) | (in[1] >> 2)
+ out[2] = ((in[1] & 0x03) << 5) | (in[2] >> 3)
+ out[3] = ((in[2] & 0x07) << 4) | (in[3] >> 4)
+ out[4] = ((in[3] & 0x0F) << 3) | (in[4] >> 5)
+ out[5] = ((in[4] & 0x1F) << 2) | (in[5] >> 6)
+ out[6] = ((in[5] & 0x3F) << 1) | (in[6] >> 7)
+ out[7] = in[6] & 0x7F
+
+ for i := 0; i < 8; i++ {
+ out[i] = (out[i] << 1) & 0xFE
+ }
+ return out
+}
+
+func deriveDesKeys(rid uint32) ([]byte, []byte) {
+ ridBytes := make([]byte, 4)
+ binary.LittleEndian.PutUint32(ridBytes, rid)
+
+ k1 := []byte{ridBytes[0], ridBytes[1], ridBytes[2], ridBytes[3], ridBytes[0], ridBytes[1], ridBytes[2]}
+ k2 := []byte{ridBytes[3], ridBytes[0], ridBytes[1], ridBytes[2], ridBytes[3], ridBytes[0], ridBytes[1]}
+
+ return transformKey(k1), transformKey(k2)
+}
+
+func removeDESLayer(crypted []byte, rid uint32) ([]byte, error) {
+ if len(crypted) < 16 {
+ return nil, errors.New("crypted hash must be at least 16 bytes")
+ }
+
+ k1, k2 := deriveDesKeys(rid)
+ c1, err := des.NewCipher(k1)
+ if err != nil {
+ return nil, err
+ }
+ c2, err := des.NewCipher(k2)
+ if err != nil {
+ return nil, err
+ }
+
+ out := make([]byte, 16)
+ c1.Decrypt(out[:8], crypted[:8])
+ c2.Decrypt(out[8:16], crypted[8:16])
+ return out, nil
+}
+
+func (c *CryptoEngine) DecryptHash(encBlob []byte, rid uint32) ([]byte, error) {
+ if len(c.PEKList) == 0 {
+ return nil, errors.New("no PEK keys loaded")
+ }
+ if len(encBlob) < 24 {
+ return nil, errors.New("encrypted hash blob too short")
+ }
+
+ header := encBlob[:8]
+ keyMaterial := encBlob[8:24]
+
+ pekIndexHex := hex.EncodeToString(header)
+ if len(pekIndexHex) < 10 {
+ return nil, errors.New("invalid header format")
+ }
+ pekIndex := int(header[4])
+ if pekIndex >= len(c.PEKList) {
+ pekIndex = 0
+ }
+ pek := c.PEKList[pekIndex]
+
+ var tmpHash []byte
+
+ if binary.LittleEndian.Uint32(header[:4]) == 0x13 {
+ if len(encBlob) < 28+16 {
+ return nil, errors.New("AES hash blob too short")
+ }
+ ciphertext := encBlob[28 : 28+16]
+
+ block, err := aes.NewCipher(pek)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create AES cipher: %w", err)
+ }
+ mode := cipher.NewCBCDecrypter(block, keyMaterial)
+ tmpHash = make([]byte, 16)
+ mode.CryptBlocks(tmpHash, ciphertext)
+ } else {
+ if len(encBlob) < 24+16 {
+ return nil, errors.New("RC4 hash blob too short")
+ }
+ ciphertext := encBlob[24 : 24+16]
+
+ h := md5.New()
+ h.Write(pek)
+ h.Write(keyMaterial)
+ tmpKey := h.Sum(nil)
+
+ rc4Cipher, err := rc4.NewCipher(tmpKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create RC4 cipher: %w", err)
+ }
+ tmpHash = make([]byte, 16)
+ rc4Cipher.XORKeyStream(tmpHash, ciphertext)
+ }
+
+ return removeDESLayer(tmpHash, rid)
+}
+
+func ParseSID(b []byte) (string, uint32, error) {
+ if len(b) < 8 {
+ return "", 0, errors.New("SID buffer too short")
+ }
+
+ revision := b[0]
+ subAuthCount := int(b[1])
+ if len(b) < 8+subAuthCount*4 {
+ return "", 0, errors.New("SID buffer truncated for subauthorities")
+ }
+
+ var authority uint64
+ for i := 2; i < 8; i++ {
+ authority = (authority << 8) | uint64(b[i])
+ }
+
+ parts := []string{fmt.Sprintf("S-%d-%d", revision, authority)}
+ var rid uint32
+
+ for i := 0; i < subAuthCount; i++ {
+ offset := 8 + i*4
+ var subAuth uint32
+ if i == subAuthCount-1 && subAuthCount > 1 {
+ subAuth = binary.BigEndian.Uint32(b[offset : offset+4])
+ rid = subAuth
+ } else {
+ subAuth = binary.LittleEndian.Uint32(b[offset : offset+4])
+ }
+ parts = append(parts, fmt.Sprintf("%d", subAuth))
+ }
+
+ return strings.Join(parts, "-"), rid, nil
+}
+
+func ParseBinarySID(b []byte) (string, uint32, error) {
+ if len(b) < 8 {
+ return "", 0, errors.New("SID buffer too short")
+ }
+
+ revision := b[0]
+ subAuthCount := int(b[1])
+ if revision != 1 || subAuthCount > 15 || len(b) < 8+subAuthCount*4 {
+ return "", 0, errors.New("SID buffer invalid or truncated")
+ }
+
+ var authority uint64
+ for i := 2; i < 8; i++ {
+ authority = (authority << 8) | uint64(b[i])
+ }
+
+ parts := []string{fmt.Sprintf("S-%d-%d", revision, authority)}
+ var rid uint32
+
+ for i := 0; i < subAuthCount; i++ {
+ offset := 8 + i*4
+ subAuth := binary.LittleEndian.Uint32(b[offset : offset+4])
+ if i == subAuthCount-1 {
+ rid = subAuth
+ }
+ parts = append(parts, fmt.Sprintf("%d", subAuth))
+ }
+
+ return strings.Join(parts, "-"), rid, nil
+}
diff --git a/pkg/ese/db.go b/pkg/ese/db.go
@@ -0,0 +1,66 @@
+package ese
+
+import (
+ "fmt"
+ "io"
+ "os"
+
+ "github.com/Velocidex/ordereddict"
+ "www.velocidex.com/golang/go-ese/parser"
+)
+
+type DB struct {
+ file *os.File
+ ctx *parser.ESEContext
+ catalog *parser.Catalog
+}
+
+func OpenDB(path string) (*DB, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open ESE file %s: %w", path, err)
+ }
+
+ ctx, err := parser.NewESEContext(f)
+ if err != nil {
+ f.Close()
+ return nil, fmt.Errorf("failed to initialize ESE context: %w", err)
+ }
+
+ catalog, err := parser.ReadCatalog(ctx)
+ if err != nil {
+ f.Close()
+ return nil, fmt.Errorf("failed to read ESE catalog: %w", err)
+ }
+
+ return &DB{
+ file: f,
+ ctx: ctx,
+ catalog: catalog,
+ }, nil
+}
+
+func (db *DB) Close() error {
+ if db.file != nil {
+ return db.file.Close()
+ }
+ return nil
+}
+
+func (db *DB) TableNames() []string {
+ if db.catalog == nil || db.catalog.Tables == nil {
+ return nil
+ }
+ return db.catalog.Tables.Keys()
+}
+
+func (db *DB) StreamTable(name string, cb func(row *ordereddict.Dict) error) error {
+ if db.catalog == nil {
+ return fmt.Errorf("database catalog is nil")
+ }
+ return db.catalog.DumpTable(name, cb)
+}
+
+func (db *DB) Reader() io.ReaderAt {
+ return db.file
+}
diff --git a/pkg/registry/bootkey.go b/pkg/registry/bootkey.go
@@ -0,0 +1,96 @@
+package registry
+
+import (
+ "encoding/binary"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "os"
+
+ "www.velocidex.com/golang/regparser"
+)
+
+var transforms = [16]int{8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7}
+
+func ExtractBootKey(systemHivePath string) ([]byte, error) {
+ f, err := os.Open(systemHivePath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open SYSTEM hive: %w", err)
+ }
+ defer f.Close()
+
+ return ExtractBootKeyFromReader(f)
+}
+
+func ExtractBootKeyFromReader(reader io.ReaderAt) ([]byte, error) {
+ reg, err := regparser.NewRegistry(reader)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse registry hive: %w", err)
+ }
+
+ controlSet := "ControlSet001"
+ selectNode := reg.OpenKey("Select")
+ if selectNode != nil {
+ var currentCS, defaultCS uint32
+ for _, v := range selectNode.Values() {
+ vd := v.ValueData()
+ if len(vd.Data) >= 4 {
+ switch v.ValueName() {
+ case "Current":
+ currentCS = binary.LittleEndian.Uint32(vd.Data)
+ case "Default":
+ defaultCS = binary.LittleEndian.Uint32(vd.Data)
+ }
+ }
+ }
+ if currentCS > 0 {
+ controlSet = fmt.Sprintf("ControlSet%03d", currentCS)
+ } else if defaultCS > 0 {
+ controlSet = fmt.Sprintf("ControlSet%03d", defaultCS)
+ }
+ }
+
+ var rawHex string
+ subkeys := []string{"JD", "Skew1", "GBG", "Data"}
+ for _, key := range subkeys {
+ path := fmt.Sprintf("%s\\Control\\Lsa\\%s", controlSet, key)
+ node := reg.OpenKey(path)
+ if node == nil {
+ return nil, fmt.Errorf("required LSA subkey not found: %s", path)
+ }
+
+ classOffset := node.Class()
+ classLen := node.ClassLength()
+ if classLen < 16 {
+ return nil, fmt.Errorf("invalid class length for subkey %s: %d", key, classLen)
+ }
+
+ buf := make([]byte, 16)
+ fileOffset := 0x1000 + int64(classOffset) + 4
+ if _, err := reader.ReadAt(buf, fileOffset); err != nil {
+ return nil, fmt.Errorf("failed to read class data for %s: %w", key, err)
+ }
+
+ var chars []rune
+ for i := 0; i < 16; i += 2 {
+ chars = append(chars, rune(binary.LittleEndian.Uint16(buf[i:i+2])))
+ }
+ rawHex += string(chars)
+ }
+
+ rawBytes, err := hex.DecodeString(rawHex)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode hex class data: %w", err)
+ }
+
+ if len(rawBytes) != 16 {
+ return nil, fmt.Errorf("expected 16 raw key bytes, got %d", len(rawBytes))
+ }
+
+ bootKey := make([]byte, 16)
+ for i := 0; i < 16; i++ {
+ bootKey[i] = rawBytes[transforms[i]]
+ }
+
+ return bootKey, nil
+}