Skip to content

Commit

Permalink
Simplify code and remove unnecessary return nones
Browse files Browse the repository at this point in the history
  • Loading branch information
NeffIsBack committed Oct 27, 2023
1 parent 9387891 commit 72500d9
Show file tree
Hide file tree
Showing 27 changed files with 5 additions and 73 deletions.
3 changes: 0 additions & 3 deletions nxc/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,6 @@ def try_credentials(self, domain, username, owned, secret, cred_type, data=None)
return self.hash_login(domain, username, secret)
elif cred_type == "aesKey":
return self.kerberos_login(domain, username, "", "", secret, self.kdcHost, False)
return None

def login(self):
"""Try to login using the credentials specified in the command line or in the database.
Expand Down Expand Up @@ -464,7 +463,6 @@ def login(self):
owned[user_index] = True
if not self.args.continue_on_success:
return True
return None
else:
if len(username) != len(secret):
self.logger.error("Number provided of usernames and passwords/hashes do not match!")
Expand All @@ -474,7 +472,6 @@ def login(self):
owned[user_index] = True
if not self.args.continue_on_success:
return True
return None

def mark_pwned(self):
return highlight(f"({pwned_label})" if self.admin_privs else "")
1 change: 0 additions & 1 deletion nxc/helpers/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,3 @@ def get_desktop_uagent(uagent=None):
return desktop_uagents[random.choice(desktop_uagents.keys())]
elif uagent:
return desktop_uagents[uagent]
return None
1 change: 0 additions & 1 deletion nxc/helpers/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,3 @@ def highlight(text, color="yellow"):
return f"{colored(text, 'yellow', attrs=['bold'])}"
elif color == "red":
return f"{colored(text, 'red', attrs=['bold'])}"
return None
1 change: 0 additions & 1 deletion nxc/helpers/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,3 @@ def _access_check(fn, mode):
name = os.path.join(p, thefile)
if _access_check(name, mode):
return name
return None
3 changes: 0 additions & 3 deletions nxc/loaders/moduleloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ def load_module(self, module_path):
except Exception as e:
self.logger.fail(f"Failed loading module at {module_path}: {e}")
self.logger.debug(traceback.format_exc())
return None

def init_module(self, module_path):
"""Initialize a module for execution"""
Expand All @@ -85,7 +84,6 @@ def init_module(self, module_path):
else:
self.logger.fail(f"Module {module.name.upper()} is not supported for protocol {self.args.protocol}")
sys.exit(1)
return None

def get_module_info(self, module_path):
"""Get the path, description, and options from a module"""
Expand All @@ -109,7 +107,6 @@ def get_module_info(self, module_path):
except Exception as e:
self.logger.fail(f"Failed loading module at {module_path}: {e}")
self.logger.debug(traceback.format_exc())
return None

def list_modules(self):
"""List modules without initializing them"""
Expand Down
2 changes: 0 additions & 2 deletions nxc/modules/find-computer.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,5 @@ def on_login(self, context, connection):
except socket.gaierror:
context.log.debug("Missing IP")
context.log.highlight(f"{answer[0]} ({answer[1]}) (No IP Found)")
return None
else:
context.log.success(f"Unable to find any computers with the text {self.TEXT}")
return None
4 changes: 1 addition & 3 deletions nxc/modules/get-desc-users.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,6 @@ def on_login(self, context, connection):
context.log.success("Found following users: ")
for answer in answers:
context.log.highlight(f"User: {answer[0]} description: {answer[1]}")
return None
return None

def filter_answer(self, context, answers):
# No option to filter
Expand All @@ -103,7 +101,7 @@ def filter_answer(self, context, answers):
conditionPasswordPolicy = False
if self.regex.search(description):
conditionPasswordPolicy = True

if (conditionFilter == self.FILTER) and (conditionPasswordPolicy == self.PASSWORDPOLICY):
answersFiltered.append([answer[0], description])
return answersFiltered
2 changes: 0 additions & 2 deletions nxc/modules/group_members.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,6 @@ def on_login(self, context, connection):
context.log.success("Found the following members of the " + self.GROUP + " group:")
for answer in self.answers:
context.log.highlight(f"{answer[0]}")
return None
return None


# Carry out an LDAP search for the Group with the supplied Group name
Expand Down
2 changes: 0 additions & 2 deletions nxc/modules/groupmembership.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,3 @@ def on_login(self, context, connection):
group_name = group_parts[0].split("=")[1]

context.log.highlight(f"{group_name}")
return None
return None
1 change: 0 additions & 1 deletion nxc/modules/hash_spider.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,6 @@ def run_lsassy(self, context, connection, cursor): # copied and pasted from lsa
self.save_credentials(context, connection, cred["domain"], cred["username"], cred["password"], cred["lmhash"], cred["nthash"])
global credentials_data
credentials_data = credentials_output
return None

def spider_pcs(self, context, connection, cursor, dbconnection, driver):
cursor.execute("SELECT * from admin_users WHERE hash is not NULL")
Expand Down
5 changes: 0 additions & 5 deletions nxc/modules/ldap-checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ async def run_ldaps_noEPA(target, credential):
# LDAPS bind successful
# because channel binding is not enforced
return False
return None

# Conduct a bind to LDAPS with channel binding supported
# but intentionally miscalculated. In the case that and
Expand All @@ -74,10 +73,8 @@ async def run_ldaps_withEPA(target, credential):
return False
elif err is not None:
context.log.fail("ERROR while connecting to " + str(connection.domain) + ": " + str(err))
return None
elif err is None:
return False
return None

# Domain Controllers do not have a certificate setup for
# LDAPS on port 636 by default. If this has not been setup,
Expand Down Expand Up @@ -128,10 +125,8 @@ async def run_ldap(target, credential):
sys.exit()
elif err is None:
return False
return None
else:
context.log.fail(str(err))
return None

# Run trough all our code blocks to determine LDAP signing and channel binding settings.
stype = asyauthSecret.PASS if not connection.nthash else asyauthSecret.NT
Expand Down
1 change: 0 additions & 1 deletion nxc/modules/lsassy_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ def on_admin_login(self, context, connection):

context.log.debug("Calling process_credentials")
self.process_credentials(context, connection, credentials_output)
return None

def process_credentials(self, context, connection, credentials):
if len(credentials) == 0:
Expand Down
3 changes: 0 additions & 3 deletions nxc/modules/mssql_priv.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ def browse_path(self, context, initial_user: User, user: User) -> User:
else:
self.context.log.display(f"{user.username} can impersonate: {grantor.username}")
return self.browse_path(context, initial_user, grantor)
return None

def query_and_get_output(self, query):
return self.mssql_conn.sql_query(query)
Expand Down Expand Up @@ -354,8 +353,6 @@ def check_dbowner_privesc(self, exec_as=""):
if db in trusted_databases:
return db

return None

def do_dbowner_privesc(self, database, exec_as=""):
"""
Executes a series of SQL queries to perform a database owner privilege escalation.
Expand Down
3 changes: 0 additions & 3 deletions nxc/modules/pso.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,5 @@ def on_login(self, context, connection):
value = self.convert_time_field(field, pso[field])
context.log.highlight(f"{field}: {value}")
context.log.highlight("-----")
return None

