Skip to content

Commit

Permalink
ruff: add flake8-return (RET) and auto-run
Browse files Browse the repository at this point in the history
  • Loading branch information
Marshall-Hallenbeck committed Oct 14, 2023
1 parent 781afc9 commit cdcde5a
Show file tree
Hide file tree
Showing 39 changed files with 113 additions and 119 deletions.
5 changes: 4 additions & 1 deletion nxc/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def gethost_addrinfo(hostname):
def requires_admin(func):
def _decorator(self, *args, **kwargs):
if self.admin_privs is False:
return
return None
return func(self, *args, **kwargs)

return wraps(func)(_decorator)
Expand Down Expand Up @@ -412,6 +412,7 @@ 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 @@ -460,6 +461,7 @@ 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 @@ -469,6 +471,7 @@ 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: 1 addition & 0 deletions nxc/helpers/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ def get_desktop_uagent(uagent=None):
return desktop_uagents[random.choice(desktop_uagents.keys())]
elif uagent:
return desktop_uagents[uagent]
return None
1 change: 1 addition & 0 deletions nxc/helpers/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ def highlight(text, color="yellow"):
return f"{colored(text, 'yellow', attrs=['bold'])}"
elif color == "red":
return f"{colored(text, 'red', attrs=['bold'])}"
return None
6 changes: 2 additions & 4 deletions nxc/helpers/powershell.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,8 @@ def obfs_ps_script(path_to_script):
# strip block comments
stripped_code = re.sub(re.compile("<#.*?#>", re.DOTALL), "", script.read())
# strip blank lines, lines starting with #, and verbose/debug statements
stripped_code = "\n".join([line for line in stripped_code.split("\n") if ((line.strip() != "") and (not line.strip().startswith("#")) and (not line.strip().lower().startswith("write-verbose ")) and (not line.strip().lower().startswith("write-debug ")))])
return "\n".join([line for line in stripped_code.split("\n") if ((line.strip() != "") and (not line.strip().startswith("#")) and (not line.strip().lower().startswith("write-verbose ")) and (not line.strip().lower().startswith("write-debug ")))])

return stripped_code


def create_ps_command(ps_command, force_ps32=False, dont_obfs=False, custom_amsi=None):
Expand Down Expand Up @@ -490,6 +489,5 @@ def invoke_obfuscation(script_string):
choice(["", " "]) + new_script + choice(["", " "]) + "|" + choice(["", " "]) + invoke_expression,
]

obfuscated_payload = choice(invoke_options)
return choice(invoke_options)

