-
Notifications
You must be signed in to change notification settings - Fork 6
/
Test-AllVirtualMemory.ps1
2152 lines (1898 loc) · 102 KB
/
Test-AllVirtualMemory.ps1
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# K2 / ktwo@ktwo.ca / https://github.com/K2
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Import-Module ShowUI
#The Internet server does not serve binaries, only local
# If you don't want to run a HashServer locally, set;
#$HashServerUri = $gRoot
$gRoot = "https://pdb2json.azurewebsites.net/api/PageHash/x"
#$HashServerUri = "http://localhost:7071/api/PageHash/x"
#$HashServerUri = $gRoot
# Set this to you're local HashServer to get the memory diffing
$HashServerUri = "http://10.0.0.118:3342/api/PageHash/x"
Function Get-FilePageOffset
{
param (
[Parameter(Mandatory=$True,Position=1)]
[string]$file,
[Parameter(Mandatory=$True,Position=2)]
[long]$offset
)
$buff = New-Object byte[] 0x1000
$stream= [System.IO.File]::OpenRead($file)
$stream.Position = $offset
[void]$stream.Read($buff, 0, $buff.Length)
$stream.Close()
return $buff
}
Function Show-Progress
{
param(
[Parameter(Mandatory=$True,Position=1)]
[int]$i,
[Parameter(Mandatory=$True,Position=2)]
[int]$total,
[Parameter(Mandatory=$True,Position=3)]
[DateTime]$StartTime
)
$i++
$percent = (($i/$($total)) * 100)
$SecondsElapsed = ((Get-Date) - $StartTime).TotalSeconds
$SecondsRemaining = ($SecondsElapsed / ($i / $total)) - $SecondsElapsed
Write-Progress -Activity "Processing Record $i of $($total)" -PercentComplete $percent -CurrentOperation "$("{0:N2}" -f ($percent,2))% Complete" -SecondsRemaining $SecondsRemaining
}
Function Add-FlowBlocks
{
param(
[Parameter(Mandatory=$True,Position=1)]
[string]$file1,
[Parameter(Mandatory=$True,Position=2)]
[string]$file2
)
Write-Verbose "building UI..."
$startTime = Get-Date
$totalLines = 257
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName PresentationFramework
$buff1 = Get-FilePageOffset -file $file1 -offset $Global:offset
$buff2 = Get-FilePageOffset -file $file2 -offset $Global:offset
Write-Verbose "In Add-FlowBlocks $file1 $file2"
$Global:offset += 0x1000
$hex1 = $buff1 | Format-Hex | Out-String -Stream|Select-Object -Skip 6
$hex2 = $buff2 | Format-Hex | Out-String -Stream|Select-Object -Skip 6
$foreGroundGood = [System.Windows.Media.Brushes]::Coral
$foreGround = $foreGroundGood
$addrColor = [System.Windows.Media.Brushes]::Cyan
$bytesColor = [System.Windows.Media.Brushes]::MistyRose
$paragraphsL = New-Object -TypeName 'System.Collections.ArrayList'
$paragraphsR = New-Object -TypeName 'System.Collections.ArrayList'
$invalidChars = [char]0x80,[char]0x85
for($inv=0; $inv -lt 0x20; $inv++) {
$invalidChars += [char]$inv
}
$re = "[{0}]" -f [RegEx]::Escape($invalidChars)
for ($i = 0; $i -lt 256; $i++) {
$inlinesL = New-Object -TypeName 'System.Collections.ArrayList'
$inlinesR = New-Object -TypeName 'System.Collections.ArrayList'
$hexL = $hex1[$i]
$hexR = $hex2[$i]
$hexBytesL = $hexL.Substring(11,47)
$hexBytesR = $hexR.Substring(11,47)
$charOutL = " "
$charOutR = " "
$charOutL += $hexL.Substring(60,16) -replace $re, "."
$charOutR += $hexR.Substring(60,16) -replace $re, "."
$paraL = New-Paragraph
$paraR = New-Paragraph
# make address portion of line
$addrInlineL = New-Run -Text $hexL.Substring(0,11) -Foreground $AddrColor
$addrInlineR = New-Run -Text $hexR.Substring(0,11) -Foreground $AddrColor
[void]$inlinesL.Add($addrInlineL)
[void]$inlinesR.Add($addrInlineR)
# if the lines are equivalent just do one line to minamize the object load
if($hexBytesL.Equals($hexBytesR)) {
$hexRunL = New-Run -Text $hexBytesL -Foreground $foreGroundGood
$hexRunR = New-Run -Text $hexBytesR -Foreground $foreGroundGood
[void]$inlinesL.Add($hexRunL)
[void]$inlinesR.Add($hexRunR)
} else {
$lineL=$hexBytesR[0]
$lineR=$hexBytesL[0]
$isLastEqual=$lineL -eq $lineR
# byte at a time, could do better if we used Linq.Intersect
for($j=1; $j -lt $hexBytesL.Length; $j++) {
if($hexBytesL[$j] -eq " ") {
$lineL += " "
$lineR += " "
} elseif ($hexBytesL[$j] -ne $hexBytesR[$j] -and -not $isLastEqual) {
$lineL += $hexBytesL[$j]
$lineR += $hexBytesR[$j]
} elseif($hexBytesL[$j] -eq $hexBytesR[$j] -and $isLastEqual) {
$lineL += $hexBytesL[$j]
$lineR += $hexBytesR[$j]
} else
{
#we changed from similarly eq or unq to oposit
if($isLastEqual) {
$foreGround = [System.Windows.Media.Brushes]::Coral
} else {
$foreGround = [System.Windows.Media.Brushes]::Crimson
}
$runL = New-Run -Text $lineL -Foreground $foreGround
$runR = New-Run -Text $lineR -Foreground $foreGround
[void]$inlinesL.Add($runL)
[void]$inlinesR.Add($runR)
$lineL=$hexBytesR[$j]
$lineR=$hexBytesL[$j]
$isLastEqual=$lineL -eq $lineR
}
}
if($isLastEqual) {
$foreGround = [System.Windows.Media.Brushes]::Coral
} else {
$foreGround = [System.Windows.Media.Brushes]::Crimson
}
$runL = New-Run -Text $lineL -Foreground $foreGround
$runR = New-Run -Text $lineR -Foreground $foreGround
[void]$inlinesL.Add($runL)
[void]$inlinesR.Add($runR)
}
$bytesInlineL = New-Run -Text $charOutL -Foreground $bytesColor
$bytesInlineR = New-Run -Text $charOutR -Foreground $bytesColor
[void]$inlinesL.Add($bytesInlineL)
[void]$inlinesR.Add($bytesInlineR)
[void]$paraL.Inlines.AddRange($inlinesL)
[void]$paraR.Inlines.AddRange($inlinesR)
[void]$paragraphsL.Add($paraL)
[void]$paragraphsR.Add($paraR)
Show-Progress $paragraphsR.Count $totalLines $startTime
#Write-Verbose "$($paragraphsR.Count * 100.0 / 256)%"
}
$Global:leftFlow.Blocks.AddRange($paragraphsL)
$Global:rightFlow.Blocks.AddRange($paragraphsR)
}
<#
.SYNOPSIS
Display a side-by-side hex dump with some syntax highlighting to indicate
where diffferences occur (line based)
To do this in a relativly more cool way you need to use FormattedText and
not a FlowDocument so I simply colorize by line since the perf impact isnt
as insane.
.DESCRIPTION
DIFF
.PARAMETER file1
File Left to compare
.PARAMETER file2
File Right to compare
.PARAMETER DeleteInputFiles
A SWITCH that indicates to delete the input files or not (pass $false to keep)
.PARAMETER infoFile1
An info line to put at the top of the display for left side
.PARAMETER infoFile2
An info line to put at the top of the display for right side
.EXAMPLE
PS C:\> Get-BinDiff -file1 "c:\temp\ctfmem3.bin" -file2 "C:\temp\mem_ctf3.bin"
.EXAMPLE
PS C:\> Get-BinDiff -file1 "c:\temp\ctfmem3.bin" -file2 "C:\temp\mem_ctf3.bin" -DeleteInputFiles:$true "i downloaded this" "other file"
.NOTES
You would want to use this perhaps if evaluating blocks of memory pulled from a system
against the pagehash server requested blocks
#>
Function Get-BinDiff
{
param (
[Parameter(Mandatory=$True,Position=1)]
[string]$file1,
[Parameter(Mandatory=$True,Position=2)]
[string]$file2,
[Parameter(Position=3)]
[Switch]$DeleteInputFiles = $false,
[Parameter(Position=4)]
[string]$infoFile1,
[Parameter(Position=5)]
[string]$infoFile2
)
Write-Verbose "running bindiff with args $file1 $file2 $DeleteInputFiles $infoFile1 $infoFile2"
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName PresentationFramework
$offset = 0
Set-Variable -Name offset -Value $offset -Scope Global
$foreGround= [System.Windows.Media.Brushes]::Coral
Write-Verbose "Enter BinDiff (mem file) $file1 with (gold file) $file2"
# golden image limit is our limit
$maxLen = ([System.IO.fileinfo]$file2).Length
$lefttb = New-RichTextBox
$lefttb.Name = "leftRtb"
$lefttb.IsReadOnly = $true
$lefttb.MaxWidth = 550
$lefttb.Background = "Black"
$righttb = New-RichTextBox
$righttb.Name = "rightRtb"
$righttb.IsReadOnly = $true
$righttb.MaxWidth = 550
$righttb.Background = "Black"
Write-Verbose "Setting up flow documents in global space"
$leftFlow = New-FlowDocument -LineStackingStrategy BlockLineHeight -LineHeight 12.0 -FontFamily "Consolas" -FontSize 12 -TextAlignment Left
$rightFlow = New-FlowDocument -LineStackingStrategy BlockLineHeight -LineHeight 12.0 -FontFamily "Consolas" -FontSize 12 -TextAlignment Left
$fgInfoLine = [System.Windows.Media.Brushes]::Aquamarine
$paraL = New-Paragraph -Inlines { New-Run -Text "Remote host memory. Length 0x$((([System.IO.fileinfo]$file1).Length).ToString(""x"")) $infoFile1" -Foreground $fgInfoLine }
$leftFlow.Blocks.Add($paraL)
$paraR = New-Paragraph -Inlines { New-Run -Text "From Golden image server. Length 0x$((([System.IO.fileinfo]$file1).Length).ToString(""x"")) $infoFile2" -Foreground $fgInfoLine }
$rightFlow.Blocks.Add($paraR)
$paraTyp = [System.Windows.Documents.Paragraph]
$astyle = new-Style -TargetType $paraTyp
$astyle.Setters.Add([System.Windows.Setter]::new([System.Windows.Documents.Paragraph]::MarginProperty, [System.Windows.Thickness]::new(1.0)))
$leftFlow.Resources.Add([System.Windows.Documents.Paragraph], $astyle)
$rightFlow.Resources.Add([System.Windows.Documents.Paragraph], $astyle)
$lefttb.SetValue([Windows.Controls.Grid]::ColumnProperty, 0)
$righttb.SetValue([Windows.Controls.Grid]::ColumnProperty, 1)
$workArea = [System.Windows.SystemParameters]::WorkArea
$screenWidth = $workArea.Width / 2.0
$screenHeight = $workArea.Height / 3.0
Set-Variable -Name leftFlow -Value $leftFlow -Scope Global
Set-Variable -Name rightFlow -Value $rightFlow -Scope Global
Add-FlowBlocks $file1 $file2
$btnBack = [System.Windows.Media.Brushes]::DarkCyan
$btnFore = [System.Windows.Media.Brushes]::Snow
$lefttb.Document = $leftFlow
$righttb.Document = $rightFlow
Write-Verbose "$screenWidth $screenHeight"
New-Window -WindowState Normal -WindowStartupLocation Manual -Width 200 -Height 200 -Background Black -UseLayoutRounding -SizeToContent WidthAndHeight -Content {
New-Grid -Rows ('Auto', '*') -VerticalAlignment Stretch -HorizontalAlignment Stretch -Children {
New-ScrollViewer -MinHeight 100 -Row 1 -Content {
New-ViewBox -StretchDirection Both -Stretch Fill -Child {
New-Grid -MinHeight 100 -Columns ('Auto', 'Auto') -Children {
$lefttb,
$righttb
}
}
}
New-StackPanel -Orientation Horizontal -Children {
New-Button "PrevPage" -VerticalContentAlignment Stretch -Background $btnBack -Foreground $btnFore -On_Click {
if($Global:offset -ge 0x1000) {
$Global:offset -= 0x1000
}
Add-FlowBlocks $file1 $file2
}
New-Button "NextPage" -IsDefault -VerticalContentAlignment Stretch -Background $btnBack -Foreground $btnFore -On_Click {
if($Global:offset -lt $maxLen-0x1000) {
$Global:offset += 0x1000
}
Add-FlowBlocks $file1 $file2
}
New-Button "LoadPage" -VerticalContentAlignment Stretch -Background $btnBack -Foreground $btnFore -On_Click {
[long]::TryParse($tbAddr.Text, [System.Globalization.NumberStyles]::AllowHexSpecifier, [System.Globalization.CultureInfo]::InvariantCulture, [ref] $value)
$Global:offset = $value
Add-FlowBlocks $file1 $file2
}
New-TextBlock -Text "Enter RVA load: " -HorizontalAlignment Right -FontFamily "Consolas" -FontSize 16 -FontWeight "Bold" -Background $btnBack -Foreground $btnFore
New-TextBox -Name "tbAddr" -FontFamily "Consolas" -FontSize 16 -FontWeight "Bold" -Background $btnBack -Foreground $btnFore
}
}
} -On_Closing {
if($DeleteInputFiles ) {
Remove-Item $file1
Remove-Item $file2
}
} -Show
}
#Get-BinDiff -file1 "c:\temp\ctfmem3.bin" -file2 "C:\temp\mem_ctf3.bin"
class FrameE : System.Windows.FrameworkElement {
##### REQUIRED OVERRIDE
[System.Windows.Media.VisualCollection] $_children
[System.Windows.Media.Visual] GetVisualChild([int] $index) {
return $this._children[$index]
}
# This has to be defined
[Int]$VisualChildrenCount;
# Also only the get_ can be here
[int] get_VisualChildrenCount() {
return $this._children.Count
}
##### REQUIRED OVERRIDE
[Double]$Height;
[Double]$Width;
[Double]$ActualHeight;
[Double]$ActualWidth;
[byte[]]$buff;
[long]$offset;
[long]$RVA;
[string]$file;
[System.Windows.Controls.Canvas]$Parent;
[System.Windows.Media.SolidColorBrush]$foreGroundGood;
[System.Windows.Media.SolidColorBrush]$foreGroundBad;
[System.Windows.Media.SolidColorBrush]$addrColor;
[System.Windows.Media.SolidColorBrush]$bytesColor;
[System.Globalization.CultureInfo]$cul;
[System.Windows.FlowDirection]$dir;
[System.Windows.Media.Typeface]$fnt;
[System.Windows.Point]$loc;
[Double]$fntSize;
FrameE([string]$file, [long]$offset, [long]$RVA) {
$this.Width = 0
$this.Height = 0
$this.RVA = $RVA
$this.file = $file
$this.offset = $offset
$this.buff = New-Object byte[] 0x1000
$this.FilePageOffset($offset)
$this.foreGroundGood = [System.Windows.Media.Brushes]::Coral
$this.foreGroundBad = [System.Windows.Media.Brushes]::Crimson
$this.addrColor = [System.Windows.Media.Brushes]::Cyan
$this.bytesColor = [System.Windows.Media.Brushes]::MistyRose
$this.cul = [System.Globalization.CultureInfo]::CurrentUICulture
$this.dir = [System.Windows.FlowDirection]::LeftToRight
$this.fnt = [System.Windows.Media.Typeface]::new("Consolas")
$this.loc = [System.Windows.Point]::new(0, 0)
$this.fntSize = 10.0
}
[void] FilePageOffset([long] $offset) {
$stream= [System.IO.File]::OpenRead($this.file)
$stream.Position=$offset
[void]$stream.Read($this.buff, 0, $this.buff.Length)
$stream.Close()
$this.offset += $this.buff.Length
}
[void] DiffOther([byte[]]$other) {
$this._children = [System.Windows.Media.VisualCollection]::new($this)
$this._children.Add($this.CreateDiffText($other))
$this.VisualChildrenCount = $this._children.Count
}
[System.Windows.Media.DrawingVisual] CreateDiffText([byte[]]$other) {
$dv = [System.Windows.Media.DrawingVisual]::new()
$dc = $dv.RenderOpen();
$currByte=0
$this.Width=0
for($address = 0; $address -lt 0x1000; $address+=16)
{
# ADDRESS
$RVADDR = $this.RVA+$address+$this.offset-0x1000
$fmt = [System.Windows.Media.FormattedText]::new($($RVADDR.ToString("x8")), $this.cul, $this.dir, $this.fnt, $this.fntSize, $this.addrColor)
$pnt=[System.Windows.Point]::new($this.Width, $this.Height)
$dc.DrawText($fmt,$pnt)
$this.Width += ($fmt.MinWidth + 10.0)
# HEX BYTES
$curr=$currByte
$byteLineLim=$currByte+16
for ($currByte; $currByte -lt $byteLineLim; $currByte++) {
$byteStr=$this.buff[$currByte].ToString("x2")
$otherStr=$other[$currByte].ToString("x2")
if($byteStr[0] -eq $otherStr[0]) { $fColor=$this.foreGroundGood } else { $fColor=$this.foreGroundBad}
$fmt = [System.Windows.Media.FormattedText]::new($byteStr[0], $this.cul, $this.dir, $this.fnt, $this.fntSize, $fColor)
$pnt=[System.Windows.Point]::new($this.Width, $this.Height)
$dc.DrawText($fmt, $pnt)
$this.Width += $fmt.MinWidth
if($byteStr[1] -eq $otherStr[1]) { $fColor=$this.foreGroundGood } else { $fColor=$this.foreGroundBad}
$fmt = [System.Windows.Media.FormattedText]::new($byteStr[1], $this.cul, $this.dir, $this.fnt, $this.fntSize, $fColor)
$pnt=[System.Windows.Point]::new($this.Width, $this.Height)
$dc.DrawText($fmt, $pnt)
$this.Width += ($fmt.MinWidth + 4.0)
}
# ASCII BYTES
$currAscii=$curr
$asciiLim=$currAscii+16
$asciiStr=""
for ($currAscii; $currAscii -lt $asciiLim; $currAscii++) {
$asciiStr+=[char]$this.buff[$currAscii]
}
$fmt = [System.Windows.Media.FormattedText]::new($asciiStr, $this.cul, $this.dir, $this.fnt, $this.fntSize, $this.bytesColor)
$this.Width += 10.0
$pnt=[System.Windows.Point]::new($this.Width, $this.Height)
$dc.DrawText($fmt, $pnt)
$this.Width+=$fmt.MinWidth
#preserve our max width
if($this.ActualWidth -lt $this.Width) {
$this.ActualWidth = $this.Width
}
$this.Width = 0
$this.Height += 12
}
$dc.Close()
#$this.Height += 12
$this.ActualHeight = $this.Height
return $dv
}
}
<#
.SYNOPSIS
Display a side-by-side hex dump with some syntax highlighting to indicate
where diffferences occur (8 bits granularity)
To do this in a relativly more cool way you need to use FormattedText and
not a FlowDocument so I simply colorize by line since the perf impact isnt
as insane.
.DESCRIPTION
DIFF
.PARAMETER file1
File Left to compare
.PARAMETER file2
File Right to compare
.PARAMETER RVA
RVA To make the addresses in sync
.PARAMETER DeleteInputFiles
A SWITCH that indicates to delete the input files or not (pass $false to keep)
.PARAMETER infoFile1
An info line to put at the top of the display for left side
.PARAMETER infoFile2
An info line to put at the top of the display for right side
.EXAMPLE
PS C:\> Get-BinDiff -file1 "c:\temp\ctfmem3.bin" -file2 "C:\temp\mem_ctf3.bin"
.EXAMPLE
PS C:\> Get-BinDiff -file1 "c:\temp\ctfmem3.bin" -file2 "C:\temp\mem_ctf3.bin" -RVA 0x12345 -DeleteInputFiles:$true "i downloaded this" "other file"
.NOTES
You would want to use this perhaps if evaluating blocks of memory pulled from a system
against the pagehash server requested blocks
#>
Function Get-FastBinDiff
{
param (
[Parameter(Mandatory=$True,Position=1)]
[string]$file1,
[Parameter(Mandatory=$True,Position=2)]
[string]$file2,
[Parameter(Position=3)]
[long]$RVA,
[Parameter(Position=4)]
[string]$infoFile1,
[Parameter(Position=5)]
[string]$infoFile2
#[Parameter(Position=6)]
#[Switch]$DeleteInputFiles = $true
)
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Import-Module ShowUI
# golden image limit
$maxLen2 = ([System.IO.fileinfo]$file2).Length
# memory image limit
$maxLen1 = ([System.IO.fileinfo]$file1).Length
$minMaxLen = $maxLen1
if($maxLen2 -lt $minMaxLen) {
$minMaxLen = $maxlen2
}
Set-Variable -Name minMaxLen -Value $minMaxLen -Scope Global
$btnBack = [System.Windows.Media.Brushes]::DarkCyan
$btnFore = [System.Windows.Media.Brushes]::Snow
$FrameL = [FrameE]::new($file1, 0, $RVA)
$FrameR = [FrameE]::new($file2, 0, $RVA)
Set-Variable -Name FrameL -Value $FrameL -Scope Global
Set-Variable -Name FrameR -Value $FrameR -Scope Global
$FrameL.DiffOther($FrameR.buff)
$FrameR.DiffOther($FrameL.buff)
$h = $FrameL.ActualHeight
$w = ($FrameL.ActualWidth *2)+20
$FrameL.SetValue([Windows.Controls.Grid]::ColumnProperty, 0)
$FrameR.SetValue([Windows.Controls.Canvas]::LeftProperty, $FrameL.ActualWidth + 10)
New-Window -WindowState Normal -WindowStartupLocation Manual -Background Black -UseLayoutRounding -SizeToContent WidthAndHeight -Content {
New-Grid -Rows ('Auto', 'Auto', '*') -VerticalAlignment Stretch -HorizontalAlignment Stretch -Children {
New-ScrollViewer -Name Scroller -MinHeight 100 -Row 2 -Content {
New-ViewBox -StretchDirection Both -Stretch Fill -Child {
New-Canvas -Name CanvasContainer -Width $w -Height $h {
$FrameL,
$FrameR
}
}
}
New-TextBlock -Row 1 -Text $infoFile1 -HorizontalAlignment Left -TextAlignment Left -Background $btnBack -Foreground $btnFore
New-TextBlock -Row 1 -Text $infoFile2 -HorizontalAlignment Right -TextAlignment Right -Background $btnBack -Foreground $btnFore
New-StackPanel -Orientation Horizontal -Children {
New-Button "Load Entire File" -IsDefault -VerticalContentAlignment Stretch -Background $btnBack -Foreground $btnFore -On_Click {
$curr = $frameL.offset
for($curr = $frameL.offset; $curr -lt $Global:minMaxLen; $curr += 0x1000)
{
$FrameL.FilePageOffset($FrameL.offset)
$FrameR.FilePageOffset($FrameR.offset)
$FrameL.DiffOther($FrameR.buff)
$FrameR.DiffOther($FrameL.buff)
$CanvasContainer.UpdateLayout()
#not sure why this isnt updating the visual yet
$CanvasContainer.Height = $FrameL.ActualHeight
$Scroller.ScrollToBottom()
}
}
New-Button "Load Next Page" -IsDefault -VerticalContentAlignment Stretch -Background $btnBack -Foreground $btnFore -On_Click {
$FrameL.FilePageOffset($FrameL.offset)
$FrameR.FilePageOffset($FrameR.offset)
$FrameL.DiffOther($FrameR.buff)
$FrameR.DiffOther($FrameL.buff)
$CanvasContainer.Height = $FrameL.ActualHeight
}
New-Button "Load Specified Page" -VerticalContentAlignment Stretch -Background $btnBack -Foreground $btnFore -On_Click {
$value = 0L
[long]::TryParse($tbAddr.Text, [System.Globalization.NumberStyles]::AllowHexSpecifier, [System.Globalization.CultureInfo]::InvariantCulture, [ref] $value)
$FrameL.FilePageOffset($value)
$FrameR.FilePageOffset($value)
$FrameL.DiffOther($FrameR.buff)
$FrameR.DiffOther($FrameL.buff)
$CanvasContainer.Height = $FrameL.ActualHeight
}
New-TextBlock -Text "Enter RVA load: " -HorizontalAlignment Right -FontFamily "Consolas" -FontSize 16 -FontWeight "Bold" -Background $btnBack -Foreground $btnFore
New-TextBox -Name "tbAddr" -FontFamily "Consolas" -FontSize 16 -FontWeight "Bold" -Background $btnBack -Foreground $btnFore
}
}
} -On_Closing {
if($DeleteInputFiles) {
Remove-Item $file1
Remove-Item $file2
}
} -Show
}
Function Get-GoldenImage {
param(
[Parameter(Mandatory=$true)][string]$file,
[Parameter(Mandatory=$true)][long]$mapped,
[Parameter(Mandatory=$true)][string]$writeOut
)
return Invoke-WebRequest -Uri "$HashServerUri/?file=$file&mapped=$mapped" -Method GET -UseBasicParsing -OutFile $writeOut
}
Function Get-ProcessMemory {
param(
[Parameter(Mandatory=$true)][object]$s,
[Parameter(Mandatory=$true)][UInt32]$ID,
[Parameter(Mandatory=$true)][Int64]$Address,
[Parameter(Mandatory=$true)][Int32]$Length)
return Invoke-Command -Session $s -ScriptBlock { [MemTest.NativeMethods]::GetMemory($argS[0], $argS[1], $argS[2]) } -ArgS $ID,$Address,$Length
}
Function Remove-InvalidFileNameChars {
param(
[Parameter(Mandatory=$true,
Position=0,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[String]$Name)
$invalidChars = [System.IO.Path]::GetInvalidFileNameChars() -join ''
$re = "[{0}]" -f [RegEx]::Escape($invalidChars)
return ($Name -replace $re, " ")
}
function Get-System {
param(
[String]
$Technique = 'Token',
[Switch]
$WhoAmI
)
# written by @mattifestation and adapted from https://github.com/obscuresec/shmoocon/blob/master/Invoke-TwitterBot
Function Local:Get-SystemToken {
[CmdletBinding()] param()
$DynAssembly = New-Object Reflection.AssemblyName('AdjPriv')
$AssemblyBuilder = [Appdomain]::Currentdomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('AdjPriv', $False)
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TokPriv1LuidTypeBuilder = $ModuleBuilder.DefineType('TokPriv1Luid', $Attributes, [System.ValueType])
$TokPriv1LuidTypeBuilder.DefineField('Count', [Int32], 'Public') | Out-Null
$TokPriv1LuidTypeBuilder.DefineField('Luid', [Int64], 'Public') | Out-Null
$TokPriv1LuidTypeBuilder.DefineField('Attr', [Int32], 'Public') | Out-Null
$TokPriv1LuidStruct = $TokPriv1LuidTypeBuilder.CreateType()
$LuidTypeBuilder = $ModuleBuilder.DefineType('LUID', $Attributes, [System.ValueType])
$LuidTypeBuilder.DefineField('LowPart', [UInt32], 'Public') | Out-Null
$LuidTypeBuilder.DefineField('HighPart', [UInt32], 'Public') | Out-Null
$LuidStruct = $LuidTypeBuilder.CreateType()
$Luid_and_AttributesTypeBuilder = $ModuleBuilder.DefineType('LUID_AND_ATTRIBUTES', $Attributes, [System.ValueType])
$Luid_and_AttributesTypeBuilder.DefineField('Luid', $LuidStruct, 'Public') | Out-Null
$Luid_and_AttributesTypeBuilder.DefineField('Attributes', [UInt32], 'Public') | Out-Null
$Luid_and_AttributesStruct = $Luid_and_AttributesTypeBuilder.CreateType()
$ConstructorInfo = [Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]
$ConstructorValue = [Runtime.InteropServices.UnmanagedType]::ByValArray
$FieldArray = @([Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst'))
$TokenPrivilegesTypeBuilder = $ModuleBuilder.DefineType('TOKEN_PRIVILEGES', $Attributes, [System.ValueType])
$TokenPrivilegesTypeBuilder.DefineField('PrivilegeCount', [UInt32], 'Public') | Out-Null
$PrivilegesField = $TokenPrivilegesTypeBuilder.DefineField('Privileges', $Luid_and_AttributesStruct.MakeArrayType(), 'Public')
$AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 1))
$PrivilegesField.SetCustomAttribute($AttribBuilder)
$TokenPrivilegesStruct = $TokenPrivilegesTypeBuilder.CreateType()
$AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder(
([Runtime.InteropServices.DllImportAttribute].GetConstructors()[0]),
'advapi32.dll',
@([Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')),
@([Bool] $True)
)
$AttribBuilder2 = New-Object Reflection.Emit.CustomAttributeBuilder(
([Runtime.InteropServices.DllImportAttribute].GetConstructors()[0]),
'kernel32.dll',
@([Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')),
@([Bool] $True)
)
$Win32TypeBuilder = $ModuleBuilder.DefineType('Win32Methods', $Attributes, [ValueType])
$Win32TypeBuilder.DefinePInvokeMethod(
'OpenProcess',
'kernel32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[IntPtr],
@([UInt32], [Bool], [UInt32]),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder2)
$Win32TypeBuilder.DefinePInvokeMethod(
'CloseHandle',
'kernel32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([IntPtr]),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder2)
$Win32TypeBuilder.DefinePInvokeMethod(
'DuplicateToken',
'advapi32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([IntPtr], [Int32], [IntPtr].MakeByRefType()),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder)
$Win32TypeBuilder.DefinePInvokeMethod(
'SetThreadToken',
'advapi32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([IntPtr], [IntPtr]),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder)
$Win32TypeBuilder.DefinePInvokeMethod(
'OpenProcessToken',
'advapi32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([IntPtr], [UInt32], [IntPtr].MakeByRefType()),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder)
$Win32TypeBuilder.DefinePInvokeMethod(
'LookupPrivilegeValue',
'advapi32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([String], [String], [IntPtr].MakeByRefType()),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder)
$Win32TypeBuilder.DefinePInvokeMethod(
'AdjustTokenPrivileges',
'advapi32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([IntPtr], [Bool], $TokPriv1LuidStruct.MakeByRefType(),[Int32], [IntPtr], [IntPtr]),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder)
$Win32Methods = $Win32TypeBuilder.CreateType()
$Win32Native = [Int32].Assembly.GetTypes() | Where-Object {$_.Name -eq 'Win32Native'}
$GetCurrentProcess = $Win32Native.GetMethod(
'GetCurrentProcess',
[Reflection.BindingFlags] 'NonPublic, Static'
)
$SE_PRIVILEGE_ENABLED = 0x00000002
$STANDARD_RIGHTS_REQUIRED = 0x000F0000
$STANDARD_RIGHTS_READ = 0x00020000
$TOKEN_ASSIGN_PRIMARY = 0x00000001
$TOKEN_DUPLICATE = 0x00000002
$TOKEN_IMPERSONATE = 0x00000004
$TOKEN_QUERY = 0x00000008
$TOKEN_QUERY_SOURCE = 0x00000010
$TOKEN_ADJUST_PRIVILEGES = 0x00000020
$TOKEN_ADJUST_GROUPS = 0x00000040
$TOKEN_ADJUST_DEFAULT = 0x00000080
$TOKEN_ADJUST_SESSIONID = 0x00000100
$TOKEN_READ = $STANDARD_RIGHTS_READ -bor $TOKEN_QUERY
$TOKEN_ALL_ACCESS = $STANDARD_RIGHTS_REQUIRED -bor
$TOKEN_ASSIGN_PRIMARY -bor
$TOKEN_DUPLICATE -bor
$TOKEN_IMPERSONATE -bor
$TOKEN_QUERY -bor
$TOKEN_QUERY_SOURCE -bor
$TOKEN_ADJUST_PRIVILEGES -bor
$TOKEN_ADJUST_GROUPS -bor
$TOKEN_ADJUST_DEFAULT -bor
$TOKEN_ADJUST_SESSIONID
[long]$Luid = 0
$tokPriv1Luid = [Activator]::CreateInstance($TokPriv1LuidStruct)
$tokPriv1Luid.Count = 1
$tokPriv1Luid.Luid = $Luid
$tokPriv1Luid.Attr = $SE_PRIVILEGE_ENABLED
$RetVal = $Win32Methods::LookupPrivilegeValue($Null, "SeDebugPrivilege", [ref]$tokPriv1Luid.Luid)
$htoken = [IntPtr]::Zero
$RetVal = $Win32Methods::OpenProcessToken($GetCurrentProcess.Invoke($Null, @()), $TOKEN_ALL_ACCESS, [ref]$htoken)
$tokenPrivileges = [Activator]::CreateInstance($TokenPrivilegesStruct)
$RetVal = $Win32Methods::AdjustTokenPrivileges($htoken, $False, [ref]$tokPriv1Luid, 12, [IntPtr]::Zero, [IntPtr]::Zero)
if(-not($RetVal)) {
Write-Error "AdjustTokenPrivileges failed, RetVal : $RetVal" -ErrorAction Stop
}
$LocalSystemNTAccount = (New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList ([Security.Principal.WellKnownSidType]::'LocalSystemSid', $null)).Translate([Security.Principal.NTAccount]).Value
$SystemHandle = Get-WmiObject -Class Win32_Process | ForEach-Object {
try {
$OwnerInfo = $_.GetOwner()
if ($OwnerInfo.Domain -and $OwnerInfo.User) {
$OwnerString = "$($OwnerInfo.Domain)\$($OwnerInfo.User)".ToUpper()
if ($OwnerString -eq $LocalSystemNTAccount.ToUpper()) {
$Process = Get-Process -Id $_.ProcessId
$Handle = $Win32Methods::OpenProcess(0x0400, $False, $Process.Id)
if ($Handle) {
$Handle
}
}
}
}
catch {}
} | Where-Object {$_ -and ($_ -ne 0)} | Select-Object -First 1
if ((-not $SystemHandle) -or ($SystemHandle -eq 0)) {
Write-Error 'Unable to obtain a handle to a system process.'
}
else {
[IntPtr]$SystemToken = [IntPtr]::Zero
$RetVal = $Win32Methods::OpenProcessToken(([IntPtr][Int] $SystemHandle), ($TOKEN_IMPERSONATE -bor $TOKEN_DUPLICATE), [ref]$SystemToken);$LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
Write-Verbose "OpenProcessToken result: $RetVal"
Write-Verbose "OpenProcessToken result: $LastError"
[IntPtr]$DulicateTokenHandle = [IntPtr]::Zero
$RetVal = $Win32Methods::DuplicateToken($SystemToken, 2, [ref]$DulicateTokenHandle);$LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
Write-Verbose "DuplicateToken result: $LastError"
$RetVal = $Win32Methods::SetThreadToken([IntPtr]::Zero, $DulicateTokenHandle);$LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
if(-not($RetVal)) {
Write-Error "SetThreadToken failed, RetVal : $RetVal" -ErrorAction Stop
}
Write-Verbose "SetThreadToken result: $LastError"
$null = $Win32Methods::CloseHandle($Handle)
}
}
if($PSBoundParameters['WhoAmI']) {
Write-Output "$([Environment]::UserDomainName)\$([Environment]::UserName)"
return
}
else {
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
Write-Error "Script must be run as administrator" -ErrorAction Stop
}
Get-SystemToken
Write-Output "Running as: $([Environment]::UserDomainName)\$([Environment]::UserName)"
}
}
Function Test-AllVirtualMemory
{
<#
.SYNOPSIS
Get Hash values from process memory. This script will remotly scan the CODE virtual memory of the target system
and perform SHA256 hash against each PAGE of memory. It identifies shared code pages and only scan's shared pages
1 time. This help's the performance (at least 1/2 the pages should be shared).
It then send's sufficent information to a cloud box that queries a hash database and applies some de-locating
so that it can match the pages hash values properly (a few more cases here).
There will be NO false positives, only false negatives. So you may be told something is NOT safe when it is.
Hopefully this isn't too often.
Only expect Microsoft binaries to be in the hash database, I don't have you're software ;)
This is an experamental server in Azure, if it get's expensive I'm going to have to shut it down or ask somebody to pay for it.
I may just hand out the server code so you can host you're own.
This script is not that fast right now and takes a while to run. But it should detect anybody using any sort of reflective DLL
injection (again if we have the software, so like if they use OLE32.dll or whatever to inject into this will find them).
We have a few trillion hashes in the server, it's very big. The cache is only 5GB though so if it get's polluted I have to empty
it manually right now. Anyhow that's my problem ;)
.DESCRIPTION
A detailed description of the remote-hash-memory.ps1 file.
.PARAMETER TargetHost
A description of the TargetHost parameter.
.PARAMETER aUserName
A description of the aUserName parameter.
.PARAMETER aPassWord
A description of the aPassWord parameter.
.PARAMETER ProcNameGlob
A description of the ProcNameGlob parameter.
.PARAMETER MaxThreads
How Parallel to go (default 256 :)
.PARAMETER GUIObject
Show a UI of the results
.PARAMETER ElevatePastAdmin
Use PowerSploit/Get-System to elevate to a system token
.PARAMETER Persist
If set, the Session to the remote host will remain open
.EXAMPLE
$rv = Test-AllVirtualMemory ...
#browse the process list
$rv.ResultDictionary.Values|select Name,PercentValid,Id|Sort-Object PercentValid
#look for a low scoring "PercentValid"
# The key in the ResultDictionary is the Pid
# The Children of a Process are the modules
# If a module has no name it's just an allocated region of memory with no DLL/exe backing
$rv.ResultDictionary[4164].Children|select PercentValid,Name
# get module names from list
$rv.ResultList.Struct.ModuleName
.EXAMPLE
Test-AllVirtualMemory -TargetHost 192.168.110.144 -aUserName test -aPassWord test -MaxThreads 256 -ElevatePastAdmin -GUIObject
.EXAMPLE
Test-AllVirtualMemory -TargetHost 192.168.110.144 -aUserName test -aPassWord test -MaxThreads 256 -ElevatePastAdmin -GUIObject -ProcNameGlob @( "chrome.exe", "iexplore.exe")
.EXAMPLE
Also scan arguments from the environment since they are passwords etc..
This is a very early version still some rough edges
PS > .\Test-AllVirtualMemory.ps1
Way below the 3 environment variables to set are;
REMOTE_HOST (target to scan)
USER_NAME (a user that has admin on the target)
PASS_WORD (that user's password)
$serverName = [Environment]::GetEnvironmentVariable("REMOTE_HOST")
$username = [Environment]::GetEnvironmentVariable("USER_NAME")
$password = [Environment]::GetEnvironmentVariable("PASS_WORD")
.NOTES
Additional information about the file.
#>
param
(
[String]$TargetHost = "",
[String]$aUserName = $env:UserName,
[String]$aPassWord = "",
[String[]]$ProcNameGlob = $null,
[int]$MaxThreads = 256,
[Switch]$GUIOutput,
[Switch]$ElevatePastAdmin,
[Switch]$Persist = $false
)
# if envronment is set use it, otherwise cmd line
$serverName = [Environment]::GetEnvironmentVariable("REMOTE_HOST")
if ([System.String]::IsNullOrWhiteSpace($serverName))
{
$serverName = $TargetHost
}
$username = [Environment]::GetEnvironmentVariable("USER_NAME")
if ([System.String]::IsNullOrWhiteSpace($username))
{