From 72500d99be59f74109cabec380ccaad243fc4b26 Mon Sep 17 00:00:00 2001 From: Alex <61382599+NeffIsBack@users.noreply.github.com> Date: Sat, 28 Oct 2023 01:04:52 +0200 Subject: [PATCH] Simplify code and remove unnecessary return nones --- nxc/connection.py | 3 --- nxc/helpers/http.py | 1 - nxc/helpers/logger.py | 1 - nxc/helpers/misc.py | 1 - nxc/loaders/moduleloader.py | 3 --- nxc/modules/find-computer.py | 2 -- nxc/modules/get-desc-users.py | 4 +--- nxc/modules/group_members.py | 2 -- nxc/modules/groupmembership.py | 2 -- nxc/modules/hash_spider.py | 1 - nxc/modules/ldap-checker.py | 5 ----- nxc/modules/lsassy_dump.py | 1 - nxc/modules/mssql_priv.py | 3 --- nxc/modules/pso.py | 3 --- nxc/modules/spider_plus.py | 2 -- nxc/modules/wcc.py | 1 - nxc/protocols/ftp.py | 5 ----- nxc/protocols/ftp/database.py | 6 +----- nxc/protocols/ldap.py | 6 ------ nxc/protocols/smb.py | 1 - nxc/protocols/smb/database.py | 6 ------ nxc/protocols/smb/firefox.py | 8 +------- nxc/protocols/smb/samrfunc.py | 1 - nxc/protocols/smb/smbexec.py | 1 - nxc/protocols/ssh/database.py | 6 +----- nxc/protocols/winrm/database.py | 1 - pyproject.toml | 2 +- 27 files changed, 5 insertions(+), 73 deletions(-) diff --git a/nxc/connection.py b/nxc/connection.py index 517731a14..a359ff85b 100755 --- a/nxc/connection.py +++ b/nxc/connection.py @@ -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. @@ -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!") @@ -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 "") diff --git a/nxc/helpers/http.py b/nxc/helpers/http.py index fdf94ecbc..6c85f5fff 100644 --- a/nxc/helpers/http.py +++ b/nxc/helpers/http.py @@ -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 diff --git a/nxc/helpers/logger.py b/nxc/helpers/logger.py index e122307d6..22db76f38 100755 --- a/nxc/helpers/logger.py +++ b/nxc/helpers/logger.py @@ -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 diff --git a/nxc/helpers/misc.py b/nxc/helpers/misc.py index 50ba0c3ef..a92646f73 100755 --- a/nxc/helpers/misc.py +++ b/nxc/helpers/misc.py @@ -77,4 +77,3 @@ def _access_check(fn, mode): name = os.path.join(p, thefile) if _access_check(name, mode): return name - return None diff --git a/nxc/loaders/moduleloader.py b/nxc/loaders/moduleloader.py index 3fb385ea7..43433da47 100755 --- a/nxc/loaders/moduleloader.py +++ b/nxc/loaders/moduleloader.py @@ -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""" @@ -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""" @@ -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""" diff --git a/nxc/modules/find-computer.py b/nxc/modules/find-computer.py index 0bd9e7c4c..dc1838bf7 100644 --- a/nxc/modules/find-computer.py +++ b/nxc/modules/find-computer.py @@ -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 diff --git a/nxc/modules/get-desc-users.py b/nxc/modules/get-desc-users.py index c1a647f14..335041fb1 100644 --- a/nxc/modules/get-desc-users.py +++ b/nxc/modules/get-desc-users.py @@ -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 @@ -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 diff --git a/nxc/modules/group_members.py b/nxc/modules/group_members.py index 5edc6384a..28b811981 100644 --- a/nxc/modules/group_members.py +++ b/nxc/modules/group_members.py @@ -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 diff --git a/nxc/modules/groupmembership.py b/nxc/modules/groupmembership.py index 80ea6d4a9..c8f9d2555 100644 --- a/nxc/modules/groupmembership.py +++ b/nxc/modules/groupmembership.py @@ -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 diff --git a/nxc/modules/hash_spider.py b/nxc/modules/hash_spider.py index ad8a1d222..9eb25524e 100644 --- a/nxc/modules/hash_spider.py +++ b/nxc/modules/hash_spider.py @@ -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") diff --git a/nxc/modules/ldap-checker.py b/nxc/modules/ldap-checker.py index eb5b54937..33bdc4fcd 100644 --- a/nxc/modules/ldap-checker.py +++ b/nxc/modules/ldap-checker.py @@ -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 @@ -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, @@ -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 diff --git a/nxc/modules/lsassy_dump.py b/nxc/modules/lsassy_dump.py index 43ec81971..f4cf6c80f 100644 --- a/nxc/modules/lsassy_dump.py +++ b/nxc/modules/lsassy_dump.py @@ -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: diff --git a/nxc/modules/mssql_priv.py b/nxc/modules/mssql_priv.py index 1cc363244..cc6f0dc55 100644 --- a/nxc/modules/mssql_priv.py +++ b/nxc/modules/mssql_priv.py @@ -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) @@ -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. diff --git a/nxc/modules/pso.py b/nxc/modules/pso.py index 3b76507d5..d50b4e042 100644 --- a/nxc/modules/pso.py +++ b/nxc/modules/pso.py @@ -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 diff --git a/nxc/modules/spider_plus.py b/nxc/modules/spider_plus.py index 619f7a1d6..8888eb10c 100755 --- a/nxc/modules/spider_plus.py +++ b/nxc/modules/spider_plus.py @@ -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. diff --git a/nxc/modules/wcc.py b/nxc/modules/wcc.py index 146f43cd0..cba61404b 100644 --- a/nxc/modules/wcc.py +++ b/nxc/modules/wcc.py @@ -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: diff --git a/nxc/protocols/ftp.py b/nxc/protocols/ftp.py index efae93682..32bc9c872 100644 --- a/nxc/protocols/ftp.py +++ b/nxc/protocols/ftp.py @@ -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` @@ -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: @@ -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") diff --git a/nxc/protocols/ftp/database.py b/nxc/protocols/ftp/database.py index 13fcb2448..613e6d1d2 100644 --- a/nxc/protocols/ftp/database.py +++ b/nxc/protocols/ftp/database.py @@ -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.""" @@ -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): @@ -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) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 9cb1241a1..feb5c310c 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -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}") @@ -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 @@ -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 @@ -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 diff --git a/nxc/protocols/smb.py b/nxc/protocols/smb.py index 3614665c2..54620e86d 100755 --- a/nxc/protocols/smb.py +++ b/nxc/protocols/smb.py @@ -1612,7 +1612,6 @@ def dpapi(self): credential.password, credential.url, ) - return None @requires_admin def lsa(self): diff --git a/nxc/protocols/smb/database.py b/nxc/protocols/smb/database.py index a7ee6e6ce..d11736d82 100755 --- a/nxc/protocols/smb/database.py +++ b/nxc/protocols/smb/database.py @@ -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.""" @@ -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.""" @@ -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) @@ -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.""" @@ -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 diff --git a/nxc/protocols/smb/firefox.py b/nxc/protocols/smb/firefox.py index d86ec6555..01829962d 100644 --- a/nxc/protocols/smb/firefox.py +++ b/nxc/protocols/smb/firefox.py @@ -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: @@ -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) diff --git a/nxc/protocols/smb/samrfunc.py b/nxc/protocols/smb/samrfunc.py index e79ede4d2..8d364a528 100644 --- a/nxc/protocols/smb/samrfunc.py +++ b/nxc/protocols/smb/samrfunc.py @@ -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.""" diff --git a/nxc/protocols/smb/smbexec.py b/nxc/protocols/smb/smbexec.py index 2acd32c83..d0dde6c3e 100755 --- a/nxc/protocols/smb/smbexec.py +++ b/nxc/protocols/smb/smbexec.py @@ -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: diff --git a/nxc/protocols/ssh/database.py b/nxc/protocols/ssh/database.py index 15f8bf29b..80a3dd87f 100644 --- a/nxc/protocols/ssh/database.py +++ b/nxc/protocols/ssh/database.py @@ -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.""" @@ -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): @@ -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) diff --git a/nxc/protocols/winrm/database.py b/nxc/protocols/winrm/database.py index a0f06e22a..fccab5135 100644 --- a/nxc/protocols/winrm/database.py +++ b/nxc/protocols/winrm/database.py @@ -307,7 +307,6 @@ def is_credential_local(self, credential_id): 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.""" diff --git a/pyproject.toml b/pyproject.toml index 402196478..2b4a0719a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -81,7 +81,7 @@ build-backend = "poetry.core.masonry.api" # Other options: pep8-naming (N), flake8-annotations (ANN), flake8-blind-except (BLE), flake8-commas (COM), flake8-pyi (PYI), flake8-pytest-style (PT), flake8-unused-arguments (ARG), etc # Should tackle flake8-use-pathlib (PTH) at some point select = ["E", "F", "D", "UP", "YTT", "ASYNC", "B", "A", "C4", "ISC", "ICN", "PIE", "PT", "Q", "RSE", "RET", "SIM", "TID", "ERA", "FLY", "PERF", "FURB", "LOG", "RUF"] -ignore = [ "E501", "F405", "D100", "D101", "D102", "D103", "D104", "D105", "D106", "D107", "D203", "D204", "D205", "D212", "D213", "D400", "D401", "D415", "D417", "D419", "RET505", "RET506", "RET507", "RET508", "PERF203", "RUF012"] +ignore = [ "E501", "F405", "D100", "D101", "D102", "D103", "D104", "D105", "D106", "D107", "D203", "D204", "D205", "D212", "D213", "D400", "D401", "D415", "D417", "D419", "RET503", "RET505", "RET506", "RET507", "RET508", "PERF203", "RUF012"] # Allow autofix for all enabled rules (when `--fix`) is provided. fixable = ["ALL"]