Skip to content

Malware University

Class is in Session

  • About
    • Privacy Policy
  • Contact
  • Resources

Category: Utilities

Manual Scraping

Posted on August 3, 2024 by admin

Sometimes it’s better to do things by hand. Google has some useful Dorks and may become difficult accessing enough results in an automated fashion. With a little JavaScript fu we can dig out of logistical messes with a human touch:

// Download from a Google search result to txt
// Get all links from the unique class (changes)
let links = document.querySelectorAll('.yuRUbf a');

// Extract the href attributes (URLs)
let urls = Array.from(links).map(link => link.href);

//
// Create a Blob from the URLs.
// This will help us create an easy-to-download text file for local consumption.
//
let blob = new Blob([urls.join('\n')], { type: 'text/plain' });

// Create a link element (to "download" later)
let link = document.createElement('a');

// Set the download attribute with a filename
link.download = 'urls.txt';

// Create a URL for the Blob and set it as the href attribute
link.href = window.URL.createObjectURL(blob);

// Append the link to the document body
document.body.appendChild(link);

// Programmatically click the link to trigger the download
link.click();

// Remove the link from the document
document.body.removeChild(link);

You can simply download and your browser should number them sequentially as you click along the results page numbers. From there, you can “cat * > somefile.txt” to aggregate results.

Happy link building, friends.

How to run: Open the Developer Tools for your browser (Ctrl + Shift + I). Click “console”. Copy/paste the code. Enjoy.

How this works: We use the results from manually searching Google to download a list of sites in the returned data series. A little JavaScript magic to create a downloadable element on-the-fly to quickly “scrape” data using Google’s coveted search capabilities.

Posted in UtilitiesTagged dorks, javascript, reconaissance, scraping

Virtualbox Automation

Posted on March 23, 2022 - March 23, 2022 by admin

The following Python code may be used to remotely control a Virtualbox-managed virtual machine. It is useful for batch testing or malware analysis (sandbox management).

#!/usr/bin/env python3

#
# Installing the virtualbox deps:
#   python3 -m pip install pyvbox
#   Download the VirtualBox SDK from https://www.virtualbox.org/wiki/Downloads
#   Unzip the package
#   cd sdk/installer
#   python3 vboxapisetup.py install
#

import virtualbox
import logging


