-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvoke-PowerDPAPI.ps1
More file actions
408 lines (348 loc) · 17.5 KB
/
Invoke-PowerDPAPI.ps1
File metadata and controls
408 lines (348 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# Generic PS function to return an OG node
Function New-OpenGraphNode {
Param(
[Parameter(Mandatory = $true)]
$NodeId,
[Parameter(Mandatory = $true)]
$NodeKind,
[Parameter(Mandatory = $false)]
$SourceKind,
[Parameter(Mandatory = $true)]
$Properties
)
# Create the list of kinds
$KindsArray = New-Object System.Collections.Generic.List[string]
$null = $KindsArray.Add($NodeKind)
# Only add SourceKind if it was actually provided
if (-not [string]::IsNullOrWhiteSpace($SourceKind)) {
$null = $KindsArray.Add($SourceKind)
}
return [pscustomobject]@{
id = $NodeId
kinds = $KindsArray.ToArray()
properties = $Properties
}
}
# Generic PS function to return an OG edge
Function New-OpenGraphEdge {
Param(
[Parameter(Mandatory = $true)]
[string]$EdgeName,
[Parameter(Mandatory = $true)]
[string]$SourceNodeId,
[Parameter(Mandatory = $true)]
[string]$TargetNodeId,
[Parameter(Mandatory = $false)]
[hashtable]$Properties = @{} # Default to an empty hashtable
)
return [pscustomobject]@{
kind = $EdgeName
start = @{ value = $SourceNodeId }
end = @{ value = $TargetNodeId }
# If $Properties is provided, it populates; if not, it's an empty {}
properties = $Properties
}
}
function Get-DPAPIMasterKeyInfo {
param (
[Parameter(Mandatory=$false)]
[string]$Path
)
# Initialize placeholders
$info = [ordered]@{
"Username" = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
"Owner_SID" = "Unknown"
"Computer_SID" = "Unkwown"
"Version" = "Unknown"
"Iterations" = "Unknown"
"Salt_Hex" = "Unknown"
"Created_At" = "Unknown"
"Full_Path" = $Path
}
if ($Path -and (Test-Path $Path)) {
try {
$bytes = [System.IO.File]::ReadAllBytes($Path)
$fileInfo = Get-Item -LiteralPath $Path -Force
# The owner SID is usually the name of the parent directory in DPAPI paths
$info["Owner_SID"] = $fileInfo.Directory.Name
$info["Created_At"] = $fileInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")
# Parsing the MasterKey Binary Structure
# Version is at offset 0 (4 bytes)
$info["Version"] = [System.BitConverter]::ToInt32($bytes, 0)
# Salt is at offset 12 (16 bytes)
$saltBytes = New-Object byte[] 16
[System.Array]::Copy($bytes, 12, $saltBytes, 0, 16)
$info["Salt_Hex"] = ($saltBytes | ForEach-Object { "{0:X2}" -f $_ }) -join ""
# Rounds/Iterations is at offset 28 (4 bytes)
$info["Iterations"] = [System.BitConverter]::ToInt32($bytes, 28)
# Use the actual filename as the GUID if it's a valid GUID
if ($fileInfo.Name -match '\{?[a-fA-F0-9-]{36}\}?') {
$info["GUID"] = $fileInfo.Name
}
}
catch {
Write-Warning "Failed to parse MasterKey at Path: $Path"
}
}
return [PSCustomObject]$info
}
function Invoke-PowerDPAPI {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Path,
[string]$Format="hex",
[Parameter(Mandatory=$false)]
[string]$Graph,
[switch]$Quiet
)
# initialize objects to prevent errors
# collection for OG data
$supplementalNodes = New-Object System.Collections.Generic.List[PSObject]
$supplementalEdges = New-Object System.Collections.Generic.List[PSObject]
$dpapiNodes = New-Object System.Collections.Generic.List[PSObject]
$dpapiEdges = New-Object System.Collections.Generic.List[PSObject]
Write-Host "[*] Running PowerDPAPI"
try {
Write-Host "[*] Querying host and user data"
# Get Current User SID
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$userSid = $currentUser.User.Value
$userName = $currentUser.Name
# Get Computer SID (stripping the relative ID from a local account SID)
$adminSID = (Get-LocalUser -Name Administrator).SID.Value
$computerSID = $adminSID.Substring(0, $adminSID.LastIndexOf('-'))
$computerName = $env:COMPUTERNAME
# Enrichment: Profile Activity
$profilePath = "$env:SystemDrive\Users\$($env:USERNAME)"
$lastActive = "Unknown"
if (Test-Path $profilePath) {
$lastActive = (Get-Item $profilePath -Force).LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
}
# Enrichment: User Properties
$userProps = @{
name = $userName
last_active = $lastActive
profile_path = $profilePath
is_admin = (New-Object Security.Principal.WindowsPrincipal($currentUser)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
domain = $env:USERDOMAIN
}
Write-Host "[*] Machine SID: $computerSID"
Write-Host "[*] User SID: $userSid"
# Create Computer Node
$compProps = @{ name = $computerName }
$computerNode = New-OpenGraphNode -NodeId $computerSID -NodeKind 'Computer' -Properties $compProps
$null = $supplementalNodes.Add($computerNode)
# Create User Profile Node
$userNode = New-OpenGraphNode -NodeId $userSid -NodeKind 'User' -Properties $userProps
$null = $supplementalNodes.Add($userNode)
# Create Relationship: User Profile on Computer
# using 'HasUserProfile' as the edge type for consistency with profilehound https://github.com/m4lwhere/profilehound
$profileEdge = New-OpenGraphEdge -EdgeName 'HasUserProfile' -SourceNodeId $computerSID -TargetNodeId $userSid
$null = $supplementalEdges.Add($profileEdge)
} catch {
Write-Warning "[-] Failed to collect system/user SID info."
}
if(Test-Path -Path $Path) {
$fileList = Get-ChildItem -Path $Path -File -Force -Recurse | select-object -ExpandProperty FullName
if($fileList) {
foreach ($file in $fileList) {
if($VerbosePreference) {
Write-Host "[>] Processing file: $file"
}
# Number of bytes to check
$byteCount = 1024
# Read bytes from file
$inputBytes = Get-Content -Path $file -Encoding Byte -TotalCount $byteCount
# Convert byte array to hex string
$hexInputBytes = ($inputBytes | ForEach-Object { "{0:X2}" -f $_ }) -join ""
# find the start index of the DPAPI blob bytes
$magicByteIndex = $hexInputBytes.IndexOf("01000000D08C9DDF0115D1118C7A00C04FC297EB")
# looks like a blob, let's try to process it
if($magicByteIndex -ge 0) {
$md5Hash = Get-FileHash -Path $file -Algorithm MD5 | Select-Object -ExpandProperty Hash
$sha1Hash = Get-FileHash -Path $file -Algorithm SHA1 | Select-Object -ExpandProperty Hash
$sha256Hash = Get-FileHash -Path $file -Algorithm SHA256 | Select-Object -ExpandProperty Hash
Write-Host "**********************************************************************"
Write-Host "[!] Probable DPAPI blob found"
Write-Host "[>] File: $file"
Write-Host "[>] MD5 Hash: $md5Hash"
Write-Host "[>] SHA-1 Hash: $sha1Hash"
Write-Host "[>] SHA-256 Hash: $sha256Hash"
if($VerbosePreference) {
Write-Host "[>] magicByteIndex: $magicByteIndex"
}
# read all of the bytes from the file
$blobFileByteArray = [System.IO.File]::ReadAllBytes($file)
# From: https://github.com/gentilkiwi/mimikatz/blob/master/modules/kull_m_dpapi.h#L24
$dwVersion = New-Object byte[] 4
$guidProvider = New-Object byte[] 16
$dwMasterKeyVersion = New-Object byte[] 4
$guidMasterKey = New-Object byte[] 16
$dwFlags = New-Object byte[] 4
$dwDescriptionLen = New-Object byte[] 4
# $szDescription = New-Object byte[] 0 # dynamic length - initialize as empty or with appropriate size if known
$algCrypt = New-Object byte[] 4
$dwAlgCryptLen = New-Object byte[] 4
$dwSaltLen = New-Object byte[] 4
# $pbSalt = New-Object byte[] 0 # dynamic length - initialize as empty or with appropriate size if known
$dwHmacKeyLen = New-Object byte[] 4
$pbHmackKey = New-Object byte[] 8
$algHash = New-Object byte[] 4
$dwAlgHashLen = New-Object byte[] 4
$dwHmac2KeyLen = New-Object byte[] 4
# $pbHmack2Key = New-Object byte[] 0 # dynamic length - initialize as empty or with appropriate size if known
$dwDataLen = New-Object byte[] 4
$dwSignLen = New-Object byte[] 4
# $pbSign = New-Object byte[] 0 # dynamic length - initialize as empty or with appropriate size if known
# the start index was found using a character string, divide by 2 for the byte location
$ptrBlob = $magicByteIndex / 2
# start our pointer from the masterKeyGuid position
$ptrBlob += $dwVersion.Length + $guidProvider.Length + $dwMasterKeyVersion.Length
# guidMasterKey
[System.Array]::Copy($blobFileByteArray, $ptrBlob, $guidMasterKey, 0, $guidMasterKey.Length)
$ptrBlob += $guidMasterKey.Length
#$masterKeyGuid = [System.Guid]::new($guidMasterKey)
$masterKeyGuid = ([System.Guid]::new($guidMasterKey)).ToString()
Write-Host "[>] Master Key GUID: $masterKeyGuid"
# advance beyond the flags to the description length
$ptrBlob += $dwFlags.Length
# dwDescriptionLen
[System.Array]::Copy($blobFileByteArray, $ptrBlob, $dwDescriptionLen, 0, $dwDescriptionLen.Length)
$ptrBlob += $dwDescriptionLen.Length
# convert the byte array to an integer, needed to allocate the description byte array
[uint32]$descriptionLength = [System.BitConverter]::ToUInt32($dwDescriptionLen, 0)
if($VerbosePreference) {
Write-Host "[>] descriptionLength: $descriptionLength"
}
if($descriptionLength -gt 0) {
$szDescription = New-Object byte[] $descriptionLength
[System.Array]::Copy($blobFileByteArray, $ptrBlob, $szDescription, 0, $descriptionLength)
$ptrBlob += $descriptionLength
$readableDescription = [System.Text.Encoding]::UTF8.GetString($szDescription)
Write-Host "[>] Blob Description: $readableDescription"
} else {
Write-Host "[>] Description is empty"
}
if (-not $Quiet) {
# write bytes to stdout
Write-Host "-------------- START blob output --------------"
if($Format -eq "base64") {
$base64EncodedBlob = [System.Convert]::ToBase64String($blobFileByteArray)
Write-Host $base64EncodedBlob
} else {
($blobFileByteArray | ForEach-Object { "\x{0:X2}" -f $_ }) -join ""
}
Write-Host "-------------- EOF blob output --------------"
}
# get the file system object for the blob
$blobFileInfo = Get-Item -LiteralPath $file -Force
# extract properties
$blobFileName = $blobFileInfo.Name
$blobSize = $blobFileInfo.Length
$blobCreated = $blobFileInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")
$blobModified = $blobFileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
# blobProperties hashtable
$blobProperties = @{
Name = $blobFileName
Full_Path = $file
Size_Bytes = $blobSize
Created_At = $blobCreated
Modified_At = $blobModified
Extension = $blobFileInfo.Extension
Computer_SID = $computerSID
Owner_SID = $userSid
}
$dpapiBlob_Node = New-OpenGraphNode -NodeId $blobFileName -NodeKind 'DPAPIBlob' -SourceKind 'DPAPI' -Properties $blobProperties
$null = $dpapiNodes.Add($dpapiBlob_Node)
$dpapiBlobToMk_Edge = New-OpenGraphEdge -EdgeName 'EncryptedWith'-SourceNodeId $blobFileName -TargetNodeId $masterKeyGuid
$null = $dpapiEdges.Add($dpapiBlobToMk_Edge)
## Let's see if we can locate the masterkey
Write-Host "[>] Locating corresponding master key file"
$protectDirectory = $Env:AppData + "\Microsoft\Protect"
$userSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
if($userSid) {
$mkDirectory = $protectDirectory + "\" + $userSid
$mkFilePath = $mkDirectory + "\" + $masterKeyGuid
if($VerbosePreference) {
Write-Host "[>] Constructed Master Key Directory:"
Write-Host " $mkDirectory"
}
if(Test-Path $mkFilePath) {
Write-Host "[>] Master Key Found:"
Write-Host " $mkFilePath"
$mkData = Get-DPAPIMasterKeyInfo -Path $mkFilePath
# enrich the result with computer SID and user SID data
$mkData.Computer_SID = $computerSID
$mkData.Owner_SID = $userSid
# Create the Node for the Master Key
$mkNode = New-OpenGraphNode -NodeId $masterKeyGuid -NodeKind 'DPAPIMasterKey' -SourceKind 'DPAPI' -Properties $mkData
$null = $dpapiNodes.Add($mkNode)
# Create the relationship between the User and the Master Key
$userToMk_Edge = New-OpenGraphEdge -EdgeName 'OwnsMasterKey' -SourceNodeId $userSid -TargetNodeId $masterKeyGuid
$null = $dpapiEdges.Add($userToMk_Edge)
# file bytes
$mkByteArray = [System.IO.File]::ReadAllBytes($mkFilePath)
if (-not $Quiet) {
# write bytes to stdout
Write-Host "-------------- START master key --------------"
if($Format -eq "base64") {
$base64EncodedMk = [System.Convert]::ToBase64String($mkByteArray)
Write-Host $base64EncodedMk
} else {
($mkByteArray | ForEach-Object { "\x{0:X2}" -f $_ }) -join ""
}
Write-Host "-------------- EOF master key --------------"
}
} else {
Write-Host "[!] Unable to find corresponding master key using path:"
Write-Host " $mkFilePath"
# If file not found, still create a node with placeholders
$placeholderData = Get-DPAPIMasterKeyInfo -Path "FILE_NOT_FOUND"
$placeholderNode = (New-OpenGraphNode -NodeId $masterKeyGuid -NodeKind 'DPAPIMasterKey' -SourceKind 'DPAPI' -Properties $placeholderData)
$null = $dpapiNodes.Add($placeholderNode)
}
} else {
Write-Host "[ERROR] Unable to determine user SID"
}
}
Write-Host "**********************************************************************"
}
# --- Graph Export ---
if (![string]::IsNullOrWhiteSpace($Graph)) {
Write-Host "[*] Graph output enabled, constructing graph object."
$dpapiOutput = [PSCustomObject]@{
metadata = [PSCustomObject]@{
source_kind = "DPAPI"
}
graph = [PSCustomObject]@{
nodes = $dpapiNodes
edges = $dpapiEdges
}
}
# Ensure the directory exists before writing
$targetDir = Split-Path -Path $Graph
if ($targetDir -and !(Test-Path $targetDir)) {
New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
}
# ConvertTo-Json only looks at the object 2 levels deep
Write-Host "[*] Writing DPAPI graph to $Graph."
$dpapiOutput | ConvertTo-Json -Depth 10 | Out-File -FilePath $Graph
$supplementalJsonPath = $Graph.Replace(".json", "-supplemental.json")
$supplementalOutput = [PSCustomObject]@{
graph = [PSCustomObject]@{
nodes = $supplementalNodes
edges = $supplementalEdges
}
}
Write-Host "[*] Writing supplemental graph to $supplementalJsonPath"
$supplementalOutput | ConvertTo-Json -Depth 10 | Out-File -FilePath $supplementalJsonPath
} else {
Write-Host "[*] No Graph path provided. Skipping OG file output."
}
}
} else {
Write-Warning "[!] ERROR: File or directory not found"
}
Write-Host "[*] Done."
}