● Notice //GitHub (@shehzade) is temporarily suspended pending an automated false-positive review. All tools are hosted on this Code Mirror and available on request (contact); GitHub links will return once reinstated.
PUBLIC MIRRORGo v1.0.0

Offline Active Directory database (ntds.dit) parser and BloodHound graph reconstructor in pure Go. Extracts directory objects, group memberships, domain trusts, and binary DACLs from dead-disk ESE database pages and registry hives.

$ git clone https://shehzade.io/repos/ntds-to-bloodhound.git Copy
Source ZIP (246.9 KB) Prebuilt Binaries
Code 21 Commits 1 Releases 5
feat: offline Active Directory ntds.dit parser and BloodHound graph reconstructor
Abdullah Ansari · 2026-11-11 23:27 · e46b0aa8f699de4d76a847c378acc12da5c65c7a
+3721 -0 ← All Commits
.gitignore
......@@ -0,0 +1,44 @@
1+# Binaries and build artifacts
2+bin/
3+dist/
4+ntds-to-bloodhound
5+ntds-to-bloodhound-*
6+*.exe
7+*.dll
8+*.so
9+*.dylib
10+
11+# Test outputs and BloodHound JSON/ZIP files
12+output/
13+output-*/
14+BloodHound_*.zip
15+*.json.gz
16+
17+# Sensitive Active Directory databases and hives (CRITICAL)
18+*.dit
19+*.DIT
20+ntds.dit
21+SYSTEM
22+SYSTEM.*
23+SAM
24+SECURITY
25+*.hiv
26+*.hive
27+
28+# Ground truth & dumped credentials
29+ground-truth.txt
30+expected_hashes.txt
31+*.hashes
32+*.ntds
33+*.secrets
34+
35+# OS and IDE files
36+.DS_Store
37+.vscode/
38+.idea/
39+*.swp
40+*~
41+hashes.txt
42+test-run/
43+*.log
44+*.json
LICENSE
......@@ -0,0 +1,201 @@
1+ Apache License
2+ Version 2.0, January 2004
3+ http://www.apache.org/licenses/
4+
5+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6+
7+ 1. Definitions.
8+
9+ "License" shall mean the terms and conditions for use, reproduction,
10+ and distribution as defined by Sections 1 through 9 of this document.
11+
12+ "Licensor" shall mean the copyright owner or entity authorized by
13+ the copyright owner that is granting the License.
14+
15+ "Legal Entity" shall mean the union of the acting entity and all
16+ other entities that control, are controlled by, or are under common
17+ control with that entity. For the purposes of this definition,
18+ "control" means (i) the power, direct or indirect, to cause the
19+ direction or management of such entity, whether by contract or
20+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21+ outstanding shares, or (iii) beneficial ownership of such entity.
22+
23+ "You" (or "Your") shall mean an individual or Legal Entity
24+ exercising permissions granted by this License.
25+
26+ "Source" form shall mean the preferred form for making modifications,
27+ including but not limited to software source code, documentation
28+ source, and configuration files.
29+
30+ "Object" form shall mean any form resulting from mechanical
31+ transformation or translation of a Source form, including but
32+ not limited to compiled object code, generated documentation,
33+ and conversions to other media types.
34+
35+ "Work" shall mean the work of authorship, whether in Source or
36+ Object form, made available under the License, as indicated by a
37+ copyright notice that is included in or attached to the work
38+ (an example is provided in the Appendix below).
39+
40+ "Derivative Works" shall mean any work, whether in Source or Object
41+ form, that is based on (or derived from) the Work and for which the
42+ editorial revisions, annotations, elaborations, or other modifications
43+ represent, as a whole, an original work of authorship. For the purposes
44+ of this License, Derivative Works shall not include works that remain
45+ separable from, or merely link (or bind by name) to the interfaces of,
46+ the Work and Derivative Works thereof.
47+
48+ "Contribution" shall mean any work of authorship, including
49+ the original version of the Work and any modifications or additions
50+ to that Work or Derivative Works thereof, that is intentionally
51+ submitted to Licensor for inclusion in the Work by the copyright owner
52+ or by an individual or Legal Entity authorized to submit on behalf of
53+ the copyright owner. For the purposes of this definition, "submitted"
54+ means any form of electronic, verbal, or written communication sent
55+ to the Licensor or its representatives, including but not limited to
56+ communication on electronic mailing lists, source code control systems,
57+ and issue tracking systems that are managed by, or on behalf of, the
58+ Licensor for the purpose of discussing and improving the Work, but
59+ excluding communication that is conspicuously marked or otherwise
60+ designated in writing by the copyright owner as "Not a Contribution."
61+
62+ "Contributor" shall mean Licensor and any individual or Legal Entity
63+ on behalf of whom a Contribution has been received by Licensor and
64+ subsequently incorporated within the Work.
65+
66+ 2. Grant of Copyright License. Subject to the terms and conditions of
67+ this License, each Contributor hereby grants to You a perpetual,
68+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69+ copyright license to reproduce, prepare Derivative Works of,
70+ publicly display, publicly perform, sublicense, and distribute the
71+ Work and such Derivative Works in Source or Object form.
72+
73+ 3. Grant of Patent License. Subject to the terms and conditions of
74+ this License, each Contributor hereby grants to You a perpetual,
75+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76+ (except as stated in this section) patent license to make, have made,
77+ use, offer to sell, sell, import, and otherwise transfer the Work,
78+ where such license applies only to those patent claims licensable
79+ by such Contributor that are necessarily infringed by their
80+ Contribution(s) alone or by combination of their Contribution(s)
81+ with the Work to which such Contribution(s) was submitted. If You
82+ institute patent litigation against any entity (including a
83+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84+ or a Contribution incorporated within the Work constitutes direct
85+ or contributory patent infringement, then any patent licenses
86+ granted to You under this License for that Work shall terminate
87+ as of the date such litigation is filed.
88+
89+ 4. Redistribution. You may reproduce and distribute copies of the
90+ Work or Derivative Works thereof in any medium, with or without
91+ modifications, and in Source or Object form, provided that You
92+ meet the following conditions:
93+
94+ (a) You must give any other recipients of the Work or
95+ Derivative Works a copy of this License; and
96+
97+ (b) You must cause any modified files to carry prominent notices
98+ stating that You changed the files; and
99+
100+ (c) You must retain, in the Source form of any Derivative Works
101+ that You distribute, all copyright, patent, trademark, and
102+ attribution notices from the Source form of the Work,
103+ excluding those notices that do not pertain to any part of
104+ the Derivative Works; and
105+
106+ (d) If the Work includes a "NOTICE" text file as part of its
107+ distribution, then any Derivative Works that You distribute must
108+ include a readable copy of the attribution notices contained
109+ within such NOTICE file, excluding those notices that do not
110+ pertain to any part of the Derivative Works, in at least one
111+ of the following places: within a NOTICE text file distributed
112+ as part of the Derivative Works; within the Source form or
113+ documentation, if provided along with the Derivative Works; or,
114+ within a display generated by the Derivative Works, if and
115+ wherever such third-party notices normally appear. The contents
116+ of the NOTICE file are for informational purposes only and
117+ do not modify the License. You may add Your own attribution
118+ notices within Derivative Works that You distribute, alongside
119+ or as an addendum to the NOTICE text from the Work, provided
120+ that such additional attribution notices cannot be construed
121+ as modifying the License.
122+
123+ You may add Your own copyright statement to Your modifications and
124+ may provide additional or different license terms and conditions
125+ for use, reproduction, or distribution of Your modifications, or
126+ for any such Derivative Works as a whole, provided Your use,
127+ reproduction, and distribution of the Work otherwise complies with
128+ the conditions stated in this License.
129+
130+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131+ any Contribution intentionally submitted for inclusion in the Work
132+ by You to the Licensor shall be under the terms and conditions of
133+ this License, without any additional terms or conditions.
134+ Notwithstanding the above, nothing herein shall supersede or modify
135+ the terms of any separate license agreement you may have executed
136+ with Licensor regarding such Contributions.
137+
138+ 6. Trademarks. This License does not grant permission to use the trade
139+ names, trademarks, service marks, or product names of the Licensor,
140+ except as required for reasonable and customary use in describing the
141+ origin of the Work and reproducing the content of the NOTICE file.
142+
143+ 7. Disclaimer of Warranty. Unless required by applicable law or
144+ agreed to in writing, Licensor provides the Work (and each
145+ Contributor provides its Contributions) on an "AS IS" BASIS,
146+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147+ implied, including, without limitation, any warranties or conditions
148+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149+ PARTICULAR PURPOSE. You are solely responsible for determining the
150+ appropriateness of using or redistributing the Work and assume any
151+ risks associated with Your exercise of permissions under this License.
152+
153+ 8. Limitation of Liability. In no event and under no legal theory,
154+ whether in tort (including negligence), contract, or otherwise,
155+ unless required by applicable law (such as deliberate and grossly
156+ negligent acts) or agreed to in writing, shall any Contributor be
157+ liable to You for damages, including any direct, indirect, special,
158+ incidental, or exemplary damages of any character arising as a
159+ result of this License or out of the use or inability to use the
160+ Work (including but not limited to damages for loss of goodwill,
161+ work stoppage, computer failure or malfunction, or any and all
162+ other commercial damages or losses), even if such Contributor
163+ has been advised of the possibility of such damages.
164+
165+ 9. Accepting Warranty or Additional Liability. While redistributing
166+ the Work or Derivative Works thereof, You may choose to offer,
167+ and charge a fee for, acceptance of support, warranty, indemnity,
168+ or other liability obligations and/or rights consistent with this
169+ License. However, in accepting such obligations, You may act only
170+ on Your own behalf and on Your sole responsibility, not on behalf
171+ of any other Contributor, and only if You agree to indemnify,
172+ defend, and hold each Contributor harmless for any liability
173+ incurred by, or claims asserted against, such Contributor by reason
174+ of your accepting any such warranty or additional liability.
175+
176+ END OF TERMS AND CONDITIONS
177+
178+ APPENDIX: How to apply the Apache License to your work.
179+
180+ To apply the Apache License to your work, attach the following
181+ boilerplate notice, with the fields enclosed by brackets "[]"
182+ replaced with your own identifying information. (Don't include
183+ the brackets!) The text should be enclosed in the appropriate
184+ comment syntax for the file format. We also recommend that a
185+ file or class name and description of purpose be included on the
186+ same "printed page" as the copyright notice for easier
187+ identification within third-party archives.
188+
189+ Copyright 2026 Abdullah Ansari
190+
191+ Licensed under the Apache License, Version 2.0 (the "License");
192+ you may not use this file except in compliance with the License.
193+ You may obtain a copy of the License at
194+
195+ http://www.apache.org/licenses/LICENSE-2.0
196+
197+ Unless required by applicable law or agreed to in writing, software
198+ distributed under the License is distributed on an "AS IS" BASIS,
199+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200+ See the License for the specific language governing permissions and
201+ limitations under the License.
Makefile
......@@ -0,0 +1,19 @@
1+BINARY_NAME=ntds-to-bloodhound
2+SRC=cmd/ntds-to-bloodhound/main.go
3+
4+.PHONY: all build build-all clean
5+
6+all: build
7+
8+build:
9+ go build -ldflags="-s -w" -o $(BINARY_NAME) $(SRC)
10+
11+build-all:
12+ GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY_NAME)-linux-amd64 $(SRC)
13+ GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o $(BINARY_NAME)-linux-arm64 $(SRC)
14+ GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY_NAME).exe $(SRC)
15+ GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY_NAME)-darwin-amd64 $(SRC)
16+ GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -o $(BINARY_NAME)-darwin-arm64 $(SRC)
17+
18+clean:
19+ rm -f $(BINARY_NAME) $(BINARY_NAME).exe $(BINARY_NAME)-*
README.md
......@@ -0,0 +1,164 @@
1+# ntds-to-bloodhound
2+
3+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.
4+
5+![ntds-to-bloodhound demo](docs/images/ntds-to-bloodhound-demo.png)
6+
7+## Table of Contents
8+
9+- [Why / The Gap This Fills](#why--the-gap-this-fills)
10+- [Internal Pipeline](#internal-pipeline)
11+- [Required Files](#required-files)
12+- [Build](#build)
13+- [Usage](#usage)
14+ - [BloodHound Community Edition (v5)](#bloodhound-community-edition-v5)
15+ - [BloodHound Legacy (v4)](#bloodhound-legacy-v4)
16+ - [Export Hashes and Graph Simultaneously](#export-hashes-and-graph-simultaneously)
17+- [Ingestion into BloodHound](#ingestion-into-bloodhound)
18+ - [BloodHound CE (v5)](#bloodhound-ce-v5)
19+ - [BloodHound Legacy (v4)](#bloodhound-legacy-v4-1)
20+ - [Querying Decrypted Hashes in BloodHound](#querying-decrypted-hashes-in-bloodhound)
21+- [License](#license)
22+
23+## Why / The Gap This Fills
24+
25+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.
26+
27+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`.
28+
29+`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.
30+
31+## Internal Pipeline
32+
33+The extraction engine operates entirely offline in memory through five stages:
34+
35+### SysKey & PEK Recovery
36+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.
37+
38+### Directory Assembly
39+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.
40+
41+### Credential Decryption
42+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.
43+
44+### Security Descriptor Translation
45+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`.
46+
47+### Output Serialization
48+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.
49+
50+## Required Files
51+
52+| File | Source Path | Description |
53+|---|---|---|
54+| `ntds.dit` | `C:\Windows\NTDS\ntds.dit` | Active Directory database |
55+| `SYSTEM` | `C:\Windows\System32\config\SYSTEM` | Registry hive containing the syskey |
56+
57+## Build
58+
59+Requires Go 1.21+.
60+
61+```bash
62+make build
63+```
64+
65+Cross-compile for Linux, Windows, and macOS:
66+
67+```bash
68+make build-all
69+```
70+
71+Compiled binaries are output to the repository root (`./ntds-to-bloodhound`).
72+
73+## Usage
74+
75+```text
76+Usage: ntds-to-bloodhound [OPTIONS]
77+
78+Required Flags:
79+ -n, -ntds string
80+ Path to offline ntds.dit database file
81+ -s, -system string
82+ Path to offline SYSTEM registry hive file
83+
84+Optional Flags:
85+ -o, -out string
86+ Output directory for generated files (default: "./output")
87+ -f, -format string
88+ Output format: "v4" (Legacy), "v5" (Community Edition), or "all" (default: "all")
89+ -d, -dump-hashes string
90+ Path to write secretsdump-compatible credential file
91+ -domain string
92+ Override Active Directory domain FQDN if not auto-detected
93+ -zip
94+ Package v5 output into BloodHound ingestion ZIP archive (default: true)
95+ -v, -verbose
96+ Enable detailed debug logging
97+ -h, -help
98+ Show help information
99+```
100+
101+### BloodHound Community Edition (v5)
102+
103+Generate a timestamped ZIP archive ready for BloodHound CE:
104+
105+```bash
106+./ntds-to-bloodhound -ntds /path/to/ntds.dit -system /path/to/SYSTEM -format v5 -out ./output
107+```
108+
109+```text
110+[*] [1/5] Extracting BootKey from SYSTEM hive: /path/to/SYSTEM
111+[+] SysKey / BootKey derived: 0x429b3bce************************
112+[*] [2/5] Opening ESE database: /path/to/ntds.dit
113+[*] [3/5] Locating and decrypting Password Encryption Keys (PEK)...
114+[+] PEK # 0 found and decrypted: d6a3bd48************************
115+[*] [4/5] Reconstructing Active Directory hierarchy, group memberships, and ACLs...
116+[+] Processed 15 users, 53 groups, 4 computers, 1 OUs, 1 domains
117+[*] [5/5] Exporting BloodHound files (format: v5) to ./output...
118+[+] BloodHound Community Edition (v5) JSON files written to ./output
119+[+] BloodHound CE Ingestion Archive created: ./output/BloodHound_20261111230000.zip
120+```
121+
122+### BloodHound Legacy (v4)
123+
124+Generate individual JSON files formatted for legacy BloodHound:
125+
126+```bash
127+./ntds-to-bloodhound -ntds /path/to/ntds.dit -system /path/to/SYSTEM -format v4 -out ./output/v4
128+```
129+
130+### Export Hashes and Graph Simultaneously
131+
132+Dump credentials in `secretsdump.py` format (`user:RID:LM:NT:::`) while generating the graph:
133+
134+```bash
135+./ntds-to-bloodhound \
136+ -ntds /path/to/ntds.dit \
137+ -system /path/to/SYSTEM \
138+ -dump-hashes ./output/hashes.txt \
139+ -out ./output
140+```
141+
142+## Ingestion into BloodHound
143+
144+### BloodHound CE (v5)
145+
146+Upload the generated `BloodHound_<timestamp>.zip` archive directly through the BloodHound Community Edition interface under **Administration** &rarr; **File Ingest**, or post the archive to the CE ingestion REST endpoint.
147+
148+### BloodHound Legacy (v4)
149+
150+Drag and drop the generated JSON files (`users.json`, `groups.json`, `computers.json`, `ous.json`, `domains.json`) into the legacy BloodHound desktop GUI window.
151+
152+### Querying Decrypted Hashes in BloodHound
153+
154+`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:
155+
156+```cypher
157+MATCH (u:User) WHERE u.nthash IS NOT NULL RETURN u.name, u.nthash
158+```
159+
160+Or view them in the node properties panel under the **Node Info** sidebar for any User or Computer object.
161+
162+## License
163+
164+Apache License 2.0
cmd/ntds-to-bloodhound/main.go
......@@ -0,0 +1,322 @@
1+package main
2+
3+import (
4+ "encoding/hex"
5+ "flag"
6+ "fmt"
7+ "os"
8+ "path/filepath"
9+ "strings"
10+ "time"
11+
12+ "github.com/Velocidex/ordereddict"
13+ "github.com/shehzade/ntds-to-bloodhound/pkg/acl"
14+ "github.com/shehzade/ntds-to-bloodhound/pkg/ad"
15+ bhv4 "github.com/shehzade/ntds-to-bloodhound/pkg/bloodhound/v4"
16+ bhv5 "github.com/shehzade/ntds-to-bloodhound/pkg/bloodhound/v5"
17+ "github.com/shehzade/ntds-to-bloodhound/pkg/crypto"
18+ "github.com/shehzade/ntds-to-bloodhound/pkg/ese"
19+ "github.com/shehzade/ntds-to-bloodhound/pkg/registry"
20+)
21+
22+const banner = `
23+======================================================================
24+ ntds-to-bloodhound - Fast Offline AD NTDS.DIT to BloodHound Parser
25+ Version: 1.0.0 (Pure Go | Zero Cgo | Ultra-Fast ESE Engine)
26+======================================================================`
27+
28+func printUsage() {
29+ fmt.Println(banner)
30+ fmt.Print(`
31+USAGE:
32+ ntds-to-bloodhound [OPTIONS]
33+
34+REQUIRED FLAGS:
35+ -n, --ntds PATH Path to the offline ntds.dit database file
36+ -s, --system PATH Path to the offline SYSTEM registry hive file
37+
38+OPTIONAL FLAGS:
39+ -o, --out PATH Output directory for generated BloodHound files (default: "./output")
40+ -f, --format FORMAT Output format: "v4" (Legacy), "v5" (Community Edition), or "all" (default: "all")
41+ -d, --dump-hashes PATH Optional path to write a secretsdump-compatible credential file
42+ --domain FQDN Override Active Directory domain FQDN if not auto-detected
43+ --zip Package v5 output into standard BloodHound ingestion ZIP archive (default: true)
44+ -v, --verbose Enable detailed debug logging and object parsing metrics
45+ -h, --help Show help information
46+`)
47+}
48+
49+func main() {
50+ var (
51+ ntdsPath string
52+ sysPath string
53+ outDir string
54+ format string
55+ dumpHashesPath string
56+ domainOverride string
57+ zipPackage bool
58+ verbose bool
59+ help bool
60+ )
61+
62+ flag.StringVar(&ntdsPath, "ntds", "", "Path to the offline ntds.dit database file")
63+ flag.StringVar(&ntdsPath, "n", "", "Path to the offline ntds.dit database file (shorthand)")
64+
65+ flag.StringVar(&sysPath, "system", "", "Path to the offline SYSTEM registry hive file")
66+ flag.StringVar(&sysPath, "s", "", "Path to the offline SYSTEM registry hive file (shorthand)")
67+
68+ flag.StringVar(&outDir, "out", "./output", "Output directory for generated BloodHound files")
69+ flag.StringVar(&outDir, "o", "./output", "Output directory (shorthand)")
70+
71+ flag.StringVar(&format, "format", "all", "Output format: v4, v5, or all")
72+ flag.StringVar(&format, "f", "all", "Output format (shorthand)")
73+
74+ flag.StringVar(&dumpHashesPath, "dump-hashes", "", "Path to write secretsdump-compatible credential file")
75+ flag.StringVar(&dumpHashesPath, "d", "", "Path to write credential file (shorthand)")
76+
77+ flag.StringVar(&domainOverride, "domain", "", "Override Active Directory domain FQDN")
78+ flag.BoolVar(&zipPackage, "zip", true, "Package v5 output into BloodHound ZIP archive")
79+
80+ flag.BoolVar(&verbose, "verbose", false, "Enable verbose logging")
81+ flag.BoolVar(&verbose, "v", false, "Enable verbose logging (shorthand)")
82+
83+ flag.BoolVar(&help, "help", false, "Show help information")
84+ flag.BoolVar(&help, "h", false, "Show help information (shorthand)")
85+
86+ flag.Parse()
87+
88+ if help || ntdsPath == "" || sysPath == "" {
89+ printUsage()
90+ if help {
91+ os.Exit(0)
92+ }
93+ os.Exit(1)
94+ }
95+
96+ formatLower := strings.ToLower(strings.TrimSpace(format))
97+ if formatLower != "v4" && formatLower != "v5" && formatLower != "all" {
98+ fmt.Printf("[-] Error: unsupported format %q (must be \"v4\", \"v5\", or \"all\")\n", format)
99+ os.Exit(1)
100+ }
101+
102+ startTime := time.Now()
103+ fmt.Println(banner)
104+ fmt.Println()
105+
106+ if _, err := os.Stat(ntdsPath); os.IsNotExist(err) {
107+ fmt.Printf("[-] Error: ntds.dit file not found: %s\n", ntdsPath)
108+ os.Exit(1)
109+ }
110+ if _, err := os.Stat(sysPath); os.IsNotExist(err) {
111+ fmt.Printf("[-] Error: SYSTEM hive file not found: %s\n", sysPath)
112+ os.Exit(1)
113+ }
114+
115+ fmt.Printf("[*] [1/5] Extracting BootKey from SYSTEM hive: %s\n", sysPath)
116+ bootKey, err := registry.ExtractBootKey(sysPath)
117+ if err != nil {
118+ fmt.Printf("[-] Failed to extract BootKey: %v\n", err)
119+ os.Exit(1)
120+ }
121+ bootKeyHex := hex.EncodeToString(bootKey)
122+ fmt.Printf("[+] SysKey / BootKey derived: 0x%s\n", bootKeyHex)
123+
124+ fmt.Printf("[*] [2/5] Opening ESE database: %s\n", ntdsPath)
125+ db, err := ese.OpenDB(ntdsPath)
126+ if err != nil {
127+ fmt.Printf("[-] Failed to open ESE database: %v\n", err)
128+ os.Exit(1)
129+ }
130+ defer db.Close()
131+
132+ fmt.Println("[*] [3/5] Locating and decrypting Password Encryption Keys (PEK)...")
133+ cryptoEngine := crypto.NewCryptoEngine(bootKey)
134+
135+ pekFound := false
136+ err = db.StreamTable("datatable", func(row *ordereddict.Dict) error {
137+ if pekFound {
138+ return nil
139+ }
140+ if val, ok := row.Get("ATTk590689"); ok && val != nil {
141+ if rawHex, ok := val.(string); ok && len(rawHex) > 0 {
142+ if b, err := hex.DecodeString(rawHex); err == nil {
143+ if err := cryptoEngine.ParsePekList(b); err == nil {
144+ pekFound = true
145+ }
146+ }
147+ }
148+ }
149+ return nil
150+ })
151+ if err != nil {
152+ fmt.Printf("[-] Error scanning for pekList: %v\n", err)
153+ os.Exit(1)
154+ }
155+ if !pekFound || len(cryptoEngine.PEKList) == 0 {
156+ fmt.Println("[-] Warning: No valid pekList found or decrypted! Account hashes will not be decrypted.")
157+ } else {
158+ for keyID, keyBytes := range cryptoEngine.PEKList {
159+ pekHex := hex.EncodeToString(keyBytes)
160+ fmt.Printf("[+] PEK # %d found and decrypted: %s\n", keyID, pekHex)
161+ }
162+ }
163+
164+ if verbose {
165+ fmt.Println("[*] Initializing Security Descriptor cache from sd_table...")
166+ }
167+ secEngine, err := acl.NewSecurityEngine(db)
168+ if err != nil {
169+ fmt.Printf("[-] Failed to load security descriptors: %v\n", err)
170+ os.Exit(1)
171+ }
172+ if verbose {
173+ fmt.Printf("[+] Cached %d binary security descriptors\n", secEngine.Count())
174+ }
175+
176+ fmt.Println("[*] [4/5] Reconstructing Active Directory hierarchy, group memberships, and ACLs...")
177+ assembler := ad.NewAssembler(db, cryptoEngine, secEngine, domainOverride)
178+ if err := assembler.Assemble(); err != nil {
179+ fmt.Printf("[-] Assembly failed: %v\n", err)
180+ os.Exit(1)
181+ }
182+ snap := assembler.Snapshot
183+
184+ userCount := len(snap.Users)
185+ groupCount := len(snap.Groups)
186+ computerCount := len(snap.Computers)
187+ ouCount := len(snap.OUs)
188+ domainCount := len(snap.Domains)
189+
190+ var credsDecrypted int
191+ for _, u := range snap.Users {
192+ if u.NTHash != "" {
193+ credsDecrypted++
194+ }
195+ }
196+
197+ var totalMemberships int
198+ for _, g := range snap.Groups {
199+ totalMemberships += len(g.Members)
200+ }
201+
202+ var totalAces int
203+ for _, u := range snap.Users {
204+ totalAces += len(u.Aces)
205+ }
206+ for _, g := range snap.Groups {
207+ totalAces += len(g.Aces)
208+ }
209+ for _, c := range snap.Computers {
210+ totalAces += len(c.Aces)
211+ }
212+ for _, d := range snap.Domains {
213+ totalAces += len(d.Aces)
214+ }
215+ for _, o := range snap.OUs {
216+ totalAces += len(o.Aces)
217+ }
218+
219+ if dumpHashesPath != "" {
220+ fmt.Printf("[*] Writing decrypted credentials to %s...\n", dumpHashesPath)
221+ if dir := filepath.Dir(dumpHashesPath); dir != "" {
222+ _ = os.MkdirAll(dir, 0755)
223+ }
224+ var sb strings.Builder
225+ for _, u := range snap.Users {
226+ sam := u.Properties["samaccountname"].(string)
227+ rid := 0
228+ parts := strings.Split(u.ObjectIdentifier, "-")
229+ if len(parts) > 0 {
230+ fmt.Sscanf(parts[len(parts)-1], "%d", &rid)
231+ }
232+ nthash := u.NTHash
233+ if nthash == "" {
234+ nthash = crypto.EmptyNTHash
235+ }
236+ sb.WriteString(fmt.Sprintf("%s:%d:%s:%s:::\n",
237+ sam, rid, crypto.EmptyLMHash, nthash))
238+ }
239+ for _, c := range snap.Computers {
240+ sam := c.Properties["samaccountname"].(string)
241+ rid := 0
242+ parts := strings.Split(c.ObjectIdentifier, "-")
243+ if len(parts) > 0 {
244+ fmt.Sscanf(parts[len(parts)-1], "%d", &rid)
245+ }
246+ nthash := c.NTHash
247+ if nthash == "" {
248+ nthash = crypto.EmptyNTHash
249+ }
250+ sb.WriteString(fmt.Sprintf("%s:%d:%s:%s:::\n",
251+ sam, rid, crypto.EmptyLMHash, nthash))
252+ }
253+ totalCreds := len(snap.Users) + len(snap.Computers)
254+ if err := os.WriteFile(dumpHashesPath, []byte(sb.String()), 0600); err != nil {
255+ fmt.Printf("[-] Failed to write credentials file: %v\n", err)
256+ } else {
257+ fmt.Printf("[+] Successfully wrote %d credentials to %s\n", totalCreds, dumpHashesPath)
258+ }
259+ }
260+
261+ fmt.Printf("[*] [5/5] Exporting BloodHound files (format: %s) to %s...\n", formatLower, outDir)
262+
263+ var createdFiles []string
264+
265+ if formatLower == "v4" || formatLower == "all" {
266+ targetV4Dir := outDir
267+ if formatLower == "all" {
268+ targetV4Dir = filepath.Join(outDir, "v4")
269+ }
270+ v4Writer := bhv4.NewWriter(targetV4Dir)
271+ if err := v4Writer.WriteSnapshot(snap); err != nil {
272+ fmt.Printf("[-] Error writing v4 files: %v\n", err)
273+ os.Exit(1)
274+ }
275+ createdFiles = append(createdFiles, filepath.Join(targetV4Dir, "{users,groups,computers,domains,ous}.json"))
276+ fmt.Printf("[+] BloodHound Legacy (v4) JSON files written to %s\n", targetV4Dir)
277+ }
278+
279+ if formatLower == "v5" || formatLower == "all" {
280+ targetV5Dir := outDir
281+ if formatLower == "all" {
282+ targetV5Dir = filepath.Join(outDir, "v5")
283+ }
284+ v5Writer := bhv5.NewWriter(targetV5Dir)
285+ if err := v5Writer.WriteSnapshot(snap); err != nil {
286+ fmt.Printf("[-] Error writing v5 files: %v\n", err)
287+ os.Exit(1)
288+ }
289+ createdFiles = append(createdFiles, filepath.Join(targetV5Dir, "{users,groups,computers,domains,ous}.json"))
290+ fmt.Printf("[+] BloodHound Community Edition (v5) JSON files written to %s\n", targetV5Dir)
291+
292+ if zipPackage {
293+ zipPath := filepath.Join(targetV5Dir, bhv5.GenerateZipFilename())
294+ if err := bhv5.CreateZipArchive(snap, zipPath); err != nil {
295+ fmt.Printf("[-] Error creating ZIP archive: %v\n", err)
296+ } else {
297+ createdFiles = append(createdFiles, zipPath)
298+ fmt.Printf("[+] BloodHound CE Ingestion Archive created: %s\n", zipPath)
299+ }
300+ }
301+ }
302+
303+ elapsed := time.Since(startTime)
304+
305+ fmt.Println()
306+ fmt.Println("======================================================================")
307+ fmt.Println(" EXTRACTION METRICS & SUMMARY ")
308+ fmt.Println("======================================================================")
309+ fmt.Printf(" Target Domain Name : %s\n", snap.DomainName)
310+ fmt.Printf(" Target Domain SID : %s\n", snap.DomainSID)
311+ fmt.Printf(" Total Users Extracted : %d\n", userCount)
312+ fmt.Printf(" Total Groups Extracted : %d\n", groupCount)
313+ fmt.Printf(" Total Computers Extracted: %d\n", computerCount)
314+ fmt.Printf(" Total OUs Extracted : %d\n", ouCount)
315+ fmt.Printf(" Domains Extracted : %d\n", domainCount)
316+ fmt.Printf(" Decrypted NT Hashes : %d / %d\n", credsDecrypted, userCount)
317+ fmt.Printf(" Group Memberships Linked : %d\n", totalMemberships)
318+ fmt.Printf(" BloodHound Edges (ACEs) : %d\n", totalAces)
319+ fmt.Printf(" Total Elapsed Processing : %s\n", elapsed)
320+ fmt.Println("======================================================================")
321+ fmt.Println("[+] Done! BloodHound collection complete.")
322+}
docs/images/ntds-to-bloodhound-demo.png
Binary files /dev/null and b/docs/images/ntds-to-bloodhound-demo.png differ
go.mod
......@@ -0,0 +1,15 @@
1+module github.com/shehzade/ntds-to-bloodhound
2+
3+go 1.21
4+
5+require (
6+ github.com/Velocidex/ordereddict v0.0.0-20261028034010-6857b08b4dab
7+ www.velocidex.com/golang/go-ese v0.2.0
8+ www.velocidex.com/golang/regparser v0.0.0-20250203141505-31e704a67ef7
9+)
10+
11+require (
12+ github.com/Velocidex/json v0.0.0-20220224052537-92f3c0326e5a // indirect
13+ github.com/Velocidex/yaml/v2 v2.2.8 // indirect
14+ github.com/davecgh/go-spew v1.1.1 // indirect
15+)
go.sum
......@@ -0,0 +1,53 @@
1+github.com/Velocidex/json v0.0.0-20220224052537-92f3c0326e5a h1:AeXPUzhU0yhID/v5JJEIkjaE85ASe+Vh4Kuv1RSLL+4=
2+github.com/Velocidex/json v0.0.0-20220224052537-92f3c0326e5a/go.mod h1:ukJBuruT9b24pdgZwWDvOaCYHeS03B7oQPCUWh25bwM=
3+github.com/Velocidex/ordereddict v0.0.0-20220107075049-3dbe58412844/go.mod h1:Y5Tfx5SKGOzkulpqfonrdILSPIuNg+GqKE/DhVJgnpg=
4+github.com/Velocidex/ordereddict v0.0.0-20261028034010-6857b08b4dab h1:IhCSLiVMsRmBuGsjsgUW5PelPrYJxHztRIZ3teL6efc=
5+github.com/Velocidex/ordereddict v0.0.0-20261028034010-6857b08b4dab/go.mod h1:+MqO5UMBemyFSm+yRXslbpFTwPUDhFHUf7HPV92twg4=
6+github.com/Velocidex/yaml/v2 v2.2.8 h1:GUrSy4SBJ6RjGt43k6MeBKtw2z/27gh4A3hfFmFY3No=
7+github.com/Velocidex/yaml/v2 v2.2.8/go.mod h1:PlXIg/Pxmoja48C1vMHo7C5pauAZvLq/UEPOQ3DsjS4=
8+github.com/alecthomas/assert v1.0.0/go.mod h1:va/d2JC+M7F6s+80kl/R3G7FUiW6JzUO+hPhLyJ36ZY=
9+github.com/alecthomas/colour v0.1.0/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0=
10+github.com/alecthomas/repr v0.0.0-20210801044451-80ca428c5142/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8=
11+github.com/alecthomas/repr v0.1.1 h1:87P60cSmareLAxMc4Hro0r2RBY4ROm0dYwkJNpS4pPs=
12+github.com/alecthomas/repr v0.1.1/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
13+github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
14+github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE=
15+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
16+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
17+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
18+github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
19+github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
20+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
21+github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
22+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
23+github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
24+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
25+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
26+github.com/sebdah/goldie v1.0.0/go.mod h1:jXP4hmWywNEwZzhMuv2ccnqTSFpuq8iyQhtQdkkZBH4=
27+github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
28+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
29+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
30+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
31+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
32+github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
33+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
34+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
35+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
36+github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
37+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
38+golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
39+golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
40+gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
41+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
42+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
43+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
44+gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
45+gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
46+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
47+gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
48+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
49+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
50+www.velocidex.com/golang/go-ese v0.2.0 h1:8/hzEMupfqEF0oMi1/EzsMN1xLN0GBFcB3GqxqRnb9s=
51+www.velocidex.com/golang/go-ese v0.2.0/go.mod h1:6fC9T6UGLbM7icuA0ugomU5HbFC5XA5I30zlWtZT8YE=
52+www.velocidex.com/golang/regparser v0.0.0-20250203141505-31e704a67ef7 h1:BMX/37sYwX+8JhHt+YNbPfbx7dXG1w1L1mXonNBtjt0=
53+www.velocidex.com/golang/regparser v0.0.0-20250203141505-31e704a67ef7/go.mod h1:pxSECT5mWM3goJ4sxB4HCJNKnKqiAlpyT8XnvBwkLGU=
pkg/acl/engine.go
......@@ -0,0 +1,134 @@
1+package acl
2+
3+import (
4+ "encoding/binary"
5+ "encoding/hex"
6+
7+ "github.com/Velocidex/ordereddict"
8+ "github.com/shehzade/ntds-to-bloodhound/pkg/ese"
9+)
10+
11+type cacheKey struct {
12+ sdID uint64
13+ objType string
14+ hasLAPS bool
15+}
16+
17+type cachedSD struct {
18+ aces []Ace
19+ isProtected bool
20+}
21+
22+type SecurityEngine struct {
23+ RawSDs map[uint64][]byte
24+ AclCache map[cacheKey]cachedSD
25+ LapsGUIDs map[string]bool
26+}
27+
28+func NewSecurityEngine(db *ese.DB) (*SecurityEngine, error) {
29+ engine := &SecurityEngine{
30+ RawSDs: make(map[uint64][]byte),
31+ AclCache: make(map[cacheKey]cachedSD),
32+ LapsGUIDs: make(map[string]bool),
33+ }
34+
35+ aliases := make(map[uint64]uint64)
36+
37+ err := db.StreamTable("sd_table", func(row *ordereddict.Dict) error {
38+ idVal, ok := row.Get("sd_id")
39+ if !ok || idVal == nil {
40+ return nil
41+ }
42+
43+ var id uint64
44+ switch v := idVal.(type) {
45+ case uint64:
46+ id = v
47+ case int64:
48+ id = uint64(v)
49+ case uint32:
50+ id = uint64(v)
51+ case int32:
52+ id = uint64(v)
53+ case int:
54+ id = uint64(v)
55+ }
56+
57+ val, _ := row.Get("sd_value")
58+ hexStr, ok := val.(string)
59+ if !ok || len(hexStr) == 0 {
60+ return nil
61+ }
62+
63+ b, err := hex.DecodeString(hexStr)
64+ if err != nil {
65+ return nil
66+ }
67+
68+ if len(b) >= 20 {
69+ engine.RawSDs[id] = b
70+ } else if len(b) == 4 {
71+ targetID := uint64(binary.LittleEndian.Uint32(b))
72+ aliases[id] = targetID
73+ }
74+
75+ return nil
76+ })
77+ if err != nil {
78+ return nil, err
79+ }
80+
81+ for srcID := range aliases {
82+ curr := srcID
83+ visited := make(map[uint64]bool)
84+ for {
85+ if visited[curr] {
86+ break
87+ }
88+ visited[curr] = true
89+ if target, ok := aliases[curr]; ok {
90+ curr = target
91+ } else {
92+ break
93+ }
94+ }
95+ if rawSD, exists := engine.RawSDs[curr]; exists {
96+ engine.RawSDs[srcID] = rawSD
97+ }
98+ }
99+
100+ return engine, nil
101+}
102+
103+func (e *SecurityEngine) Count() int {
104+ return len(e.RawSDs)
105+}
106+
107+func (e *SecurityEngine) GetAces(sdID uint64) []Ace {
108+ aces, _ := e.GetAcesForObject(sdID, "", false)
109+ return aces
110+}
111+
112+func (e *SecurityEngine) GetAcesForObject(sdID uint64, objectType string, hasLAPS bool) ([]Ace, bool) {
113+ key := cacheKey{sdID: sdID, objType: objectType, hasLAPS: hasLAPS}
114+ if cached, exists := e.AclCache[key]; exists {
115+ out := make([]Ace, len(cached.aces))
116+ copy(out, cached.aces)
117+ return out, cached.isProtected
118+ }
119+
120+ rawSD, exists := e.RawSDs[sdID]
121+ if !exists {
122+ return nil, false
123+ }
124+
125+ aces, isProtected, err := ParseSecurityDescriptorForType(rawSD, objectType, hasLAPS, e.LapsGUIDs)
126+ if err != nil {
127+ return nil, false
128+ }
129+
130+ e.AclCache[key] = cachedSD{aces: aces, isProtected: isProtected}
131+ out := make([]Ace, len(aces))
132+ copy(out, aces)
133+ return out, isProtected
134+}
pkg/acl/sd.go
......@@ -0,0 +1,381 @@
1+package acl
2+
3+import (
4+ "encoding/binary"
5+ "fmt"
6+ "strings"
7+
8+ "github.com/shehzade/ntds-to-bloodhound/pkg/crypto"
9+)
10+
11+type Ace struct {
12+ PrincipalSID string `json:"PrincipalSID"`
13+ PrincipalType string `json:"PrincipalType"`
14+ RightName string `json:"RightName"`
15+ IsInherited bool `json:"IsInherited"`
16+}
17+
18+const (
19+ EdgeOwns = "Owns"
20+ EdgeGenericAll = "GenericAll"
21+ EdgeWriteDacl = "WriteDacl"
22+ EdgeWriteOwner = "WriteOwner"
23+ EdgeGenericWrite = "GenericWrite"
24+ EdgeAllExtendedRights = "AllExtendedRights"
25+ EdgeForceChangePassword = "ForceChangePassword"
26+ EdgeGetChanges = "GetChanges"
27+ EdgeGetChangesAll = "GetChangesAll"
28+ EdgeGetChangesInFilteredSet = "GetChangesInFilteredSet"
29+ EdgeAddMember = "AddMember"
30+ EdgeAddSelf = "AddSelf"
31+ EdgeAddAllowedToAct = "AddAllowedToAct"
32+ EdgeAddKeyCredentialLink = "AddKeyCredentialLink"
33+ EdgeWriteSPN = "WriteSPN"
34+ EdgeWriteAccountRestrictions = "WriteAccountRestrictions"
35+ EdgeWriteGPLink = "WriteGPLink"
36+ EdgeReadLAPSPassword = "ReadLAPSPassword"
37+ EdgeReadGMSAPassword = "ReadGMSAPassword"
38+)
39+
40+const (
41+ GUIDAllZero = "00000000-0000-0000-0000-000000000000"
42+ GUIDUserForceChangePassword = "00299570-246d-11d0-a768-00aa006e0529"
43+ GUIDReplicationGetChanges = "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2"
44+ GUIDReplicationGetChangesAll = "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2"
45+ GUIDReplicationFiltered = "89e95b76-444d-4c62-991a-0facbeda640c"
46+ GUIDGroupMemberAttr = "bf9679c0-0de6-11d0-a285-00aa003049e2"
47+ GUIDMembershipPropertySet = "bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
48+ GUIDAllowedToAct = "3f78c3e5-f79a-46bd-a0b8-9d18116ddc79"
49+ GUIDKeyCredentialLink = "5b47d60f-6090-40b2-9f37-2a4de88f3063"
50+ GUIDServicePrincipalName = "f3a64788-5306-11d1-a9c5-0000f80367c1"
51+ GUIDUserAccountRestrictions = "4c164200-20c0-11d0-a768-00aa006e0529"
52+ GUIDWriteGPLink = "f30e3bbe-9ff0-11d1-b603-0000f80367c1"
53+
54+ GUIDClassUser = "bf967aba-0de6-11d0-a285-00aa003049e2"
55+ GUIDClassInetOrg = "ce206244-5827-4a86-ba1c-1c0c386c1b64"
56+ GUIDClassGMSA = "7b8b558a-93a5-4af7-adca-c017e67f1057"
57+ GUIDClassMSA = "febc6632-080d-422c-a779-c22712b713b0"
58+ GUIDClassComputer = "bf967a86-0de6-11d0-a285-00aa003049e2"
59+ GUIDClassGroup = "bf967a9c-0de6-11d0-a285-00aa003049e2"
60+ GUIDClassDomain = "19195a5a-6da0-11d0-afd3-00c04fd930c9"
61+ GUIDClassOU = "bf967aa5-0de6-11d0-a285-00aa003049e2"
62+)
63+
64+func isIgnoredSID(sid string) bool {
65+ return sid == "S-1-3-0" || sid == "S-1-5-18" || sid == "S-1-5-10"
66+}
67+
68+func formatGUID(b []byte) string {
69+ if len(b) < 16 {
70+ return ""
71+ }
72+ d1 := binary.LittleEndian.Uint32(b[0:4])
73+ d2 := binary.LittleEndian.Uint16(b[4:6])
74+ d3 := binary.LittleEndian.Uint16(b[6:8])
75+ return fmt.Sprintf("%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
76+ d1, d2, d3, b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15])
77+}
78+
79+func inheritedGUIDApplies(inheritedGUID, objectType string) bool {
80+ if inheritedGUID == "" || inheritedGUID == GUIDAllZero || objectType == "" {
81+ return true
82+ }
83+ g := strings.ToLower(inheritedGUID)
84+ switch strings.ToLower(objectType) {
85+ case "user":
86+ return g == GUIDClassUser || g == GUIDClassInetOrg || g == GUIDClassGMSA || g == GUIDClassMSA
87+ case "computer":
88+ return g == GUIDClassComputer || g == GUIDClassGMSA
89+ case "group":
90+ return g == GUIDClassGroup
91+ case "domain":
92+ return g == GUIDClassDomain
93+ case "ou":
94+ return g == GUIDClassOU
95+ default:
96+ return true
97+ }
98+}
99+
100+func ParseSecurityDescriptor(sdBytes []byte) ([]Ace, error) {
101+ aces, _, err := ParseSecurityDescriptorForType(sdBytes, "", false, nil)
102+ return aces, err
103+}
104+
105+func ParseSecurityDescriptorForType(sdBytes []byte, objectType string, hasLAPS bool, lapsGUIDs map[string]bool) ([]Ace, bool, error) {
106+ if len(sdBytes) < 20 {
107+ return nil, false, nil
108+ }
109+
110+ control := binary.LittleEndian.Uint16(sdBytes[2:4])
111+ isACLProtected := (control & 0x1000) != 0
112+
113+ type seenKey struct {
114+ sid string
115+ right string
116+ inherited bool
117+ }
118+ seen := make(map[seenKey]bool)
119+ var results []Ace
120+
121+ addAce := func(sid, right string, inherited bool) {
122+ if sid == "" || right == "" {
123+ return
124+ }
125+ k := seenKey{sid: sid, right: right, inherited: inherited}
126+ if seen[k] {
127+ return
128+ }
129+ seen[k] = true
130+ results = append(results, Ace{
131+ PrincipalSID: sid,
132+ PrincipalType: "Base",
133+ RightName: right,
134+ IsInherited: inherited,
135+ })
136+ }
137+
138+ objLower := strings.ToLower(objectType)
139+
140+ ownerOffset := int(binary.LittleEndian.Uint32(sdBytes[4:8]))
141+ if objLower != "rbcd" && objLower != "gmsa" && ownerOffset >= 20 && ownerOffset+8 <= len(sdBytes) {
142+ ownerSID, _, err := crypto.ParseBinarySID(sdBytes[ownerOffset:])
143+ if err == nil && ownerSID != "" && !isIgnoredSID(ownerSID) {
144+ addAce(ownerSID, EdgeOwns, false)
145+ }
146+ }
147+
148+ if control&0x0004 == 0 {
149+ return results, isACLProtected, nil
150+ }
151+
152+ daclOffset := int(binary.LittleEndian.Uint32(sdBytes[16:20]))
153+ if daclOffset == 0 || daclOffset >= len(sdBytes) || daclOffset+8 > len(sdBytes) {
154+ return results, isACLProtected, nil
155+ }
156+
157+ daclBytes := sdBytes[daclOffset:]
158+ aclSize := int(binary.LittleEndian.Uint16(daclBytes[2:4]))
159+ aceCount := int(binary.LittleEndian.Uint16(daclBytes[4:6]))
160+ if aclSize > len(daclBytes) {
161+ aclSize = len(daclBytes)
162+ }
163+
164+ offset := 8
165+ for i := 0; i < aceCount && offset+4 <= aclSize; i++ {
166+ aceType := daclBytes[offset]
167+ aceFlags := daclBytes[offset+1]
168+ aceSize := int(binary.LittleEndian.Uint16(daclBytes[offset+2 : offset+4]))
169+ if aceSize <= 0 || offset+aceSize > aclSize {
170+ break
171+ }
172+
173+ isInherited := (aceFlags & 0x10) != 0
174+ isInheritOnly := (aceFlags & 0x08) != 0
175+
176+ if isInheritOnly {
177+ offset += aceSize
178+ continue
179+ }
180+
181+ if aceType == 0x00 && aceSize >= 12 {
182+ mask := binary.LittleEndian.Uint32(daclBytes[offset+4 : offset+8])
183+ sidBytes := daclBytes[offset+8 : offset+aceSize]
184+ principalSID, _, err := crypto.ParseBinarySID(sidBytes)
185+ if err == nil && principalSID != "" {
186+ if objLower == "rbcd" {
187+ if mask != 0 {
188+ addAce(principalSID, EdgeGenericAll, isInherited)
189+ }
190+ } else if objLower == "gmsa" {
191+ if mask&0x00000100 != 0 || mask&0x10000000 != 0 || mask&0x00020014 != 0 {
192+ addAce(principalSID, EdgeReadGMSAPassword, isInherited)
193+ }
194+ } else if !isIgnoredSID(principalSID) {
195+ for _, edge := range mapStandardMaskToEdges(mask, objLower, principalSID) {
196+ addAce(principalSID, edge, isInherited)
197+ }
198+ }
199+ }
200+ } else if aceType == 0x05 && aceSize >= 12 {
201+ mask := binary.LittleEndian.Uint32(daclBytes[offset+4 : offset+8])
202+ objFlags := binary.LittleEndian.Uint32(daclBytes[offset+8 : offset+12])
203+ sidOffset := offset + 12
204+ var objectTypeGUID string
205+ var inheritedTypeGUID string
206+
207+ if objFlags&0x00000001 != 0 {
208+ if sidOffset+16 <= offset+aceSize {
209+ objectTypeGUID = formatGUID(daclBytes[sidOffset : sidOffset+16])
210+ sidOffset += 16
211+ }
212+ }
213+ if objFlags&0x00000002 != 0 {
214+ if sidOffset+16 <= offset+aceSize {
215+ inheritedTypeGUID = formatGUID(daclBytes[sidOffset : sidOffset+16])
216+ sidOffset += 16
217+ }
218+ }
219+
220+ if isInherited && (objFlags&0x00000002 != 0) && !inheritedGUIDApplies(inheritedTypeGUID, objLower) {
221+ offset += aceSize
222+ continue
223+ }
224+
225+ if sidOffset < offset+aceSize {
226+ sidBytes := daclBytes[sidOffset : offset+aceSize]
227+ principalSID, _, err := crypto.ParseBinarySID(sidBytes)
228+ if err == nil && principalSID != "" {
229+ if objLower == "rbcd" {
230+ if mask != 0 {
231+ addAce(principalSID, EdgeGenericAll, isInherited)
232+ }
233+ } else if objLower == "gmsa" {
234+ if mask&0x00000100 != 0 || mask&0x10000000 != 0 || mask&0x00020014 != 0 {
235+ addAce(principalSID, EdgeReadGMSAPassword, isInherited)
236+ }
237+ } else if !isIgnoredSID(principalSID) {
238+ for _, edge := range mapObjectMaskToEdges(mask, objFlags, objectTypeGUID, objLower, principalSID, hasLAPS, lapsGUIDs) {
239+ addAce(principalSID, edge, isInherited)
240+ }
241+ }
242+ }
243+ }
244+ }
245+
246+ offset += aceSize
247+ }
248+
249+ return results, isACLProtected, nil
250+}
251+
252+func hasGenericAll(mask uint32) bool {
253+ return mask&0x10000000 != 0 || (mask&0x000F01FF == 0x000F01FF) || (mask&0x001F01FF == 0x001F01FF)
254+}
255+
256+func hasGenericWrite(mask uint32) bool {
257+ return mask&0x40000000 != 0 || (mask&0x00020028 == 0x00020028) || mask&0x00000020 != 0
258+}
259+
260+func mapStandardMaskToEdges(mask uint32, objType, principalSID string) []string {
261+ var edges []string
262+
263+ if hasGenericAll(mask) {
264+ return []string{EdgeGenericAll}
265+ }
266+
267+ if hasGenericWrite(mask) && objType != "domain" {
268+ edges = append(edges, EdgeGenericWrite)
269+ }
270+ if mask&0x00080000 != 0 {
271+ edges = append(edges, EdgeWriteOwner)
272+ }
273+ if mask&0x00040000 != 0 {
274+ edges = append(edges, EdgeWriteDacl)
275+ }
276+ if mask&0x00000100 != 0 {
277+ switch objType {
278+ case "", "user", "domain":
279+ edges = append(edges, EdgeAllExtendedRights)
280+ case "computer":
281+ if principalSID != "S-1-5-32-544" && !strings.HasSuffix(principalSID, "-512") {
282+ edges = append(edges, EdgeAllExtendedRights)
283+ }
284+ }
285+ }
286+
287+ return edges
288+}
289+
290+func mapObjectMaskToEdges(mask, objFlags uint32, objectGUID, objType, principalSID string, hasLAPS bool, lapsGUIDs map[string]bool) []string {
291+ var edges []string
292+
293+ objTypePresent := (objFlags & 0x00000001) != 0
294+ guidLower := strings.ToLower(objectGUID)
295+ genericApplicable := !objTypePresent || guidLower == "" || guidLower == GUIDAllZero
296+
297+ if genericApplicable {
298+ if hasGenericAll(mask) {
299+ return []string{EdgeGenericAll}
300+ }
301+ if hasGenericWrite(mask) {
302+ edges = append(edges, EdgeGenericWrite)
303+ }
304+ if mask&0x00040000 != 0 {
305+ edges = append(edges, EdgeWriteDacl)
306+ }
307+ if mask&0x00080000 != 0 {
308+ edges = append(edges, EdgeWriteOwner)
309+ }
310+ if mask&0x00000100 != 0 {
311+ switch objType {
312+ case "", "user", "domain":
313+ edges = append(edges, EdgeAllExtendedRights)
314+ case "computer":
315+ if hasLAPS {
316+ edges = append(edges, EdgeAllExtendedRights)
317+ }
318+ }
319+ }
320+ if (objType == "" || objType == "group") && mask&0x00000008 != 0 {
321+ edges = append(edges, EdgeAddSelf)
322+ }
323+ return edges
324+ }
325+
326+ canWriteProp := mask&0x00000020 != 0 || hasGenericAll(mask) || mask&0x40000000 != 0
327+ hasExtRight := mask&0x00000100 != 0 || hasGenericAll(mask)
328+
329+ switch guidLower {
330+ case GUIDGroupMemberAttr, GUIDMembershipPropertySet:
331+ if objType == "" || objType == "group" {
332+ if canWriteProp {
333+ edges = append(edges, EdgeAddMember)
334+ } else if mask&0x00000008 != 0 {
335+ edges = append(edges, EdgeAddSelf)
336+ }
337+ }
338+ case GUIDUserForceChangePassword:
339+ if (objType == "" || objType == "user" || objType == "computer") && hasExtRight {
340+ edges = append(edges, EdgeForceChangePassword)
341+ }
342+ case GUIDReplicationGetChanges:
343+ if (objType == "" || objType == "domain") && hasExtRight {
344+ edges = append(edges, EdgeGetChanges)
345+ }
346+ case GUIDReplicationGetChangesAll:
347+ if (objType == "" || objType == "domain") && hasExtRight {
348+ edges = append(edges, EdgeGetChangesAll)
349+ }
350+ case GUIDReplicationFiltered:
351+ if (objType == "" || objType == "domain") && hasExtRight {
352+ edges = append(edges, EdgeGetChangesInFilteredSet)
353+ }
354+ case GUIDAllowedToAct:
355+ if (objType == "" || objType == "computer") && canWriteProp {
356+ edges = append(edges, EdgeAddAllowedToAct)
357+ }
358+ case GUIDKeyCredentialLink:
359+ if (objType == "" || objType == "user" || objType == "computer") && canWriteProp {
360+ edges = append(edges, EdgeAddKeyCredentialLink)
361+ }
362+ case GUIDServicePrincipalName:
363+ if (objType == "" || objType == "user" || objType == "computer") && canWriteProp {
364+ edges = append(edges, EdgeWriteSPN)
365+ }
366+ case GUIDUserAccountRestrictions:
367+ if (objType == "" || objType == "user" || objType == "computer") && canWriteProp && !strings.HasSuffix(principalSID, "-512") {
368+ edges = append(edges, EdgeWriteAccountRestrictions)
369+ }
370+ case GUIDWriteGPLink:
371+ if (objType == "" || objType == "ou" || objType == "domain") && canWriteProp {
372+ edges = append(edges, EdgeWriteGPLink)
373+ }
374+ default:
375+ if objType == "computer" && hasLAPS && lapsGUIDs != nil && lapsGUIDs[guidLower] && (hasExtRight || mask&0x00000010 != 0) {
376+ edges = append(edges, EdgeReadLAPSPassword)
377+ }
378+ }
379+
380+ return edges
381+}
pkg/ad/assembler.go
......@@ -0,0 +1,952 @@
1+package ad
2+
3+import (
4+ "encoding/binary"
5+ "encoding/hex"
6+ "fmt"
7+ "strings"
8+
9+ "github.com/Velocidex/ordereddict"
10+ "github.com/shehzade/ntds-to-bloodhound/pkg/acl"
11+ "github.com/shehzade/ntds-to-bloodhound/pkg/crypto"
12+ "github.com/shehzade/ntds-to-bloodhound/pkg/ese"
13+)
14+
15+type Assembler struct {
16+ db *ese.DB
17+ cryptoEngine *crypto.CryptoEngine
18+ secEngine *acl.SecurityEngine
19+ tree *Tree
20+ Snapshot *ADSnapshot
21+ domainOverride string
22+
23+ groupsByDNT map[uint64]*GroupObject
24+ ousByDNT map[uint64]*OUObject
25+ deletedDNTs map[uint64]bool
26+ domainDNT uint64
27+ domainAces []acl.Ace
28+ domainACLProtect bool
29+ domainFuncLevel string
30+ domainDescription interface{}
31+ domainTrusts []DomainTrust
32+}
33+
34+func NewAssembler(db *ese.DB, cryptoEngine *crypto.CryptoEngine, secEngine *acl.SecurityEngine, domainOverride string) *Assembler {
35+ return &Assembler{
36+ db: db,
37+ cryptoEngine: cryptoEngine,
38+ secEngine: secEngine,
39+ tree: NewTree(),
40+ Snapshot: NewADSnapshot(),
41+ domainOverride: strings.TrimSpace(domainOverride),
42+ groupsByDNT: make(map[uint64]*GroupObject),
43+ ousByDNT: make(map[uint64]*OUObject),
44+ deletedDNTs: make(map[uint64]bool),
45+ domainFuncLevel: "2016",
46+ domainTrusts: make([]DomainTrust, 0),
47+ }
48+}
49+
50+func (a *Assembler) Assemble() error {
51+ if err := a.buildTreeAndDomain(); err != nil {
52+ return fmt.Errorf("failed to build tree and domain: %w", err)
53+ }
54+
55+ if err := a.extractObjects(); err != nil {
56+ return fmt.Errorf("failed to extract objects: %w", err)
57+ }
58+
59+ if err := a.processLinks(); err != nil {
60+ return fmt.Errorf("failed to process links: %w", err)
61+ }
62+
63+ a.processPrimaryGroups()
64+
65+ a.synthesizeWellKnownGroups()
66+
67+ a.resolvePrincipalsAndAces()
68+
69+ a.linkContainment()
70+
71+ return nil
72+}
73+
74+func (a *Assembler) buildTreeAndDomain() error {
75+ var fallbackDomainSID string
76+ var dcCandidateDNTs []uint64
77+
78+ err := a.db.StreamTable("datatable", func(row *ordereddict.Dict) error {
79+ dnt, ok := readUint64(row, "DNT_col")
80+ if !ok || dnt == 0 {
81+ return nil
82+ }
83+ pdnt, _ := readUint64(row, "PDNT_col")
84+ a.Snapshot.PDNTByDNT[dnt] = pdnt
85+
86+ if a.secEngine != nil {
87+ ldapName := strings.ToLower(readString(row, "ATTm131532"))
88+ if ldapName == "ms-mcs-admpwd" || ldapName == "mslaps-password" || ldapName == "mslaps-encryptedpassword" {
89+ if guidHex := readString(row, "ATTk589972"); len(guidHex) == 32 {
90+ if gb, err := hex.DecodeString(guidHex); err == nil && len(gb) == 16 {
91+ a.secEngine.LapsGUIDs[formatGUIDLower(gb)] = true
92+ }
93+ }
94+ }
95+ }
96+
97+ var rdnCol string = "ATTm3"
98+ rdnTyp, hasRDNTyp := readInt64(row, "RDNtyp_col")
99+ if !hasRDNTyp {
100+ rdnTyp = 3
101+ } else {
102+ rdnCol = fmt.Sprintf("ATTm%d", rdnTyp)
103+ }
104+
105+ rdn := readString(row, rdnCol)
106+ if rdn == "" {
107+ rdn = readString(row, "ATTm3")
108+ }
109+ if rdn == "" {
110+ rdn = readString(row, "ATTm589825")
111+ }
112+ if rdn == "" {
113+ rdn = readString(row, "ATTm1376281")
114+ }
115+ if rdn == "" {
116+ rdn = readString(row, "ATTm1376280")
117+ }
118+
119+ if isRowDeleted(row, rdn) {
120+ a.deletedDNTs[dnt] = true
121+ }
122+
123+ if sidHex := readString(row, "ATTr589970"); sidHex != "" {
124+ if sidBytes, err := hex.DecodeString(sidHex); err == nil {
125+ if sidStr, _, err := crypto.ParseSID(sidBytes); err == nil && strings.HasPrefix(sidStr, "S-1-5-21-") {
126+ parts := strings.Split(sidStr, "-")
127+ if len(parts) == 7 {
128+ a.Snapshot.DomainSID = sidStr
129+ a.domainDNT = dnt
130+ if lvl, hasLvl := readInt64(row, "ATTj591540"); hasLvl {
131+ a.domainFuncLevel = functionalLevelName(lvl)
132+ }
133+ a.domainDescription = readOptionalDescription(row)
134+ } else if len(parts) >= 8 && fallbackDomainSID == "" {
135+ fallbackDomainSID = strings.Join(parts[:7], "-")
136+ }
137+ }
138+ }
139+ }
140+
141+ if rdn == "" {
142+ return nil
143+ }
144+
145+ prefix := "CN="
146+ if rdnTyp == 1376281 || strings.HasPrefix(strings.ToLower(rdn), "dc=") {
147+ prefix = "DC="
148+ dcCandidateDNTs = append(dcCandidateDNTs, dnt)
149+ } else if rdnTyp == 1376280 || rdnTyp == 11 || strings.HasPrefix(strings.ToLower(rdn), "ou=") {
150+ prefix = "OU="
151+ }
152+
153+ cleanRDN := rdn
154+ if strings.HasPrefix(strings.ToUpper(cleanRDN), prefix) {
155+ cleanRDN = cleanRDN[len(prefix):]
156+ }
157+
158+ a.tree.AddNode(dnt, pdnt, cleanRDN, prefix)
159+ return nil
160+ })
161+ if err != nil {
162+ return err
163+ }
164+
165+ if a.Snapshot.DomainSID == "" && fallbackDomainSID != "" {
166+ a.Snapshot.DomainSID = fallbackDomainSID
167+ }
168+
169+ if a.domainDNT != 0 {
170+ if dom := domainFromDN(a.tree.ResolveDN(a.domainDNT)); dom != "" {
171+ a.Snapshot.DomainName = dom
172+ }
173+ }
174+ if a.Snapshot.DomainName == "" {
175+ for _, candDNT := range dcCandidateDNTs {
176+ if dom := domainFromDN(a.tree.ResolveDN(candDNT)); dom != "" {
177+ a.Snapshot.DomainName = dom
178+ if a.domainDNT == 0 {
179+ a.domainDNT = candDNT
180+ }
181+ break
182+ }
183+ }
184+ }
185+
186+ if a.domainOverride != "" {
187+ a.Snapshot.DomainName = strings.ToUpper(a.domainOverride)
188+ }
189+
190+ return nil
191+}
192+
193+func (a *Assembler) extractSDID(row *ordereddict.Dict) (uint64, bool) {
194+ if sdVal := readString(row, "ATTp131353"); len(sdVal) == 16 {
195+ if b, err := hex.DecodeString(sdVal); err == nil && len(b) == 8 {
196+ return binary.LittleEndian.Uint64(b), true
197+ }
198+ }
199+ for _, colName := range []string{"ATTb590606", "ATTb49"} {
200+ if v, ok := row.Get(colName); ok && v != nil {
201+ switch val := v.(type) {
202+ case uint64:
203+ return val, true
204+ case int64:
205+ return uint64(val), true
206+ case uint32:
207+ return uint64(val), true
208+ case int32:
209+ return uint64(val), true
210+ case string:
211+ if len(val) == 16 {
212+ if b, err := hex.DecodeString(val); err == nil && len(b) == 8 {
213+ return binary.LittleEndian.Uint64(b), true
214+ }
215+ }
216+ }
217+ }
218+ }
219+ return 0, false
220+}
221+
222+func (a *Assembler) resolveObjectSD(sdID uint64, foundSD bool, objType string, hasLAPS bool) ([]acl.Ace, bool) {
223+ if a.secEngine == nil || !foundSD {
224+ return make([]acl.Ace, 0), false
225+ }
226+ aces, isProtected := a.secEngine.GetAcesForObject(sdID, objType, hasLAPS)
227+ if aces == nil {
228+ aces = make([]acl.Ace, 0)
229+ }
230+ return aces, isProtected
231+}
232+
233+func (a *Assembler) extractObjects() error {
234+ return a.db.StreamTable("datatable", func(row *ordereddict.Dict) error {
235+ dnt, ok := readUint64(row, "DNT_col")
236+ if !ok || dnt == 0 || a.deletedDNTs[dnt] {
237+ return nil
238+ }
239+
240+ pdnt, _ := readUint64(row, "PDNT_col")
241+ a.Snapshot.PDNTByDNT[dnt] = pdnt
242+
243+ dn := a.tree.ResolveDN(dnt)
244+ dnUpper := strings.ToUpper(dn)
245+ if isRowDeleted(row, a.tree.GetRDN(dnt)) || isNonDomainPartitionDN(dnUpper) {
246+ return nil
247+ }
248+
249+ var sidStr string
250+ var rid uint32
251+ if sidHex := readString(row, "ATTr589970"); sidHex != "" {
252+ if sidBytes, err := hex.DecodeString(sidHex); err == nil {
253+ if s, r, err := crypto.ParseSID(sidBytes); err == nil {
254+ sidStr = s
255+ rid = r
256+ }
257+ }
258+ }
259+
260+ sdID, foundSD := a.extractSDID(row)
261+
262+ if dnt == a.domainDNT || (sidStr != "" && sidStr == a.Snapshot.DomainSID) {
263+ a.domainDNT = dnt
264+ a.domainAces, a.domainACLProtect = a.resolveObjectSD(sdID, foundSD, "domain", false)
265+ }
266+
267+ if trust, isTrust := extractTrustFromRow(row, a.tree.GetRDN(dnt)); isTrust {
268+ a.domainTrusts = append(a.domainTrusts, trust)
269+ return nil
270+ }
271+
272+ samVal, _ := row.Get("ATTm590045")
273+ if samVal == nil {
274+ rdnTyp, hasRDN := readInt64(row, "RDNtyp_col")
275+ if !hasRDN {
276+ rdnTyp = 3
277+ }
278+
279+ var guidStr string
280+ if guidHex := readString(row, "ATTk589826"); len(guidHex) == 32 {
281+ if gb, err := hex.DecodeString(guidHex); err == nil && len(gb) == 16 {
282+ guidStr = formatGUIDUpper(gb)
283+ }
284+ }
285+
286+ if rdnTyp == 1376280 || rdnTyp == 11 || (dnUpper != "" && strings.HasPrefix(dnUpper, "OU=")) {
287+ ouName := readString(row, "ATTm11")
288+ if ouName == "" {
289+ ouName = readString(row, "ATTm1376280")
290+ }
291+ if ouName == "" {
292+ ouName = a.tree.GetRDN(dnt)
293+ }
294+ if guidStr == "" {
295+ guidStr = fmt.Sprintf("OU-%d", dnt)
296+ }
297+
298+ blocksInheritance := false
299+ if gpOpt, hasGP := readInt64(row, "ATTj589846"); hasGP && (gpOpt&1) != 0 {
300+ blocksInheritance = true
301+ } else if readString(row, "ATTm589846") == "1" {
302+ blocksInheritance = true
303+ }
304+
305+ aces, isACLProtected := a.resolveObjectSD(sdID, foundSD, "ou", false)
306+
307+ ouObj := &OUObject{
308+ ObjectIdentifier: guidStr,
309+ ChildObjects: make([]TypedPrincipal, 0),
310+ Links: make([]interface{}, 0),
311+ Aces: aces,
312+ IsACLProtected: isACLProtected,
313+ DNT: dnt,
314+ PDNT: pdnt,
315+ Properties: map[string]interface{}{
316+ "domain": a.Snapshot.DomainName,
317+ "name": fmt.Sprintf("%s@%s", strings.ToUpper(ouName), a.Snapshot.DomainName),
318+ "distinguishedname": dnUpper,
319+ "domainsid": a.Snapshot.DomainSID,
320+ "highvalue": false,
321+ "objectid": guidStr,
322+ "blocksinheritance": blocksInheritance,
323+ "isaclprotected": isACLProtected,
324+ "description": readOptionalDescription(row),
325+ },
326+ }
327+ a.Snapshot.OUs = append(a.Snapshot.OUs, ouObj)
328+ a.Snapshot.OUsByGUID[guidStr] = ouObj
329+ a.ousByDNT[dnt] = ouObj
330+ a.Snapshot.ObjectsByDNT[dnt] = TypedPrincipal{ObjectIdentifier: guidStr, ObjectType: "OU"}
331+ }
332+ return nil
333+ }
334+
335+ sam, ok := samVal.(string)
336+ if !ok || len(sam) == 0 || sidStr == "" {
337+ return nil
338+ }
339+
340+ uacVal, _ := readInt64(row, "ATTj589832")
341+ uac := uint32(uacVal)
342+
343+ samAccountType, _ := readInt64(row, "ATTj590126")
344+ if samAccountType == 805306370 || (uac&0x0800) != 0 {
345+ return nil
346+ }
347+
348+ var primaryGroupID uint32 = 513
349+ pgInt, hasPG := readInt64(row, "ATTj589922")
350+ if hasPG {
351+ primaryGroupID = uint32(pgInt)
352+ }
353+
354+ acInt, _ := readInt64(row, "ATTj589842")
355+ isAdmin := acInt > 0
356+
357+ var pwdLastSet int64 = -1
358+ if plsInt, hasPLS := readInt64(row, "ATTq589983"); hasPLS {
359+ pwdLastSet = filetimeToUnix(plsInt)
360+ }
361+
362+ var lastLogonTS int64 = -1
363+ if llTSInt, hasLLTS := readInt64(row, "ATTq590204"); hasLLTS {
364+ lastLogonTS = filetimeToUnix(llTSInt)
365+ }
366+
367+ var lastLogon int64 = -1
368+ if llInt, hasLL := readInt64(row, "ATTq589876"); hasLL {
369+ lastLogon = filetimeToUnix(llInt)
370+ }
371+
372+ var ntHashHex string
373+ if a.cryptoEngine != nil && len(a.cryptoEngine.PEKList) > 0 && rid > 0 {
374+ if pwdVal, ok := row.Get("ATTk589914"); ok && pwdVal != nil {
375+ if pwdHex, ok := pwdVal.(string); ok && len(pwdHex) > 0 {
376+ if encBytes, err := hex.DecodeString(pwdHex); err == nil {
377+ if decHash, err := a.cryptoEngine.DecryptHash(encBytes, rid); err == nil {
378+ ntHashHex = hex.EncodeToString(decHash)
379+ }
380+ }
381+ }
382+ }
383+ }
384+
385+ spns := readStringSlice(row, "ATTm590595")
386+ delegateTargets := readStringSlice(row, "ATTm591788")
387+ sidHistory := readESESIDSlice(row, "ATTr590433")
388+ if sidHistory == nil {
389+ sidHistory = make([]string, 0)
390+ }
391+ desc := readOptionalDescription(row)
392+ gmsaHex := readString(row, "ATTk592202")
393+ rbcdHex := readString(row, "ATTk592023")
394+
395+ _, hasLegacyLAPSExp := readInt64(row, "ATTq591790")
396+ _, hasWinLAPSExp := readInt64(row, "ATTq592270")
397+ hasLAPS := hasLegacyLAPSExp || hasWinLAPSExp || readString(row, "ATTm591789") != ""
398+
399+ isGroup := samAccountType == 268435456 || samAccountType == 268435457 ||
400+ samAccountType == 536870912 || samAccountType == 536870913 ||
401+ (samAccountType == 0 && uac == 0 && !hasPG && ntHashHex == "" && !strings.HasSuffix(sam, "$"))
402+
403+ isComputer := !isGroup && gmsaHex == "" &&
404+ (samAccountType == 805306369 || (samAccountType == 0 && strings.HasSuffix(sam, "$")))
405+
406+ if isComputer {
407+ dnsName := readString(row, "ATTm590443")
408+ if dnsName == "" {
409+ baseHost := strings.TrimSuffix(sam, "$")
410+ dnsName = fmt.Sprintf("%s.%s", baseHost, a.Snapshot.DomainName)
411+ }
412+
413+ osName := readString(row, "ATTm590187")
414+ osVer := readString(row, "ATTm590188")
415+ isDC := (uac&0x2000) != 0 || primaryGroupID == 516 || strings.Contains(dnUpper, "OU=DOMAIN CONTROLLERS,")
416+
417+ aces, isACLProtected := a.resolveObjectSD(sdID, foundSD, "computer", hasLAPS)
418+
419+ var rawAllowedToAct []string
420+ if rbcdHex != "" {
421+ if rbcdBytes, err := hex.DecodeString(rbcdHex); err == nil {
422+ rbcdAces, _, _ := acl.ParseSecurityDescriptorForType(rbcdBytes, "rbcd", false, nil)
423+ for _, ra := range rbcdAces {
424+ rawAllowedToAct = append(rawAllowedToAct, ra.PrincipalSID)
425+ }
426+ }
427+ }
428+
429+ comp := &ComputerObject{
430+ ObjectIdentifier: sidStr,
431+ PrimaryGroupSID: fmt.Sprintf("%s-%d", a.Snapshot.DomainSID, primaryGroupID),
432+ AllowedToDelegate: make([]TypedPrincipal, 0),
433+ AllowedToAct: make([]TypedPrincipal, 0),
434+ HasSIDHistory: make([]TypedPrincipal, 0),
435+ DumpSMSAPassword: make([]TypedPrincipal, 0),
436+ Sessions: EmptySessionCollection(),
437+ PrivilegedSessions: EmptySessionCollection(),
438+ RegistrySessions: EmptySessionCollection(),
439+ LocalGroups: make([]interface{}, 0),
440+ UserRights: make([]interface{}, 0),
441+ Aces: aces,
442+ IsACLProtected: isACLProtected,
443+ IsDC: isDC,
444+ DNT: dnt,
445+ PDNT: pdnt,
446+ NTHash: ntHashHex,
447+ RawDelegateTargets: delegateTargets,
448+ RawAllowedToAct: rawAllowedToAct,
449+ RawSIDHistory: sidHistory,
450+ Properties: map[string]interface{}{
451+ "domain": a.Snapshot.DomainName,
452+ "name": strings.ToUpper(dnsName),
453+ "distinguishedname": dnUpper,
454+ "domainsid": a.Snapshot.DomainSID,
455+ "highvalue": isDC,
456+ "objectid": sidStr,
457+ "samaccountname": sam,
458+ "enabled": (uac & 2) == 0,
459+ "haslaps": hasLAPS,
460+ "isaclprotected": isACLProtected,
461+ "isdc": isDC,
462+ "operatingsystem": osName,
463+ "operatingsystemversion": osVer,
464+ "pwdlastset": pwdLastSet,
465+ "lastlogon": lastLogon,
466+ "lastlogontimestamp": lastLogonTS,
467+ "unconstraineddelegation": (uac & 0x80000) != 0,
468+ "trustedtoauth": (uac & 0x1000000) != 0,
469+ "serviceprincipalnames": spns,
470+ "sidhistory": sidHistory,
471+ "description": desc,
472+ "nthash": ntHashHex,
473+ },
474+ }
475+ a.Snapshot.Computers = append(a.Snapshot.Computers, comp)
476+ a.Snapshot.ComputersBySID[sidStr] = comp
477+ a.Snapshot.ObjectsByDNT[dnt] = TypedPrincipal{ObjectIdentifier: sidStr, ObjectType: "Computer"}
478+
479+ } else if !isGroup {
480+ upn := readString(row, "ATTm590480")
481+ aces, isACLProtected := a.resolveObjectSD(sdID, foundSD, "user", false)
482+
483+ if gmsaHex != "" {
484+ if gmsaBytes, err := hex.DecodeString(gmsaHex); err == nil {
485+ gmsaAces, _, _ := acl.ParseSecurityDescriptorForType(gmsaBytes, "gmsa", false, nil)
486+ aces = append(aces, gmsaAces...)
487+ }
488+ }
489+
490+ userName := fmt.Sprintf("%s@%s", strings.ToUpper(sam), a.Snapshot.DomainName)
491+ user := &UserObject{
492+ ObjectIdentifier: sidStr,
493+ PrimaryGroupSID: fmt.Sprintf("%s-%d", a.Snapshot.DomainSID, primaryGroupID),
494+ AllowedToDelegate: make([]TypedPrincipal, 0),
495+ SPNTargets: make([]interface{}, 0),
496+ HasSIDHistory: make([]TypedPrincipal, 0),
497+ Aces: aces,
498+ IsACLProtected: isACLProtected,
499+ DNT: dnt,
500+ PDNT: pdnt,
501+ NTHash: ntHashHex,
502+ RawDelegateTargets: delegateTargets,
503+ RawSIDHistory: sidHistory,
504+ Properties: map[string]interface{}{
505+ "domain": a.Snapshot.DomainName,
506+ "name": userName,
507+ "distinguishedname": dnUpper,
508+ "domainsid": a.Snapshot.DomainSID,
509+ "highvalue": isAdmin || rid == 500,
510+ "objectid": sidStr,
511+ "samaccountname": sam,
512+ "enabled": (uac & 2) == 0,
513+ "pwdlastset": pwdLastSet,
514+ "lastlogon": lastLogon,
515+ "lastlogontimestamp": lastLogonTS,
516+ "userprincipalname": upn,
517+ "admincount": isAdmin,
518+ "dontreqpreauth": (uac & 0x400000) != 0,
519+ "passwordnotreqd": (uac & 0x20) != 0,
520+ "pwdneverexpires": (uac & 0x10000) != 0,
521+ "sensitive": (uac & 0x100000) != 0,
522+ "unconstraineddelegation": (uac & 0x80000) != 0,
523+ "trustedtoauth": (uac & 0x1000000) != 0,
524+ "isaclprotected": isACLProtected,
525+ "hasspn": len(spns) > 0,
526+ "serviceprincipalnames": spns,
527+ "sidhistory": sidHistory,
528+ "haslaps": false,
529+ "description": desc,
530+ "nthash": ntHashHex,
531+ },
532+ }
533+ a.Snapshot.Users = append(a.Snapshot.Users, user)
534+ a.Snapshot.UsersBySID[sidStr] = user
535+ a.Snapshot.ObjectsByDNT[dnt] = TypedPrincipal{ObjectIdentifier: sidStr, ObjectType: "User"}
536+
537+ } else {
538+ aces, isACLProtected := a.resolveObjectSD(sdID, foundSD, "group", false)
539+ objID := sidStr
540+ if _, isWK := wellKnownSIDs[sidStr]; isWK && a.Snapshot.DomainName != "" {
541+ objID = fmt.Sprintf("%s-%s", a.Snapshot.DomainName, sidStr)
542+ }
543+
544+ groupName := fmt.Sprintf("%s@%s", strings.ToUpper(sam), a.Snapshot.DomainName)
545+ grp := &GroupObject{
546+ ObjectIdentifier: objID,
547+ Members: make([]MemberReference, 0),
548+ Aces: aces,
549+ IsACLProtected: isACLProtected,
550+ DNT: dnt,
551+ PDNT: pdnt,
552+ Properties: map[string]interface{}{
553+ "domain": a.Snapshot.DomainName,
554+ "name": groupName,
555+ "distinguishedname": dnUpper,
556+ "domainsid": a.Snapshot.DomainSID,
557+ "highvalue": isAdmin || isHighValueGroupSID(sidStr, rid),
558+ "objectid": objID,
559+ "samaccountname": sam,
560+ "admincount": isAdmin,
561+ "isaclprotected": isACLProtected,
562+ "description": desc,
563+ },
564+ }
565+ a.Snapshot.Groups = append(a.Snapshot.Groups, grp)
566+ a.Snapshot.GroupsBySID[objID] = grp
567+ if objID != sidStr {
568+ a.Snapshot.GroupsBySID[sidStr] = grp
569+ }
570+ a.groupsByDNT[dnt] = grp
571+ a.Snapshot.ObjectsByDNT[dnt] = TypedPrincipal{ObjectIdentifier: objID, ObjectType: "Group"}
572+ }
573+
574+ return nil
575+ })
576+}
577+
578+func (a *Assembler) processLinks() error {
579+ return a.db.StreamTable("link_table", func(row *ordereddict.Dict) error {
580+ linkBaseVal, ok := row.Get("link_base")
581+ if !ok || linkBaseVal == nil {
582+ return nil
583+ }
584+
585+ var linkBase uint32
586+ switch v := linkBaseVal.(type) {
587+ case int32:
588+ linkBase = uint32(v)
589+ case uint32:
590+ linkBase = v
591+ case int64:
592+ linkBase = uint32(v)
593+ case uint64:
594+ linkBase = uint32(v)
595+ }
596+ if linkBase != 1 {
597+ return nil
598+ }
599+
600+ linkDNTVal, _ := row.Get("link_DNT")
601+ backlinkDNTVal, _ := row.Get("backlink_DNT")
602+ if linkDNTVal == nil || backlinkDNTVal == nil {
603+ return nil
604+ }
605+
606+ var groupDNT, memberDNT uint64
607+ switch v := linkDNTVal.(type) {
608+ case uint64:
609+ groupDNT = v
610+ case int64:
611+ groupDNT = uint64(v)
612+ case int32:
613+ groupDNT = uint64(v)
614+ case uint32:
615+ groupDNT = uint64(v)
616+ }
617+ switch v := backlinkDNTVal.(type) {
618+ case uint64:
619+ memberDNT = v
620+ case int64:
621+ memberDNT = uint64(v)
622+ case int32:
623+ memberDNT = uint64(v)
624+ case uint32:
625+ memberDNT = uint64(v)
626+ }
627+
628+ grp, exists := a.groupsByDNT[groupDNT]
629+ if !exists {
630+ return nil
631+ }
632+
633+ targetPrincipal, exists := a.Snapshot.ObjectsByDNT[memberDNT]
634+ if !exists || targetPrincipal.ObjectIdentifier == "" {
635+ return nil
636+ }
637+
638+ for _, m := range grp.Members {
639+ if m.ObjectIdentifier == targetPrincipal.ObjectIdentifier {
640+ return nil
641+ }
642+ }
643+
644+ grp.Members = append(grp.Members, MemberReference{
645+ ObjectIdentifier: targetPrincipal.ObjectIdentifier,
646+ ObjectType: targetPrincipal.ObjectType,
647+ })
648+
649+ return nil
650+ })
651+}
652+
653+func (a *Assembler) processPrimaryGroups() {
654+ for _, u := range a.Snapshot.Users {
655+ if grp, exists := a.Snapshot.GroupsBySID[u.PrimaryGroupSID]; exists {
656+ alreadyMember := false
657+ for _, m := range grp.Members {
658+ if m.ObjectIdentifier == u.ObjectIdentifier {
659+ alreadyMember = true
660+ break
661+ }
662+ }
663+ if !alreadyMember {
664+ grp.Members = append(grp.Members, MemberReference{
665+ ObjectIdentifier: u.ObjectIdentifier,
666+ ObjectType: "User",
667+ })
668+ }
669+ }
670+ }
671+
672+ for _, c := range a.Snapshot.Computers {
673+ if grp, exists := a.Snapshot.GroupsBySID[c.PrimaryGroupSID]; exists {
674+ alreadyMember := false
675+ for _, m := range grp.Members {
676+ if m.ObjectIdentifier == c.ObjectIdentifier {
677+ alreadyMember = true
678+ break
679+ }
680+ }
681+ if !alreadyMember {
682+ grp.Members = append(grp.Members, MemberReference{
683+ ObjectIdentifier: c.ObjectIdentifier,
684+ ObjectType: "Computer",
685+ })
686+ }
687+ }
688+ }
689+
690+ if a.Snapshot.DomainSID != "" {
691+ if a.domainAces == nil {
692+ a.domainAces = make([]acl.Ace, 0)
693+ }
694+ domDN := fmt.Sprintf("DC=%s", strings.ReplaceAll(strings.ToUpper(a.Snapshot.DomainName), ".", ",DC="))
695+ domObj := &DomainObject{
696+ ObjectIdentifier: a.Snapshot.DomainSID,
697+ ChildObjects: make([]TypedPrincipal, 0),
698+ Trusts: a.domainTrusts,
699+ Links: make([]interface{}, 0),
700+ Aces: a.domainAces,
701+ IsACLProtected: a.domainACLProtect,
702+ DNT: a.domainDNT,
703+ Properties: map[string]interface{}{
704+ "domain": a.Snapshot.DomainName,
705+ "name": a.Snapshot.DomainName,
706+ "distinguishedname": domDN,
707+ "domainsid": a.Snapshot.DomainSID,
708+ "highvalue": true,
709+ "objectid": a.Snapshot.DomainSID,
710+ "functionallevel": a.domainFuncLevel,
711+ "isaclprotected": a.domainACLProtect,
712+ "collected": true,
713+ "description": a.domainDescription,
714+ },
715+ }
716+ a.Snapshot.Domains = append(a.Snapshot.Domains, domObj)
717+ }
718+}
719+
720+func (a *Assembler) synthesizeWellKnownGroups() {
721+ if a.Snapshot.DomainName == "" {
722+ return
723+ }
724+
725+ defaults := []struct {
726+ rawSID string
727+ name string
728+ }{
729+ {rawSID: "S-1-1-0", name: "EVERYONE"},
730+ {rawSID: "S-1-5-11", name: "AUTHENTICATED USERS"},
731+ {rawSID: "S-1-5-4", name: "INTERACTIVE"},
732+ {rawSID: "S-1-5-9", name: "ENTERPRISE DOMAIN CONTROLLERS"},
733+ }
734+
735+ for _, def := range defaults {
736+ prefixedID := fmt.Sprintf("%s-%s", a.Snapshot.DomainName, def.rawSID)
737+ if _, exists := a.Snapshot.GroupsBySID[prefixedID]; exists {
738+ continue
739+ }
740+ if _, exists := a.Snapshot.GroupsBySID[def.rawSID]; exists {
741+ continue
742+ }
743+
744+ members := make([]MemberReference, 0)
745+ if def.rawSID == "S-1-5-9" {
746+ for _, comp := range a.Snapshot.Computers {
747+ if comp.IsDC {
748+ members = append(members, MemberReference{
749+ ObjectIdentifier: comp.ObjectIdentifier,
750+ ObjectType: "Computer",
751+ })
752+ }
753+ }
754+ }
755+
756+ grp := &GroupObject{
757+ ObjectIdentifier: prefixedID,
758+ Members: members,
759+ Aces: make([]acl.Ace, 0),
760+ Synthetic: true,
761+ Properties: map[string]interface{}{
762+ "domain": a.Snapshot.DomainName,
763+ "domainsid": a.Snapshot.DomainSID,
764+ "name": fmt.Sprintf("%s@%s", def.name, a.Snapshot.DomainName),
765+ "objectid": prefixedID,
766+ "highvalue": false,
767+ },
768+ }
769+ a.Snapshot.Groups = append(a.Snapshot.Groups, grp)
770+ a.Snapshot.GroupsBySID[prefixedID] = grp
771+ a.Snapshot.GroupsBySID[def.rawSID] = grp
772+ }
773+}
774+
775+func (a *Assembler) resolveSID(rawSID string) (string, string) {
776+ if rawSID == "" {
777+ return "", "Base"
778+ }
779+ if rawSID == a.Snapshot.DomainSID {
780+ return rawSID, "Domain"
781+ }
782+ if u, ok := a.Snapshot.UsersBySID[rawSID]; ok {
783+ return u.ObjectIdentifier, "User"
784+ }
785+ if c, ok := a.Snapshot.ComputersBySID[rawSID]; ok {
786+ return c.ObjectIdentifier, "Computer"
787+ }
788+ if g, ok := a.Snapshot.GroupsBySID[rawSID]; ok {
789+ return g.ObjectIdentifier, "Group"
790+ }
791+ if wk, ok := wellKnownSIDs[rawSID]; ok && a.Snapshot.DomainName != "" {
792+ return fmt.Sprintf("%s-%s", a.Snapshot.DomainName, rawSID), wk.Type
793+ }
794+ return rawSID, "Base"
795+}
796+
797+func (a *Assembler) resolveDelegateSPNs(spns []string) []TypedPrincipal {
798+ out := make([]TypedPrincipal, 0)
799+ if len(spns) == 0 {
800+ return out
801+ }
802+
803+ compByHost := make(map[string]*ComputerObject)
804+ for _, c := range a.Snapshot.Computers {
805+ if nameStr, ok := c.Properties["name"].(string); ok && nameStr != "" {
806+ upper := strings.ToUpper(nameStr)
807+ compByHost[upper] = c
808+ if idx := strings.IndexByte(upper, '.'); idx > 0 {
809+ compByHost[upper[:idx]] = c
810+ }
811+ }
812+ if samStr, ok := c.Properties["samaccountname"].(string); ok && samStr != "" {
813+ short := strings.ToUpper(strings.TrimSuffix(samStr, "$"))
814+ compByHost[short] = c
815+ }
816+ }
817+
818+ seen := make(map[string]bool)
819+ for _, spn := range spns {
820+ parts := strings.SplitN(spn, "/", 2)
821+ if len(parts) < 2 {
822+ continue
823+ }
824+ host := strings.ToUpper(parts[1])
825+ if idx := strings.IndexByte(host, ':'); idx > 0 {
826+ host = host[:idx]
827+ }
828+ if idx := strings.IndexByte(host, '/'); idx > 0 {
829+ host = host[:idx]
830+ }
831+ comp, ok := compByHost[host]
832+ if !ok {
833+ if dot := strings.IndexByte(host, '.'); dot > 0 {
834+ comp, ok = compByHost[host[:dot]]
835+ }
836+ }
837+ if ok && comp != nil && !seen[comp.ObjectIdentifier] {
838+ seen[comp.ObjectIdentifier] = true
839+ out = append(out, TypedPrincipal{
840+ ObjectIdentifier: comp.ObjectIdentifier,
841+ ObjectType: "Computer",
842+ })
843+ }
844+ }
845+ return out
846+}
847+
848+func (a *Assembler) resolveSIDList(rawSIDs []string) []TypedPrincipal {
849+ out := make([]TypedPrincipal, 0, len(rawSIDs))
850+ seen := make(map[string]bool)
851+ for _, s := range rawSIDs {
852+ id, pType := a.resolveSID(s)
853+ if id != "" && !seen[id] {
854+ seen[id] = true
855+ out = append(out, TypedPrincipal{
856+ ObjectIdentifier: id,
857+ ObjectType: pType,
858+ })
859+ }
860+ }
861+ return out
862+}
863+
864+func (a *Assembler) rewriteAces(aces []acl.Ace) {
865+ for i := range aces {
866+ aces[i].PrincipalSID, aces[i].PrincipalType = a.resolveSID(aces[i].PrincipalSID)
867+ }
868+}
869+
870+func (a *Assembler) resolvePrincipalsAndAces() {
871+ for _, u := range a.Snapshot.Users {
872+ a.rewriteAces(u.Aces)
873+ u.AllowedToDelegate = a.resolveDelegateSPNs(u.RawDelegateTargets)
874+ u.HasSIDHistory = a.resolveSIDList(u.RawSIDHistory)
875+ }
876+ for _, g := range a.Snapshot.Groups {
877+ a.rewriteAces(g.Aces)
878+ }
879+ for _, c := range a.Snapshot.Computers {
880+ a.rewriteAces(c.Aces)
881+ c.AllowedToDelegate = a.resolveDelegateSPNs(c.RawDelegateTargets)
882+ c.AllowedToAct = a.resolveSIDList(c.RawAllowedToAct)
883+ c.HasSIDHistory = a.resolveSIDList(c.RawSIDHistory)
884+ }
885+ for _, d := range a.Snapshot.Domains {
886+ a.rewriteAces(d.Aces)
887+ }
888+ for _, o := range a.Snapshot.OUs {
889+ a.rewriteAces(o.Aces)
890+ }
891+}
892+
893+func (a *Assembler) linkContainment() {
894+ var rootDom *DomainObject
895+ if len(a.Snapshot.Domains) > 0 {
896+ rootDom = a.Snapshot.Domains[0]
897+ }
898+
899+ addChild := func(pdnt uint64, childID string, childType string) {
900+ if childID == "" {
901+ return
902+ }
903+ tp := TypedPrincipal{
904+ ObjectIdentifier: childID,
905+ ObjectType: childType,
906+ }
907+
908+ curr := pdnt
909+ visited := make(map[uint64]bool)
910+ for curr != 0 && !visited[curr] {
911+ visited[curr] = true
912+ if ou, ok := a.ousByDNT[curr]; ok {
913+ ou.ChildObjects = append(ou.ChildObjects, tp)
914+ return
915+ }
916+ if a.domainDNT != 0 && curr == a.domainDNT {
917+ if rootDom != nil {
918+ rootDom.ChildObjects = append(rootDom.ChildObjects, tp)
919+ }
920+ return
921+ }
922+ next, exists := a.Snapshot.PDNTByDNT[curr]
923+ if !exists || next == curr {
924+ break
925+ }
926+ curr = next
927+ }
928+
929+ if a.domainDNT == 0 && rootDom != nil {
930+ rootDom.ChildObjects = append(rootDom.ChildObjects, tp)
931+ }
932+ }
933+
934+ for _, ou := range a.Snapshot.OUs {
935+ addChild(ou.PDNT, ou.ObjectIdentifier, "OU")
936+ }
937+
938+ for _, u := range a.Snapshot.Users {
939+ addChild(u.PDNT, u.ObjectIdentifier, "User")
940+ }
941+
942+ for _, c := range a.Snapshot.Computers {
943+ addChild(c.PDNT, c.ObjectIdentifier, "Computer")
944+ }
945+
946+ for _, g := range a.Snapshot.Groups {
947+ if g.Synthetic {
948+ continue
949+ }
950+ addChild(g.PDNT, g.ObjectIdentifier, "Group")
951+ }
952+}
pkg/ad/helpers.go
......@@ -0,0 +1,355 @@
1+package ad
2+
3+import (
4+ "encoding/binary"
5+ "encoding/hex"
6+ "fmt"
7+ "strings"
8+
9+ "github.com/Velocidex/ordereddict"
10+ "github.com/shehzade/ntds-to-bloodhound/pkg/crypto"
11+)
12+
13+type wellKnownDef struct {
14+ Name string
15+ Type string
16+}
17+
18+var wellKnownSIDs = map[string]wellKnownDef{
19+ "S-1-0": {Name: "Null Authority", Type: "User"},
20+ "S-1-0-0": {Name: "Nobody", Type: "User"},
21+ "S-1-1": {Name: "World Authority", Type: "User"},
22+ "S-1-1-0": {Name: "Everyone", Type: "Group"},
23+ "S-1-2": {Name: "Local Authority", Type: "User"},
24+ "S-1-2-0": {Name: "Local", Type: "Group"},
25+ "S-1-2-1": {Name: "Console Logon", Type: "Group"},
26+ "S-1-3": {Name: "Creator Authority", Type: "User"},
27+ "S-1-3-0": {Name: "Creator Owner", Type: "User"},
28+ "S-1-3-1": {Name: "Creator Group", Type: "Group"},
29+ "S-1-3-2": {Name: "Creator Owner Server", Type: "Computer"},
30+ "S-1-3-3": {Name: "Creator Group Server", Type: "Computer"},
31+ "S-1-3-4": {Name: "Owner Rights", Type: "Group"},
32+ "S-1-4": {Name: "Non-unique Authority", Type: "User"},
33+ "S-1-5": {Name: "NT Authority", Type: "User"},
34+ "S-1-5-1": {Name: "Dialup", Type: "Group"},
35+ "S-1-5-2": {Name: "Network", Type: "Group"},
36+ "S-1-5-3": {Name: "Batch", Type: "Group"},
37+ "S-1-5-4": {Name: "Interactive", Type: "Group"},
38+ "S-1-5-6": {Name: "Service", Type: "Group"},
39+ "S-1-5-7": {Name: "Anonymous", Type: "Group"},
40+ "S-1-5-8": {Name: "Proxy", Type: "Group"},
41+ "S-1-5-9": {Name: "Enterprise Domain Controllers", Type: "Group"},
42+ "S-1-5-10": {Name: "Principal Self", Type: "User"},
43+ "S-1-5-11": {Name: "Authenticated Users", Type: "Group"},
44+ "S-1-5-12": {Name: "Restricted Code", Type: "Group"},
45+ "S-1-5-13": {Name: "Terminal Server Users", Type: "Group"},
46+ "S-1-5-14": {Name: "Remote Interactive Logon", Type: "Group"},
47+ "S-1-5-15": {Name: "This Organization", Type: "Group"},
48+ "S-1-5-17": {Name: "IUSR", Type: "User"},
49+ "S-1-5-18": {Name: "Local System", Type: "User"},
50+ "S-1-5-19": {Name: "NT Authority", Type: "User"},
51+ "S-1-5-20": {Name: "Network Service", Type: "User"},
52+ "S-1-5-80-0": {Name: "All Services", Type: "Group"},
53+ "S-1-5-32-544": {Name: "Administrators", Type: "Group"},
54+ "S-1-5-32-545": {Name: "Users", Type: "Group"},
55+ "S-1-5-32-546": {Name: "Guests", Type: "Group"},
56+ "S-1-5-32-547": {Name: "Power Users", Type: "Group"},
57+ "S-1-5-32-548": {Name: "Account Operators", Type: "Group"},
58+ "S-1-5-32-549": {Name: "Server Operators", Type: "Group"},
59+ "S-1-5-32-550": {Name: "Print Operators", Type: "Group"},
60+ "S-1-5-32-551": {Name: "Backup Operators", Type: "Group"},
61+ "S-1-5-32-552": {Name: "Replicators", Type: "Group"},
62+ "S-1-5-32-554": {Name: "Pre-Windows 2000 Compatible Access", Type: "Group"},
63+ "S-1-5-32-555": {Name: "Remote Desktop Users", Type: "Group"},
64+ "S-1-5-32-556": {Name: "Network Configuration Operators", Type: "Group"},
65+ "S-1-5-32-557": {Name: "Incoming Forest Trust Builders", Type: "Group"},
66+ "S-1-5-32-558": {Name: "Performance Monitor Users", Type: "Group"},
67+ "S-1-5-32-559": {Name: "Performance Log Users", Type: "Group"},
68+ "S-1-5-32-560": {Name: "Windows Authorization Access Group", Type: "Group"},
69+ "S-1-5-32-561": {Name: "Terminal Server License Servers", Type: "Group"},
70+ "S-1-5-32-562": {Name: "Distributed COM Users", Type: "Group"},
71+ "S-1-5-32-568": {Name: "IIS_IUSRS", Type: "Group"},
72+ "S-1-5-32-569": {Name: "Cryptographic Operators", Type: "Group"},
73+ "S-1-5-32-573": {Name: "Event Log Readers", Type: "Group"},
74+ "S-1-5-32-574": {Name: "Certificate Service DCOM Access", Type: "Group"},
75+ "S-1-5-32-575": {Name: "RDS Remote Access Servers", Type: "Group"},
76+ "S-1-5-32-576": {Name: "RDS Endpoint Servers", Type: "Group"},
77+ "S-1-5-32-577": {Name: "RDS Management Servers", Type: "Group"},
78+ "S-1-5-32-578": {Name: "Hyper-V Administrators", Type: "Group"},
79+ "S-1-5-32-579": {Name: "Access Control Assistance Operators", Type: "Group"},
80+ "S-1-5-32-580": {Name: "Remote Management Users", Type: "Group"},
81+ "S-1-5-32-582": {Name: "Storage Replica Administrators", Type: "Group"},
82+}
83+
84+func functionalLevelName(level int64) string {
85+ switch level {
86+ case 0:
87+ return "2000 Mixed/Native"
88+ case 1:
89+ return "2003 Interim"
90+ case 2:
91+ return "2003"
92+ case 3:
93+ return "2008"
94+ case 4:
95+ return "2008 R2"
96+ case 5:
97+ return "2012"
98+ case 6:
99+ return "2012 R2"
100+ case 7:
101+ return "2016"
102+ default:
103+ if level > 7 {
104+ return "2016"
105+ }
106+ return "Unknown"
107+ }
108+}
109+
110+func isHighValueGroupSID(rawSID string, rid uint32) bool {
111+ if rid == 512 || rid == 516 || rid == 519 {
112+ return true
113+ }
114+ switch rawSID {
115+ 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":
116+ return true
117+ }
118+ return false
119+}
120+
121+func filetimeToUnix(ft int64) int64 {
122+ if ft <= 0 || ft == 0x7FFFFFFFFFFFFFFF {
123+ if ft == 0 {
124+ return 0
125+ }
126+ return -1
127+ }
128+ const epochDiff = int64(116444736000000000)
129+ if ft < epochDiff {
130+ return ft
131+ }
132+ return (ft - epochDiff) / 10000000
133+}
134+
135+func readInt64(row *ordereddict.Dict, col string) (int64, bool) {
136+ val, ok := row.Get(col)
137+ if !ok || val == nil {
138+ return 0, false
139+ }
140+ switch v := val.(type) {
141+ case int64:
142+ return v, true
143+ case uint64:
144+ return int64(v), true
145+ case int32:
146+ return int64(v), true
147+ case uint32:
148+ return int64(v), true
149+ case int:
150+ return int64(v), true
151+ case bool:
152+ if v {
153+ return 1, true
154+ }
155+ return 0, true
156+ }
157+ return 0, false
158+}
159+
160+func readUint64(row *ordereddict.Dict, col string) (uint64, bool) {
161+ v, ok := readInt64(row, col)
162+ if !ok {
163+ return 0, false
164+ }
165+ return uint64(v), true
166+}
167+
168+func readString(row *ordereddict.Dict, col string) string {
169+ val, ok := row.Get(col)
170+ if !ok || val == nil {
171+ return ""
172+ }
173+ if s, ok := val.(string); ok {
174+ return s
175+ }
176+ return ""
177+}
178+
179+func readOptionalDescription(row *ordereddict.Dict) interface{} {
180+ s := readString(row, "ATTm13")
181+ if s == "" {
182+ return nil
183+ }
184+ return s
185+}
186+
187+func readStringSlice(row *ordereddict.Dict, col string) []string {
188+ val, ok := row.Get(col)
189+ if !ok || val == nil {
190+ return make([]string, 0)
191+ }
192+ switch v := val.(type) {
193+ case string:
194+ if v == "" {
195+ return make([]string, 0)
196+ }
197+ return []string{v}
198+ case []string:
199+ out := make([]string, 0, len(v))
200+ for _, item := range v {
201+ if item != "" {
202+ out = append(out, item)
203+ }
204+ }
205+ return out
206+ case []interface{}:
207+ out := make([]string, 0, len(v))
208+ for _, item := range v {
209+ if s, ok := item.(string); ok && s != "" {
210+ out = append(out, s)
211+ }
212+ }
213+ return out
214+ }
215+ return make([]string, 0)
216+}
217+
218+func readESESIDSlice(row *ordereddict.Dict, col string) []string {
219+ rawVals := readStringSlice(row, col)
220+ if len(rawVals) == 0 {
221+ return nil
222+ }
223+ var out []string
224+ for _, hexStr := range rawVals {
225+ if b, err := hex.DecodeString(hexStr); err == nil {
226+ if s, _, err := crypto.ParseSID(b); err == nil && s != "" {
227+ out = append(out, s)
228+ }
229+ }
230+ }
231+ return out
232+}
233+
234+func isRowDeleted(row *ordereddict.Dict, rdn string) bool {
235+ if delVal, ok := readInt64(row, "ATTb589872"); ok && delVal != 0 {
236+ return true
237+ }
238+ if strings.Contains(rdn, "\nDEL:") || strings.Contains(rdn, "\\0ADEL:") {
239+ return true
240+ }
241+ return false
242+}
243+
244+func isNonDomainPartitionDN(dnUpper string) bool {
245+ if dnUpper == "" {
246+ return false
247+ }
248+ return strings.Contains(dnUpper, "CN=DELETED OBJECTS,") ||
249+ strings.Contains(dnUpper, "\nDEL:") ||
250+ strings.Contains(dnUpper, "CN=SCHEMA,") ||
251+ strings.Contains(dnUpper, "CN=CONFIGURATION,") ||
252+ strings.Contains(dnUpper, "DC=DOMAINDNSZONES,") ||
253+ strings.Contains(dnUpper, "DC=FORESTDNSZONES,")
254+}
255+
256+func domainFromDN(dn string) string {
257+ var dcParts []string
258+ for _, part := range strings.Split(dn, ",") {
259+ p := strings.TrimSpace(part)
260+ if len(p) > 3 && strings.EqualFold(p[:3], "DC=") {
261+ comp := p[3:]
262+ if strings.EqualFold(comp, "DomainDnsZones") || strings.EqualFold(comp, "ForestDnsZones") {
263+ return ""
264+ }
265+ dcParts = append(dcParts, comp)
266+ }
267+ }
268+ if len(dcParts) == 0 {
269+ return ""
270+ }
271+ return strings.ToUpper(strings.Join(dcParts, "."))
272+}
273+
274+func formatGUIDUpper(b []byte) string {
275+ if len(b) < 16 {
276+ return ""
277+ }
278+ return fmt.Sprintf("%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
279+ binary.LittleEndian.Uint32(b[0:4]),
280+ binary.LittleEndian.Uint16(b[4:6]),
281+ binary.LittleEndian.Uint16(b[6:8]),
282+ b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15])
283+}
284+
285+func formatGUIDLower(b []byte) string {
286+ return strings.ToLower(formatGUIDUpper(b))
287+}
288+
289+func extractTrustFromRow(row *ordereddict.Dict, fallbackName string) (DomainTrust, bool) {
290+ partner := readString(row, "ATTm590362")
291+ dirVal, hasDir := readInt64(row, "ATTj589956")
292+ typeVal, hasType := readInt64(row, "ATTj589960")
293+ if partner == "" && (!hasDir || !hasType) {
294+ return DomainTrust{}, false
295+ }
296+ if partner == "" {
297+ partner = readString(row, "ATTm590359")
298+ }
299+ if partner == "" {
300+ partner = fallbackName
301+ }
302+ if partner == "" {
303+ return DomainTrust{}, false
304+ }
305+
306+ attrVal, _ := readInt64(row, "ATTj590294")
307+ var targetSID string
308+ if sidHex := readString(row, "ATTr589953"); sidHex != "" {
309+ if sb, err := hex.DecodeString(sidHex); err == nil {
310+ if s, _, err := crypto.ParseSID(sb); err == nil {
311+ targetSID = s
312+ }
313+ }
314+ }
315+
316+ nonTransitive := (attrVal & 0x00000001) != 0
317+ quarantined := (attrVal & 0x00000004) != 0
318+ forestTransitive := (attrVal & 0x00000008) != 0
319+ crossOrg := (attrVal & 0x00000010) != 0
320+ withinForest := (attrVal & 0x00000020) != 0
321+ treatAsExternal := (attrVal & 0x00000040) != 0
322+
323+ bhType := 4
324+ isTransitive := false
325+ sidFiltering := true
326+
327+ if withinForest {
328+ bhType = 0
329+ isTransitive = true
330+ sidFiltering = quarantined
331+ } else if forestTransitive {
332+ bhType = 2
333+ isTransitive = true
334+ sidFiltering = !treatAsExternal
335+ } else if treatAsExternal || crossOrg || quarantined {
336+ bhType = 3
337+ isTransitive = false
338+ sidFiltering = true
339+ } else {
340+ if typeVal == 1 || typeVal == 2 {
341+ bhType = 3
342+ }
343+ isTransitive = !nonTransitive
344+ sidFiltering = true
345+ }
346+
347+ return DomainTrust{
348+ TargetDomainName: strings.ToUpper(partner),
349+ TargetDomainSid: targetSID,
350+ IsTransitive: isTransitive,
351+ TrustDirection: int(dirVal),
352+ TrustType: bhType,
353+ SidFilteringEnabled: sidFiltering,
354+ }, true
355+}
pkg/ad/model.go
......@@ -0,0 +1,276 @@
1+package ad
2+
3+import "github.com/shehzade/ntds-to-bloodhound/pkg/acl"
4+
5+type MemberReference struct {
6+ ObjectIdentifier string `json:"ObjectIdentifier"`
7+ ObjectType string `json:"ObjectType"`
8+}
9+
10+type TypedPrincipal struct {
11+ ObjectIdentifier string `json:"ObjectIdentifier"`
12+ ObjectType string `json:"ObjectType"`
13+}
14+
15+type SessionCollection struct {
16+ Collected bool `json:"Collected"`
17+ FailureReason *string `json:"FailureReason"`
18+ Results []interface{} `json:"Results"`
19+}
20+
21+func EmptySessionCollection() SessionCollection {
22+ return SessionCollection{
23+ Collected: false,
24+ FailureReason: nil,
25+ Results: make([]interface{}, 0),
26+ }
27+}
28+
29+type DomainTrust struct {
30+ TargetDomainName string
31+ TargetDomainSid string
32+ IsTransitive bool
33+ TrustDirection int
34+ TrustType int
35+ SidFilteringEnabled bool
36+}
37+
38+type DomainTrustV4 struct {
39+ TargetDomainName string `json:"TargetDomainName"`
40+ TargetDomainSid string `json:"TargetDomainSid"`
41+ IsTransitive bool `json:"IsTransitive"`
42+ TrustDirection int `json:"TrustDirection"`
43+ TrustType int `json:"TrustType"`
44+ SidFilteringEnabled bool `json:"SidFilteringEnabled"`
45+}
46+
47+type DomainTrustV5 struct {
48+ TargetDomainName string `json:"TargetDomainName"`
49+ TargetDomainSid string `json:"TargetDomainSid"`
50+ IsTransitive bool `json:"IsTransitive"`
51+ TrustDirection string `json:"TrustDirection"`
52+ TrustType string `json:"TrustType"`
53+ SidFilteringEnabled bool `json:"SidFilteringEnabled"`
54+}
55+
56+func (t DomainTrust) DirectionString() string {
57+ switch t.TrustDirection {
58+ case 0:
59+ return "Disabled"
60+ case 1:
61+ return "Inbound"
62+ case 2:
63+ return "Outbound"
64+ case 3:
65+ return "Bidirectional"
66+ default:
67+ return "Disabled"
68+ }
69+}
70+
71+func (t DomainTrust) TypeString() string {
72+ switch t.TrustType {
73+ case 0:
74+ return "ParentChild"
75+ case 1:
76+ return "CrossLink"
77+ case 2:
78+ return "Forest"
79+ case 3:
80+ return "External"
81+ default:
82+ return "Unknown"
83+ }
84+}
85+
86+func (t DomainTrust) ToV4() DomainTrustV4 {
87+ return DomainTrustV4{
88+ TargetDomainName: t.TargetDomainName,
89+ TargetDomainSid: t.TargetDomainSid,
90+ IsTransitive: t.IsTransitive,
91+ TrustDirection: t.TrustDirection,
92+ TrustType: t.TrustType,
93+ SidFilteringEnabled: t.SidFilteringEnabled,
94+ }
95+}
96+
97+func (t DomainTrust) ToV5() DomainTrustV5 {
98+ return DomainTrustV5{
99+ TargetDomainName: t.TargetDomainName,
100+ TargetDomainSid: t.TargetDomainSid,
101+ IsTransitive: t.IsTransitive,
102+ TrustDirection: t.DirectionString(),
103+ TrustType: t.TypeString(),
104+ SidFilteringEnabled: t.SidFilteringEnabled,
105+ }
106+}
107+
108+type UserObject struct {
109+ ObjectIdentifier string `json:"ObjectIdentifier"`
110+ PrimaryGroupSID string `json:"PrimaryGroupSID,omitempty"`
111+ AllowedToDelegate []TypedPrincipal `json:"AllowedToDelegate"`
112+ SPNTargets []interface{} `json:"SPNTargets"`
113+ HasSIDHistory []TypedPrincipal `json:"HasSIDHistory"`
114+ Aces []acl.Ace `json:"Aces"`
115+ IsACLProtected bool `json:"IsACLProtected"`
116+ IsDeleted bool `json:"IsDeleted"`
117+ Properties map[string]interface{} `json:"Properties"`
118+ DNT uint64 `json:"-"`
119+ PDNT uint64 `json:"-"`
120+ NTHash string `json:"-"`
121+ LMHash string `json:"-"`
122+ RawDelegateTargets []string `json:"-"`
123+ RawSIDHistory []string `json:"-"`
124+}
125+
126+type GroupObject struct {
127+ ObjectIdentifier string `json:"ObjectIdentifier"`
128+ Members []MemberReference `json:"Members"`
129+ Aces []acl.Ace `json:"Aces"`
130+ IsACLProtected bool `json:"IsACLProtected"`
131+ IsDeleted bool `json:"IsDeleted"`
132+ Properties map[string]interface{} `json:"Properties"`
133+ DNT uint64 `json:"-"`
134+ PDNT uint64 `json:"-"`
135+ Synthetic bool `json:"-"`
136+}
137+
138+type ComputerObject struct {
139+ ObjectIdentifier string `json:"ObjectIdentifier"`
140+ PrimaryGroupSID string `json:"PrimaryGroupSID,omitempty"`
141+ AllowedToDelegate []TypedPrincipal `json:"AllowedToDelegate"`
142+ AllowedToAct []TypedPrincipal `json:"AllowedToAct"`
143+ HasSIDHistory []TypedPrincipal `json:"HasSIDHistory"`
144+ DumpSMSAPassword []TypedPrincipal `json:"DumpSMSAPassword"`
145+ Sessions SessionCollection `json:"Sessions"`
146+ PrivilegedSessions SessionCollection `json:"PrivilegedSessions"`
147+ RegistrySessions SessionCollection `json:"RegistrySessions"`
148+ LocalGroups []interface{} `json:"LocalGroups"`
149+ UserRights []interface{} `json:"UserRights"`
150+ Aces []acl.Ace `json:"Aces"`
151+ IsACLProtected bool `json:"IsACLProtected"`
152+ IsDeleted bool `json:"IsDeleted"`
153+ IsDC bool `json:"IsDC"`
154+ Status *string `json:"Status"`
155+ Properties map[string]interface{} `json:"Properties"`
156+ NTHash string `json:"-"`
157+ LMHash string `json:"-"`
158+ DNT uint64 `json:"-"`
159+ PDNT uint64 `json:"-"`
160+ RawDelegateTargets []string `json:"-"`
161+ RawAllowedToAct []string `json:"-"`
162+ RawSIDHistory []string `json:"-"`
163+}
164+
165+type DomainObject struct {
166+ ObjectIdentifier string `json:"ObjectIdentifier"`
167+ ChildObjects []TypedPrincipal `json:"ChildObjects"`
168+ Trusts []DomainTrust `json:"Trusts"`
169+ Links []interface{} `json:"Links"`
170+ Aces []acl.Ace `json:"Aces"`
171+ IsACLProtected bool `json:"IsACLProtected"`
172+ IsDeleted bool `json:"IsDeleted"`
173+ Properties map[string]interface{} `json:"Properties"`
174+ DNT uint64 `json:"-"`
175+}
176+
177+type DomainObjectV4 struct {
178+ ObjectIdentifier string `json:"ObjectIdentifier"`
179+ ChildObjects []TypedPrincipal `json:"ChildObjects"`
180+ Trusts []DomainTrustV4 `json:"Trusts"`
181+ Links []interface{} `json:"Links"`
182+ Aces []acl.Ace `json:"Aces"`
183+ IsACLProtected bool `json:"IsACLProtected"`
184+ IsDeleted bool `json:"IsDeleted"`
185+ Properties map[string]interface{} `json:"Properties"`
186+}
187+
188+type DomainObjectV5 struct {
189+ ObjectIdentifier string `json:"ObjectIdentifier"`
190+ ChildObjects []TypedPrincipal `json:"ChildObjects"`
191+ Trusts []DomainTrustV5 `json:"Trusts"`
192+ Links []interface{} `json:"Links"`
193+ Aces []acl.Ace `json:"Aces"`
194+ IsACLProtected bool `json:"IsACLProtected"`
195+ IsDeleted bool `json:"IsDeleted"`
196+ Properties map[string]interface{} `json:"Properties"`
197+}
198+
199+func (d *DomainObject) ToV4() DomainObjectV4 {
200+ trusts := make([]DomainTrustV4, len(d.Trusts))
201+ for i, t := range d.Trusts {
202+ trusts[i] = t.ToV4()
203+ }
204+ return DomainObjectV4{
205+ ObjectIdentifier: d.ObjectIdentifier,
206+ ChildObjects: d.ChildObjects,
207+ Trusts: trusts,
208+ Links: d.Links,
209+ Aces: d.Aces,
210+ IsACLProtected: d.IsACLProtected,
211+ IsDeleted: d.IsDeleted,
212+ Properties: d.Properties,
213+ }
214+}
215+
216+func (d *DomainObject) ToV5() DomainObjectV5 {
217+ trusts := make([]DomainTrustV5, len(d.Trusts))
218+ for i, t := range d.Trusts {
219+ trusts[i] = t.ToV5()
220+ }
221+ return DomainObjectV5{
222+ ObjectIdentifier: d.ObjectIdentifier,
223+ ChildObjects: d.ChildObjects,
224+ Trusts: trusts,
225+ Links: d.Links,
226+ Aces: d.Aces,
227+ IsACLProtected: d.IsACLProtected,
228+ IsDeleted: d.IsDeleted,
229+ Properties: d.Properties,
230+ }
231+}
232+
233+type OUObject struct {
234+ ObjectIdentifier string `json:"ObjectIdentifier"`
235+ ChildObjects []TypedPrincipal `json:"ChildObjects"`
236+ Links []interface{} `json:"Links"`
237+ Aces []acl.Ace `json:"Aces"`
238+ IsACLProtected bool `json:"IsACLProtected"`
239+ IsDeleted bool `json:"IsDeleted"`
240+ Properties map[string]interface{} `json:"Properties"`
241+ DNT uint64 `json:"-"`
242+ PDNT uint64 `json:"-"`
243+}
244+
245+type ADSnapshot struct {
246+ DomainName string
247+ DomainSID string
248+ Users []*UserObject
249+ Groups []*GroupObject
250+ Computers []*ComputerObject
251+ Domains []*DomainObject
252+ OUs []*OUObject
253+
254+ UsersBySID map[string]*UserObject
255+ GroupsBySID map[string]*GroupObject
256+ ComputersBySID map[string]*ComputerObject
257+ OUsByGUID map[string]*OUObject
258+ ObjectsByDNT map[uint64]TypedPrincipal
259+ PDNTByDNT map[uint64]uint64
260+}
261+
262+func NewADSnapshot() *ADSnapshot {
263+ return &ADSnapshot{
264+ Users: make([]*UserObject, 0),
265+ Groups: make([]*GroupObject, 0),
266+ Computers: make([]*ComputerObject, 0),
267+ Domains: make([]*DomainObject, 0),
268+ OUs: make([]*OUObject, 0),
269+ UsersBySID: make(map[string]*UserObject),
270+ GroupsBySID: make(map[string]*GroupObject),
271+ ComputersBySID: make(map[string]*ComputerObject),
272+ OUsByGUID: make(map[string]*OUObject),
273+ ObjectsByDNT: make(map[uint64]TypedPrincipal),
274+ PDNTByDNT: make(map[uint64]uint64),
275+ }
276+}
pkg/ad/tree.go
......@@ -0,0 +1,68 @@
1+package ad
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+type TreeNode struct {
9+ DNT uint64
10+ PDNT uint64
11+ RDN string
12+ Prefix string
13+}
14+
15+type Tree struct {
16+ nodes map[uint64]*TreeNode
17+}
18+
19+func NewTree() *Tree {
20+ return &Tree{
21+ nodes: make(map[uint64]*TreeNode),
22+ }
23+}
24+
25+func (t *Tree) AddNode(dnt, pdnt uint64, rdn, prefix string) {
26+ if prefix == "" {
27+ prefix = "CN="
28+ }
29+ t.nodes[dnt] = &TreeNode{
30+ DNT: dnt,
31+ PDNT: pdnt,
32+ RDN: rdn,
33+ Prefix: prefix,
34+ }
35+}
36+
37+func (t *Tree) GetRDN(dnt uint64) string {
38+ if n, ok := t.nodes[dnt]; ok {
39+ return n.RDN
40+ }
41+ return ""
42+}
43+
44+func (t *Tree) ResolveDN(startDNT uint64) string {
45+ curr := startDNT
46+ var parts []string
47+ visited := make(map[uint64]bool)
48+
49+ for curr != 0 && curr != 2 {
50+ if visited[curr] {
51+ break
52+ }
53+ visited[curr] = true
54+
55+ node, exists := t.nodes[curr]
56+ if !exists || node.RDN == "" {
57+ break
58+ }
59+
60+ parts = append(parts, fmt.Sprintf("%s%s", node.Prefix, node.RDN))
61+ if node.PDNT == 0 || node.PDNT == curr {
62+ break
63+ }
64+ curr = node.PDNT
65+ }
66+
67+ return strings.Join(parts, ",")
68+}
pkg/bloodhound/types.go
......@@ -0,0 +1,20 @@
1+package bloodhound
2+
3+type Meta struct {
4+ Methods int `json:"methods"`
5+ Type string `json:"type"`
6+ Count int `json:"count"`
7+ Version int `json:"version"`
8+}
9+
10+type Container struct {
11+ Data []interface{} `json:"data"`
12+ Meta Meta `json:"meta"`
13+}
14+
15+type FormatVersion int
16+
17+const (
18+ Version4 FormatVersion = 4
19+ Version5 FormatVersion = 5
20+)
pkg/bloodhound/v4/writer.go
......@@ -0,0 +1,91 @@
1+package v4
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "os"
7+ "path/filepath"
8+
9+ "github.com/shehzade/ntds-to-bloodhound/pkg/ad"
10+ "github.com/shehzade/ntds-to-bloodhound/pkg/bloodhound"
11+)
12+
13+type Writer struct {
14+ outDir string
15+}
16+
17+func NewWriter(outDir string) *Writer {
18+ return &Writer{outDir: outDir}
19+}
20+
21+func (w *Writer) WriteSnapshot(snap *ad.ADSnapshot) error {
22+ if err := os.MkdirAll(w.outDir, 0755); err != nil {
23+ return fmt.Errorf("failed to create output directory %s: %w", w.outDir, err)
24+ }
25+
26+ usersData := make([]interface{}, len(snap.Users))
27+ for i, u := range snap.Users {
28+ usersData[i] = u
29+ }
30+ if err := w.writeFile("users.json", "users", usersData); err != nil {
31+ return err
32+ }
33+
34+ groupsData := make([]interface{}, len(snap.Groups))
35+ for i, g := range snap.Groups {
36+ groupsData[i] = g
37+ }
38+ if err := w.writeFile("groups.json", "groups", groupsData); err != nil {
39+ return err
40+ }
41+
42+ computersData := make([]interface{}, len(snap.Computers))
43+ for i, c := range snap.Computers {
44+ computersData[i] = c
45+ }
46+ if err := w.writeFile("computers.json", "computers", computersData); err != nil {
47+ return err
48+ }
49+
50+ domainsData := make([]interface{}, len(snap.Domains))
51+ for i, d := range snap.Domains {
52+ domainsData[i] = d.ToV4()
53+ }
54+ if err := w.writeFile("domains.json", "domains", domainsData); err != nil {
55+ return err
56+ }
57+
58+ ousData := make([]interface{}, len(snap.OUs))
59+ for i, o := range snap.OUs {
60+ ousData[i] = o
61+ }
62+ if err := w.writeFile("ous.json", "ous", ousData); err != nil {
63+ return err
64+ }
65+
66+ return nil
67+}
68+
69+func (w *Writer) writeFile(filename, objType string, data []interface{}) error {
70+ container := bloodhound.Container{
71+ Data: data,
72+ Meta: bloodhound.Meta{
73+ Methods: 0,
74+ Type: objType,
75+ Count: len(data),
76+ Version: 4,
77+ },
78+ }
79+
80+ bytes, err := json.MarshalIndent(container, "", " ")
81+ if err != nil {
82+ return fmt.Errorf("failed to marshal %s: %w", filename, err)
83+ }
84+
85+ filePath := filepath.Join(w.outDir, filename)
86+ if err := os.WriteFile(filePath, bytes, 0644); err != nil {
87+ return fmt.Errorf("failed to write %s: %w", filePath, err)
88+ }
89+
90+ return nil
91+}
pkg/bloodhound/v5/writer.go
......@@ -0,0 +1,91 @@
1+package v5
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "os"
7+ "path/filepath"
8+
9+ "github.com/shehzade/ntds-to-bloodhound/pkg/ad"
10+ "github.com/shehzade/ntds-to-bloodhound/pkg/bloodhound"
11+)
12+
13+type Writer struct {
14+ outDir string
15+}
16+
17+func NewWriter(outDir string) *Writer {
18+ return &Writer{outDir: outDir}
19+}
20+
21+func (w *Writer) WriteSnapshot(snap *ad.ADSnapshot) error {
22+ if err := os.MkdirAll(w.outDir, 0755); err != nil {
23+ return fmt.Errorf("failed to create output directory %s: %w", w.outDir, err)
24+ }
25+
26+ usersData := make([]interface{}, len(snap.Users))
27+ for i, u := range snap.Users {
28+ usersData[i] = u
29+ }
30+ if err := w.writeFile("users.json", "users", usersData); err != nil {
31+ return err
32+ }
33+
34+ groupsData := make([]interface{}, len(snap.Groups))
35+ for i, g := range snap.Groups {
36+ groupsData[i] = g
37+ }
38+ if err := w.writeFile("groups.json", "groups", groupsData); err != nil {
39+ return err
40+ }
41+
42+ computersData := make([]interface{}, len(snap.Computers))
43+ for i, c := range snap.Computers {
44+ computersData[i] = c
45+ }
46+ if err := w.writeFile("computers.json", "computers", computersData); err != nil {
47+ return err
48+ }
49+
50+ domainsData := make([]interface{}, len(snap.Domains))
51+ for i, d := range snap.Domains {
52+ domainsData[i] = d.ToV5()
53+ }
54+ if err := w.writeFile("domains.json", "domains", domainsData); err != nil {
55+ return err
56+ }
57+
58+ ousData := make([]interface{}, len(snap.OUs))
59+ for i, o := range snap.OUs {
60+ ousData[i] = o
61+ }
62+ if err := w.writeFile("ous.json", "ous", ousData); err != nil {
63+ return err
64+ }
65+
66+ return nil
67+}
68+
69+func (w *Writer) writeFile(filename, objType string, data []interface{}) error {
70+ container := bloodhound.Container{
71+ Data: data,
72+ Meta: bloodhound.Meta{
73+ Methods: 0,
74+ Type: objType,
75+ Count: len(data),
76+ Version: 5,
77+ },
78+ }
79+
80+ bytes, err := json.MarshalIndent(container, "", " ")
81+ if err != nil {
82+ return fmt.Errorf("failed to marshal %s: %w", filename, err)
83+ }
84+
85+ filePath := filepath.Join(w.outDir, filename)
86+ if err := os.WriteFile(filePath, bytes, 0644); err != nil {
87+ return fmt.Errorf("failed to write %s: %w", filePath, err)
88+ }
89+
90+ return nil
91+}
pkg/bloodhound/v5/zip.go
......@@ -0,0 +1,104 @@
1+package v5
2+
3+import (
4+ "archive/zip"
5+ "encoding/json"
6+ "fmt"
7+ "os"
8+ "path/filepath"
9+ "time"
10+
11+ "github.com/shehzade/ntds-to-bloodhound/pkg/ad"
12+ "github.com/shehzade/ntds-to-bloodhound/pkg/bloodhound"
13+)
14+
15+func GenerateZipFilename() string {
16+ now := time.Now().UTC()
17+ return fmt.Sprintf("BloodHound_%s.zip", now.Format("20060102150405"))
18+}
19+
20+func CreateZipArchive(snap *ad.ADSnapshot, targetZipPath string) error {
21+ dir := filepath.Dir(targetZipPath)
22+ if err := os.MkdirAll(dir, 0755); err != nil {
23+ return fmt.Errorf("failed to create directory %s: %w", dir, err)
24+ }
25+
26+ zipFile, err := os.Create(targetZipPath)
27+ if err != nil {
28+ return fmt.Errorf("failed to create zip file %s: %w", targetZipPath, err)
29+ }
30+ defer zipFile.Close()
31+
32+ zipWriter := zip.NewWriter(zipFile)
33+ defer zipWriter.Close()
34+
35+ writeEntry := func(filename, objType string, data []interface{}) error {
36+ container := bloodhound.Container{
37+ Data: data,
38+ Meta: bloodhound.Meta{
39+ Methods: 0,
40+ Type: objType,
41+ Count: len(data),
42+ Version: 5,
43+ },
44+ }
45+
46+ bytes, err := json.MarshalIndent(container, "", " ")
47+ if err != nil {
48+ return fmt.Errorf("failed to marshal %s: %w", filename, err)
49+ }
50+
51+ w, err := zipWriter.Create(filename)
52+ if err != nil {
53+ return fmt.Errorf("failed to create zip entry %s: %w", filename, err)
54+ }
55+
56+ if _, err := w.Write(bytes); err != nil {
57+ return fmt.Errorf("failed to write zip entry %s: %w", filename, err)
58+ }
59+
60+ return nil
61+ }
62+
63+ usersData := make([]interface{}, len(snap.Users))
64+ for i, u := range snap.Users {
65+ usersData[i] = u
66+ }
67+ if err := writeEntry("users.json", "users", usersData); err != nil {
68+ return err
69+ }
70+
71+ groupsData := make([]interface{}, len(snap.Groups))
72+ for i, g := range snap.Groups {
73+ groupsData[i] = g
74+ }
75+ if err := writeEntry("groups.json", "groups", groupsData); err != nil {
76+ return err
77+ }
78+
79+ computersData := make([]interface{}, len(snap.Computers))
80+ for i, c := range snap.Computers {
81+ computersData[i] = c
82+ }
83+ if err := writeEntry("computers.json", "computers", computersData); err != nil {
84+ return err
85+ }
86+
87+ domainsData := make([]interface{}, len(snap.Domains))
88+ for i, d := range snap.Domains {
89+ domainsData[i] = d.ToV5()
90+ }
91+ if err := writeEntry("domains.json", "domains", domainsData); err != nil {
92+ return err
93+ }
94+
95+ ousData := make([]interface{}, len(snap.OUs))
96+ for i, o := range snap.OUs {
97+ ousData[i] = o
98+ }
99+ if err := writeEntry("ous.json", "ous", ousData); err != nil {
100+ return err
101+ }
102+
103+ return nil
104+}
pkg/crypto/crypto.go
......@@ -0,0 +1,269 @@
1+package crypto
2+
3+import (
4+ "crypto/aes"
5+ "crypto/cipher"
6+ "crypto/des"
7+ "crypto/md5"
8+ "crypto/rc4"
9+ "encoding/binary"
10+ "encoding/hex"
11+ "errors"
12+ "fmt"
13+ "strings"
14+)
15+
16+const (
17+ EmptyLMHash = "aad3b435b51404eeaad3b435b51404ee"
18+ EmptyNTHash = "31d6cfe0d16ae931b73c59d7e0c089c0"
19+)
20+
21+type CryptoEngine struct {
22+ BootKey []byte
23+ PEKList [][]byte
24+}
25+
26+func NewCryptoEngine(bootKey []byte) *CryptoEngine {
27+ return &CryptoEngine{
28+ BootKey: bootKey,
29+ PEKList: make([][]byte, 0),
30+ }
31+}
32+
33+func (c *CryptoEngine) ParsePekList(pekListRaw []byte) error {
34+ if len(pekListRaw) < 24 {
35+ return errors.New("pekList blob too short")
36+ }
37+
38+ header := pekListRaw[:8]
39+ keyMaterial := pekListRaw[8:24]
40+ encryptedPek := pekListRaw[24:]
41+
42+ var decryptedPekList []byte
43+
44+ if binary.LittleEndian.Uint32(header[:4]) == 0x02 {
45+ h := md5.New()
46+ h.Write(c.BootKey)
47+ for i := 0; i < 1000; i++ {
48+ h.Write(keyMaterial)
49+ }
50+ tmpKey := h.Sum(nil)
51+ rc4Cipher, err := rc4.NewCipher(tmpKey)
52+ if err != nil {
53+ return fmt.Errorf("failed to create RC4 cipher for PEK: %w", err)
54+ }
55+ decryptedPekList = make([]byte, len(encryptedPek))
56+ rc4Cipher.XORKeyStream(decryptedPekList, encryptedPek)
57+ } else if binary.LittleEndian.Uint32(header[:4]) == 0x03 {
58+ block, err := aes.NewCipher(c.BootKey)
59+ if err != nil {
60+ return fmt.Errorf("failed to create AES cipher for PEK: %w", err)
61+ }
62+ if len(encryptedPek)%aes.BlockSize != 0 {
63+ return fmt.Errorf("encrypted PEK size %d is not a multiple of block size", len(encryptedPek))
64+ }
65+ mode := cipher.NewCBCDecrypter(block, keyMaterial)
66+ decryptedPekList = make([]byte, len(encryptedPek))
67+ mode.CryptBlocks(decryptedPekList, encryptedPek)
68+ } else {
69+ return fmt.Errorf("unsupported PEK header version: %x", header[:4])
70+ }
71+
72+ if len(decryptedPekList) < 32 {
73+ return errors.New("decrypted PEK list too short")
74+ }
75+
76+ plainEntries := decryptedPekList[32:]
77+ pos := 0
78+ curIndex := uint32(0)
79+
80+ for pos+20 <= len(plainEntries) {
81+ index := binary.LittleEndian.Uint32(plainEntries[pos : pos+4])
82+ pekKey := make([]byte, 16)
83+ copy(pekKey, plainEntries[pos+4:pos+20])
84+
85+ if index != curIndex {
86+ break
87+ }
88+ c.PEKList = append(c.PEKList, pekKey)
89+ curIndex++
90+ pos += 20
91+ }
92+
93+ if len(c.PEKList) == 0 {
94+ return errors.New("no valid PEK keys found in pekList")
95+ }
96+
97+ return nil
98+}
99+
100+func transformKey(in []byte) []byte {
101+ out := make([]byte, 8)
102+ out[0] = in[0] >> 1
103+ out[1] = ((in[0] & 0x01) << 6) | (in[1] >> 2)
104+ out[2] = ((in[1] & 0x03) << 5) | (in[2] >> 3)
105+ out[3] = ((in[2] & 0x07) << 4) | (in[3] >> 4)
106+ out[4] = ((in[3] & 0x0F) << 3) | (in[4] >> 5)
107+ out[5] = ((in[4] & 0x1F) << 2) | (in[5] >> 6)
108+ out[6] = ((in[5] & 0x3F) << 1) | (in[6] >> 7)
109+ out[7] = in[6] & 0x7F
110+
111+ for i := 0; i < 8; i++ {
112+ out[i] = (out[i] << 1) & 0xFE
113+ }
114+ return out
115+}
116+
117+func deriveDesKeys(rid uint32) ([]byte, []byte) {
118+ ridBytes := make([]byte, 4)
119+ binary.LittleEndian.PutUint32(ridBytes, rid)
120+
121+ k1 := []byte{ridBytes[0], ridBytes[1], ridBytes[2], ridBytes[3], ridBytes[0], ridBytes[1], ridBytes[2]}
122+ k2 := []byte{ridBytes[3], ridBytes[0], ridBytes[1], ridBytes[2], ridBytes[3], ridBytes[0], ridBytes[1]}
123+
124+ return transformKey(k1), transformKey(k2)
125+}
126+
127+func removeDESLayer(crypted []byte, rid uint32) ([]byte, error) {
128+ if len(crypted) < 16 {
129+ return nil, errors.New("crypted hash must be at least 16 bytes")
130+ }
131+
132+ k1, k2 := deriveDesKeys(rid)
133+ c1, err := des.NewCipher(k1)
134+ if err != nil {
135+ return nil, err
136+ }
137+ c2, err := des.NewCipher(k2)
138+ if err != nil {
139+ return nil, err
140+ }
141+
142+ out := make([]byte, 16)
143+ c1.Decrypt(out[:8], crypted[:8])
144+ c2.Decrypt(out[8:16], crypted[8:16])
145+ return out, nil
146+}
147+
148+func (c *CryptoEngine) DecryptHash(encBlob []byte, rid uint32) ([]byte, error) {
149+ if len(c.PEKList) == 0 {
150+ return nil, errors.New("no PEK keys loaded")
151+ }
152+ if len(encBlob) < 24 {
153+ return nil, errors.New("encrypted hash blob too short")
154+ }
155+
156+ header := encBlob[:8]
157+ keyMaterial := encBlob[8:24]
158+
159+ pekIndexHex := hex.EncodeToString(header)
160+ if len(pekIndexHex) < 10 {
161+ return nil, errors.New("invalid header format")
162+ }
163+ pekIndex := int(header[4])
164+ if pekIndex >= len(c.PEKList) {
165+ pekIndex = 0
166+ }
167+ pek := c.PEKList[pekIndex]
168+
169+ var tmpHash []byte
170+
171+ if binary.LittleEndian.Uint32(header[:4]) == 0x13 {
172+ if len(encBlob) < 28+16 {
173+ return nil, errors.New("AES hash blob too short")
174+ }
175+ ciphertext := encBlob[28 : 28+16]
176+
177+ block, err := aes.NewCipher(pek)
178+ if err != nil {
179+ return nil, fmt.Errorf("failed to create AES cipher: %w", err)
180+ }
181+ mode := cipher.NewCBCDecrypter(block, keyMaterial)
182+ tmpHash = make([]byte, 16)
183+ mode.CryptBlocks(tmpHash, ciphertext)
184+ } else {
185+ if len(encBlob) < 24+16 {
186+ return nil, errors.New("RC4 hash blob too short")
187+ }
188+ ciphertext := encBlob[24 : 24+16]
189+
190+ h := md5.New()
191+ h.Write(pek)
192+ h.Write(keyMaterial)
193+ tmpKey := h.Sum(nil)
194+
195+ rc4Cipher, err := rc4.NewCipher(tmpKey)
196+ if err != nil {
197+ return nil, fmt.Errorf("failed to create RC4 cipher: %w", err)
198+ }
199+ tmpHash = make([]byte, 16)
200+ rc4Cipher.XORKeyStream(tmpHash, ciphertext)
201+ }
202+
203+ return removeDESLayer(tmpHash, rid)
204+}
205+
206+func ParseSID(b []byte) (string, uint32, error) {
207+ if len(b) < 8 {
208+ return "", 0, errors.New("SID buffer too short")
209+ }
210+
211+ revision := b[0]
212+ subAuthCount := int(b[1])
213+ if len(b) < 8+subAuthCount*4 {
214+ return "", 0, errors.New("SID buffer truncated for subauthorities")
215+ }
216+
217+ var authority uint64
218+ for i := 2; i < 8; i++ {
219+ authority = (authority << 8) | uint64(b[i])
220+ }
221+
222+ parts := []string{fmt.Sprintf("S-%d-%d", revision, authority)}
223+ var rid uint32
224+
225+ for i := 0; i < subAuthCount; i++ {
226+ offset := 8 + i*4
227+ var subAuth uint32
228+ if i == subAuthCount-1 && subAuthCount > 1 {
229+ subAuth = binary.BigEndian.Uint32(b[offset : offset+4])
230+ rid = subAuth
231+ } else {
232+ subAuth = binary.LittleEndian.Uint32(b[offset : offset+4])
233+ }
234+ parts = append(parts, fmt.Sprintf("%d", subAuth))
235+ }
236+
237+ return strings.Join(parts, "-"), rid, nil
238+}
239+
240+func ParseBinarySID(b []byte) (string, uint32, error) {
241+ if len(b) < 8 {
242+ return "", 0, errors.New("SID buffer too short")
243+ }
244+
245+ revision := b[0]
246+ subAuthCount := int(b[1])
247+ if revision != 1 || subAuthCount > 15 || len(b) < 8+subAuthCount*4 {
248+ return "", 0, errors.New("SID buffer invalid or truncated")
249+ }
250+
251+ var authority uint64
252+ for i := 2; i < 8; i++ {
253+ authority = (authority << 8) | uint64(b[i])
254+ }
255+
256+ parts := []string{fmt.Sprintf("S-%d-%d", revision, authority)}
257+ var rid uint32
258+
259+ for i := 0; i < subAuthCount; i++ {
260+ offset := 8 + i*4
261+ subAuth := binary.LittleEndian.Uint32(b[offset : offset+4])
262+ if i == subAuthCount-1 {
263+ rid = subAuth
264+ }
265+ parts = append(parts, fmt.Sprintf("%d", subAuth))
266+ }
267+
268+ return strings.Join(parts, "-"), rid, nil
269+}
pkg/ese/db.go
......@@ -0,0 +1,66 @@
1+package ese
2+
3+import (
4+ "fmt"
5+ "io"
6+ "os"
7+
8+ "github.com/Velocidex/ordereddict"
9+ "www.velocidex.com/golang/go-ese/parser"
10+)
11+
12+type DB struct {
13+ file *os.File
14+ ctx *parser.ESEContext
15+ catalog *parser.Catalog
16+}
17+
18+func OpenDB(path string) (*DB, error) {
19+ f, err := os.Open(path)
20+ if err != nil {
21+ return nil, fmt.Errorf("failed to open ESE file %s: %w", path, err)
22+ }
23+
24+ ctx, err := parser.NewESEContext(f)
25+ if err != nil {
26+ f.Close()
27+ return nil, fmt.Errorf("failed to initialize ESE context: %w", err)
28+ }
29+
30+ catalog, err := parser.ReadCatalog(ctx)
31+ if err != nil {
32+ f.Close()
33+ return nil, fmt.Errorf("failed to read ESE catalog: %w", err)
34+ }
35+
36+ return &DB{
37+ file: f,
38+ ctx: ctx,
39+ catalog: catalog,
40+ }, nil
41+}
42+
43+func (db *DB) Close() error {
44+ if db.file != nil {
45+ return db.file.Close()
46+ }
47+ return nil
48+}
49+
50+func (db *DB) TableNames() []string {
51+ if db.catalog == nil || db.catalog.Tables == nil {
52+ return nil
53+ }
54+ return db.catalog.Tables.Keys()
55+}
56+
57+func (db *DB) StreamTable(name string, cb func(row *ordereddict.Dict) error) error {
58+ if db.catalog == nil {
59+ return fmt.Errorf("database catalog is nil")
60+ }
61+ return db.catalog.DumpTable(name, cb)
62+}
63+
64+func (db *DB) Reader() io.ReaderAt {
65+ return db.file
66+}
pkg/registry/bootkey.go
......@@ -0,0 +1,96 @@
1+package registry
2+
3+import (
4+ "encoding/binary"
5+ "encoding/hex"
6+ "fmt"
7+ "io"
8+ "os"
9+
10+ "www.velocidex.com/golang/regparser"
11+)
12+
13+var transforms = [16]int{8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7}
14+
15+func ExtractBootKey(systemHivePath string) ([]byte, error) {
16+ f, err := os.Open(systemHivePath)
17+ if err != nil {
18+ return nil, fmt.Errorf("failed to open SYSTEM hive: %w", err)
19+ }
20+ defer f.Close()
21+
22+ return ExtractBootKeyFromReader(f)
23+}
24+
25+func ExtractBootKeyFromReader(reader io.ReaderAt) ([]byte, error) {
26+ reg, err := regparser.NewRegistry(reader)
27+ if err != nil {
28+ return nil, fmt.Errorf("failed to parse registry hive: %w", err)
29+ }
30+
31+ controlSet := "ControlSet001"
32+ selectNode := reg.OpenKey("Select")
33+ if selectNode != nil {
34+ var currentCS, defaultCS uint32
35+ for _, v := range selectNode.Values() {
36+ vd := v.ValueData()
37+ if len(vd.Data) >= 4 {
38+ switch v.ValueName() {
39+ case "Current":
40+ currentCS = binary.LittleEndian.Uint32(vd.Data)
41+ case "Default":
42+ defaultCS = binary.LittleEndian.Uint32(vd.Data)
43+ }
44+ }
45+ }
46+ if currentCS > 0 {
47+ controlSet = fmt.Sprintf("ControlSet%03d", currentCS)
48+ } else if defaultCS > 0 {
49+ controlSet = fmt.Sprintf("ControlSet%03d", defaultCS)
50+ }
51+ }
52+
53+ var rawHex string
54+ subkeys := []string{"JD", "Skew1", "GBG", "Data"}
55+ for _, key := range subkeys {
56+ path := fmt.Sprintf("%s\\Control\\Lsa\\%s", controlSet, key)
57+ node := reg.OpenKey(path)
58+ if node == nil {
59+ return nil, fmt.Errorf("required LSA subkey not found: %s", path)
60+ }
61+
62+ classOffset := node.Class()
63+ classLen := node.ClassLength()
64+ if classLen < 16 {
65+ return nil, fmt.Errorf("invalid class length for subkey %s: %d", key, classLen)
66+ }
67+
68+ buf := make([]byte, 16)
69+ fileOffset := 0x1000 + int64(classOffset) + 4
70+ if _, err := reader.ReadAt(buf, fileOffset); err != nil {
71+ return nil, fmt.Errorf("failed to read class data for %s: %w", key, err)
72+ }
73+
74+ var chars []rune
75+ for i := 0; i < 16; i += 2 {
76+ chars = append(chars, rune(binary.LittleEndian.Uint16(buf[i:i+2])))
77+ }
78+ rawHex += string(chars)
79+ }
80+
81+ rawBytes, err := hex.DecodeString(rawHex)
82+ if err != nil {
83+ return nil, fmt.Errorf("failed to decode hex class data: %w", err)
84+ }
85+
86+ if len(rawBytes) != 16 {
87+ return nil, fmt.Errorf("expected 16 raw key bytes, got %d", len(rawBytes))
88+ }
89+
90+ bootKey := make([]byte, 16)
91+ for i := 0; i < 16; i++ {
92+ bootKey[i] = rawBytes[transforms[i]]
93+ }
94+
95+ return bootKey, nil
96+}