return obfuscated_payload
1 change: 1 addition & 0 deletions nxc/loaders/moduleloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ 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 Down
3 changes: 1 addition & 2 deletions nxc/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,13 +176,12 @@ def init_log_file():
newpath = os.path.expanduser("~/.nxc") + "/logs/" + datetime.now().strftime("%Y-%m-%d")
if not os.path.exists(newpath):
os.makedirs(newpath)
log_filename = os.path.join(
return os.path.join(
os.path.expanduser("~/.nxc"),
"logs",
datetime.now().strftime("%Y-%m-%d"),
f"log_{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.log",
)
return log_filename


class TermEscapeCodeFormatter(logging.Formatter):
Expand Down
3 changes: 1 addition & 2 deletions nxc/modules/daclread.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,12 +408,11 @@ def resolveSID(self, context, sid):
searchFilter=f"(objectSid={sid})",
attributes=["sAMAccountName"],
)[0][0]
samname = self.ldap_session.search(
return self.ldap_session.search(
searchBase=self.baseDN,
searchFilter=f"(objectSid={sid})",
attributes=["sAMAccountName"],
)[0][1][0][1][0]
return samname
except Exception:
context.log.debug(f"SID not found in LDAP: {sid}")
return ""
Expand Down
4 changes: 2 additions & 2 deletions nxc/modules/dfscoerce.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,12 @@ def connect(self, username, password, domain, lmhash, nthash, aesKey, target, do
dce.connect()
except Exception as e:
nxc_logger.debug(f"Something went wrong, check error status => {str(e)}")
return
return None
try:
dce.bind(uuidtup_to_bin(("4FC742E0-4A10-11CF-8273-00AA004AE673", "3.0")))
except Exception as e:
nxc_logger.debug(f"Something went wrong, check error status => {str(e)}")
return
return None
nxc_logger.debug("[+] Successfully bound!")
return dce

Expand Down
3 changes: 1 addition & 2 deletions nxc/modules/enum_av.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,7 @@ def LsarLookupNames(self, dce, policyHandle, service):
request["Names"].append(name1)
request["TranslatedSids"]["Sids"] = NULL
request["LookupLevel"] = lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta
resp = dce.request(request)
return resp
return dce.request(request)


conf = {
Expand Down
2 changes: 2 additions & 0 deletions nxc/modules/find-computer.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,5 +78,7 @@ 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
2 changes: 2 additions & 0 deletions nxc/modules/get-desc-users.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ 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 Down
8 changes: 4 additions & 4 deletions nxc/modules/group_members.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ 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 All @@ -82,11 +84,9 @@ def do_search(self, context, connection, searchFilter, attributeName):
for attribute in item["attributes"]:
if str(attribute["type"]) == attributeName:
if attributeName == "objectSid":
attribute_value = bytes(attribute["vals"][0])
return attribute_value
return bytes(attribute["vals"][0])
elif attributeName == "distinguishedName":
attribute_value = bytes(attribute["vals"][0])
return attribute_value
return bytes(attribute["vals"][0])
else:
attribute_value = str(attribute["vals"][0])
if attribute_value is not None:
Expand Down
2 changes: 2 additions & 0 deletions nxc/modules/groupmembership.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,5 @@ def on_login(self, context, connection):

# print("Group name: %s" % group_name)
context.log.highlight(f"{group_name}")
return None
return None
4 changes: 2 additions & 2 deletions nxc/modules/hash_spider.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ def neo4j_local_admins(context, driver):
except Exception as e:
context.log.fail(f"Could not pull admins: {e}")
return None
results = list(admins.data())
return results
return list(admins.data())


def create_db(local_admins, dbconnection, cursor):
Expand Down Expand Up @@ -233,6 +232,7 @@ 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: 5 additions & 0 deletions nxc/modules/ldap-checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ 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 @@ -73,8 +74,10 @@ 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 @@ -125,8 +128,10 @@ async def run_ldap(target, credential):
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: 1 addition & 0 deletions nxc/modules/lsassy_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ 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: 1 addition & 2 deletions nxc/modules/ms17-010.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,8 @@ def calculate_doublepulsar_xor_key(s):
temp = ((s & 0xFF00) | (s << 16)) << 8 | (((s >> 16) | s & 0xFF0000) >> 8)

# Multiply the temp value by 2 and perform a bitwise XOR with 0xFFFFFFFF
x = 2 * temp ^ 0xFFFFFFFF
return 2 * temp ^ 0xFFFFFFFF

return x


def negotiate_proto_request():
Expand Down
10 changes: 4 additions & 6 deletions nxc/modules/mssql_priv.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,10 @@ 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):
results = self.mssql_conn.sql_query(query)
return results
return self.mssql_conn.sql_query(query)

def sql_exec_as(self, grantors: list) -> str:
"""
Expand Down Expand Up @@ -276,8 +276,7 @@ def get_databases(self, exec_as="") -> list:
self.revert_context(exec_as)
self.context.log.debug(f"Response: {res}")
self.context.log.debug(f"Response Type: {type(res)}")
tables = [table["name"] for table in res]
return tables
return [table["name"] for table in res]

def is_db_owner(self, database, exec_as="") -> bool:
"""
Expand Down Expand Up @@ -426,8 +425,7 @@ def get_impersonate_users(self, exec_as="") -> list:
WHERE a.permission_name like 'IMPERSONATE%'"""
res = self.query_and_get_output(exec_as + query)
self.revert_context(exec_as)
users = [user["name"] for user in res]
return users
return [user["name"] for user in res]

def remove_sysadmin_priv(self) -> bool:
"""
Expand Down
2 changes: 2 additions & 0 deletions nxc/modules/pso.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ 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
3 changes: 1 addition & 2 deletions nxc/modules/spider_plus.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,7 @@ def list_path(self, share, subfolder):
def get_remote_file(self, share, path):
"""Checks if a path is readable in a SMB share."""
try:
remote_file = RemoteFile(self.smb.conn, path, share, access=FILE_READ_DATA)
return remote_file
return RemoteFile(self.smb.conn, path, share, access=FILE_READ_DATA)
except SessionError:
if self.reconnect():
return self.get_remote_file(share, path)
Expand Down
2 changes: 1 addition & 1 deletion nxc/modules/wcc.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ 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
return None

ans = self._open_root_key(dce, connection, root_key)
if ans is None:
Expand Down
3 changes: 1 addition & 2 deletions nxc/netexec.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@


def create_db_engine(db_path):
db_engine = sqlalchemy.create_engine(f"sqlite:///{db_path}", isolation_level="AUTOCOMMIT", future=True)
return db_engine
return sqlalchemy.create_engine(f"sqlite:///{db_path}", isolation_level="AUTOCOMMIT", future=True)


async def start_run(protocol_obj, args, db, targets):
Expand Down
3 changes: 1 addition & 2 deletions nxc/nxcdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ class UserExitedProto(Exception):


def create_db_engine(db_path):
db_engine = create_engine(f"sqlite:///{db_path}", isolation_level="AUTOCOMMIT", future=True)
return db_engine
return create_engine(f"sqlite:///{db_path}", isolation_level="AUTOCOMMIT", future=True)


def print_table(data, title=None):
Expand Down
1 change: 1 addition & 0 deletions nxc/protocols/ftp.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ 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
17 changes: 7 additions & 10 deletions nxc/protocols/ftp/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ 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 @@ -179,8 +180,7 @@ def add_credential(self, username, password):

# hacky way to get cred_id since we can't use returning() yet
if len(credentials) == 1:
cred_id = self.get_credential(username, password)
return cred_id
return self.get_credential(username, password)
else:
return credentials

Expand Down Expand Up @@ -225,8 +225,7 @@ def get_credentials(self, filter_term=None):
else:
q = select(self.CredentialsTable)

results = self.sess.execute(q).all()
return results
return self.sess.execute(q).all()

def is_host_valid(self, host_id):
"""Check if this host ID is valid."""
Expand Down Expand Up @@ -260,8 +259,7 @@ def is_user_valid(self, cred_id):

def get_user(self, username):
q = select(self.CredentialsTable).filter(func.lower(self.CredentialsTable.c.username) == func.lower(username))
results = self.sess.execute(q).all()
return results
return self.sess.execute(q).all()

def get_users(self, filter_term=None):
q = select(self.CredentialsTable)
Expand All @@ -272,8 +270,7 @@ def get_users(self, filter_term=None):
elif filter_term and filter_term != "":
like_term = func.lower(f"%{filter_term}%")
q = q.filter(func.lower(self.CredentialsTable.c.username).like(like_term))
results = self.sess.execute(q).all()
return results
return self.sess.execute(q).all()

def add_loggedin_relation(self, cred_id, host_id):
relation_query = select(self.LoggedinRelationsTable).filter(
Expand All @@ -296,15 +293,15 @@ 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)
if cred_id:
q = q.filter(self.LoggedinRelationsTable.c.credid == cred_id)
if host_id:
q = q.filter(self.LoggedinRelationsTable.c.hostid == host_id)
results = self.sess.execute(q).all()
return results
return self.sess.execute(q).all()

def remove_loggedin_relations(self, cred_id=None, host_id=None):
q = delete(self.LoggedinRelationsTable)
Expand Down
Loading

0 comments on commit cdcde5a

Please sign in to comment.