Skip to content

Commit

Permalink
Merge branch 'fortra:master' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
GeisericII authored Dec 6, 2024
2 parents f8a22b4 + e9a47ff commit 8000cc4
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 16 deletions.
11 changes: 8 additions & 3 deletions examples/mssqlclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
'Authentication (default False)')
parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')
parser.add_argument('-show', action='store_true', help='show the queries')
parser.add_argument('-command', action='extend', nargs='*', help='Commands to execute in the SQL shell. Multiple commands can be passed.')
parser.add_argument('-file', type=argparse.FileType('r'), help='input file with commands to execute in the SQL shell')

group = parser.add_argument_group('authentication')
Expand Down Expand Up @@ -107,10 +108,14 @@
res = False
if res is True:
shell = SQLSHELL(ms_sql, options.show)
if options.file is None:
shell.cmdloop()
else:
if options.file:
for line in options.file.readlines():
print("SQL> %s" % line, end=' ')
shell.onecmd(line)
elif options.command:
for c in options.command:
print("SQL> %s" % c)
shell.onecmd(c)
else:
shell.cmdloop()
ms_sql.disconnect()
6 changes: 3 additions & 3 deletions examples/wmiquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ def printReply(self, iEnum):
print('%s |' % record[key]['value'], end=' ')
print()
except Exception as e:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
if str(e).find('S_FALSE') < 0:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
raise
else:
break
Expand Down
2 changes: 1 addition & 1 deletion impacket/dcerpc/v5/dcom/wmi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2613,7 +2613,7 @@ def SpawnInstance(self):
def createProperties(self, properties):
for property in properties:
# Do we have an object property?
if properties[property]['type'] == CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value:
if properties[property]['type'] == CIM_TYPE_ENUM.CIM_TYPE_OBJECT.value and properties[property]['value'] != None:
# Yes.. let's create an Object for it too
objRef = OBJREF_CUSTOM()
objRef['iid'] = self._iid
Expand Down
8 changes: 4 additions & 4 deletions impacket/dcerpc/v5/samr.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
Expand Down Expand Up @@ -2590,11 +2590,11 @@ def hSamrCreateUser2InDomain(dce, domainHandle, name, accountType=USER_NORMAL_AC
return dce.request(request)
except DCERPCSessionError as e:
if e.error_code == 0xc0000022:
raise Exception("Relayed user doesn't have right to create a machine account!")
raise Exception("Authenticating account doesn't have the right to create a new machine account!")
elif e.error_code == 0xc00002e7:
raise Exception("Relayed user machine quota exceeded!")
raise Exception("Authenticating account's machine account quota exceeded!")
elif e.error_code == 0xc0000062:
raise Exception("Account name not accepted, maybe the '$' at the end is missing ?")
raise Exception("Account name not accepted, maybe the '$' at the end is missing?")
else:
raise e

Expand Down
62 changes: 61 additions & 1 deletion impacket/examples/mssqlshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
import cmd
import sys

# for "do_upload"
import hashlib
import base64
import shlex

class SQLSHELL(cmd.Cmd):
def __init__(self, SQL, show_queries=False, tcpShell=None):
if tcpShell is not None:
Expand Down Expand Up @@ -65,6 +70,7 @@ def do_help(self, line):
sp_start_job {cmd} - executes cmd using the sql server agent (blind)
use_link {link} - linked server to use (set use_link localhost to go back to local or use_link .. to get back one step)
! {cmd} - executes a local shell cmd
upload {from} {to} - uploads file {from} to the SQLServer host {to}
show_query - show query
mask_query - mask query
""")
Expand Down Expand Up @@ -133,6 +139,60 @@ def sql_query(self, query, show=True):
def do_shell(self, s):
os.system(s)

def do_upload(self, line):
BUFFER_SIZE = 5 * 1024
try:
# validate "xp_cmdshell" is enabled
self.sql.sql_query("exec master.dbo.sp_configure 'show advanced options', 1; RECONFIGURE;")
result = self.sql.sql_query("exec master.dbo.sp_configure 'xp_cmdshell'")
self.sql.sql_query("exec master.dbo.sp_configure 'show advanced options', 0; RECONFIGURE;")
if result[0].get('run_value') != 1:
print("[-] xp_cmdshell not enabled. Try running 'enable_xp_cmdshell' first")
return

args = shlex.split(line, posix=False)
local_path = args[0]
remote_path = args[1]

# upload file
with open(local_path, 'rb') as f:
data = f.read()
md5sum = hashlib.md5(data).hexdigest()
b64enc_data = b"".join(base64.b64encode(data).split()).decode()
print("[+] Data length (b64-encoded): %.2f KB with MD5: %s" % (len(b64enc_data) / 1024, str(md5sum)))
print("[+] Uploading...")
for i in range(0, len(b64enc_data), BUFFER_SIZE):
cmd = 'echo ' + b64enc_data[i:i+BUFFER_SIZE] + ' >> "' + remote_path + '.b64"'
self.sql.sql_query("EXEC xp_cmdshell '" + cmd + "'")
result = self.sql.sql_query("EXEC xp_fileexist '" + remote_path + ".b64'")
if result[0].get('File Exists') != 1:
print("[-] Error uploading file. Check permissions in the configured remote path")
return
print("[+] Uploaded")

# decode
cmd = 'certutil -decode "' + remote_path + '.b64" "' + remote_path + '"'
self.sql.sql_query("EXEC xp_cmdshell '" + cmd + "'")
print("[+] " + cmd)

# remove encoded
cmd = 'del "' + remote_path + '.b64"'
self.sql.sql_query("EXEC xp_cmdshell '" + cmd + "'")
print("[+] " + cmd)

# validate hash
cmd = 'certutil -hashfile "' + remote_path + '" MD5'
result = self.sql.sql_query("EXEC xp_cmdshell '" + cmd + "'")
print("[+] " + cmd)
md5sum_uploaded = result[1].get('output').replace(" ", "")
if md5sum == md5sum_uploaded:
print("[+] MD5 hashes match")
else:
print("[-] ERROR! MD5 hashes do NOT match!")
print("[+] Uploaded file MD5: %s" % md5sum_uploaded)
except Exception as e:
print("[-] Unhandled Exception:", e)

def do_xp_dirtree(self, s):
try:
self.sql_query("exec master.sys.xp_dirtree '%s',1,1" % s)
Expand Down Expand Up @@ -277,4 +337,4 @@ def emptyline(self):
def do_exit(self, line):
if self.shell is not None:
self.shell.close()
return True
return True
2 changes: 1 addition & 1 deletion impacket/examples/ntlmrelayx/servers/smbrelayserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ def SmbSessionSetup(self, connId, smbServer, recvPacket):
mechStr = MechTypes[mechType]
else:
mechStr = hexlify(mechType)
smbServer.log("Unsupported MechType '%s'" % mechStr, logging.CRITICAL)
smbServer.log("Unsupported MechType '%s'" % mechStr, logging.DEBUG)
# We don't know the token, we answer back again saying
# we just support NTLM.
respToken = SPNEGO_NegTokenResp()
Expand Down
2 changes: 1 addition & 1 deletion impacket/examples/ntlmrelayx/servers/wcfrelayserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def handle(self):
mechStr = MechTypes[mechType]
else:
mechStr = hexlify(mechType)
LOG.error("Unsupported MechType '%s'" % mechStr)
LOG.debug("Unsupported MechType '%s'" % mechStr)
# We don't know the token, we answer back again saying
# we just support NTLM.
respToken = SPNEGO_NegTokenResp()
Expand Down
4 changes: 2 additions & 2 deletions impacket/smbserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -2460,7 +2460,7 @@ def smbComSessionSetupAndX(connId, smbServer, SMBCommand, recvPacket):
mechStr = MechTypes[mechType]
else:
mechStr = hexlify(mechType)
smbServer.log("Unsupported MechType '%s'" % mechStr, logging.CRITICAL)
smbServer.log("Unsupported MechType '%s'" % mechStr, logging.DEBUG)
# We don't know the token, we answer back again saying
# we just support NTLM.
# ToDo: Build this into a SPNEGO_NegTokenResp()
Expand Down Expand Up @@ -2862,7 +2862,7 @@ def smb2SessionSetup(connId, smbServer, recvPacket):
mechStr = MechTypes[mechType]
else:
mechStr = hexlify(mechType)
smbServer.log("Unsupported MechType '%s'" % mechStr, logging.CRITICAL)
smbServer.log("Unsupported MechType '%s'" % mechStr, logging.DEBUG)
# We don't know the token, we answer back again saying
# we just support NTLM.
# ToDo: Build this into a SPNEGO_NegTokenResp()
Expand Down

0 comments on commit 8000cc4

Please sign in to comment.