class Sandbox(object):
    def __init__(self, name):
        vbox = virtualbox.VirtualBox()
        self.vm = vbox.find_machine(name)
        #self.session = virtualbox.Session()
        self.session = virtualbox.library.ISession(self.vm.create_session())

        return


    def start(self):
        logging.info('Starting the VM from Office snapshot')
        self.snapshot = self.vm.find_snapshot('Office 2007 Live')
        progress = self.session.machine.restore_snapshot(self.snapshot)
        progress.wait_for_completion()
        self.session.unlock_machine()
        # progress = self.vm.launch_vm_process(self.session, 'headless', '')
        progress = self.vm.launch_vm_process(self.session, '', '')
        progress.wait_for_completion()

        if self.vm.state == self.vm.state.running:
            print('Successfully running')
        print('Done')

        # Create guest session.
        self.console = virtualbox.library.IConsole(self.session.console)
        self.guest = self.console.guest
        # self.guest.sessions[0] contains our IGuestSession object
        self.os_type = self.guest.os_type_id	    # Example
        # self.guest = virtualbox.library.IGuest(self.session)
        # Session is already established in snapshot of unlocked machine?
        self.g_session = self.guest.create_session('malware', 'password', '', '')

        return


    #
    # Username is 'malware'; password is 'password'
    #
    def guest_session_test(self):
        self.console = virtualbox.library.IConsole(self.session.console)
        self.guest = self.console.guest
        # self.guest.sessions[0] contains our IGuestSession object
        self.os_type = self.guest.os_type_id	    # Example
        # self.guest = virtualbox.library.IGuest(self.session)
        # Session is already established in snapshot of unlocked machine?
        self.g_session = self.guest.create_session('malware', 'password', '', '')
        # 1 = R
        # 2 = 
        # 3 = RW
        flag = virtualbox.library.FileCopyFlag(0)
        # This stores the file in your user's home directory by default.
        self.g_session.file_copy_from_guest('C:/Program Files (x86)/Microsoft Office/Office12/GRAPH.EXE', 'C:/WINDOWS/Temp/graph.exe', [flag])


    def drop_artifact(self, artifact_path, destination_on_guest):
        logging.info('About to drop "{}" to "{}"'.format(artifact_path, destination_on_guest))
        flag = virtualbox.library.FileCopyFlag(0)
        progress = self.g_session.file_copy_to_guest(artifact_path, destination_on_guest, [flag])
        progress.wait_for_completion()
        logging.info('"{}" successfully dropped to guest'.format(artifact_path))

        return


    def receive_artifact(self, src_on_guest, path_host_save):
        logging.info('About to pull "{}" to "{}"'.format(src_on_guest, path_host_save))
        flag = virtualbox.library.FileCopyFlag(0)
        progress = self.g_session.file_copy_from_guest(src_on_guest, path_host_save, [flag])
        progress.wait_for_completion()
        logging.info('"{}" successfully saved to "{}"'.format(src_on_guest, path_host_save))

        return


    def execute_command(self, 
                        executable_path: str, 
                        arguments: [str],
                        environment_changes: [str],
                        process_create_flag: [virtualbox.library.ProcessCreateFlag],
                        timeout_ms: int,
                        priority: virtualbox.library.ProcessPriority,
                        affinity: [int]):
        terminate_flag = virtualbox.library.ProcessWaitForFlag(2)

        self.guest_process = self.g_session.process_create_ex(  executable_path, 
                                                                arguments, 
                                                                environment_changes,
                                                                process_create_flag,
                                                                timeout_ms,
                                                                priority,
                                                                affinity)
        logging.info('Process "{}" successfully kicked off...waiting for it to finish'.format(executable_path))
        self.process_wait_result = self.guest_process.wait_for(terminate_flag)
        if self.process_wait_result == virtualbox.library.ProcessWaitResult(5):
            logging.info('Process "{}" exceeded the timeout threashold of {} milliseconds'.format(  executable_path,
                                                                                                    str(timeout_ms))) 
        elif self.process_wait_result == virtualbox.library.ProcessWaitResult(2):
            logging.info('Process "{}" terminated gracefully'.format(executable_path))


    def stop(self):
        # Shut off VM
        progress = self.session.console.power_down()
        progress.wait_for_completion()

        return


s = Sandbox('Windows 7 Office')
s.start()
# s.guest_session_test()
s.drop_artifact('C:/WINDOWS/System32/cmd.exe', 'C:/WINDOWS/Temp/cmd_2016.exe')
#s.execute_command(  'C:/WINDOWS/Temp/cmd_2016.exe',
s.execute_command(  'C:/Program Files (x86)/Microsoft Office/Office12/GRAPH.EXE',
                    [],
                    [],
                    [virtualbox.library.ProcessCreateFlag(0)],
                    20000,
                    virtualbox.library.ProcessPriority(1),
                    [])
s.stop()
Posted in UtilitiesTagged automation, hypervisor, io, malware analysis, Python, sandbox, test, virtualbox

WHOIS Quick Summary

Posted on October 9, 2021 - October 9, 2021 by admin

This is a useful WHOIS query tool. Gives you the most important information you need in an easy-to-read-and-understand format.

#!/bin/bash

if [ -e ${1} ]; then
    echo "You did not supply a domain"
    exit 1
fi

DOMAIN=${1}
CMD=$(whois ${DOMAIN})