else:
context.log.info("No Password Settings Objects (PSO) found.")
return None
2 changes: 0 additions & 2 deletions nxc/modules/spider_plus.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,6 @@ def get_remote_file(self, share, path):
if self.reconnect():
return self.get_remote_file(share, path)

return None

def read_chunk(self, remote_file, chunk_size=CHUNK_SIZE):
"""Reads the next chunk of data from the provided remote file using the specified chunk size.
If a `SessionError` is encountered, it retries up to 3 times by reconnecting the SMB connection.
Expand Down
1 change: 0 additions & 1 deletion nxc/modules/wcc.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,6 @@ def get_value(subkey_handle, dwIndex=0):
root_key, subkey = keyName.split("\\", 1)
except ValueError:
self.context.log.error(f"HostChecker.reg_query_value(): Could not split keyname {keyName}")
return None

ans = self._open_root_key(dce, connection, root_key)
if ans is None:
Expand Down
5 changes: 0 additions & 5 deletions nxc/protocols/ftp.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@ def plaintext_login(self, username, password):
self.conn.close()
return True
self.conn.close()
return None

def list_directory_full(self):
# in the future we can use mlsd/nlst if we want, but this gives a full output like `ls -la`
Expand Down Expand Up @@ -147,10 +146,8 @@ def get_file(self, filename):
# Check if the file was downloaded
if os.path.isfile(downloaded_file):
self.logger.success(f"Downloaded: {filename}")
return None
else:
self.logger.fail(f"Failed to download: {filename}")
return None

def put_file(self, local_file, remote_file):
try:
Expand All @@ -165,10 +162,8 @@ def put_file(self, local_file, remote_file):
# Check if the file was uploaded
if self.conn.size(remote_file) > 0:
self.logger.success(f"Uploaded: {local_file} to {remote_file}")
return None
else:
self.logger.fail(f"Failed to upload: {local_file} to {remote_file}")
return None

def supported_commands(self):
raw_supported_commands = self.conn.sendcmd("HELP")
Expand Down
6 changes: 1 addition & 5 deletions nxc/protocols/ftp/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,6 @@ def add_host(self, host, port, banner):
if updated_ids:
nxc_logger.debug(f"add_host() - Host IDs Updated: {updated_ids}")
return updated_ids
return None

def add_credential(self, username, password):
"""Check if this credential has already been added to the database, if not add it in."""
Expand Down Expand Up @@ -205,9 +204,7 @@ def get_credential(self, username, password):
self.CredentialsTable.c.password == password,
)
results = self.sess.execute(q).first()
if results is None:
return None
else:
if results is not None:
return results.id

def get_credentials(self, filter_term=None):
Expand Down Expand Up @@ -291,7 +288,6 @@ def add_loggedin_relation(self, cred_id, host_id):
return inserted_id_results[0].id
except Exception as e:
nxc_logger.debug(f"Error inserting LoggedinRelation: {e}")
return None

def get_loggedin_relations(self, cred_id=None, host_id=None):
q = select(self.LoggedinRelationsTable) # .returning(self.LoggedinRelationsTable.c.id)
Expand Down
6 changes: 0 additions & 6 deletions nxc/protocols/ldap.py
Original file line number Diff line number Diff line change
Expand Up @@ -834,7 +834,6 @@ def asreproast(self):
resp = self.search(search_filter, attributes, 0)
if resp == []:
self.logger.highlight("No entries found!")
return None
elif resp:
answers = []
self.logger.display(f"Total of records returned {len(resp):d}")
Expand Down Expand Up @@ -884,10 +883,8 @@ def asreproast(self):
return True
else:
self.logger.highlight("No entries found!")
return None
else:
self.logger.fail("Error with the LDAP account used")
return None

def kerberoasting(self):
# Building the search filter
Expand Down Expand Up @@ -984,9 +981,7 @@ def kerberoasting(self):
return True
else:
self.logger.highlight("No entries found!")
return None
self.logger.fail("Error with the LDAP account used")
return None

def trusted_for_delegation(self):
# Building the search filter
Expand Down Expand Up @@ -1117,7 +1112,6 @@ def password_not_required(self):
self.logger.highlight(f"User: {value[0]} Status: {value[5]}")
else:
self.logger.fail("No entries found!")
return None

def admin_count(self):
# Building the search filter
Expand Down
1 change: 0 additions & 1 deletion nxc/protocols/smb.py
Original file line number Diff line number Diff line change
Expand Up @@ -1612,7 +1612,6 @@ def dpapi(self):
credential.password,
credential.url,
)
return None

@requires_admin
def lsa(self):
Expand Down
6 changes: 0 additions & 6 deletions nxc/protocols/smb/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,6 @@ def add_host(
if updated_ids:
nxc_logger.debug(f"add_host() - Host IDs Updated: {updated_ids}")
return updated_ids
return None

def add_credential(self, credtype, domain, username, password, group_id=None, pillaged_from=None):
"""Check if this credential has already been added to the database, if not add it in."""
Expand Down Expand Up @@ -452,9 +451,7 @@ def is_credential_local(self, credential_id):
if user_domain:
q = select(self.HostsTable).filter(func.lower(self.HostsTable.c.id) == func.lower(user_domain))
results = self.conn.execute(q).all()

return len(results) > 0
return None

def is_host_valid(self, host_id):
"""Check if this host ID is valid."""
Expand Down Expand Up @@ -826,7 +823,6 @@ def add_loggedin_relation(self, user_id, host_id):
return inserted_id_results[0].id
except Exception as e:
nxc_logger.debug(f"Error inserting LoggedinRelation: {e}")
return None

def get_loggedin_relations(self, user_id=None, host_id=None):
q = select(self.LoggedinRelationsTable) # .returning(self.LoggedinRelationsTable.c.id)
Expand Down Expand Up @@ -897,7 +893,6 @@ def add_check(self, name, description):
if updated_ids:
nxc_logger.debug(f"add_check() - Checks IDs Updated: {updated_ids}")
return updated_ids
return None

def add_check_result(self, host_id, check_id, secure, reasons):
"""Check if this check result has already been added to the database, if not, add it in."""
Expand All @@ -910,4 +905,3 @@ def add_check_result(self, host_id, check_id, secure, reasons):
if updated_ids:
nxc_logger.debug(f"add_check_result() - Check Results IDs Updated: {updated_ids}")
return updated_ids
return None
8 changes: 1 addition & 7 deletions nxc/protocols/smb/firefox.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ def get_key(self, key4_data, master_password=b""):
fh.close()
return b""
fh.close()
return None

def is_master_password_correct(self, key_data, master_password=b""):
try:
Expand Down Expand Up @@ -236,9 +235,4 @@ def decrypt_3des(decoded_item, master_password, global_salt):
# 04 is OCTETSTRING, 0x0e is length == 14
encrypted_value = decoded_item[0][1].asOctets()
cipher = AES.new(key, AES.MODE_CBC, iv)
decrypted = cipher.decrypt(encrypted_value)
if decrypted is not None:
return decrypted
else:
return None
return None
return cipher.decrypt(encrypted_value)
1 change: 0 additions & 1 deletion nxc/protocols/smb/samrfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ def get_server_handle(self):
return resp["ServerHandle"]
else:
nxc_logger.debug("Error creating Samr handle")
return None

def get_domains(self):
"""Calls the hSamrEnumerateDomainsInSamServer() method directly with list comprehension and extracts the "Name" value from each element in the "Buffer" list."""
Expand Down
1 change: 0 additions & 1 deletion nxc/protocols/smb/smbexec.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,6 @@ def execute_remote(self, data):
pass

self.get_output_remote()
return None

def get_output_remote(self):
if self.__retOutput is False:
Expand Down
6 changes: 1 addition & 5 deletions nxc/protocols/ssh/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,6 @@ def add_host(self, host, port, banner, os=None):
if updated_ids:
nxc_logger.debug(f"add_host() - Host IDs Updated: {updated_ids}")
return updated_ids
return None

def add_credential(self, credtype, username, password, key=None):
"""Check if this credential has already been added to the database, if not add it in."""
Expand Down Expand Up @@ -350,9 +349,7 @@ def get_credential(self, cred_type, username, password):
self.CredentialsTable.c.credtype == cred_type,
)
results = self.sess.execute(q).first()
if results is None:
return None
else:
if results is not None:
return results.id

def is_host_valid(self, host_id):
Expand Down Expand Up @@ -421,7 +418,6 @@ def add_loggedin_relation(self, cred_id, host_id, shell=False):
return inserted_id_results[0].id
except Exception as e:
nxc_logger.debug(f"Error inserting LoggedinRelation: {e}")
return None

def get_loggedin_relations(self, cred_id=None, host_id=None, shell=None):
q = select(self.LoggedinRelationsTable) # .returning(self.LoggedinRelationsTable.c.id)
Expand Down
Loading

0 comments on commit 72500d9

Please sign in to comment.