沙箱技術發展已非常成熟,與之而來的沙箱逃逸技術也多種多樣,如基於主機名、內存、開源沙箱的特徵等等進行判斷,如爲沙箱環境,則關閉自身系統(所檢測沙箱特徵越多越好)。本文沙箱逃逸比較簡單,主要是通過鍵盤、鼠標、時間差等三個維度進行檢測,超出指定閾值則退出。
一、源代碼
# -*- coding: UTF-8 -*-
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):
__file__ = [("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 ("間隔時間 %d" % elapsed);
return elapsed;
#獲取鼠標左鍵數量、左鍵按鍵時間、鍵盤數量
def get_key_press():
global mouse_clicks; #鼠標
global keystrokes; #鍵盤
#0xff換成十進制爲255。A,B,C,D,E,F這五個字母來分別表示10,11,12,13,14,15。
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;
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_click = 10;#雙擊最大次數
double_click_threshold = 0.250 ;#雙擊時間差
first_double_click = None;#第一次雙擊時間
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_click:
#短時間內,連續雙擊
if keypress_time - first_double_click <=(max_double_click*max_input_threshold):
sys.exit(0);
if keystrokes >=max_keystrokes and double_clicks >=max_double_click and mouse_clicks >=max_mouse_clicks:
return;
previous_timestamp = keypress_time;
elif keypress_time is not None:
#先前時間戳初始化
previous_timestamp = keypress_time;
detect_sandbox();
print("監測正常");
二、說點其它
基於python的滲透及防護內容暫時告一段落,下一步我打算深入操作系統,以C++爲主要編程語言,實現基於windows操作系統的滲透與防範(包括:註冊表、進程注入、逆向、hook等),希望豐富自身安全經驗同時,可以更好的幫助用戶解決安全問題。