function HandleRIPE {
    # I wanted to make life hard on myself by echoing out the unformatted string.
    # We get to play with grep-based look ahead parsing to extract strings.
    # xargs will clean the output.
    # echo "INetNum|"$(echo ${CMD} | grep -o -P '(?<=inetnum:).*(?=netname:)' | xargs)
    echo "INetNum|"$(echo "${CMD}" | grep -m 1 'inetnum' | cut -d':' -f2- | xargs 2>/dev/null)
    echo "Country|"$(echo "${CMD}" | grep -m 1 'country' | cut -d':' -f2- | xargs 2>/dev/null)
    echo "OrgName|"$(echo "${CMD}" | grep -m 1 'org-name' | cut -d':' -f2- | xargs 2>/dev/null)
    echo "Phone|"$(echo "${CMD}" | grep -m 1 'phone' | cut -d':' -f2- | xargs 2>/dev/null)
    Remarks=()
    # echo "${CMD}" | grep 'remarks' | while read -r line ; do
    while read line; do
        found=0
        fmt_line=$(echo "${line}" | cut -d':' -f2- | xargs 2>/dev/null)
        len_remarks=${#Remarks[@]}
        if [ ${len_remarks} -eq 0 ]; then
            Remarks+=("${fmt_line}") 
            # echo "Remarks|${fmt_line}"
        else
            for i in "${Remarks[@]}"; do 
                echo "$i" | grep "${fmt_line}" 2>&1 > /dev/null
                if [ $? -eq 0 ]; then 
                    # Remarks+=("${fmt_line}")
                    # echo "Remarks|${fmt_line}"
                    found=1
                fi
            done
            # BASH is not a real programming language.
            # Can't do [ ! ${found} ]
            # # true -eq false if [[ ${found} -eq false ]]; then
            if [ ${found} -eq 0 ]; then 
                Remarks+=("${fmt_line}")
            fi
        fi
    # done
    done < <(echo "${CMD}" | grep 'remarks')
    # Damned subshells, need to implement process substitution to redirect output from separate processes to keep
    # this variable alive.
    for i in "${Remarks[@]}"; do
        echo "Remarks|${i}"
    done
}

function HandleARIN {
    # I wanted to make life hard on myself by echoing out the unformatted string.
    # We get to play with grep-based look ahead parsing to extract strings.
    # xargs will clean the output.
    # echo "INetNum|"$(echo ${CMD} | grep -o -P '(?<=inetnum:).*(?=netname:)' | xargs)
    echo "INetNum|"$(echo "${CMD}" | grep -m 1 'NetRange' | cut -d':' -f2- | xargs 2>/dev/null)
    echo "Country|"$(echo "${CMD}" | grep -m 1 'Country' | cut -d':' -f2- | xargs 2>/dev/null)
    echo "OrgName|"$(echo "${CMD}" | grep -m 1 'OrgName' | cut -d':' -f2- | xargs 2>/dev/null)
    echo "Phone|"$(echo "${CMD}" | grep -m 1 'OrgAbusePhone' | cut -d':' -f2- | xargs 2>/dev/null)
    Remarks=()
    # echo "${CMD}" | grep 'remarks' | while read -r line ; do
    while read line; do
        found=0
        fmt_line=$(echo "${line}" | cut -d':' -f2- | xargs 2>/dev/null)
        len_remarks=${#Remarks[@]}
        if [ ${len_remarks} -eq 0 ]; then
            Remarks+=("${fmt_line}") 
            # echo "Remarks|${fmt_line}"
        else
            for i in "${Remarks[@]}"; do 
                echo "$i" | grep "${fmt_line}" 2>&1 > /dev/null
                if [ $? -eq 0 ]; then 
                    # Remarks+=("${fmt_line}")
                    # echo "Remarks|${fmt_line}"
                    found=1
                fi
            done
            # BASH is not a real programming language.
            # Can't do [ ! ${found} ]
            # # true -eq false if [[ ${found} -eq false ]]; then
            if [ ${found} -eq 0 ]; then 
                Remarks+=("${fmt_line}")
            fi
        fi
    # done
    done < <(echo "${CMD}" | grep 'remarks')
    # Damned subshells, need to implement process substitution to redirect output from separate processes to keep
    # this variable alive.
    for i in "${Remarks[@]}"; do
        echo "Remarks|${i}"
    done
}

#
# If we receive a RIPE query, the user supplied an IP.
# We also need to handle ARIN queries.
#
echo "${CMD}" | grep "RIPE" 2>&1 > /dev/null
if [ $? -eq 0 ]; then
    HandleRIPE  
    exit 0
fi
echo "${CMD}" | grep "ARIN" 2>&1 > /dev/null
if [ $? -eq 0 ]; then
    HandleARIN
    exit 0
fi

#
# Command xargs by itself removes the whitespace, amazing!
#
echo "Registrar|"$(echo "${CMD}" | grep -m 1 'Registrar URL' | cut -d':' -f2- | xargs 2>/dev/null)
echo "AbuseEmail|"$(echo "${CMD}" | grep -m 1 'Registrar Abuse Contact Email' | cut -d':' -f2 | xargs 2>/dev/null)
echo "AbusePhone|"$(echo "${CMD}" | grep -m 1 'Registrar Abuse Contact Phone' | cut -d':' -f2 | xargs 2>/dev/null)
# Two results are returned on some WHOIS in the field.  Only show the date, not time.
echo "CreationDate|"$(echo "${CMD}" | grep -m 1 'Creation Date' | cut -d':' -f2 | cut -d'T' -f1 | xargs 2>/dev/null)
Posted in UtilitiesTagged osint, reconaissance, scripting, shell, threat intelligence, whoisLeave a comment

PowerShell Monitor File Activity

Posted on September 14, 2021 - September 14, 2021 by admin

This script allows you to monitor the file-related events (recursive) under a given folder. Be careful with short paths.

$folder = 'c:\scripts' # Enter the root path you want to monitor.
$filter = '*.*'  # You can enter a wildcard filter here.  Like *.bat.

# In the following line, you can change 'IncludeSubdirectories to $true if required.                          
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

# Here, all three events are registerd.  You need only subscribe to events that you need:

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}

Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore red
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}

Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore white
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}
Posted in UtilitiesTagged file activity, monitoring, Powershell, windowsLeave a comment

