-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
1917 lines (1783 loc) · 85.8 KB
/
Copy pathForm1.cs
File metadata and controls
1917 lines (1783 loc) · 85.8 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
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
/*
TODO:
-------------------------------------------------
Legend:
. pending
- canceled
/ in progress, tentative, needs testing, etc.
+ completed
-------------------------------------------------
. binary, handle misalignment where len(find) - len(rep) % len(padding) != 0 (GetBytes() encoded length)
. 32-bit and 64-bit applications see different registries, need an option
+ with binary replacement, only use string functions on the section of the buffer that contains the result,
don't try to convert the whole thing to UTF-16 and back
Right now, buffer copying needs work, keep track of offset differences
+ Optional root path
+ with case insensitive searches, determine the case of the detection and substitute the proper case tranformed replacement string
+ case sensitivity
+ handle set default value
+ Set default value for a key from powershell
maybe this can help:
(get-itemproperty -literalpath HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice).'(default)'
remember that if the value is not set it returns $null then also your method return the correct value ;)
Forgot to say that HKCR is not defined at default, use:
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
then you can do correctly:
(get-itemproperty -literalpath HKCR:\http\shell\open\command\).'(default)'
+ Refactor data scan to work on default same as named vals
+ hexifyPS(binData) lol slow, avoid string concatenation plz
+ pad binary replacement, warn if replacement string is longer than original and binary option is checked
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Design;
namespace RegReplace
{
public partial class Form1 : Form
{
const string DefaultRegistryValueSentinelStringConstant = "RegReplace_dot_Form1_Dot_DefaultRegistryValueSentinelStringConstant_7af4b33f-3a4d-4b8a-9f40-8c01bbc27b14";
bool m_userCancel = false;
TimeSpan m_lastRefreshTime = new TimeSpan();
TimeSpan m_refreshInterval = new TimeSpan(100);
System.Diagnostics.Stopwatch m_runningTime = new System.Diagnostics.Stopwatch();
[Flags]
enum SearchOptionFlags
{
ZERO = 0,
KEYS = 1,
VALUES = 2,
DATA = 4,
HKCR = 8,
HKU = 0x10,
HKCU = 0x20,
HKLM = 0x40,
HKCC = 0x80,
HKPD = 0x100,
STRING = 0x200,
MULTISTRING = 0x400,
EXPANDSTRING = 0x800,
BINARY = 0x1000,
CASE_SENSITIVE = 0x2000,
MATCH_RESULT_CASE = 0x4000
}
struct SearchOptions
{
public SearchOptionFlags flags;
public StringComparison stringCompareStyle;
public System.Globalization.CultureInfo culture;
public string rootPath;
public string searchString;
public byte[] searchStringBinA;
public byte[] searchStringBinW;
public string replacementString;
public byte[] replacementStringBinA;
public byte[] replacementStringBinW;
public byte[] replacementStringUpperBinA;
public byte[] replacementStringUpperBinW;
public byte[] replacementStringLowerBinA;
public byte[] replacementStringLowerBinW;
}
enum StringCaseType
{
MIXED,
UPPER,
LOWER
}
[Flags]
enum MatchTypeEnum
{
ZERO = 0,
KEY = 1,
VALUE = 2,
DATA = 4,
DEFAULT = 8,
ASCII = 0x10,
UNICODE = 0x20
}
class KeyMatch
{
public string path; // includes name as last element in path
public string name; // redundant but provides easy pre-parsed data
public string newName;
public string newPath;
}
class ValueMatch
{
public string path;
public string valueName;
public string rep;
}
class DataMatch
{
public string path;
public string valueName;
public RegistryValueKind kind;
public MatchTypeEnum matchType;
//public object data;
//public object newData;
public bool defaultValue;
}
char padchar = '\0';
//delegate void MatchHandler(string keyPath, string valueName, object data, RegistryValueKind kind, MatchTypeEnum matchType );
delegate void MatchHandler(string keyPath, string valueName, RegistryValueKind kind, MatchTypeEnum matchType);
public Form1()
{
InitializeComponent();
}
StringCaseType determineCase(string s, SearchOptions op)
{
string u, l;
//System.Globalization.CultureInfo ci;
switch (op.stringCompareStyle)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
l = s.ToLower(System.Globalization.CultureInfo.CurrentCulture);
break;
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
l = s.ToLower(System.Globalization.CultureInfo.InvariantCulture);
break;
case StringComparison.Ordinal:
case StringComparison.OrdinalIgnoreCase:
default:
l = s.ToLower();
break;
}
if (s == l) { return StringCaseType.LOWER; }
switch (op.stringCompareStyle)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
//ci = System.Globalization.CultureInfo.CurrentCulture;
u = s.ToUpper(System.Globalization.CultureInfo.CurrentCulture);
l = s.ToLower(System.Globalization.CultureInfo.CurrentCulture);
break;
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
//ci = System.Globalization.CultureInfo.InvariantCulture;
u = s.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
l = s.ToLower(System.Globalization.CultureInfo.InvariantCulture);
break;
case StringComparison.Ordinal:
case StringComparison.OrdinalIgnoreCase:
default:
//ci = System.Globalization.CultureInfo.InstalledUICulture;
u = s.ToUpper();
l = s.ToLower();
break;
}
if (s == u) { return StringCaseType.UPPER; }
return StringCaseType.MIXED;
}
string getFileOpen()
{
var dlg = new OpenFileDialog();
var r = dlg.ShowDialog();
if (r == DialogResult.Cancel) { return ""; }
return dlg.FileName;
}
string getFileSave()
{
var dlg = new SaveFileDialog();
dlg.AddExtension = true;
dlg.DefaultExt = "ps1";
dlg.Filter = "PowerShell Scripts (*.ps1)|*.ps1";
var r = dlg.ShowDialog();
if (r == DialogResult.Cancel) { return ""; }
return dlg.FileName;
}
string getFolder()
{
var dlg = new FolderBrowserDialog();
var r = dlg.ShowDialog();
if (r == DialogResult.Cancel) { return ""; }
return dlg.SelectedPath;
}
private void btnFindFile_Click(object sender, EventArgs e)
{
var s = getFileOpen();
if (s != "") { txtFind.Text = s; }
}
private void btnFindFolder_Click(object sender, EventArgs e)
{
var s = getFolder();
if (s != "") { txtFind.Text = s; }
}
private void btnReplaceFile_Click(object sender, EventArgs e)
{
var s = getFileOpen();
if (s != "") { txtReplaceWith.Text = s; }
}
private void btnReplaceFolder_Click(object sender, EventArgs e)
{
var s = getFolder();
if (s != "") { txtReplaceWith.Text = s; }
}
private void btnUndoFileBrowse_Click(object sender, EventArgs e)
{
var s = getFileSave();
if (s != "") { txtUndoFile.Text = s; }
}
private void btnRedoFileBrowse_Click(object sender, EventArgs e)
{
var s = getFileSave();
if (s != "") { txtRedoFile.Text = s; }
}
private void btnDump_Click(object sender, EventArgs e)
{
btnDump.Enabled = false;
btnStop.Enabled = true;
m_userCancel = false;
m_lastRefreshTime = TimeSpan.Zero;
SearchOptions op = optionSnapshot();
txtResult.Text = "Scanning...\r\n";
//txtResult.Refresh();
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
m_runningTime.Reset();
m_runningTime.Start();
m_lastRefreshTime = TimeSpan.Zero;
// make copies of these fields in case events are processed and text box changes
string findstr = txtFind.Text;
string repstr = txtReplaceWith.Text;
string undoFilename = txtUndoFile.Text;
string redoFilename = txtRedoFile.Text;
int repBinLength = System.Text.Encoding.Unicode.GetBytes(repstr).Length;
int searchBinLength = System.Text.Encoding.Unicode.GetBytes(findstr).Length;
int padBinLength = System.Text.Encoding.Unicode.GetBytes(new String(padchar, 1)).Length;
if (((repBinLength < searchBinLength) && op.flags.HasFlag(SearchOptionFlags.BINARY)))
{
if (MessageBox.Show("Binary replacement data is longer than search term. This will result in a different length, which may cause pointer errors, crashes, and/or data corruption. Exercise caution before executing the script file. Do you want to continue?", "Binary replace", MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
{
return;
}
}
if (((int)Math.Abs(searchBinLength - repBinLength)) % padBinLength != 0)
{
txtResult.Text += "WARNING: UTF-16 alignment error. The difference in length between search text and replacement text is not divisible by the encoded length of the pad character.";
if (MessageBox.Show("UTF-16 alignment error: The difference in length between search text and replacement text is not divisible by the encoded length of the pad character. This will cause misalignment. Do you want to continue?", "Binary replace", MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
{
return;
}
}
if (chkUseRootPath.Checked)
{
RegistryKey keyTest = OpenKey(txtRootPath.Text, op);
if (keyTest == null)
{
txtResult.Text += "ERROR: Root path not found.\r\n";
m_runningTime.Stop();
return;
}
keyTest.Close();
}
StreamWriter undo, redo;
try
{
undo = new System.IO.StreamWriter(undoFilename);
}
catch (Exception ex)
{
txtResult.Text += ex.Message + "\r\n";
m_runningTime.Stop();
return;
}
try
{
redo = new System.IO.StreamWriter(redoFilename);
}
catch (Exception ex)
{
undo.Close();
txtResult.Text += ex.Message + "\r\n";
m_runningTime.Stop();
return;
}
//undo.WriteLine("REGEDIT4");
//undo.WriteLine("");
//redo.WriteLine("REGEDIT4");
//redo.WriteLine("");
List<KeyMatch> keyMatches = new List<KeyMatch>();
List<ValueMatch> valueMatches = new List<ValueMatch>();
List<DataMatch> dataMatches = new List<DataMatch>();
//#############################################################################################################
// MAIN DUMP FUNCTION
try
{
regfind(txtFind.Text, op,
//(string keyPath, string valueName, object dataObj, RegistryValueKind kind, MatchTypeEnum matchType) =>
(string keyPath, string valueName, RegistryValueKind kind, MatchTypeEnum matchType) =>
{
if (matchType.HasFlag(MatchTypeEnum.KEY))
{
KeyMatch km = new KeyMatch();
km.path = keyPath;
km.name = valueName;
keyMatches.Add(km);
}
if (matchType.HasFlag(MatchTypeEnum.VALUE))
{
ValueMatch m = new ValueMatch();
m.path = keyPath;
m.valueName = valueName;
valueMatches.Add(m);
}
if (matchType.HasFlag(MatchTypeEnum.DATA))
{
DataMatch m = new DataMatch();
m.path = keyPath;
m.matchType = matchType;
if (valueName == DefaultRegistryValueSentinelStringConstant)
{
m.defaultValue = true;
m.valueName = "";
}
else
{
m.defaultValue = false;
m.valueName = valueName;
}
//m.data = dataObj;
m.kind = kind;
if (matchType.HasFlag(MatchTypeEnum.DEFAULT)) { m.defaultValue = true; }
//else { m.defaultValue = false; }
dataMatches.Add(m);
}
});
}
// END MAIN DUMP FUNCTION
//#############################################################################################################
catch (Exception ex)
{
txtResult.Text += ex.Message + "\r\n" + ex.StackTrace + "\r\n";
undo.Close();
redo.Close();
sw.Stop();
txtResult.Text += "Error after " + sw.Elapsed.TotalSeconds.ToString() + " seconds.\r\n";
return;
}
//finally
//{
// undo.Close();
// redo.Close();
// sw.Stop();
// txtResult.Text += "Finished in " + sw.Elapsed.TotalSeconds.ToString() + " seconds.\r\n";
//}
// For the 'do' or 'redo' file, we set data, then values, then keys, so all the paths work out.
// If there's a key that needs renaming, but there's also a data value under it that will be modified,
// need to change the data and values before the key path.
// For the 'undo' file, need to work in the opposite order
//int p;
// HKLM and HKCU are built in
undo.WriteLine("New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS");
redo.WriteLine("New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS");
undo.WriteLine("New-PSDrive -PSProvider Registry -Name HKCR -Root HKEY_CLASSES_ROOT");
redo.WriteLine("New-PSDrive -PSProvider Registry -Name HKCR -Root HKEY_CLASSES_ROOT");
undo.WriteLine("New-PSDrive -PSProvider Registry -Name HKCC -Root HKEY_CURRENT_CONFIG");
redo.WriteLine("New-PSDrive -PSProvider Registry -Name HKCC -Root HKEY_CURRENT_CONFIG");
undo.WriteLine("New-PSDrive -PSProvider Registry -Name HKPD -Root HKEY_PERFORMANCE_DATA");
redo.WriteLine("New-PSDrive -PSProvider Registry -Name HKPD -Root HKEY_PERFORMANCE_DATA");
//if (op.flags.HasFlag(SearchOptionFlags.HKU))
//{
// undo.WriteLine("New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS");
// redo.WriteLine("New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS");
//}
//if (op.flags.HasFlag(SearchOptionFlags.HKCR))
//{
// undo.WriteLine("New-PSDrive -PSProvider Registry -Name HKCR -Root HKEY_CLASSES_ROOT");
// redo.WriteLine("New-PSDrive -PSProvider Registry -Name HKCR -Root HKEY_CLASSES_ROOT");
//}
//if (op.flags.HasFlag(SearchOptionFlags.HKCC))
//{
// undo.WriteLine("New-PSDrive -PSProvider Registry -Name HKCC -Root HKEY_CURRENT_CONFIG");
// redo.WriteLine("New-PSDrive -PSProvider Registry -Name HKCC -Root HKEY_CURRENT_CONFIG");
//}
//if (op.flags.HasFlag(SearchOptionFlags.HKPD))
//{
// undo.WriteLine("New-PSDrive -PSProvider Registry -Name HKPD -Root HKEY_PERFORMANCE_DATA");
// redo.WriteLine("New-PSDrive -PSProvider Registry -Name HKPD -Root HKEY_PERFORMANCE_DATA");
//}
string line;
object tempDataObjRef;
RegistryKey tempKey;
foreach (var dm in dataMatches)
{
tempKey = OpenKey(dm.path, op);
if (tempKey == null)
{
txtResult.Text += "WARNING: Can not open previously matched key " + dm.path + "\r\n";
continue;
}
if (dm.defaultValue)
{
tempDataObjRef = tempKey.GetValue(null, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
}
else
{
tempDataObjRef = tempKey.GetValue(dm.valueName, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
}
tempKey.Close();
//dm.newData = doReplace(dm.kind, dm.data, findstr, repstr, op);
//object newData = doReplace(dm.kind, tempDataObjRef, findstr, repstr, op, dm.matchType);
object newData = doReplace(dm.kind, tempDataObjRef, op, dm.matchType);
if (dm.defaultValue)
{
//line = "Set-ItemProperty -LiteralPath \"" + dm.path + "\" -Name '(Default)' -Type " + regKindStr(dm.kind) + " -Value " + exportStr(dm.kind, dm.newData);
line = "Set-ItemProperty -LiteralPath \"" + dm.path + "\" -Name '(Default)' -Type " + regKindStr(dm.kind) + " -Value " + exportStr(dm.kind, newData);
}
else
{
//line = "Set-ItemProperty -Path \"" + dm.path + "\" -Name \"" + dm.valueName + "\" -Type " + regKindStr(dm.kind) + " -Value " + exportStr(dm.kind, dm.newData);
line = "Set-ItemProperty -Path \"" + dm.path + "\" -Name \"" + dm.valueName + "\" -Type " + regKindStr(dm.kind) + " -Value " + exportStr(dm.kind, newData);
}
redo.WriteLine(line);
}
tempDataObjRef = null;
foreach (var vm in valueMatches)
{
//vm.rep = ((string)doReplace(RegistryValueKind.String, vm.valueName, findstr, repstr, op));
vm.rep = ((string)doReplace(RegistryValueKind.String, vm.valueName, op));
line = "Rename-ItemProperty -Path \"" + vm.path + "\" -Name \"" + vm.valueName + "\" -NewName \"" + vm.rep + "\"";
redo.WriteLine(line);
}
foreach (var km in keyMatches)
{
//km.newName = (string)doReplace(RegistryValueKind.String, km.name, findstr, repstr, op);
km.newName = (string)doReplace(RegistryValueKind.String, km.name, op);
int pp = km.path.LastIndexOf("\\");
if (pp >= 0)
{
km.newPath = km.path.Substring(0, pp) + km.newName;
//string checkPath = (string)doReplace(RegistryValueKind.String, km.path, findstr, repstr, op);
string checkPath = (string)doReplace(RegistryValueKind.String, km.path, op);
if (checkPath == km.newPath)
{
line = "Rename-Item -Path \"" + km.path + "\" -NewName \"" + km.newName + "\"";
redo.WriteLine(line);
}
else
{
km.newPath = km.path;
km.newName = km.name;
txtResult.Text += "WARNING: Rename operation results in an inconsistent path, skipping " + km.path + "\r\n";
}
}
else
{
km.newPath = km.path;
km.newName = km.name;
txtResult.Text += "WARNING: Rename operation results in an inconsistent path, skipping " + km.path + "\r\n";
}
}
tempDataObjRef = null;
tempKey = null;
// Now the undo/backup
keyMatches.Reverse();
foreach (var km in keyMatches)
{
line = "Rename-Item -Path \"" + km.newPath + "\" -NewName \"" + km.name + "\"";
undo.WriteLine(line);
}
foreach (var vm in valueMatches)
{
line = "Rename-ItemProperty -Path \"" + vm.path + "\" -Name \"" + vm.rep + "\" -NewName \"" + vm.valueName + "\"";
undo.WriteLine(line);
}
foreach (var dm in dataMatches)
{
tempKey = OpenKey(dm.path, op);
if (tempKey == null)
{
txtResult.Text += "WARNING: Can not open previously matched key " + dm.path + "\r\n";
continue;
}
if (dm.defaultValue)
{
tempDataObjRef = tempKey.GetValue(null, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
}
else
{
tempDataObjRef = tempKey.GetValue(dm.valueName, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
}
tempKey.Close();
//dm.newData = doReplace(dm.kind, dm.data, findstr, repstr, op);
//object newData = doReplace(dm.kind, tempDataObjRef, findstr, repstr, op, dm.matchType);
//object newData = doReplace(dm.kind, tempDataObjRef, op, dm.matchType);
if (dm.defaultValue)
{
//line = "Set-ItemProperty -LiteralPath \"" + dm.path + "\" -Name '(Default)' -Type " + regKindStr(dm.kind) + " -Value " + exportStr(dm.kind, dm.data);
line = "Set-ItemProperty -LiteralPath \"" + dm.path + "\" -Name '(Default)' -Type " + regKindStr(dm.kind) + " -Value " + exportStr(dm.kind, tempDataObjRef);
}
else
{
//line = "Set-ItemProperty -Path \"" + dm.path + "\" -Name \"" + dm.valueName + "\" -Type " + regKindStr(dm.kind) + " -Value " + exportStr(dm.kind, dm.data);
line = "Set-ItemProperty -Path \"" + dm.path + "\" -Name \"" + dm.valueName + "\" -Type " + regKindStr(dm.kind) + " -Value " + exportStr(dm.kind, tempDataObjRef);
}
undo.WriteLine(line);
}
undo.WriteLine("write-host \"Finished. Press any key to close...\"");
undo.WriteLine("[void][System.Console]::ReadKey($true)");
redo.WriteLine("write-host \"Finished. Press any key to close...\"");
redo.WriteLine("[void][System.Console]::ReadKey($true)");
undo.Close();
redo.Close();
sw.Stop();
m_runningTime.Stop();
txtResult.Text += "Finished in " + sw.Elapsed.TotalSeconds.ToString() + " seconds.\r\n";
txtCurrentLocation.Text = "";
}
string binAsciiToString(byte[] binData)
{
if (binData == null) { return ""; }
return System.Text.Encoding.ASCII.GetString(binData);
//var enc = System.Text.Encoding.ASCII;
////var enc = new System.Text.ASCIIEncoding();
//return enc.GetString(binData);
////string ret = "";
////for (int i = 0; i < binData.Length; i++)
////{
//// ret += (char)(binData[i]);
////}
////return ret;
}
string binWCharToStringLittleEndian(byte[] binData)
{
if (binData == null) { return ""; }
return System.Text.Encoding.Unicode.GetString(binData);
//var enc = System.Text.Encoding.Unicode;
////var enc = new System.Text.UnicodeEncoding(false, false);
//return enc.GetString(binData);
////string ret = "";
////for (int i = 0; i + 1 < binData.Length; i += 2)
////{
//// ret += (char)(((int)binData[i]) + (((int)(binData[i + 1])) * 0x100));
////}
////if (binData.Length % 2 != 0)
////{
//// ret += (char)(binData[binData.Length - 1]);
////}
////return ret;
}
string ToUpperOption(string orig, SearchOptions op)
{
switch (op.stringCompareStyle)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return orig.ToUpper(System.Globalization.CultureInfo.CurrentCulture);
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return orig.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
case StringComparison.Ordinal:
case StringComparison.OrdinalIgnoreCase:
default:
return orig.ToUpper();
}
}
string ToLowerOption(string orig, SearchOptions op)
{
switch (op.stringCompareStyle)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return orig.ToLower(System.Globalization.CultureInfo.CurrentCulture);
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return orig.ToLower(System.Globalization.CultureInfo.InvariantCulture);
case StringComparison.Ordinal:
case StringComparison.OrdinalIgnoreCase:
default:
return orig.ToLower();
}
}
string replacementStringCased(string dataStr, string repStr, SearchOptions op)
{
StringCaseType detection = determineCase(dataStr, op);
switch (detection)
{
case StringCaseType.UPPER:
return ToUpperOption(repStr, op);
case StringCaseType.LOWER:
return ToLowerOption(repStr, op);
case StringCaseType.MIXED:
default:
return repStr;
}
}
void dumpBin(String filename, Byte[] data)
{
var fsBefore = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
var before = new BinaryWriter(fsBefore);
before.Write(data);
before.Close();
fsBefore.Close();
}
object doReplace(RegistryValueKind kind, object data, SearchOptions op, MatchTypeEnum matchType = MatchTypeEnum.ZERO)
{
//#if DEBUG
// const bool debugDumpBinaryReplacement = true;
//#endif
string findstr = op.searchString;
string repstr = op.replacementString;
string retStr;
string dataStr;
string[] dataMultiStr;
string[] retMultiStr;
byte[] dataBin;
byte[] retBin;
byte[] t1;
//byte[] repBin;
//string binAStr, binWStr;
int p;
//bool foundBinaryMatch = false;
//string findCase;
//if (op.flags.HasFlag(SearchOptions.CASE_SENSITIVE)) { findCase = findstr; }
//else { findCase = findstr.ToLower(); }
//string searchCase = "";
switch (kind)
{
case RegistryValueKind.Binary:
// Should I worry about wide characters... bleh
dataBin = (byte[])data;
if (matchType.HasFlag(MatchTypeEnum.ASCII))
{
List<long> ascMatchList;
if (op.flags.HasFlag(SearchOptionFlags.CASE_SENSITIVE))
{
ascMatchList = dataBin.IndexesOf(op.searchStringBinA);
}
else
{
ascMatchList = dataBin.IndexesOfNoCase(op.searchString, System.Text.Encoding.ASCII, op.culture);
}
if (ascMatchList.Count > 0)
{
if (op.replacementStringBinA.Length > op.searchStringBinA.Length)
{
int sizeDiffPerElement = op.replacementStringBinA.Length - op.searchStringBinA.Length;
t1 = new byte[dataBin.Length + (ascMatchList.Count * sizeDiffPerElement)];
}
else
{
t1 = new byte[dataBin.Length];
}
int ascMatchListIndex = 0;
int ascSourceOfs = 0;
int t1Next = 0;
int copyLen;
int matchOfs = 0;
foreach (var asciiMatchOfs in ascMatchList)
{
matchOfs = (int)asciiMatchOfs;
copyLen = matchOfs - ascSourceOfs;
Buffer.BlockCopy(dataBin, ascSourceOfs, t1, t1Next, copyLen);
t1Next += copyLen;
if (op.flags.HasFlag(SearchOptionFlags.MATCH_RESULT_CASE))
{
byte[] binCaseTest = new byte[op.searchStringBinA.Length];
Buffer.BlockCopy(dataBin, matchOfs, binCaseTest, 0, op.searchStringBinA.Length);
string caseTest = System.Text.Encoding.ASCII.GetString(binCaseTest);
var ct = determineCase(caseTest, op);
if (ct == StringCaseType.LOWER)
{
Buffer.BlockCopy(op.replacementStringLowerBinA, 0, t1, t1Next, op.replacementStringLowerBinA.Length);
t1Next += op.replacementStringLowerBinA.Length;
}
else if (ct == StringCaseType.UPPER)
{
Buffer.BlockCopy(op.replacementStringUpperBinA, 0, t1, t1Next, op.replacementStringUpperBinA.Length);
t1Next += op.replacementStringUpperBinA.Length;
}
else
{
Buffer.BlockCopy(op.replacementStringBinA, 0, t1, t1Next, op.replacementStringBinA.Length);
t1Next += op.replacementStringBinA.Length; // dest buffer ofs, add replacement string length
}
}
else
{
Buffer.BlockCopy(op.replacementStringBinA, 0, t1, t1Next, op.replacementStringBinA.Length);
t1Next += op.replacementStringBinA.Length; // dest buffer ofs, add replacement string length
}
ascSourceOfs += copyLen + op.searchStringBinA.Length; // source buffer, add search string length
ascMatchListIndex++;
}
Buffer.BlockCopy(dataBin, ascSourceOfs, t1, t1Next, dataBin.Length - ascSourceOfs);
}
else
{
t1 = dataBin;
}
}
else { t1 = dataBin; }
// Now work with t1 in place of dataBin
if (matchType.HasFlag(MatchTypeEnum.UNICODE))
{
//var uniMatchList = dataBin.IndexesOf(op.searchStringBinW);
List<long> uniMatchList;
if (op.flags.HasFlag(SearchOptionFlags.CASE_SENSITIVE))
{
uniMatchList = t1.IndexesOf(op.searchStringBinW);
}
else
{
uniMatchList = t1.IndexesOfNoCase(op.searchString, System.Text.Encoding.Unicode, op.culture);
}
if (uniMatchList.Count > 0)
{
if (op.replacementStringBinW.Length > op.searchStringBinW.Length)
{
int sizeDiffPerElement = op.replacementStringBinW.Length - op.searchStringBinW.Length;
retBin = new byte[t1.Length + (uniMatchList.Count * sizeDiffPerElement)];
}
else
{
retBin = new byte[t1.Length];
}
int uniMatchListIndex = 0;
int uniSourceOfs = 0;
int retNext = 0;
int copyLen;
int matchOfs = 0;
foreach (var uniMatchOfs in uniMatchList)
{
matchOfs = (int)uniMatchOfs;
copyLen = matchOfs - uniSourceOfs;
Buffer.BlockCopy(dataBin, uniSourceOfs, retBin, retNext, copyLen);
retNext += copyLen;
if (op.flags.HasFlag(SearchOptionFlags.MATCH_RESULT_CASE))
{
byte[] binCaseTest = new byte[op.searchStringBinW.Length];
Buffer.BlockCopy(dataBin, matchOfs, binCaseTest, 0, op.searchStringBinW.Length);
string caseTest = System.Text.Encoding.Unicode.GetString(binCaseTest);
var ct = determineCase(caseTest, op);
if (ct == StringCaseType.LOWER)
{
Buffer.BlockCopy(op.replacementStringLowerBinW, 0, retBin, retNext, op.replacementStringLowerBinW.Length);
retNext += op.replacementStringLowerBinW.Length;
}
else if (ct == StringCaseType.UPPER)
{
Buffer.BlockCopy(op.replacementStringUpperBinW, 0, retBin, retNext, op.replacementStringUpperBinW.Length);
retNext += op.replacementStringUpperBinW.Length;
}
else
{
Buffer.BlockCopy(op.replacementStringBinW, 0, retBin, retNext, op.replacementStringBinW.Length);
retNext += op.replacementStringBinW.Length; // dest buffer ofs, add replacement string length
}
}
else
{
Buffer.BlockCopy(op.replacementStringBinW, 0, retBin, retNext, op.replacementStringBinW.Length);
retNext += op.replacementStringBinW.Length; // dest buffer ofs, add replacement string length
}
uniSourceOfs += copyLen + op.searchStringBinW.Length; // source buffer, add search string length
uniMatchListIndex++;
}
Buffer.BlockCopy(dataBin, uniSourceOfs, retBin, retNext, t1.Length - uniSourceOfs);
}
else { retBin = t1; }
}
else { retBin = t1; }
//string repCase;
//string originalCut;
//binAStr = binAsciiToString(dataBin);
//
//
//p = binAStr.IndexOf(findstr, op.stringCompareStyle);
//if (p >= 0)
//{
// string paddedReplacementA;
// originalCut = binAStr.Substring(p, findstr.Length);
// repCase = replacementStringCased(originalCut, repstr, op);
// repBin = System.Text.Encoding.ASCII.GetBytes(repCase);
// //if (findstr.Length >= repstr.Length)
// //{
// int padlen = findstr.Length - repstr.Length;
// //paddedReplacementA = repstr + new string(padchar, findstr.Length - repstr.Length);
// padlen++;
// do
// {
// padlen--;
// paddedReplacementA = replacementStringCased(originalCut, repstr, op)
// + new string(padchar, padlen);
// retStr = binAStr.Substring(0, p) + paddedReplacementA + binAStr.Substring(p + findstr.Length);
// retBin = System.Text.Encoding.ASCII.GetBytes(retStr);
// } while ((padlen >= 0) && (retBin.Length > dataBin.Length)); // + findstr.Length - repstr.Length));
// // I don't think there's too much reason to worry about encoding length on ascii, but i gotta do it for utf-16 anyway,
// // might as well figure it out here.
// while (retBin.Length < dataBin.Length)
// {
// padlen++;
// paddedReplacementA = replacementStringCased(originalCut, repstr, op)
// + new string(padchar, padlen);
// retStr = binAStr.Substring(0, p) + paddedReplacementA + binAStr.Substring(p + findstr.Length);
// retBin = System.Text.Encoding.ASCII.GetBytes(retStr);
// }
// //}
// //else
// //{
// // paddedReplacementA = replacementStringCased(originalCut, repstr, op);
// // retStr = binAStr.Substring(0, p) + paddedReplacementA + binAStr.Substring(p + findstr.Length);
// // retBin = System.Text.Encoding.ASCII.GetBytes(retStr);
// //}
//
// //foundBinaryMatch = true;
// //retStr = binAStr.Substring(0, p) + repstr + binAStr.Substring(p + findstr.Length);
//
// //int retlen = dataBin.Length + (paddedReplacementA.Length - findstr.Length);
// //retStr = binAStr.Substring(0, p) + paddedReplacementA + binAStr.Substring(p + findstr.Length);
//
// //retBin = new byte[retStr.Length];
// //// TODO: What if they're using some wierd higher characters that use multiple word encoding? The length will be different.
// //for (int i = 0; i < retStr.Length; i++)
// //{
// // retBin[i] = (byte)retStr[i];
// //}
//
// //retBin = System.Text.Encoding.ASCII.GetBytes(retStr);
// //while (retBin.Length > dataBin.Length + findstr.Length - repstr.Length)
//foreach (int p in dataBin.IndexesOf(op.searchStringBinW))
//#if DEBUG
// if (debugDumpBinaryReplacement)
// {
// dumpBin("DebugDump_doReplace_01_before.bin", dataBin);
// dumpBin("DebugDump_doReplace_02_after.bin", retBin);
// }
//#endif
// return retBin;
//}
//binAStr = null;
//
//binWStr = binWCharToStringLittleEndian(dataBin);
//p = binWStr.IndexOf(findstr, op.stringCompareStyle);
//if (p >= 0)
//{
// string paddedReplacementW;
// originalCut = binWStr.Substring(p, findstr.Length);
// //if (findstr.Length >= repstr.Length)
// //{
// int padlen = findstr.Length - repstr.Length;
// padlen++;
// do
// {
// padlen--;
// //paddedReplacementW = repstr + new string(padchar, findstr.Length - repstr.Length);
// paddedReplacementW = replacementStringCased(originalCut, repstr, op)
// + new string(padchar, findstr.Length - repstr.Length);
// retStr = binWStr.Substring(0, p) + paddedReplacementW + binWStr.Substring(p + findstr.Length);
// //retBin = new byte[retStr.Length * 2];
// retBin = System.Text.Encoding.Unicode.GetBytes(retStr);
// } while ((padlen >= 0) && (retBin.Length > dataBin.Length));
// while (retBin.Length < dataBin.Length)
// {
// padlen++;
// paddedReplacementW = replacementStringCased(binWStr, repstr, op)
// + new string(padchar, findstr.Length - repstr.Length);
// retStr = binWStr.Substring(0, p) + paddedReplacementW + binWStr.Substring(p + findstr.Length);
// //retBin = new byte[retStr.Length * 2];
// retBin = System.Text.Encoding.Unicode.GetBytes(retStr);
// }
// //}
// //else
// //{
// // //paddedReplacementW = repstr;
// // paddedReplacementW = replacementStringCased(binWStr, repstr, op);
// // retStr = binWStr.Substring(0, p) + paddedReplacementW + binWStr.Substring(p + findstr.Length);
// // retBin = new byte[retStr.Length * 2];
// //}
//
//
// //retStr = binWStr.Substring(0, p) + repstr + binWStr.Substring(p + findstr.Length);
// //retStr = binWStr.Substring(0, p) + paddedReplacementW + binWStr.Substring(p + findstr.Length);
// //retBin = new byte[retStr.Length * 2];
// //for (int i = 0; i < retStr.Length; i++)
// //{
// // // little endian
// // retBin[i * 2] = (byte)(retStr[i] % 0x100);
// // retBin[(i * 2) + 1] = (byte)(retStr[i] / 0x100);
// //}
//#if DEBUG
// if (debugDumpBinaryReplacement)
// {
// dumpBin("DebugDump_doReplace_01_before.bin", dataBin);
// dumpBin("DebugDump_doReplace_02_after.bin", retBin);
// }
//#endif
// byte[] ba = new byte[100];