Repository navigation
Conversation
|
Last commit patches the --lsa and --sam functions so that they work as intended with the modifications I applied. Both functions look like: @requires_admin
def put_file(self, download_path=None, remote_path=None):
if remote_path is None and download_path is None:
download_path = self.args.put_file[0]
remote_path = self.args.put_file[1]Which allows calling the function as a method filling remote and local path. Or via the command line from self.args. |
…unning and with which service account
| self.logger.fail("Command execution blocked by AMSI") | ||
| return "" | ||
|
|
||
| if (self.args.execute or self.args.ps_execute or self.args.clr_assembly_explicitly_set): |
There was a problem hiding this comment.
clr_assembly_explicitly_set only exists on the namespace when --clr-assembly was passed, so every caller that goes through execute() without -x/-X crashes here. nxc mssql <ip> -u <user> -p <pass> -M test_connection -o HOST=localhost gives:
Same for met_inject, web_delivery and any module calling connection.execute(). I think the simplest fix is to drop the DefaultTrackingAction on both options, use default=None, and test if self.args.clr_assembly: / if self.args.exec_method:. That also removes the three getattr(self.args, ...) at lines 354, 406 and 417.
| if getattr(self.args, "exec_method_explicitly_set", False): | ||
| methods = [self.args.exec_method] | ||
| if not methods: | ||
| methods = ["mssqlexec", "oleexec", "clrexec"] |
There was a problem hiding this comment.
The fallback list is dead code: the loop breaks as soon as the class is instantiated, and none of the constructors can fail (only JOBEXEC does a query, and it is not in the list). So when xp_cmdshell fails we never try oleexec or clrexec. Was the fallback supposed to happen on execution failure? If not, please drop the loop and use a dict:
exec_methods = {"mssqlexec": MSSQLEXEC, "oleexec": OLEEXEC, "clrexec": CLREXEC, "jobexec": JOBEXEC}
exec_method = exec_methods[self.args.exec_method](self)That also removes the four copy-pasted try/except Exception blocks and the if "exec_method" in locals() at line 402.
| # This part is hacky because we need to be able to determine whether the user used -x/-X with a command | ||
| # Or with a custom assembly to execute. | ||
| clr_assembly_explicitly_set = getattr(self.args, "clr_assembly_explicitly_set", False) | ||
| if (self.args.execute is True or self.args.ps_execute is True) and not clr_assembly_explicitly_set: |
There was a problem hiding this comment.
I am not a fan of -x / -X with nargs="?" and the is True checks here. -x alone used to be an argparse error, now it logs in on every target before telling the user the command is missing, and -x --clr-assembly a.dll runs the procedure with @cmd = N'None'. Since the custom assembly does not use the command at all, could --clr-assembly PATH be its own action (a clr_assembly() method called by call_cmd_args, like --put-file)? Then -x keeps its required value and the whole block goes away.
| self.lmhash = "" | ||
| self.nthash = "" | ||
| self.no_ntlm = False | ||
| self.args = args |
There was a problem hiding this comment.
connection.__init__ already sets self.args, please remove it.
| LSA.dumpCachedHashes() | ||
| LSA.dumpSecrets() | ||
|
|
||
| def _is_option_enabled(self, option): |
There was a problem hiding this comment.
No _ prefix on methods please, is_option_enabled() as before. Same for _cleanup_stale(), _cleanup() and _restore_all() in clrexec.py.
| result_rows = self.mssql_conn.sql_query(get_output_query) | ||
| if self.mssql_conn.lastError or not result_rows: | ||
| self.logger.fail(f"Fail running command execution: {self.mssql_conn.lastError}") | ||
| return |
There was a problem hiding this comment.
This early return leaves the job on the server, sp_delete_job is only reached on the happy path. On my lab the job runs fine (history shows run_status 1) but the history row is not written yet when we read it, so --exec-method jobexec -x whoami always ends here and I had two nxc_mssql_* jobs left in msdb.dbo.sysjobs after two runs. Then execute() in mssql.py calls .decode() on the None we return:
Please put the cleanup in a finally and return a str on every path.
| self.logger.debug(f"Running {wait_job_finished_query}") | ||
| for _ in range(10): | ||
| rows = self.mssql_conn.sql_query(wait_job_finished_query) | ||
| if rows and rows[0].get("stop_execution_date") != "NULL": |
There was a problem hiding this comment.
impacket returns None for a SQL NULL now, so != "NULL" is always true and the loop exits on the first iteration without waiting. That is why the history is empty above. Please use is not None, and I think the loop should wait on the history row rather than on stop_execution_date, since the row is written a bit after the job stops. 5 seconds is also short for a real command, the timeout should follow --timeout.
| self.logger.fail(f"Fail running command execution: {self.mssql_conn.lastError}") | ||
| return | ||
|
|
||
| if match := search(r"\.(.*?)\.", result_rows[0]["message"]): |
There was a problem hiding this comment.
Taking what is between the first two dots of the message does not hold: with Executed as user: RD.OCD\svc_sql. <output>. Process Exit Code 0. it returns OCD\svc_sql, any output containing a dot (ipconfig, an IP, a file name) is cut at that dot, and a multi-line output does not match at all, in which case output is never assigned and line 100 raises UnboundLocalError. The message is also localised (my lab returns Exécuté en tant qu'utilisateur : ...). Writing the output to a file with @output_file_name in sp_add_jobstep and reading it back with the OPENROWSET from get_file() would be more reliable
| SELECT * | ||
| FROM sys.dm_server_services | ||
| WHERE servicename LIKE '%SQL Server Agent%' | ||
| AND status = 4; |
There was a problem hiding this comment.
The query already filters on status = 4, so rows[0]["status"] != 4 at line 27 can never be true, if not rows: is enough. This is also the same query as sql_agent() in mssql.py, please drop one and call the other. Doing a query and logging a failure in __init__ is what forces the is_sql_server_agent_running is False special case in mssql.py, I would move the check into execute().
| cgroup.add_argument("--db-hash", action="store_true", help="dump local database hashes") | ||
|
|
||
| cgroup = mssql_parser.add_argument_group("Command Execution") | ||
| cgroup.add_argument("--exec-method", choices={"mssqlexec", "oleexec", "clrexec", "jobexec"}, default="mssqlexec", help="method to execute the command. Ignored if in MSSQL mode", action=DefaultTrackingAction) |
There was a problem hiding this comment.
Ignored if in MSSQL mode is copied from the smb parser and does not mean anything here, please describe the four methods instead. choices should be a list, with a set the order in --help changes on every run. At line 28 the f-string around path.join() is not needed.



Description
This PR adds two new exec methods for the MSSQL protocol:
As such, I have added the --exec-method {mssqlexec, oleexec, crlexec} mechanism as well.
Concerning the CRL exec method, it relies on an assembly which is a binary file that is sent as hexadecimal to the SQL server and used to run the command. This file is located in NXC_DATA/mssql_clr and the corresponding C# code is the following:
If using the --exec-method crlexec, it is possible to use a custom assembly specifying the --clr-assembly PATH_TO_ASSEMBLY. In that case the -x "COMMAND" is not used at all and the CLR assembly is executed.
Note that this PR is work in progress. Indeed, there are few issues:
I know it sucks but for the moment, and considering how -x and -X are designed, it's not really possible to do much better.
Type of change
Insert an "x" inside the brackets for relevant items (do not delete options)
Setup guide for the review
Nothing to setup, it works on default MSSQL server.
Screenshots (if appropriate):
Notice that -x doesn't have any COMMAND, that's because I had to modify proto_args.
Checklist:
Insert an "x" inside the brackets for completed and relevant items (do not delete options)
poetry run ruff check ., use--fixto automatically fix what it can)tests/e2e_commands.txtfile if necessary (new modules or features are required to be added to the e2e tests)IMPORTANT
I honestly believe we can simplify the way we execute commands. Knowing that most -X command exec rely on cmd /c powershell COMMAND, is absurd to me. Question is whether we are keen modifying that part (which is a huge change) or hack protocols so that we can use more advanced protocol capabilities like the CRL on MSSQL for example. Let me know what you guys think :)