TDL4 IDAPython Decryptor

Posted on September 14, 2021 - September 14, 2021 by admin

This is a script used to unpack a hidden area of the bootsector after a TDL4 infection. This is classic code but still useful is anyone needs it. Written by your humble admin many years ago.

import idaapi

# Simulate C-style for() loop.
def cfor(first, test, update):
    while test(first):
        yield first
        first = update(first)


# Bit-shifting operations.
#def ROR(x, n, bits = 32):
#    mask = (2L**n) - 1
#    mask_bits = x & mask
#    return (x >> n) | (mask_bits << (bits - n))

#def ROL(x, n, bits = 32):
#    return ROR(x, bits - n, bits)
def ROR(byte, count):
    while count > 0:
        byte = (byte >> 1 | byte << 7) & 0xFF
        count -= 1
    return byte


if __name__ == "__main__":
    print "TDL4 Decrypt"
    print "A script to unpack the contents hidden on the bootsector of a TDL4 infected host"
    print ""
    
    encryptedBytes = [None] * 311
    
    rorCount = 311  # 0x137 (CX)
    count = 0
    # target starts at 0x62A in memory
    for i in cfor(int('0x2A', 16), lambda i : i < (311 + i), lambda i : i + 1):
        cryptedByte = idaapi.get_byte(i)
        print "Byte[" + hex(i) + "]:    " + hex(cryptedByte)
        idaapi.patch_byte(i, ROR(cryptedByte, rorCount - count))
        count += 1
        if count == 311:
            break
Posted in UtilitiesTagged bootsector, decryptor, ida pro, idapython, malware, tdl4, windowsLeave a comment

Chainsaw

Posted on September 8, 2021 - September 8, 2021 by admin

A new tool called Chainsaw was released on August 14, 2021. It helps blue teams find potential threats in Windows event logs. It was originally made for environments without an endpoint detection and response (EDR) solution was not available during a compromise.

Windows event logs store system activity such as application activity and logins. Such information is vital to defenders and investigators in incident response scenarios. Manually combing through the raw logs is time consuming due to the potentially large volume of information.

Chainsaw is written in the Rust programming language. It parses the event logs to find suspicious strings or entries of interest indicating a possible threat. The Sigma signature format to allow analysts or outside contributors to describe log events in patterns which may be useful for finding potential malicious activity.

Posted in UtilitiesTagged blue teaming, chainsaw, EDR, incident response, sigma, threat detection, threat huntingLeave a comment

Cobalt Strike MS Office Macro Shellcode Decoder/Dumper

Posted on July 28, 2021 - July 28, 2021 by admin

One of the more popular Cobalt Strike attacks involves building an Office VBA payload. Unsophisticated attackers will not likely modify the generated payloads from the framework. This gives a defender an easier opportunity to find CS payloads and easily dump/analyze them.

The following tool (Python3) will help an analyst or security system to discover functionality of the embedded payload. Once extracted, you can use an online disassembler like ODA to analyze the x86 shellcode. Keep in mind it has both code and data embedded. Hence we leave possible decoded ASCII in a separate view.

#!/usr/bin/env python3
# (@) - Extracts shellcode from Array() in VBA Macro attack
#       Also prints possible ASCII values embedded in payload
#
import sys
import re

content_file=sys.argv[1]
contents = ''

try:
    with open(content_file, 'r') as f:
        contents = f.read()
except Exception as e:
    print(str(e))
    print('Usage:  python3 ' + sys.argv[0] + ' <generated_vba_file>')
    raise

start_location = contents.find('myArray = Array(')
end_location = contents.index('If Len(Environ("ProgramW6432"')

what_we_want = contents[start_location:end_location - 1]
what_we_want = re.sub(r'^.*?\(', ' ', what_we_want)
what_we_want = what_we_want.replace(' _', '')
what_we_want = what_we_want.replace(")", "")
what_we_want = what_we_want.replace(',', ' ')

disasm_this = ''
text_this = ''
for element in what_we_want.split(' '):
    if not element:
        continue
    new_number = int(element)
    asm_num = format(new_number & 0xff, "02X")
    disasm_this += asm_num + ' '
    if new_number < 0:
        continue
    text_this += bytes.fromhex(asm_num).decode('ascii')
print('x86 payload:')
print(disasm_this)
print('\n\n')
print('Possible ASCII data found:')
print(text_this)
Posted in UtilitiesTagged automation, blue team, CND, cobalt strike, macro, malware analysis, office, vbaLeave a comment

7zip Password Cracker (BASH)

Posted on December 21, 2020 by admin

Dependency: p7zip GNU package.

#!/bin/bash
# @(#) p7crack -- Password crack a target 7z file
# Usage:  ./p7crack.sh <target_file>

declare -a LIST=(password1 password2 password3)

for x in ${LIST[@]); do
   7z x ${1} -p${x}
   if [ $? -eq 0 ]; then
      echo "${x} is the password"
   fi
done
Posted in UtilitiesLeave a comment

Recent Posts

  • Manual Scraping
  • Nitter Replacement
  • MFA Abuse in Splunk
  • Virtualbox Automation
  • Repository Poisoning

Recent Comments

    Archives

    • August 2024
    • July 2023
    • August 2022
    • March 2022
    • November 2021
    • October 2021
    • September 2021
    • August 2021
    • July 2021
    • June 2021
    • February 2021
    • December 2020
    • October 2020
    • September 2020
    • April 2020
    • March 2020
    • January 2020
    • July 2019
    • June 2019

    Categories

    • Campaign Analysis
    • Campaign Management
    • Code Analysis
    • Current Events
    • Malware Development
    • Techniques
    • Uncategorized
    • Utilities

    Meta

    • Log in
    • Entries feed
    • Comments feed
    • WordPress.org
    Proudly powered by WordPress | Theme: micro, developed by DevriX.