Compare commits

...
55 Commits
Author SHA1 Message Date
PYDT 7784544583 Add files via upload 2025-08-18 15:34:45 +08:00
PYDT f742937296 Add files via upload 2025-08-18 00:29:36 +08:00
PYDT 5fd9242291 Add files via upload 2025-08-17 15:30:24 +08:00
PYDT 9f343196a9 Add files via upload 2025-08-17 00:04:25 +08:00
PYDT 5468eded04 Add files via upload 2025-08-17 00:01:22 +08:00
PYDT 1b97758fc9 Add files via upload 2025-08-16 23:57:22 +08:00
PYDT b2e8e49447 Add files via upload 2025-08-16 23:56:03 +08:00
PYDT 3eec781139 Add files via upload 2025-08-16 15:37:39 +08:00
PYDT b6f1977fa0 Add files via upload 2025-08-16 00:02:23 +08:00
PYDT e0aa080f00 Add files via upload 2025-08-15 23:56:43 +08:00
PYDT 66aa76c836 Add files via upload 2025-08-15 23:55:49 +08:00
PYDT bb9444e1ae Update README_zh_CN.md 2025-08-15 19:19:35 +08:00
PYDT 6c9bfa7755 Update README_zh_TW.md 2025-08-15 19:18:26 +08:00
PYDT c4fa849290 Update README_zh_TW.md 2025-08-15 19:17:58 +08:00
PYDT 4807e2c410 Update README.md 2025-08-15 19:15:51 +08:00
PYDT 5388efdebc Update README.md 2025-08-15 19:13:15 +08:00
PYDT 1d656de7ba Add files via upload 2025-08-15 18:31:42 +08:00
PYDT eaa1d725a9 Update README_zh_TW.md 2025-08-15 18:01:43 +08:00
PYDT dea2150d63 Update README_zh_CN.md 2025-08-15 18:00:55 +08:00
PYDT 80f9d6cf75 Update README.md 2025-08-15 17:56:38 +08:00
PYDT 7430d38594 Update README.md 2025-08-15 17:54:45 +08:00
PYDT 6804e4af9f Update README_zh_CN.md 2025-08-15 16:38:23 +08:00
PYDT 138756c31d Update README_zh_TW.md 2025-08-15 16:37:50 +08:00
PYDT 349bc293c6 Update README.md 2025-08-15 16:37:17 +08:00
PYDT 2f87cd10f2 Update README.md 2025-08-15 16:30:41 +08:00
PYDT fc50eafcca Add files via upload 2025-08-15 16:13:36 +08:00
PYDT b48e20a727 Update README_zh_CN.md 2025-08-15 15:58:20 +08:00
PYDT ce7ed2e6eb Update README_zh_TW.md 2025-08-15 15:58:04 +08:00
PYDT 043d71e0ff Update README.md 2025-08-15 15:57:32 +08:00
PYDT 1855ae0e1d Delete Plugins/Filter/PYAS_Driver.sys 2025-08-15 15:48:29 +08:00
PYDT 77323a50df Add files via upload 2025-08-15 15:48:14 +08:00
PYDT 1c2f6b85ca Add files via upload 2025-08-15 15:47:36 +08:00
PYDT 2b5c478e4b Update and rename LICENSE.md to LICENSE.txt 2025-08-15 15:39:17 +08:00
PYDT 90fd83a81f Rename LICENSE.proprietary to LICENSE.md 2025-08-15 15:38:29 +08:00
PYDT 8fa2a166f3 Delete LICENSE 2025-08-15 15:36:54 +08:00
PYDT e8cc45ebe7 Update LICENSE.proprietary 2025-08-15 15:36:00 +08:00
PYDT eb87117b91 Rename LICENSE.md to LICENSE 2025-08-15 14:51:50 +08:00
PYDT 3799dfa1e8 Rename LICENSE.proprietary.md to LICENSE.proprietary 2025-08-15 14:51:37 +08:00
PYDT 163c7fd680 Rename LICENSE.proprietary to LICENSE.proprietary.md 2025-08-15 14:51:22 +08:00
PYDT 44ca762f69 Create LICENSE.proprietary 2025-08-15 14:50:15 +08:00
PYDT 8db311ba33 Add files via upload 2025-08-15 14:21:22 +08:00
PYDT 99d8604db4 Add files via upload 2025-08-15 11:14:46 +08:00
PYDT 90aa88daeb Update README.md 2025-08-14 20:31:29 +08:00
PYDT ae6eebad4d Update README_zh_CN.md 2025-08-14 20:30:39 +08:00
PYDT cd31ce1c38 Update README_zh_TW.md 2025-08-14 20:30:00 +08:00
PYDT ed3846e451 Update README_zh_TW.md 2025-08-14 20:28:02 +08:00
PYDT 0c79cf8e37 Update README_zh_CN.md 2025-08-14 20:25:36 +08:00
PYDT 81c7e16c0e Update README_zh_CN.md 2025-08-14 20:23:44 +08:00
PYDT 16c03095b8 Update README.md 2025-08-14 20:22:36 +08:00
PYDT b5dab3aa22 Update README_zh_CN.md 2025-08-14 20:21:11 +08:00
PYDT e4a3c871f8 Update README.md 2025-08-14 20:15:46 +08:00
PYDT a2fe947b08 Update README.md 2025-08-14 20:13:26 +08:00
PYDT 8df49ecfc1 Update README.md 2025-08-14 20:03:11 +08:00
PYDT 526b9bd4c7 Update README.md 2025-08-14 20:00:42 +08:00
PYDT c67ff3d936 Add files via upload 2025-08-14 14:21:47 +08:00
23 changed files with 1821 additions and 175 deletions

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
import os, hashlib
def calc_sha256(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).digest()
def dedup_realtime(root):
seen = set()
deleted = 0
for dirpath, _, files in os.walk(root):
for name in files:
p = os.path.join(dirpath, name)
try:
h = calc_sha256(p)
except Exception:
continue
if h in seen:
try:
os.remove(p)
print(p)
deleted += 1
except Exception:
pass
else:
seen.add(h)
print(f"deleted {deleted}")
if __name__ == "__main__":
dedup_realtime(r".\Image_File")
+2 -1
View File
@@ -67,7 +67,6 @@ def se_block(x, reduction):
s = layers.Conv2D(filters // reduction, 1, padding='same', activation='gelu')(x)
s = layers.BatchNormalization()(s)
s = layers.Conv2D(filters, 1, padding='same', activation='sigmoid')(s)
s = layers.BatchNormalization()(s)
return layers.multiply([x, s])
def build_model(input_shape, num_classes):
@@ -98,6 +97,7 @@ train_ds, val_ds = load_dataset(r'./Image_File', r'./Image_File')
for imgs, _ in train_ds.take(1):
train_ds.image_shape = imgs.shape[1:]
break
strategy = tf.distribute.MirroredStrategy(cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
with strategy.scope():
try:
@@ -106,6 +106,7 @@ with strategy.scope():
except:
print("Creating a new model")
model = build_model(train_ds.image_shape, len(train_ds.class_indices))
print(f"Total parameters: {model.count_params()}")
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(train_ds, epochs=30, callbacks=[CustomModelCheckpoint(), callbacks.LearningRateScheduler(lr_scheduler)], validation_data=val_ds)
input("Training complete.")
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020-2025 87owo (PYAS Security)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+27
View File
@@ -0,0 +1,27 @@
PYAS Security Software Development License Agreement
Last updated: 2025-08-15
1. License & Ownership
– A single device key may be required to activate the software or source code.
– Non exclusive, non transferable, and for personal, internal use only.
– 87owo reserves all rights. Intellectual property rights are not transferred.
2. Use & Prohibitions
– Private redistribution, sublicensing, or rental is prohibited.
– Private reverse engineering or removal of notices is prohibited.
– Any of the above requires prior authorization from the original author.
– Only personal internal use or modification of the source code is permitted.
– Use of the software or source code for any illegal purpose is prohibited.
3. License Components
– All project script archives and executable files are proprietary.
4. Updates & Terms
– Updates to new versions may include patches, enhancements, or modifications.
– Continued use constitutes your acceptance of these features or terms.
5. Warranty & Liability
– This software is provided "as is," without warranty of any kind.
– In no event shall there be any liability for consequential damages.
© 2020–2025 87owo (PYAS Security). All rights reserved.
+137 -27
View File
@@ -1,7 +1,7 @@
import os, gc, re, sys, time, json, base64
import ctypes, ctypes.wintypes, threading
import requests, pyperclip, winreg, shutil
import traceback, hashlib, msvcrt
import requests, webbrowser, winreg, shutil
import traceback, hashlib, msvcrt, pyperclip
from PYAS_Config import *
from PYAS_Engine import *
@@ -112,17 +112,17 @@ class MainWindow_Controller(QMainWindow):
"traditional_switch", "simplified_switch", "english_switch",
]
self.pyas_default = {
"version": "3.3.3",
"version": "3.3.4",
"product": "00000-00000-00000-00000-00000",
"language": "english_switch",
"theme": "white_switch",
"sensitive": 95,
"custom_rule": {},
"process_switch": True,
"document_switch": True,
"system_switch": True,
"driver_switch": True,
"network_switch": True,
"custom_rule": [],
}
self.pass_windows = [
{"exe": "System Idle Process", "class": "", "title": ""},
@@ -230,7 +230,14 @@ class MainWindow_Controller(QMainWindow):
return default_value.copy()
def load_config(self):
existed = os.path.exists(self.file_config)
self.pyas_config = self.read_config(self.file_config, self.pyas_default)
if existed:
dv = str(self.pyas_default.get("version", "")).strip()
cv = str(self.pyas_config.get("version", "")).strip()
if dv and dv != cv:
self.pyas_config["version"] = dv
self.save_config(self.file_config, self.pyas_config)
def config_list(self, key):
if key not in self.pyas_config:
@@ -341,7 +348,6 @@ class MainWindow_Controller(QMainWindow):
elif self.install_system_driver():
self.start_daemon_thread(self.pipe_server_thread)
else:
self.pyas_config[name] = False
self.send_message("驅動防護啟用失敗", "warn", True)
elif name == "network_switch":
if checked:
@@ -349,7 +355,6 @@ class MainWindow_Controller(QMainWindow):
else:
self.send_message(f"此功能不支持使用", "info", True)
self.save_config(self.file_config, self.pyas_config)
self.apply_settings()
def init_thread(self):
self.start_daemon_thread(self.popup_intercept_thread)
@@ -393,9 +398,13 @@ class MainWindow_Controller(QMainWindow):
if not widget.property("_connected_toggle"):
widget.toggled.connect(lambda checked, b=widget: self.toggle_switch_text(b, checked))
widget.setProperty("_connected_toggle", True)
else:
if not hasattr(widget, "_origin_text"):
widget._origin_text = self.get_widget_text(widget)
widget.setText(self.trans(lang, widget._origin_text))
elif hasattr(widget, "setText"):
if name == "log_text":
if name in ["log_text","license_text"]:
pass
else:
if not hasattr(widget, "_origin_text"):
@@ -630,12 +639,13 @@ class MainWindow_Controller(QMainWindow):
elif m == "save":
select = QFileDialog.getSaveFileName(self, message)[0]
select = select or False
now = time.strftime("%Y-%m-%d %H:%M:%S")
output = f"[{now}] | {mode} | {message} | {select}"
log_widget = self.widgets.get("log_text")
if log_widget:
log_widget.append(output)
return select or False
return select
except Exception:
traceback.print_exc()
return False
@@ -749,8 +759,8 @@ class MainWindow_Controller(QMainWindow):
elapsed = int(time.time() - self.scan_start)
count = len(self.virus_results)
result = (
f"發現 {count} 個病毒,耗時 {elapsed} 秒,共掃描 {self.scan_count} 檔案"
if count else f"未發現病毒,耗時 {elapsed} 秒,共掃描 {self.scan_count} 檔案")
f"發現 {count} 個病毒,共掃描 {self.scan_count} 檔案,耗時 {elapsed} 秒"
if count else f"未發現病毒,共掃描 {self.scan_count} 檔案,耗時 {elapsed} 秒")
self.progress_title_signal.emit(self.trans(self.pyas_config["language"], "病毒掃描"))
self.scan_result_signal.emit(self.trans(self.pyas_config["language"], result))
@@ -784,20 +794,37 @@ class MainWindow_Controller(QMainWindow):
def solve_button(self):
deleted = 0
started = False
virus_list = self.widgets["virus_list"]
start_ts = time.time()
for i in reversed(range(virus_list.count())):
item = virus_list.item(i)
if item.checkState() == Qt.Checked:
file_path = self.norm_path(item.text().split(">")[1].strip())
if not started:
self.progress_title_signal.emit(self.trans(self.pyas_config["language"], "正在刪除"))
started = True
self.scan_progress_signal.emit(file_path)
try:
file_path = self.norm_path(item.text().split(">")[1].strip())
os.remove(file_path)
deleted += 1
virus_list.takeItem(i)
try:
self.virus_results.remove(file_path)
except ValueError:
pass
except Exception as e:
self.send_message(e, "warn", False)
virus_list.takeItem(i)
self.widgets["solve_button"].hide()
msg = f"已清理 {deleted} 個病毒檔案" if deleted else "無檔案被刪除"
self.widgets["progress_text"].setText(self.trans(self.pyas_config["language"], msg))
QApplication.processEvents()
remain = virus_list.count()
elapsed = int(time.time() - start_ts)
self.widgets["solve_button"].setVisible(remain > 0)
self.progress_title_signal.emit(self.trans(self.pyas_config["language"], "病毒掃描"))
result = (
f"剩餘 {remain} 個病毒,共刪除 {deleted} 檔案,耗時 {elapsed} 秒"
if remain else f"未剩餘病毒,共刪除 {deleted} 檔案,耗時 {elapsed} 秒")
self.scan_result_signal.emit(self.trans(self.pyas_config["language"], result))
def stop_button(self):
self.scan_running = False
@@ -1310,6 +1337,51 @@ class MainWindow_Controller(QMainWindow):
except Exception:
return ""
####################################################################################################
def website_button(self):
try:
webbrowser.open("https://github.com/87owo/PYAS")
return True
except Exception as e:
self.send_message(e, "warn", False)
return False
def update_button(self):
try:
current = str(self.pyas_config.get("version", "")).strip()
page = "https://github.com/87owo/PYAS/releases"
latest = ""
try:
j = requests.get("https://api.github.com/repos/87owo/PYAS/releases/latest", headers={"Accept": "application/vnd.github+json", "User-Agent": "PYAS"}, timeout=10).json()
latest = (j.get("tag_name") or j.get("name") or "").strip()
page = j.get("html_url") or page
except Exception:
try:
u = requests.get("https://github.com/87owo/PYAS/releases/latest", headers={"User-Agent": "PYAS"}, allow_redirects=True, timeout=10).url
page = u or page
m = re.search(r"/tag/([^/]+)$", str(u))
latest = m.group(1).strip() if m else ""
except Exception:
pass
rl = re.sub(r"^[vV]\s*", "", str(latest))
cl = re.sub(r"^[vV]\s*", "", str(current))
tr = tuple(int(x) for x in re.findall(r"\d+", rl))
tl = tuple(int(x) for x in re.findall(r"\d+", cl))
if tr and (not tl or tr > tl):
if self.send_message(f"發現新版本 {latest},您確定要前往更新嗎?", "quest", True):
webbrowser.open(page)
else:
if cl:
self.send_message(f"當前已是最新版本 {current}", "info", True)
else:
webbrowser.open(page)
return True
except Exception as e:
self.send_message(e, "warn", False)
return False
####################################################################################################
def lock_file(self, file, lock):
@@ -1372,7 +1444,7 @@ class MainWindow_Controller(QMainWindow):
state = self.scan_engine(file_path)
if state:
self.kernel32.TerminateProcess(h, 0)
self.send_message(f"進程防護攔截 | 靜態掃描攔截 | {pid} | {file_path} | None", "notify", True)
self.send_message(f"進程防護 | 靜態掃描攔截 | {pid} | {file_path} | None", "notify", True)
self.suspend_process(h, False)
self.kernel32.CloseHandle(h)
except Exception as e:
@@ -1419,8 +1491,7 @@ class MainWindow_Controller(QMainWindow):
####################################################################################################
def protect_file_thread(self):
FILE_LIST_DIRECTORY = 0x0001
hDir = self.kernel32.CreateFileW(self.path_user, FILE_LIST_DIRECTORY, 0x00000007, None, 3, 0x02000000, None)
hDir = self.kernel32.CreateFileW(self.path_user, 0x0001, 0x00000007, None, 3, 0x02000000, None)
buffer = ctypes.create_string_buffer(65536)
while self.pyas_config.get("document_switch", False):
@@ -1438,7 +1509,7 @@ class MainWindow_Controller(QMainWindow):
state = self.scan_engine(file_path)
if state:
self.add_to_quarantine([file_path])
self.send_message(f"檔案防護攔截 | 靜態掃描攔截 | None | {file_path} | None", "notify", True)
self.send_message(f"檔案防護 | 靜態掃描攔截 | None | {file_path} | None", "notify", True)
except Exception as e:
self.send_message(e, "warn", False)
self.kernel32.CloseHandle(hDir)
@@ -1466,15 +1537,12 @@ class MainWindow_Controller(QMainWindow):
try:
connections = set()
size = ctypes.wintypes.DWORD()
AF_INET = 2
TCP_TABLE_OWNER_PID_ALL = 5
ret = self.iphlpapi.GetExtendedTcpTable(None, ctypes.byref(size), True, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)
ret = self.iphlpapi.GetExtendedTcpTable(None, ctypes.byref(size), True, 2, 5, 0)
if ret != 122:
raise ctypes.WinError(ret)
buf = ctypes.create_string_buffer(size.value)
ret = self.iphlpapi.GetExtendedTcpTable(buf, ctypes.byref(size), True, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)
ret = self.iphlpapi.GetExtendedTcpTable(buf, ctypes.byref(size), True, 2, 5, 0)
if ret != 0:
raise ctypes.WinError(ret)
@@ -1503,7 +1571,7 @@ class MainWindow_Controller(QMainWindow):
if file_path and os.path.exists(file_path) and not self.is_in_whitelist(file_path):
if hasattr(self.rule, "network") and remote_ip in self.rule.network:
self.kernel32.TerminateProcess(h_process, 0)
self.send_message(f"網路防護攔截 | 規則列表攔截 | {pid} | {file_path} | {remote_ip}", "notify", True)
self.send_message(f"網路防護 | 規則列表攔截 | {pid} | {file_path} | {remote_ip}", "notify", True)
self.kernel32.CloseHandle(h_process)
except Exception as e:
self.send_message(e, "warn", False)
@@ -1564,8 +1632,50 @@ class MainWindow_Controller(QMainWindow):
####################################################################################################
def pipe_server_thread(self):
# The source code cannot be made public due to security concerns
pass
pipe_path = r"\\.\pipe\PYAS_Output_Pipe"
PIPE_BUF_SIZE = 65536
while self.pyas_config.get("driver_switch", False):
try:
hPipe = self.kernel32.CreateNamedPipeW(pipe_path, 0x00000001, 0x00000004 | 0x00000002, 1, PIPE_BUF_SIZE, PIPE_BUF_SIZE, 0, None)
if hPipe == ctypes.c_void_p(-1).value:
time.sleep(0.2)
continue
while self.pyas_config.get("driver_switch", False):
if not self.kernel32.ConnectNamedPipe(hPipe, None) and self.kernel32.GetLastError() != 535:
time.sleep(0.2)
continue
buf = ctypes.create_string_buffer(PIPE_BUF_SIZE)
bytes_read = ctypes.c_ulong(0)
if not self.kernel32.ReadFile(hPipe, buf, PIPE_BUF_SIZE, ctypes.byref(bytes_read), None) or bytes_read.value == 0:
self.kernel32.DisconnectNamedPipe(hPipe)
time.sleep(0.2)
continue
msg = buf.raw[:bytes_read.value].decode("utf-8", errors="ignore")
parts = [p.strip() for p in msg.split("|", 3)]
if len(parts) == 4:
rules, pid, raw_path, target = parts
for old, new in self.block_replace.items():
rules = rules.replace(old, new)
self.send_message(f"驅動防護 | {rules} | {pid} | {raw_path} | {target}", "notify", True)
if not self.is_in_whitelist(self.device_path_to_drive(raw_path)):
try:
h = self.kernel32.OpenProcess(0x1F0FFF, False, int(pid.strip()))
if h:
self.kernel32.TerminateProcess(h, 0xC0000022)
self.kernel32.CloseHandle(h)
except Exception as e:
self.send_message(e, "warn", False)
self.kernel32.DisconnectNamedPipe(hPipe)
self.kernel32.CloseHandle(hPipe)
except Exception as e:
self.send_message(e, "warn", False)
time.sleep(0.5)
####################################################################################################
+3 -2
View File
@@ -20,7 +20,7 @@ translate_dict = {
"載":"载","誤":"误","報":"报","鏈":"链","竄":"窜","蹤":"踪","與":"与",
"異":"异","實":"实","時":"时","彈":"弹","窗":"窗","暫":"暂","訂":"订",
"資":"资","產":"产","金":"密","離":"离","規":"规","則":"则","來":"来",
"殼":"壳","碼":"码","線":"线",},
"殼":"壳","碼":"码","線":"线","餘":"余",},
"english_switch": {"開啟":"On","關閉":"Off","开启":"On","关闭":"Off",",":", ",
"立即刪除":"Delete Now","安全模式":"Safe Mode","官方網站":"Official Website ",
@@ -72,7 +72,8 @@ translate_dict = {
"建立":"Create ","環境":"Environment ","沙箱":"Sandbox ","化":"", "表":"",
"達":"Reached ", "上限":"Limit ", "區":"", "金鑰":"Key ", "產品":"Product ",
"托管":"CLR ","殼碼":"Shellcode ","線程":"Thread ","注入":"Inject ",
"前往":"Go ","檢查":"Check ","可用":"Available ","靜態":"Static ", " ":" "},
"前往":"Go ","檢查":"Check ","可用":"Available ","靜態":"Static ",
"版本":"Version ","是":"","剩餘":"Remain "," ":" "},
"white_switch": {
"_white": "_black",},
+12 -18
View File
@@ -39,18 +39,18 @@ class rule_scanner:
return False, False
class model_scanner:
SHELLS = {
"0","1","2","3","4","5","6","7","8","9","cry","tvm","dec","enc","vmp","upx","aes","lzma","press","pack",
"enigma","protect","secur","asmstub","base","bss","clr_uef","cursors","transit","trs_age","engine","fio",
"fothk","h~;","icapsec","malloc_h","miniex","mssmixer","ndr64","nsys_wr","obr","wow","wow64svc","wpp_sf",
"pad","pgae","poolmi","proxy","qihoo","retpol","uedbg","tracesup","rwexec","rygs","s:@","sanontcp","segm",
"test","res","wisevec","viahwaes","orpc","nep","ace","extjmp","no_bbt","data","page","hexpthk"}
def __init__(self):
self.models = {}
self.suffix = {".com", ".exe", ".dll", ".sys", ".scr", ".bat", ".cmd", ".ps1", ".vbs", ".wsf"}
self.labels = ["Pefile/White", "Script/White", "Pefile/General", "Script/General"]
self.detect = {"Pefile/General", "Script/General"}
self.suffix = {
".com", ".dll", ".drv", ".exe", ".ocx", ".scr", ".sys",
".bat", ".cmd", ".html", ".js", ".php", ".ps1", ".vbs", ".wsf", ".xml"
}
self.labels = [
"Pefile/White", "Script/White", "Pefile/General", "Script/General"
]
self.detect = {
"Pefile/General", "Script/General"
}
self.resize = (224, 224)
def load_path(self, path):
@@ -65,14 +65,8 @@ class model_scanner:
except Exception:
return False
def is_valid_suffix(self, file_path):
return os.path.splitext(file_path)[-1].lower() in self.suffix
def model_scan(self, file_path):
try:
if not self.models or not self.is_valid_suffix(file_path):
return False, False
model = next(iter(self.models.values()))
shape = model.get_inputs()[0].shape
channels = shape[-1] if shape[-1] in (1, 3) else (shape[1] if shape[1] in (1, 3) else 1)
@@ -131,7 +125,7 @@ class model_scanner:
def get_type(self, file_path):
match_data = {}
if not self.is_valid_suffix(file_path):
if not os.path.splitext(file_path)[-1].lower() in self.suffix:
return match_data
try:
with pefile.PE(file_path, fast_load=True) as pe:
@@ -140,7 +134,7 @@ class model_scanner:
return {}
for section in pe.sections:
name = section.Name.rstrip(b'\x00').decode('latin1').lower()
if (section.Characteristics & 0x00000020) and name not in self.SHELLS:
if section.Characteristics & 0x00000020:
match_data[name] = section.get_data()
except pefile.PEFormatError:
with open(file_path, 'rb') as f:
+51 -50
View File
@@ -665,9 +665,7 @@ class Ui_main_window(object):
self.license_text = QTextEdit(self.license_widget)
self.license_text.setObjectName(u"license_text")
self.license_text.setGeometry(QRect(10, 10, 730, 220))
font7 = QFont()
font7.setPointSize(9)
self.license_text.setFont(font7)
self.license_text.setFont(font2)
self.license_text.setLayoutDirection(Qt.LeftToRight)
self.license_text.setStyleSheet(u"QTextEdit { background-color: transparent; color: rgb(0, 0, 0); border: 1px solid rgb(235, 235, 235); border-radius: 10px; outline: none; } QTextEdit QScrollBar:vertical { background: transparent; width: 6px; margin: 0px; } QTextEdit QScrollBar::handle:vertical { background: rgb(200, 200, 200); border-radius: 3px; min-height: 20px; } QTextEdit QScrollBar:horizontal { background: transparent; height: 6px; margin: 0px; } QTextEdit QScrollBar::handle:horizontal { background: rgb(200, 200, 200); border-radius: 3px; min-width: 20px; } QTextEdit QScrollBar::handle:hover { background: rgb(180, 180, 180); } QTextEdit QScrollBar::add-line, QTextEdit QScrollBar::sub-line { width: 0px; height: 0px; } QTextEdit QScrollBar::add-page, QTextEdit QScrollBar::sub-page { background: transparent; }\n"
"")
@@ -1196,15 +1194,15 @@ class Ui_main_window(object):
self.log_text = QTextEdit(self.log_widget)
self.log_text.setObjectName(u"log_text")
self.log_text.setGeometry(QRect(10, 10, 730, 220))
font8 = QFont()
font8.setFamilies([u"Microsoft YaHei"])
font8.setPointSize(9)
font8.setBold(False)
font8.setItalic(False)
font8.setStrikeOut(False)
font8.setKerning(True)
font8.setStyleStrategy(QFont.PreferAntialias)
self.log_text.setFont(font8)
font7 = QFont()
font7.setFamilies([u"Microsoft YaHei"])
font7.setPointSize(9)
font7.setBold(False)
font7.setItalic(False)
font7.setStrikeOut(False)
font7.setKerning(True)
font7.setStyleStrategy(QFont.PreferAntialias)
self.log_text.setFont(font7)
self.log_text.setLayoutDirection(Qt.LeftToRight)
self.log_text.setAutoFillBackground(False)
self.log_text.setStyleSheet(u"QTextEdit { background-color: transparent; color: rgb(0, 0, 0); border: 1px solid rgb(235, 235, 235); border-radius: 10px; outline: none; } QTextEdit QScrollBar:vertical { background: transparent; width: 6px; margin: 0px; } QTextEdit QScrollBar::handle:vertical { background: rgb(200, 200, 200); border-radius: 3px; min-height: 20px; } QTextEdit QScrollBar:horizontal { background: transparent; height: 6px; margin: 0px; } QTextEdit QScrollBar::handle:horizontal { background: rgb(200, 200, 200); border-radius: 3px; min-width: 20px; } QTextEdit QScrollBar::handle:hover { background: rgb(180, 180, 180); } QTextEdit QScrollBar::add-line, QTextEdit QScrollBar::sub-line { width: 0px; height: 0px; } QTextEdit QScrollBar::add-page, QTextEdit QScrollBar::sub-page { background: transparent; }\n"
@@ -1225,12 +1223,12 @@ class Ui_main_window(object):
self.state_title = QLabel(self.state_widget)
self.state_title.setObjectName(u"state_title")
self.state_title.setGeometry(QRect(10, 200, 730, 30))
font9 = QFont()
font9.setFamilies([u"Microsoft YaHei"])
font9.setPointSize(14)
font9.setBold(True)
font9.setStyleStrategy(QFont.PreferAntialias)
self.state_title.setFont(font9)
font8 = QFont()
font8.setFamilies([u"Microsoft YaHei"])
font8.setPointSize(14)
font8.setBold(True)
font8.setStyleStrategy(QFont.PreferAntialias)
self.state_title.setFont(font8)
self.state_title.setLayoutDirection(Qt.LeftToRight)
self.state_title.setStyleSheet(u"QLabel { background-color: transparent; color: rgb(0, 0, 0); }\n"
"")
@@ -1242,13 +1240,13 @@ class Ui_main_window(object):
self.state_icon.setSizePolicy(sizePolicy)
self.state_icon.setMinimumSize(QSize(0, 171))
self.state_icon.setMaximumSize(QSize(16777215, 16777215))
font10 = QFont()
font10.setFamilies([u"Microsoft YaHei"])
font10.setPointSize(10)
font10.setStrikeOut(False)
font10.setKerning(True)
font10.setStyleStrategy(QFont.PreferAntialias)
self.state_icon.setFont(font10)
font9 = QFont()
font9.setFamilies([u"Microsoft YaHei"])
font9.setPointSize(10)
font9.setStrikeOut(False)
font9.setKerning(True)
font9.setStyleStrategy(QFont.PreferAntialias)
self.state_icon.setFont(font9)
self.state_icon.setContextMenuPolicy(Qt.DefaultContextMenu)
self.state_icon.setLayoutDirection(Qt.LeftToRight)
self.state_icon.setStyleSheet(u"")
@@ -1478,37 +1476,40 @@ class Ui_main_window(object):
self.license_text.setHtml(QCoreApplication.translate("main_window", u"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"</style></head><body style=\" font-family:'Microsoft YaHei'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">PYAS Security Software Development License Agreement</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Last updated: 2025-08-07</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Last updated: 2025-08-15</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">1. License &amp; Ownership </p>\n"
"<p style=\" margin-top:0px; m"
"argin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 A single device key is required for activation.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 Non exclusive, non transferable, internal use only. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 87owo retains all rights; IP not transferred.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">1. License &amp; Ownership</p>\n"
"<p style=\" margin-top:0px; ma"
"rgin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 A single device key may be required to activate the software or source code.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 Non exclusive, non transferable, and for personal, internal use only.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 87owo reserves all rights. Intellectual property rights are not transferred.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">2. Use &amp; Prohibitions </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 No redistribution, sublicensing, rental "
"or leasing. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 No reverse engineering, modification or removal of notices. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 The software may not be used for any unlawful purpose.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">3. Open Source Component </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 The main Python script is licensed under MIT License.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">2. Use &amp; Prohibitions</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent"
":0; text-indent:0px;\"> \u2013 All drivers Protect*.c/h script remain proprietary.</p>\n"
":0; text-indent:0px;\"> \u2013 Private redistribution, sublicensing, or rental is prohibited.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 Private reverse engineering or removal of notices is prohibited.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 Any of the above requires prior authorization from the original author.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 Only personal internal use or modification of the source code is permitted.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 Use of the software or source code for any illegal purpose is prohibited.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin"
"-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">3. License Components</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 All project script archives and executable files are proprietary.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">4. Updates &amp; Terms </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 Updates may include patches, enhancements, or new versions. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 Continued use of the software implies acceptance of the terms.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">4. Updates &amp; Terms</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 Updates to new versions may include patches, enhancements, or modifications.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-lef"
"t:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 Continued use constitutes your acceptance of these features or terms.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin"
"-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">5. Warranty &amp; Liability </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 The software is provided \u201cas is,\u201d without warranty. </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 No liability for indirect or consequential damages.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">\u00a9 2020\u20132025 87owo (PYAS Security). All rights reserved. </p></body></html>", None))
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">5. Warranty &amp; Liability</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 This software is provided &quot;as is,&quot; without warranty of any kind.</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> \u2013 In no event shall there be any liability for consequential damages.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-in"
"dent:0px;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">\u00a9 2020\u20132025 87owo (PYAS Security). All rights reserved.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>", None))
self.process_title.setText(QCoreApplication.translate("main_window", u"\u9032\u7a0b\u9632\u8b77", None))
self.process_text.setText(QCoreApplication.translate("main_window", u"\u6b64\u9078\u9805\u53ef\u4ee5\u6514\u622a\u9032\u7a0b\u75c5\u6bd2", None))
self.process_switch.setText(QCoreApplication.translate("main_window", u"\u95dc\u9589", None))
+1 -1
View File
@@ -2,7 +2,7 @@ import pyinstaller_versionfile
pyinstaller_versionfile.create_versionfile(
output_file="versionfile.txt",
version='3.3.3',
version='3.3.4',
company_name="PYAS Security",
file_description="Python Antivirus Software",
internal_name="PYAS",
+224
View File
@@ -0,0 +1,224 @@
#include <ntifs.h>
#include "DriverEntry.h"
#include "ProtectRules.h"
LARGE_INTEGER g_CmRegHandle;
PDEVICE_OBJECT g_ControlDeviceObject;
KSPIN_LOCK g_ProtectLock;
FAST_MUTEX HookMutex;
PDRIVER_OBJECT DiskDrvObj = NULL;
KEVENT g_LogDrainEvent;
BOOLEAN g_Unloading = FALSE;
BOOLEAN g_CmRegActive = FALSE;
EX_RUNDOWN_REF g_Rundown;
PDEVICE_OBJECT g_GuardDevice = NULL;
volatile LONG g_LogWorkCount = 0;
static UNICODE_STRING g_DeviceName;
static WCHAR g_DeviceNameBuf[64];
static UNICODE_STRING g_SymLink = RTL_CONSTANT_STRING(L"\\??\\PYAS_Driver");
static BOOLEAN g_SymLinkCreated = FALSE;
static NTSTATUS CombinedDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
if (DeviceObject == g_ControlDeviceObject) {
PIO_STACK_LOCATION s = IoGetCurrentIrpStackLocation(Irp);
if (s->MajorFunction == IRP_MJ_CREATE || s->MajorFunction == IRP_MJ_CLOSE || s->MajorFunction == IRP_MJ_CLEANUP) {
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_INVALID_DEVICE_REQUEST;
}
{
PIO_STACK_LOCATION s = IoGetCurrentIrpStackLocation(Irp);
if (s->MajorFunction == IRP_MJ_PNP) {
PDEVICE_OBJECT lower = (PDEVICE_OBJECT)DeviceObject->DeviceExtension;
if (s->MinorFunction == IRP_MN_REMOVE_DEVICE) {
NTSTATUS st;
IoSkipCurrentIrpStackLocation(Irp);
st = lower ? IoCallDriver(lower, Irp) : STATUS_SUCCESS;
if (lower) IoDetachDevice(lower);
IoDeleteDevice(DeviceObject);
return st;
}
IoSkipCurrentIrpStackLocation(Irp);
return IoCallDriver((PDEVICE_OBJECT)DeviceObject->DeviceExtension, Irp);
}
}
return FileProtectDispatch(DeviceObject, Irp);
}
static NTSTATUS AttachDiskFilters(PDRIVER_OBJECT DriverObject)
{
UNICODE_STRING name = RTL_CONSTANT_STRING(L"\\Driver\\Disk");
UNICODE_STRING sym = RTL_CONSTANT_STRING(L"IoDriverObjectType");
POBJECT_TYPE* pType = (POBJECT_TYPE*)MmGetSystemRoutineAddress(&sym);
if (!pType || !*pType)
return STATUS_NOT_SUPPORTED;
NTSTATUS status = ObReferenceObjectByName(&name, OBJ_CASE_INSENSITIVE, NULL, 0, *pType, KernelMode, NULL, (PVOID*)&DiskDrvObj);
if (!NT_SUCCESS(status))
return status;
ULONG done = 0;
status = IoEnumerateDeviceObjectList(DiskDrvObj, NULL, 0, &done);
if (status != STATUS_BUFFER_TOO_SMALL && status != STATUS_SUCCESS) {
ObDereferenceObject(DiskDrvObj);
DiskDrvObj = NULL;
return status;
}
PDEVICE_OBJECT* list = ExAllocatePool2(POOL_FLAG_NON_PAGED, done * sizeof(PDEVICE_OBJECT), 'dskT');
if (!list) {
ObDereferenceObject(DiskDrvObj);
DiskDrvObj = NULL;
return STATUS_INSUFFICIENT_RESOURCES;
}
status = IoEnumerateDeviceObjectList(DiskDrvObj, list, done * sizeof(PDEVICE_OBJECT), &done);
if (!NT_SUCCESS(status)) {
ExFreePool2(list, 'dskT', NULL, 0);
ObDereferenceObject(DiskDrvObj);
DiskDrvObj = NULL;
return status;
}
for (ULONG i = 0; i < done && g_MbrFilterCount < MAX_MBR_TARGETS; ++i) {
PDEVICE_OBJECT lower = list[i], filter, attached = NULL;
status = IoCreateDevice(DriverObject, 0, NULL, lower->DeviceType, lower->Characteristics, FALSE, &filter);
if (!NT_SUCCESS(status))
continue;
filter->Flags |= (lower->Flags & (DO_BUFFERED_IO | DO_DIRECT_IO | DO_POWER_PAGABLE));
status = IoAttachDeviceToDeviceStackSafe(filter, lower, &attached);
if (!NT_SUCCESS(status) || !attached) {
IoDeleteDevice(filter);
continue;
}
filter->StackSize = lower->StackSize + 1;
filter->AlignmentRequirement = lower->AlignmentRequirement;
filter->DeviceExtension = attached;
filter->Flags &= ~DO_DEVICE_INITIALIZING;
g_MbrFilterTargets[g_MbrFilterCount++] = filter;
}
for (ULONG i = 0; i < done; ++i)
ObDereferenceObject(list[i]);
ExFreePool2(list, 'dskT', NULL, 0);
return STATUS_SUCCESS;
}
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
{
UNREFERENCED_PARAMETER(RegistryPath);
KeInitializeSpinLock(&g_ProtectLock);
ExInitializeFastMutex(&HookMutex);
KeInitializeEvent(&g_LogDrainEvent, NotificationEvent, TRUE);
g_Unloading = FALSE;
g_CmRegActive = FALSE;
InterlockedExchange(&g_LogWorkCount, 0);
ExInitializeRundownProtection(&g_Rundown);
{
UNICODE_STRING guardName = RTL_CONSTANT_STRING(L"\\Device\\PYAS_Driver_Guard");
NTSTATUS gs = IoCreateDevice(DriverObject, 0, &guardName, FILE_DEVICE_UNKNOWN, 0, FALSE, &g_GuardDevice);
if (!NT_SUCCESS(gs))
return STATUS_DEVICE_BUSY;
}
{
LARGE_INTEGER t = KeQueryPerformanceCounter(NULL);
g_DeviceName.Buffer = g_DeviceNameBuf;
g_DeviceName.MaximumLength = sizeof(g_DeviceNameBuf);
RtlStringCchPrintfW(g_DeviceName.Buffer, RTL_NUMBER_OF(g_DeviceNameBuf), L"\\Device\\PYAS_Driver_%p_%I64x", DriverObject, t.QuadPart);
g_DeviceName.Length = (USHORT)(wcslen(g_DeviceName.Buffer) * sizeof(WCHAR));
}
NTSTATUS status = IoCreateDevice(DriverObject, 0, &g_DeviceName, FILE_DEVICE_UNKNOWN, 0, FALSE, &g_ControlDeviceObject);
if (!NT_SUCCESS(status))
return status;
DriverObject->DriverUnload = DriverUnload;
for (ULONG i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; ++i)
DriverObject->MajorFunction[i] = CombinedDispatch;
g_ControlDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
IoDeleteSymbolicLink(&g_SymLink);
{
UINT i = 0;
for (; i < 50; ++i) {
status = IoCreateSymbolicLink(&g_SymLink, &g_DeviceName);
if (NT_SUCCESS(status))
break;
LARGE_INTEGER d = { 0 };
d.QuadPart = -10LL * 1000LL * 10LL;
KeDelayExecutionThread(KernelMode, FALSE, &d);
IoDeleteSymbolicLink(&g_SymLink);
}
if (!NT_SUCCESS(status)) {
IoDeleteDevice(g_ControlDeviceObject);
g_ControlDeviceObject = NULL;
if (g_GuardDevice) {
IoDeleteDevice(g_GuardDevice);
g_GuardDevice = NULL;
}
return status;
}
}
g_SymLinkCreated = TRUE;
{
static WCHAR regAltBuf[32];
static UNICODE_STRING regAlt;
LARGE_INTEGER t = KeQueryPerformanceCounter(NULL);
RtlStringCchPrintfW(regAltBuf, RTL_NUMBER_OF(regAltBuf), L"385100.%I64x", t.QuadPart);
RtlInitUnicodeString(&regAlt, regAltBuf);
status = CmRegisterCallbackEx(RegistryProtectCallback, &regAlt, DriverObject, NULL, &g_CmRegHandle, NULL);
if (NT_SUCCESS(status))
g_CmRegActive = TRUE;
}
InitImageProtect();
InitInjectProtect();
AttachDiskFilters(DriverObject);
return STATUS_SUCCESS;
}
VOID DriverUnload(PDRIVER_OBJECT DriverObject)
{
UNREFERENCED_PARAMETER(DriverObject);
g_Unloading = TRUE;
if (g_SymLinkCreated) {
IoDeleteSymbolicLink(&g_SymLink);
g_SymLinkCreated = FALSE;
}
if (g_CmRegActive) {
CmUnRegisterCallback(g_CmRegHandle);
g_CmRegActive = FALSE;
}
UninitInjectProtect();
UninitImageProtect();
ExWaitForRundownProtectionRelease(&g_Rundown);
if (InterlockedCompareExchange(&g_LogWorkCount, 0, 0) != 0) {
KeResetEvent(&g_LogDrainEvent);
while (InterlockedCompareExchange(&g_LogWorkCount, 0, 0) != 0)
KeWaitForSingleObject(&g_LogDrainEvent, Executive, KernelMode, FALSE, NULL);
}
for (ULONG i = 0; i < g_MbrFilterCount; ++i) {
if (g_MbrFilterTargets[i]) {
IoDetachDevice((PDEVICE_OBJECT)g_MbrFilterTargets[i]->DeviceExtension);
IoDeleteDevice(g_MbrFilterTargets[i]);
g_MbrFilterTargets[i] = NULL;
}
}
g_MbrFilterCount = 0;
if (DiskDrvObj) {
ObDereferenceObject(DiskDrvObj);
DiskDrvObj = NULL;
}
if (g_ControlDeviceObject) {
IoDeleteDevice(g_ControlDeviceObject);
g_ControlDeviceObject = NULL;
}
if (g_GuardDevice) {
IoDeleteDevice(g_GuardDevice);
g_GuardDevice = NULL;
}
}
+147
View File
@@ -0,0 +1,147 @@
#pragma once
#include <ntifs.h>
#include <ntstrsafe.h>
#include <ntdddisk.h>
#define PIPE_NAME L"\\??\\pipe\\PYAS_Output_Pipe"
#define MAX_MBR_TARGETS 52
#ifndef POOL_FLAG_NON_PAGED
#define POOL_FLAG_NON_PAGED 0x00000001
#endif
#ifndef PROCESS_CREATE_THREAD
#define PROCESS_CREATE_THREAD 0x0002
#endif
#ifndef PROCESS_VM_OPERATION
#define PROCESS_VM_OPERATION 0x0008
#endif
#ifndef PROCESS_VM_WRITE
#define PROCESS_VM_WRITE 0x0020
#endif
#ifndef PROCESS_VM_READ
#define PROCESS_VM_READ 0x0010
#endif
#ifndef PROCESS_DUP_HANDLE
#define PROCESS_DUP_HANDLE 0x0040
#endif
#ifndef PROCESS_CREATE_PROCESS
#define PROCESS_CREATE_PROCESS 0x0080
#endif
#ifndef PROCESS_SET_QUOTA
#define PROCESS_SET_QUOTA 0x0100
#endif
#ifndef PROCESS_SET_INFORMATION
#define PROCESS_SET_INFORMATION 0x0200
#endif
#ifndef PROCESS_SUSPEND_RESUME
#define PROCESS_SUSPEND_RESUME 0x0800
#endif
#ifndef PROCESS_QUERY_LIMITED_INFORMATION
#define PROCESS_QUERY_LIMITED_INFORMATION 0x1000
#endif
#ifndef PROCESS_SET_LIMITED_INFORMATION
#define PROCESS_SET_LIMITED_INFORMATION 0x2000
#endif
#ifndef THREAD_IMPERSONATE
#define THREAD_IMPERSONATE 0x0100
#endif
#ifndef THREAD_DIRECT_IMPERSONATION
#define THREAD_DIRECT_IMPERSONATION 0x0200
#endif
#ifndef UINT
typedef unsigned int UINT;
#endif
extern volatile LONG g_LogWorkCount;
extern BOOLEAN g_Unloading;
extern KEVENT g_LogDrainEvent;
extern PDEVICE_OBJECT g_MbrFilterTargets[MAX_MBR_TARGETS];
extern ULONG g_MbrFilterCount;
extern KSPIN_LOCK g_ProtectLock;
extern LARGE_INTEGER g_CmRegHandle;
extern POBJECT_TYPE* IoDriverObjectType;
extern FAST_MUTEX HookMutex;
extern PDRIVER_OBJECT DiskDrvObj;
extern PCSTR PsGetProcessImageFileName(PEPROCESS Process);
extern EX_RUNDOWN_REF g_Rundown;
extern PDEVICE_OBJECT g_GuardDevice;
typedef PVOID(NTAPI* _pyas_ExAllocatePool2)(ULONG, SIZE_T, ULONG);
typedef VOID(NTAPI* _pyas_ExFreePool2)(PVOID, ULONG, PVOID, ULONG);
typedef PVOID(NTAPI* _pyas_ExAllocatePoolWithTag)(POOL_TYPE, SIZE_T, ULONG);
typedef VOID(NTAPI* _pyas_ExFreePoolWithTag)(PVOID, ULONG);
static __forceinline PVOID PYAS_ExAllocatePool2(ULONG f, SIZE_T s, ULONG t) {
static _pyas_ExAllocatePool2 p2 = 0;
if (!p2) {
UNICODE_STRING n = RTL_CONSTANT_STRING(L"ExAllocatePool2");
p2 = (_pyas_ExAllocatePool2)MmGetSystemRoutineAddress(&n);
}
if (p2)
return p2(f, s, t);
static _pyas_ExAllocatePoolWithTag p1 = 0;
if (!p1) {
UNICODE_STRING n = RTL_CONSTANT_STRING(L"ExAllocatePoolWithTag");
p1 = (_pyas_ExAllocatePoolWithTag)MmGetSystemRoutineAddress(&n);
}
if (p1)
return p1((f & POOL_FLAG_NON_PAGED) ? NonPagedPoolNx : PagedPool, s, t);
return NULL;
}
static __forceinline VOID PYAS_ExFreePool2(PVOID a, ULONG t, PVOID h, ULONG f) {
UNREFERENCED_PARAMETER(h);
UNREFERENCED_PARAMETER(f);
static _pyas_ExFreePool2 p2 = 0;
if (!p2) {
UNICODE_STRING n = RTL_CONSTANT_STRING(L"ExFreePool2");
p2 = (_pyas_ExFreePool2)MmGetSystemRoutineAddress(&n);
}
if (p2) {
p2(a, t, h, f);
return;
}
static _pyas_ExFreePoolWithTag p1 = 0;
if (!p1) {
UNICODE_STRING n = RTL_CONSTANT_STRING(L"ExFreePoolWithTag");
p1 = (_pyas_ExFreePoolWithTag)MmGetSystemRoutineAddress(&n);
}
if (p1) {
p1(a, t);
return;
}
}
#define ExAllocatePool2 PYAS_ExAllocatePool2
#define ExFreePool2 PYAS_ExFreePool2
VOID DriverUnload(PDRIVER_OBJECT DriverObject);
VOID SendPipeLog(PCSTR msg, SIZE_T len);
VOID UninitImageProtect(VOID);
VOID UninitInjectProtect(VOID);
NTSYSAPI NTSTATUS NTAPI ZwQueryInformationProcess(
_In_ HANDLE ProcessHandle,
_In_ PROCESSINFOCLASS ProcessInformationClass,
_Out_writes_bytes_opt_(ProcessInformationLength) PVOID ProcessInformation,
_In_ ULONG ProcessInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSTATUS ObReferenceObjectByName(
IN PUNICODE_STRING ObjectName,
IN ULONG Attributes,
IN PACCESS_STATE PassedAccessState OPTIONAL,
IN ACCESS_MASK DesiredAccess OPTIONAL,
IN POBJECT_TYPE ObjectType,
IN KPROCESSOR_MODE AccessMode,
IN OUT PVOID ParseContext OPTIONAL,
OUT PVOID* Object
);
NTSTATUS FileProtectDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp);
NTSTATUS RegistryProtectCallback(PVOID ctx, PVOID arg1, PVOID arg2);
NTSTATUS InitImageProtect(VOID);
NTSTATUS InitInjectProtect(VOID);
BOOLEAN GetProcessImagePathByPid(HANDLE pid, PUNICODE_STRING ProcessImagePath);
+63
View File
@@ -0,0 +1,63 @@
#include <ntifs.h>
#include "DriverEntry.h"
extern PDEVICE_OBJECT g_ControlDeviceObject;
typedef struct _PIPE_LOG_CTX {
PIO_WORKITEM Item;
SIZE_T Len;
PCHAR Buf;
}PIPE_LOG_CTX, * PPIPE_LOG_CTX;
static VOID PipeLogWork(PDEVICE_OBJECT DeviceObject, PVOID Context)
{
UNREFERENCED_PARAMETER(DeviceObject);
PPIPE_LOG_CTX ctx = (PPIPE_LOG_CTX)Context;
HANDLE h = NULL;
UNICODE_STRING name;
OBJECT_ATTRIBUTES oa = { 0 };
IO_STATUS_BLOCK iosb;
RtlInitUnicodeString(&name, PIPE_NAME);
InitializeObjectAttributes(&oa, &name, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
if (NT_SUCCESS(ZwCreateFile(&h, FILE_GENERIC_WRITE, &oa, &iosb, NULL, 0, 0, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0)))
{
ZwWriteFile(h, NULL, NULL, NULL, &iosb, ctx->Buf, (ULONG)(ctx->Len > 0xFFFFFFFF ? 0xFFFFFFFF : ctx->Len), NULL, NULL);
ZwClose(h);
}
IoFreeWorkItem(ctx->Item);
ExFreePool2(ctx->Buf, 'golP', NULL, 0);
ExFreePool2(ctx, 'golP', NULL, 0);
if (InterlockedDecrement(&g_LogWorkCount) == 0 && g_Unloading)
KeSetEvent(&g_LogDrainEvent, IO_NO_INCREMENT, FALSE);
}
VOID SendPipeLog(PCSTR msg, SIZE_T len)
{
if (!msg || len == 0)
return;
if (!g_ControlDeviceObject)
return;
if (g_Unloading)
return;
PPIPE_LOG_CTX ctx = (PPIPE_LOG_CTX)ExAllocatePool2(POOL_FLAG_NON_PAGED, sizeof(PIPE_LOG_CTX), 'golP');
if (!ctx)
return;
ctx->Len = len;
ctx->Buf = (PCHAR)ExAllocatePool2(POOL_FLAG_NON_PAGED, ctx->Len, 'golP');
if (!ctx->Buf) {
ExFreePool2(ctx, 'golP', NULL, 0);
return;
}
RtlCopyMemory(ctx->Buf, msg, ctx->Len);
ctx->Item = IoAllocateWorkItem(g_ControlDeviceObject);
if (!ctx->Item) {
ExFreePool2(ctx->Buf, 'golP', NULL, 0);
ExFreePool2(ctx, 'golP', NULL, 0);
return;
}
InterlockedIncrement(&g_LogWorkCount);
IoQueueWorkItem(ctx->Item, PipeLogWork, DelayedWorkQueue, ctx);
}
+27
View File
@@ -0,0 +1,27 @@
[Version]
Signature = "$WINDOWS NT$"
Class = System
ClassGuid = {4d36e97d-e325-11ce-bfc1-08002be10318}
Provider = %ManufacturerName%
CatalogFile = PYAS_Driver.cat
PnpLockdown = 1
DriverVer =
[DestinationDirs]
DefaultDestDir = 13
[DefaultInstall.ntamd64]
CopyFiles = @PYAS_Driver.sys
AddService = PYAS_Driver,0x00000002
[SourceDisksFiles]
PYAS_Driver.sys = 1
[SourceDisksNames]
1 = %DiskName%,,,""
[Strings]
ManufacturerName = "PYAS_Driver"
DiskName = "PYAS_Driver"
ServiceName="PYAS_Driver"
ServiceDisplayName="PYAS_Driver"
Binary file not shown.
+123
View File
@@ -0,0 +1,123 @@
#include <ntifs.h>
#include "DriverEntry.h"
#include "ProtectRules.h"
PDEVICE_OBJECT g_MbrFilterTargets[MAX_MBR_TARGETS] = { 0 };
ULONG g_MbrFilterCount = 0;
NTSTATUS FileProtectDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
PDEVICE_OBJECT lower = (PDEVICE_OBJECT)DeviceObject->DeviceExtension;
if (!lower) {
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_INVALID_DEVICE_REQUEST;
}
if (!ExAcquireRundownProtection(&g_Rundown)) {
IoSkipCurrentIrpStackLocation(Irp);
return IoCallDriver(lower, Irp);
}
if (g_Unloading) {
IoSkipCurrentIrpStackLocation(Irp);
NTSTATUS st = IoCallDriver(lower, Irp);
ExReleaseRundownProtection(&g_Rundown);
return st;
}
PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);
if (stack->MajorFunction == IRP_MJ_POWER) {
PoStartNextPowerIrp(Irp);
IoSkipCurrentIrpStackLocation(Irp);
NTSTATUS st = PoCallDriver(lower, Irp);
ExReleaseRundownProtection(&g_Rundown);
return st;
}
HANDLE pid = PsGetCurrentProcessId();
ULONG currentPid = (ULONG)(ULONG_PTR)pid;
if (currentPid == 0 || currentPid == 4) {
IoSkipCurrentIrpStackLocation(Irp);
NTSTATUS st = IoCallDriver(lower, Irp);
ExReleaseRundownProtection(&g_Rundown);
return st;
}
BOOLEAN blocked = FALSE, is_white = FALSE;
CHAR logbuf[1024] = { 0 };
WCHAR exeBuf[512] = { 0 };
UNICODE_STRING exeName = { 0 };
exeName.Buffer = exeBuf;
exeName.MaximumLength = sizeof(exeBuf);
exeName.Length = 0;
if (KeGetCurrentIrql() == PASSIVE_LEVEL) {
if (GetProcessImagePathByPid(pid, &exeName))
is_white = IsWhitelist(&exeName);
else {
PEPROCESS eproc = PsGetCurrentProcess();
PCSTR n = PsGetProcessImageFileName(eproc);
size_t l = n ? strlen(n) : 0;
for (size_t i = 0; i < l && i < RTL_NUMBER_OF(exeBuf) - 1; i++)
exeBuf[i] = (WCHAR)n[i];
exeBuf[l] = 0;
exeName.Length = (USHORT)(l * sizeof(WCHAR));
}
}
if (!is_white) {
UCHAR mj = stack->MajorFunction;
BOOLEAN isDisk = (DeviceObject->DeviceType == FILE_DEVICE_DISK);
if (!isDisk) {
PDEVICE_OBJECT tdo = IoGetAttachedDeviceReference(lower);
if (tdo) {
isDisk = (tdo->DeviceType == FILE_DEVICE_DISK || tdo->DeviceType == FILE_DEVICE_DISK_FILE_SYSTEM);
ObDereferenceObject(tdo);
}
}
if (isDisk) {
if (mj == IRP_MJ_WRITE || mj == IRP_MJ_SET_INFORMATION || mj == IRP_MJ_DEVICE_CONTROL || mj == IRP_MJ_INTERNAL_DEVICE_CONTROL) blocked = TRUE;
}
}
if (blocked) {
if (KeGetCurrentIrql() == PASSIVE_LEVEL) {
CHAR target[64] = "None";
ULONG ret = 0;
POBJECT_NAME_INFORMATION oni = (POBJECT_NAME_INFORMATION)ExAllocatePool2(POOL_FLAG_NON_PAGED, 1024, 'nOmD');
if (oni && NT_SUCCESS(ObQueryNameString(lower, oni, 1024, &ret)) && oni->Name.Buffer && oni->Name.Length >= sizeof(WCHAR) * 2) {
USHORT len = oni->Name.Length / sizeof(WCHAR);
ULONG dr = 0;
BOOLEAN hasDr = FALSE;
for (USHORT i = 0; i + 2 < len; i++) {
if (oni->Name.Buffer[i] == L'D' && oni->Name.Buffer[i + 1] == L'R') {
USHORT j = i + 2;
ULONG x = 0;
while (j < len && oni->Name.Buffer[j] >= L'0' && oni->Name.Buffer[j] <= L'9') {
x = x * 10 + (oni->Name.Buffer[j] - L'0');
j++;
}
dr = x;
hasDr = TRUE;
break;
}
}
if (hasDr)
RtlStringCchPrintfA(target, sizeof(target), "Disk\\Device\\DR%u", dr);
}
if (oni)
ExFreePool2(oni, 'nOmD', NULL, 0);
RtlStringCchPrintfA(logbuf, sizeof(logbuf), "BOOT_BLOCK | %u | %wZ | %s", currentPid, &exeName, target);
SendPipeLog(logbuf, strlen(logbuf));
}
Irp->IoStatus.Status = STATUS_ACCESS_DENIED;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
ExReleaseRundownProtection(&g_Rundown);
return STATUS_ACCESS_DENIED;
}
IoSkipCurrentIrpStackLocation(Irp);
NTSTATUS st = IoCallDriver(lower, Irp);
ExReleaseRundownProtection(&g_Rundown);
return st;
}
+158
View File
@@ -0,0 +1,158 @@
#include <ntifs.h>
#include "DriverEntry.h"
#include "ProtectRules.h"
static BOOLEAN g_ImageNotifyEnabled = FALSE;
static BOOLEAN StrStrI(const wchar_t* s, const wchar_t* sub) {
if (!s || !sub)
return FALSE;
size_t n = wcslen(s), m = wcslen(sub);
if (m == 0 || n < m)
return FALSE;
for (size_t i = 0; i + m <= n; i++) {
size_t j = 0;
for (; j < m; j++) {
WCHAR a = s[i + j], b = sub[j];
if (a >= L'A' && a <= L'Z')
a += 32;
if (b >= L'A' && b <= L'Z')
b += 32;
if (a != b)
break;
}
if (j == m)
return TRUE;
}
return FALSE;
}
static BOOLEAN CheckStackVAD(PVOID a) {
MEMORY_BASIC_INFORMATION mbi = { 0 };
SIZE_T ret = 0;
NTSTATUS s = ZwQueryVirtualMemory(NtCurrentProcess(), a, MemoryBasicInformation, &mbi, sizeof(mbi), &ret);
if (!NT_SUCCESS(s))
return FALSE;
if (mbi.State != MEM_COMMIT)
return FALSE;
if (mbi.Type == SEC_IMAGE)
return FALSE;
if (mbi.Type != MEM_PRIVATE && mbi.Type != MEM_MAPPED)
return FALSE;
return (mbi.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)) != 0;
}
static BOOLEAN CheckShellcodeWalkStack(ULONG h) {
#define MAXWALK 20
PVOID frames[MAXWALK] = { 0 };
ULONG c = RtlWalkFrameChain(frames, MAXWALK, 1);
if (c == 0)
return FALSE;
ULONG limit = RTL_NUMBER_OF(frames);
ULONG count = c < limit ? c : limit;
ULONG d = h < count ? h : count;
for (ULONG i = 0; i < d; i++) {
PVOID p = frames[i];
if (p && CheckStackVAD(p))
return TRUE;
}
for (ULONG i = 0; i < d; i++) {
ULONG idx = count - 1 - i;
if (idx >= d) {
PVOID p = frames[idx];
if (p && CheckStackVAD(p))
return TRUE;
}
}
return FALSE;
}
static BOOLEAN IsFrameworkClrPath(const wchar_t* s) {
if (!s)
return FALSE;
if (!StrStrI(s, L"\\Windows\\Microsoft.NET\\"))
return FALSE;
if (!StrStrI(s, L"\\Framework\\") && !StrStrI(s, L"\\Framework64\\"))
return FALSE;
if (StrStrI(s, L"\\clr.dll") || StrStrI(s, L"\\mscorwks.dll"))
return TRUE;
return FALSE;
}
static VOID ImageLoadNotify(IN PUNICODE_STRING FullImageName, IN HANDLE ProcessId, IN PIMAGE_INFO ImageInfo)
{
UNREFERENCED_PARAMETER(ImageInfo);
if (g_Unloading)
return;
if (ProcessId == (HANDLE)0 || ProcessId == (HANDLE)4)
return;
if (KeGetCurrentIrql() != PASSIVE_LEVEL)
return;
if (!ExAcquireRundownProtection(&g_Rundown))
return;
WCHAR exeBuf[512] = { 0 };
UNICODE_STRING exeName = { 0 };
exeName.Buffer = exeBuf;
exeName.MaximumLength = sizeof(exeBuf);
exeName.Length = 0;
if (!GetProcessImagePathByPid(ProcessId, &exeName)) {
PEPROCESS eproc = PsGetCurrentProcess();
PCSTR n = PsGetProcessImageFileName(eproc);
size_t l = n ? strlen(n) : 0;
for (size_t i = 0; i < l && i < RTL_NUMBER_OF(exeBuf) - 1; i++)
exeBuf[i] = (WCHAR)n[i];
exeBuf[l] = 0;
exeName.Length = (USHORT)(l * sizeof(WCHAR));
}
if (exeName.Length & 1) exeName.Length--;
{
size_t elen = exeName.Length / sizeof(WCHAR);
if ((elen >= 14 && _wcsnicmp(exeName.Buffer + elen - 14, L"powershell.exe", 14) == 0) ||
(elen >= 8 && _wcsnicmp(exeName.Buffer + elen - 8, L"pwsh.exe", 8) == 0)) {
ExReleaseRundownProtection(&g_Rundown);
return;
}
}
if (IsWhitelist(&exeName)) {
ExReleaseRundownProtection(&g_Rundown);
return;
}
CHAR logbuf[1024] = { 0 };
if (FullImageName && FullImageName->Buffer) {
if ((StrStrI(FullImageName->Buffer, L"clr.dll") || StrStrI(FullImageName->Buffer, L"mscorwks.dll")) && !IsFrameworkClrPath(FullImageName->Buffer)) {
RtlStringCchPrintfA(logbuf, sizeof(logbuf), "CLR_BLOCK | %u | %wZ | %wZ", (ULONG)(ULONG_PTR)ProcessId, &exeName, FullImageName);
SendPipeLog(logbuf, strlen(logbuf));
ExReleaseRundownProtection(&g_Rundown);
return;
}
}
if (CheckShellcodeWalkStack(8)) {
RtlStringCchPrintfA(logbuf, sizeof(logbuf), "SHELLCODE_BLOCK | %u | %wZ | None", (ULONG)(ULONG_PTR)ProcessId, &exeName);
SendPipeLog(logbuf, strlen(logbuf));
ExReleaseRundownProtection(&g_Rundown);
return;
}
ExReleaseRundownProtection(&g_Rundown);
}
NTSTATUS InitImageProtect(VOID) {
NTSTATUS s = PsSetLoadImageNotifyRoutine(ImageLoadNotify);
if (NT_SUCCESS(s))
g_ImageNotifyEnabled = TRUE;
return s;
}
VOID UninitImageProtect(VOID) {
if (g_ImageNotifyEnabled) {
PsRemoveLoadImageNotifyRoutine(ImageLoadNotify);
g_ImageNotifyEnabled = FALSE;
}
}
+187
View File
@@ -0,0 +1,187 @@
#include <ntifs.h>
#include "DriverEntry.h"
#include "ProtectRules.h"
static PVOID g_ObRegHandle = NULL;
static POB_OPERATION_REGISTRATION g_ObOps = NULL;
static OB_CALLBACK_REGISTRATION g_ObReg = { 0 };
static OB_PREOP_CALLBACK_STATUS PreProcessCallback(PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION Info)
{
UNREFERENCED_PARAMETER(RegistrationContext);
if (g_Unloading)
return OB_PREOP_SUCCESS;
if (!Info || Info->KernelHandle)
return OB_PREOP_SUCCESS;
if (!Info->Object)
return OB_PREOP_SUCCESS;
if (Info->Operation != OB_OPERATION_HANDLE_CREATE && Info->Operation != OB_OPERATION_HANDLE_DUPLICATE)
return OB_PREOP_SUCCESS;
if (!ExAcquireRundownProtection(&g_Rundown))
return OB_PREOP_SUCCESS;
HANDLE cur = PsGetCurrentProcessId();
if (cur == (HANDLE)0 || cur == (HANDLE)4) {
ExReleaseRundownProtection(&g_Rundown);
return OB_PREOP_SUCCESS;
}
HANDLE target = PsGetProcessId((PEPROCESS)Info->Object);
if (target == cur) {
ExReleaseRundownProtection(&g_Rundown);
return OB_PREOP_SUCCESS;
}
ACCESS_MASK* desired = (Info->Operation == OB_OPERATION_HANDLE_CREATE) ? &Info->Parameters->CreateHandleInformation.DesiredAccess : &Info->Parameters->DuplicateHandleInformation.DesiredAccess;
ACCESS_MASK mask = PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE;
PCSTR tn = PsGetProcessImageFileName((PEPROCESS)Info->Object);
if (tn && (_stricmp(tn, "lsass.exe") == 0))
mask |= PROCESS_VM_READ;
if ((*desired & mask) == 0) {
ExReleaseRundownProtection(&g_Rundown);
return OB_PREOP_SUCCESS;
}
BOOLEAN logok = (KeGetCurrentIrql() == PASSIVE_LEVEL);
WCHAR cbuf[512] = { 0 }, tbuf[512] = { 0 };
UNICODE_STRING cexe = { 0 }, texe = { 0 };
cexe.Buffer = cbuf; cexe.MaximumLength = sizeof(cbuf);
texe.Buffer = tbuf; texe.MaximumLength = sizeof(tbuf);
if (logok)
GetProcessImagePathByPid(cur, &cexe);
if (logok && IsWhitelist(&cexe)) {
ExReleaseRundownProtection(&g_Rundown);
return OB_PREOP_SUCCESS;
}
ACCESS_MASK old = *desired;
*desired &= ~mask;
if ((*desired) != old && logok) {
GetProcessImagePathByPid(target, &texe);
if (cexe.Length == 0) {
PEPROCESS eproc = PsGetCurrentProcess();
PCSTR n = PsGetProcessImageFileName(eproc);
size_t l = n ? strlen(n) : 0;
for (size_t i = 0; i < l && i < RTL_NUMBER_OF(cbuf) - 1; i++)
cbuf[i] = (WCHAR)n[i];
cbuf[l] = 0;
cexe.Length = (USHORT)(l * sizeof(WCHAR));
}
CHAR logbuf[1024] = { 0 };
RtlStringCchPrintfA(logbuf, sizeof(logbuf), "INJECT_BLOCK | %u | %wZ | %wZ", (ULONG)(ULONG_PTR)cur, &cexe, &texe);
SendPipeLog(logbuf, strlen(logbuf));
}
ExReleaseRundownProtection(&g_Rundown);
return OB_PREOP_SUCCESS;
}
static OB_PREOP_CALLBACK_STATUS PreThreadCallback(PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION Info)
{
UNREFERENCED_PARAMETER(RegistrationContext);
if (!Info || Info->KernelHandle)
return OB_PREOP_SUCCESS;
if (Info->Object == NULL)
return OB_PREOP_SUCCESS;
if (Info->Operation != OB_OPERATION_HANDLE_CREATE && Info->Operation != OB_OPERATION_HANDLE_DUPLICATE)
return OB_PREOP_SUCCESS;
if (!ExAcquireRundownProtection(&g_Rundown))
return OB_PREOP_SUCCESS;
HANDLE cur = PsGetCurrentProcessId();
if (cur == (HANDLE)0 || cur == (HANDLE)4) {
ExReleaseRundownProtection(&g_Rundown);
return OB_PREOP_SUCCESS;
}
HANDLE owner = PsGetThreadProcessId((PETHREAD)Info->Object);
if (owner == cur) {
ExReleaseRundownProtection(&g_Rundown);
return OB_PREOP_SUCCESS;
}
ACCESS_MASK tmask = THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME | THREAD_IMPERSONATE | THREAD_DIRECT_IMPERSONATION;
ACCESS_MASK* desired = (Info->Operation == OB_OPERATION_HANDLE_CREATE) ? &Info->Parameters->CreateHandleInformation.DesiredAccess : &Info->Parameters->DuplicateHandleInformation.DesiredAccess;
if ((*desired & tmask) == 0) {
ExReleaseRundownProtection(&g_Rundown);
return OB_PREOP_SUCCESS;
}
BOOLEAN logok = (KeGetCurrentIrql() == PASSIVE_LEVEL);
WCHAR cbuf[512] = { 0 };
UNICODE_STRING cexe = { 0 };
cexe.Buffer = cbuf;
cexe.MaximumLength = sizeof(cbuf);
if (logok)
GetProcessImagePathByPid(cur, &cexe);
if (logok && IsWhitelist(&cexe)) {
ExReleaseRundownProtection(&g_Rundown);
return OB_PREOP_SUCCESS;
}
ACCESS_MASK old = *desired;
*desired &= ~tmask;
if ((*desired) != old && logok) {
CHAR logbuf[1024] = { 0 };
if (cexe.Length == 0) {
PEPROCESS eproc = PsGetCurrentProcess();
PCSTR n = PsGetProcessImageFileName(eproc);
size_t l = n ? strlen(n) : 0;
for (size_t i = 0; i < l && i < RTL_NUMBER_OF(cbuf) - 1; i++)
cbuf[i] = (WCHAR)n[i];
cbuf[l] = 0;
cexe.Length = (USHORT)(l * sizeof(WCHAR));
}
RtlStringCchPrintfA(logbuf, sizeof(logbuf), "THREAD_BLOCK | %u | %wZ | %u", (ULONG)(ULONG_PTR)cur, &cexe, (ULONG)(ULONG_PTR)owner);
SendPipeLog(logbuf, strlen(logbuf));
}
ExReleaseRundownProtection(&g_Rundown);
return OB_PREOP_SUCCESS;
}
NTSTATUS InitInjectProtect(VOID)
{
static WCHAR obAltBuf[32];
static UNICODE_STRING obAlt;
LARGE_INTEGER t = KeQueryPerformanceCounter(NULL);
RtlStringCchPrintfW(obAltBuf, RTL_NUMBER_OF(obAltBuf), L"385000.%I64x", t.QuadPart);
RtlInitUnicodeString(&obAlt, obAltBuf);
g_ObOps = (POB_OPERATION_REGISTRATION)ExAllocatePool2(POOL_FLAG_NON_PAGED, sizeof(OB_OPERATION_REGISTRATION) * 2, 'bOpr');
if (!g_ObOps)
return STATUS_INSUFFICIENT_RESOURCES;
RtlZeroMemory(g_ObOps, sizeof(OB_OPERATION_REGISTRATION) * 2);
g_ObOps[0].ObjectType = PsProcessType;
g_ObOps[0].Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE;
g_ObOps[0].PreOperation = PreProcessCallback;
g_ObOps[1].ObjectType = PsThreadType;
g_ObOps[1].Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE;
g_ObOps[1].PreOperation = PreThreadCallback;
RtlZeroMemory(&g_ObReg, sizeof(g_ObReg));
g_ObReg.Version = OB_FLT_REGISTRATION_VERSION;
g_ObReg.OperationRegistrationCount = 2;
g_ObReg.Altitude = obAlt;
g_ObReg.RegistrationContext = NULL;
g_ObReg.OperationRegistration = g_ObOps;
NTSTATUS s = ObRegisterCallbacks(&g_ObReg, &g_ObRegHandle);
if (!NT_SUCCESS(s)) {
ExFreePool2(g_ObOps, 'bOpr', NULL, 0);
g_ObOps = NULL;
RtlZeroMemory(&g_ObReg, sizeof(g_ObReg));
}
return s;
}
VOID UninitInjectProtect(VOID)
{
if (g_ObRegHandle) {
ObUnRegisterCallbacks(g_ObRegHandle);
g_ObRegHandle = NULL;
}
if (g_ObOps) {
ExFreePool2(g_ObOps, 'bOpr', NULL, 0);
g_ObOps = NULL;
}
RtlZeroMemory(&g_ObReg, sizeof(g_ObReg));
}
+119
View File
@@ -0,0 +1,119 @@
#include <ntifs.h>
#include "ProtectRules.h"
#include "DriverEntry.h"
static BOOLEAN QueryRegPathFromObject(PVOID KeyObject, PUNICODE_STRING OutPath, POBJECT_NAME_INFORMATION* OutInfo)
{
ULONG len = 0;
NTSTATUS s = ObQueryNameString(KeyObject, NULL, 0, &len);
if (s != STATUS_INFO_LENGTH_MISMATCH)
return FALSE;
POBJECT_NAME_INFORMATION p = (POBJECT_NAME_INFORMATION)ExAllocatePool2(POOL_FLAG_NON_PAGED, len, 'rgeR');
if (!p)
return FALSE;
s = ObQueryNameString(KeyObject, p, len, &len);
if (!NT_SUCCESS(s) || !p->Name.Buffer || p->Name.Length == 0) {
ExFreePool2(p, 'rgeR', NULL, 0);
return FALSE;
}
*OutInfo = p;
OutPath->Buffer = p->Name.Buffer;
OutPath->Length = p->Name.Length;
OutPath->MaximumLength = p->Name.Length;
return TRUE;
}
NTSTATUS RegistryProtectCallback(PVOID ctx, PVOID arg1, PVOID arg2)
{
UNREFERENCED_PARAMETER(ctx);
if (g_Unloading)
return STATUS_SUCCESS;
if (!ExAcquireRundownProtection(&g_Rundown))
return STATUS_SUCCESS;
REG_NOTIFY_CLASS type = (REG_NOTIFY_CLASS)(ULONG_PTR)arg1;
NTSTATUS status = STATUS_SUCCESS;
UNICODE_STRING checkReg = { 0 };
POBJECT_NAME_INFORMATION nameInfo = NULL;
UNICODE_STRING exe = { 0 };
WCHAR exeBuf[260] = { 0 };
exe.Buffer = exeBuf;
exe.MaximumLength = sizeof(exeBuf);
exe.Length = 0;
HANDLE pid = PsGetCurrentProcessId();
if (pid == (HANDLE)0 || pid == (HANDLE)4) {
ExReleaseRundownProtection(&g_Rundown);
return STATUS_SUCCESS;
}
PUNICODE_STRING valueName = NULL;
BOOLEAN need_log = FALSE;
CHAR logbuf[1024] = { 0 };
BOOLEAN canQuery = (KeGetCurrentIrql() == PASSIVE_LEVEL);
if (type == RegNtPreSetValueKey) {
PREG_SET_VALUE_KEY_INFORMATION s = (PREG_SET_VALUE_KEY_INFORMATION)arg2;
valueName = s->ValueName;
if (canQuery)
QueryRegPathFromObject(s->Object, &checkReg, &nameInfo);
}
else if (type == RegNtPreDeleteValueKey) {
PREG_DELETE_VALUE_KEY_INFORMATION d = (PREG_DELETE_VALUE_KEY_INFORMATION)arg2;
valueName = d->ValueName;
if (canQuery)
QueryRegPathFromObject(d->Object, &checkReg, &nameInfo);
}
else if (type == RegNtPreDeleteKey) {
PREG_DELETE_KEY_INFORMATION d = (PREG_DELETE_KEY_INFORMATION)arg2;
if (canQuery)
QueryRegPathFromObject(d->Object, &checkReg, &nameInfo);
}
else if (type == RegNtPreRenameKey) {
PREG_RENAME_KEY_INFORMATION r = (PREG_RENAME_KEY_INFORMATION)arg2;
if (canQuery)
QueryRegPathFromObject(r->Object, &checkReg, &nameInfo);
}
else if (type == RegNtPreCreateKeyEx) {
PREG_CREATE_KEY_INFORMATION c = (PREG_CREATE_KEY_INFORMATION)arg2;
if (c->CompleteName)
checkReg = *c->CompleteName;
}
else if (type == RegNtPreReplaceKey) {
PREG_REPLACE_KEY_INFORMATION rk = (PREG_REPLACE_KEY_INFORMATION)arg2;
if (canQuery)
QueryRegPathFromObject(rk->Object, &checkReg, &nameInfo);
}
else if (type == RegNtPreSaveKey) {
PREG_SAVE_KEY_INFORMATION sk = (PREG_SAVE_KEY_INFORMATION)arg2;
if (canQuery)
QueryRegPathFromObject(sk->Object, &checkReg, &nameInfo);
}
else if (type == RegNtPreRestoreKey) {
PREG_RESTORE_KEY_INFORMATION res = (PREG_RESTORE_KEY_INFORMATION)arg2;
if (canQuery)
QueryRegPathFromObject(res->Object, &checkReg, &nameInfo);
}
else if (type == RegNtPreLoadKey) {
PREG_LOAD_KEY_INFORMATION lk = (PREG_LOAD_KEY_INFORMATION)arg2;
if (lk->KeyName)
checkReg = *lk->KeyName;
}
if (checkReg.Buffer || (valueName && valueName->Buffer)) {
GetProcessImagePathByPid(pid, &exe);
if (IsRegistryBlock(&checkReg, valueName, &exe)) {
RtlStringCchPrintfA(logbuf, sizeof(logbuf), "REG_BLOCK | %u | %wZ | %wZ", (ULONG)(ULONG_PTR)pid, &exe, &checkReg);
need_log = TRUE;
status = STATUS_ACCESS_DENIED;
}
}
if (nameInfo)
ExFreePool2(nameInfo, 'rgeR', NULL, 0);
if (need_log)
SendPipeLog(logbuf, strlen(logbuf));
ExReleaseRundownProtection(&g_Rundown);
return status;
}
+391
View File
@@ -0,0 +1,391 @@
#include <ntifs.h>
#include "ProtectRules.h"
#include "DriverEntry.h"
wchar_t* g_Whitelist[] = {
L"\\Device\\HarddiskVolume*\\Windows\\**",
L"\\Device\\HarddiskVolume*\\Program*\\**",
L"\\Device\\HarddiskVolume*\\Users\\*\\AppData\\**",
L"**\\PYAS*.exe",
L"Registry",
L"vmmem*",
NULL
};
wchar_t* g_WhitelistExcept[] = {
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\vds.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\bcdedit.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\reg.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\cmd.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\mshta.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\wscript.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\cscript.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\schtasks.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\diskpart.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\format.com",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\mountvol.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\wbadmin.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\bcdboot.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\dism.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\bootsect.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\cipher.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\net.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\net1.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\msiexec.exe",
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\WindowsPowerShell\\*\\powershell.exe",
L"\\Device\\HarddiskVolume*\\Program*\\PowerShell\\*\\pwsh.exe",
NULL
};
wchar_t* g_AttachDisk[] = {
L"\\FileSystem\\Ntfs",
L"\\FileSystem\\Refs",
L"\\FileSystem\\Fastfat",
L"\\FileSystem\\exfat",
L"\\FileSystem\\Udfs",
NULL
};
wchar_t* g_BlockFile[] = {
L"\\DosDevices\\**",
L"\\Device\\Harddisk*\\Partition\\**",
L"\\Device\\HarddiskVolume*\\Boot\\**",
L"\\Device\\HarddiskVolume*\\EFI\\**",
L"\\Device\\HarddiskVolume*\\bootmgr",
L"\\Device\\HarddiskVolume*\\Recovery\\**",
L"\\Device\\HarddiskVolume*\\System Volume Information\\**",
L"\\Device\\HarddiskVolume*\\Windows\\**",
L"\\Device\\HarddiskVolume*\\ProgramData\\PYAS\\**",
L"\\Device\\HarddiskVolume*\\$*\\**",
L"**\\CON**",
L"**\\PRN**",
L"**\\AUX**",
L"**\\NUL**",
L"**\\COM*\\**",
L"**\\LPT*\\**",
L"**\\evil*.exe",
L"**\\OSDATA**",
NULL
};
wchar_t* g_BlockRansom[] = {
L"\\Device\\HarddiskVolume*\\Users\\*\\Desktop\\**",
L"\\Device\\HarddiskVolume*\\Users\\*\\Downloads\\**",
L"\\Device\\HarddiskVolume*\\Users\\*\\Documents\\**",
L"\\Device\\HarddiskVolume*\\Users\\*\\Music\\**",
L"\\Device\\HarddiskVolume*\\Users\\*\\Pictures\\**",
L"\\Device\\HarddiskVolume*\\Users\\*\\Videos\\**",
NULL
};
wchar_t* g_BlockReg[] = {
L"\\REGISTRY\\MACHINE\\BCD00000000\\**",
L"\\REGISTRY\\MACHINE\\SAM\\**",
L"\\REGISTRY\\MACHINE\\SECURITY\\**",
L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control\\**",
L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Enum\\**",
L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\**",
L"\\REGISTRY\\MACHINE\\SYSTEM\\MountedDevices\\**",
L"\\REGISTRY\\MACHINE\\SYSTEM\\Setup\\**",
L"\\REGISTRY\\MACHINE\\SOFTWARE\\Classes\\**",
L"\\REGISTRY\\MACHINE\\SOFTWARE\\Policies\\Microsoft\\MMC\\**",
L"\\REGISTRY\\MACHINE\\SOFTWARE\\Policies\\Microsoft\\Windows\\System\\**",
L"\\REGISTRY\\MACHINE\\SOFTWARE\\Wow6432Node\\**",
L"\\REGISTRY\\MACHINE\\**\\Microsoft\\Windows Defender\\**",
L"\\REGISTRY\\**\\SOFTWARE\\Microsoft\\Active Setup\\Installed Components\\*\\StubPath",
L"\\REGISTRY\\**\\SOFTWARE\\Microsoft\\Windows*\\CurrentVersion\\**",
L"\\REGISTRY\\**\\SOFTWARE\\Microsoft\\Windows Script Host\\Settings\\**",
L"\\REGISTRY\\USER\\*_Classes\\*\\shell\\open\\command\\**",
L"\\REGISTRY\\USER\\*_Classes\\CLSID\\{fdb00e52-a214-4aa1-8fba-4357bb0072ec}\\**",
L"\\REGISTRY\\USER\\S-1-*\\SOFTWARE\\NetWire\\**",
L"\\REGISTRY\\USER\\S-1-*\\SOFTWARE\\Remcos*\\**",
L"\\REGISTRY\\USER\\S-1-*\\SOFTWARE\\DC3_FEXEC\\**",
L"DisableAntiSpyware",
L"DisableWindowsUpdateAccess",
L"EnableLUA",
L"ConsentPromptBehaviorAdmin",
L"NoControlPanel",
L"NoDrives",
L"NoFileMenu",
L"NoFind",
L"NoStartMenuPinnedList",
L"NoSetFolders",
L"NoSetFolderOptions",
L"NoViewOnDrive",
L"NoClose",
L"NoDesktop",
L"NoLogoff",
L"NoFolderOptions",
L"RestrictRun",
L"NoViewContextMenu",
L"HideClock",
L"NoStartMenuMyGames",
L"NoStartMenuMyMusic",
L"DisableCMD",
L"NoAddingComponents",
L"NoWinKeys",
L"NoStartMenuLogOff",
L"NoSimpleNetIDList",
L"NoLowDiskSpaceChecks",
L"DisableLockWorkstation",
L"Restrict_Run",
L"DisableTaskMgr",
L"DisableRegistryTools",
L"DisableChangePassword",
L"Wallpaper",
L"NoComponents",
L"NoStartMenuMorePrograms",
L"NoActiveDesktop",
L"NoSetActiveDesktop",
L"NoRecentDocsMenu",
L"NoWindowsUpdate",
L"NoChangeStartMenu",
L"NoFavoritesMenu",
L"NoRecentDocsHistory",
L"NoSetTaskbar",
L"NoSMHelp",
L"NoTrayContextMenu",
L"NoManageMyComputerVerb",
L"NoRealMode",
L"NoRun",
L"ClearRecentDocsOnExit",
L"NoActiveDesktopChanges",
L"NoStartMenuNetworkPlaces",
L"NoLockScreen",
L"HideFastUserSwitching",
L"ConsentPromptBehaviorUser",
L"EnableSecureUIAPaths",
L"NoSRM",
L"NoInteractiveServices",
L"ShutdownWithoutLogon",
L"AutoAdminLogon",
L"ImagePath",
L"BootExecute",
L"SubSystems",
L"FirmwareBootDevice",
L"BootDriverFlags",
L"SystemStartOptions",
L"CrashDumpEnabled",
L"DisableAutomaticRestartOnFailure",
L"SystemBiosVersion",
L"NoTheme",
L"PendingFileRenameOperations",
L"SystemSetupInProgress",
L"CmdLine",
L"SetupType",
L"AutoReboot",
L"Shell",
L"Userinit",
L"UIHost",
L"Debugger",
L"DefaultUserName",
L"DefaultPassword",
L"AltDefaultUserName",
L"AltDefaultPassword",
L"DisableCAD",
L"LegalNoticeCaption",
L"LegalNoticeText",
NULL
};
static BOOLEAN WildMatchN(const wchar_t* str, SIZE_T n, const wchar_t* pat)
{
if (*pat == 0)
return n == 0;
if (*pat == L'*') {
if (pat[1] == L'*') {
for (SIZE_T i = 0; i <= n; ++i)
if (WildMatchN(str + i, n - i, pat + 2))
return TRUE;
return FALSE;
}
SIZE_T i = 0;
for (; i < n && str[i] != L'\\'; ++i)
if (WildMatchN(str + i, n - i, pat + 1))
return TRUE;
return WildMatchN(str + i, n - i, pat + 1);
}
if (*pat == L'?')
return n > 0 && str[0] != L'\\' && WildMatchN(str + 1, n - 1, pat + 1);
if (n == 0)
return FALSE;
WCHAR sc = str[0], pc = *pat;
if (sc >= L'A' && sc <= L'Z')
sc += 32;
if (pc >= L'A' && pc <= L'Z')
pc += 32;
return sc == pc && WildMatchN(str + 1, n - 1, pat + 1);
}
static BOOLEAN MatchList(PUNICODE_STRING s, wchar_t** list)
{
if (!s || !s->Buffer || s->Length == 0)
return FALSE;
size_t s_len = s->Length / sizeof(WCHAR);
for (SIZE_T i = 0; list[i]; ++i) {
wchar_t* pat = list[i];
size_t pat_len = wcslen(pat);
if (wcschr(pat, L'*') || wcschr(pat, L'?')) {
if (WildMatchN(s->Buffer, s_len, pat))
return TRUE;
}
else {
if (s_len == pat_len && _wcsnicmp(s->Buffer, pat, pat_len) == 0)
return TRUE;
if (s_len > pat_len && _wcsnicmp(s->Buffer + s_len - pat_len, pat, pat_len) == 0)
return TRUE;
if (s_len > pat_len && _wcsnicmp(s->Buffer, pat, pat_len) == 0)
return TRUE;
}
}
return FALSE;
}
static wchar_t* MatchListGetRule(PUNICODE_STRING s, wchar_t** list)
{
if (!s || !s->Buffer || s->Length == 0)
return 0;
size_t s_len = s->Length / sizeof(WCHAR);
for (SIZE_T i = 0; list[i]; ++i) {
wchar_t* pat = list[i];
size_t pat_len = wcslen(pat);
if (wcschr(pat, L'*') || wcschr(pat, L'?')) {
if (WildMatchN(s->Buffer, s_len, pat))
return pat;
}
else {
if (s_len == pat_len && _wcsnicmp(s->Buffer, pat, pat_len) == 0)
return pat;
if (s_len > pat_len && _wcsnicmp(s->Buffer + s_len - pat_len, pat, pat_len) == 0)
return pat;
if (s_len > pat_len && _wcsnicmp(s->Buffer, pat, pat_len) == 0)
return pat;
}
}
return 0;
}
static __forceinline BOOLEAN USOK(PUNICODE_STRING s)
{
return s && s->Buffer && s->Length;
}
BOOLEAN IsRegistryBlock(PUNICODE_STRING key, PUNICODE_STRING valueName, PUNICODE_STRING exe)
{
if (USOK(exe)) {
if (IsWhitelist(exe))
return FALSE;
}
if (USOK(exe) && USOK(key)) {
size_t elen = exe->Length / sizeof(WCHAR);
size_t klen = key->Length / sizeof(WCHAR);
if (((elen >= 12 && _wcsnicmp(exe->Buffer + elen - 12, L"services.exe", 12) == 0) ||
(elen >= 11 && _wcsnicmp(exe->Buffer + elen - 11, L"svchost.exe", 11) == 0) ||
(elen >= 6 && _wcsnicmp(exe->Buffer + elen - 6, L"sc.exe", 6) == 0))) {
if (WildMatchN(key->Buffer, klen, L"\\REGISTRY\\**\\SYSTEM\\CurrentControlSet\\Services\\**"))
return FALSE;
}
if ((elen >= 14 && _wcsnicmp(exe->Buffer + elen - 14, L"powershell.exe", 14) == 0) ||
(elen >= 8 && _wcsnicmp(exe->Buffer + elen - 8, L"pwsh.exe", 8) == 0)) {
if (WildMatchN(key->Buffer, klen, L"\\REGISTRY\\**\\CurrentVersion\\Internet Settings\\ZoneMap") ||
WildMatchN(key->Buffer, klen, L"\\REGISTRY\\**\\CurrentVersion\\Internet Settings\\ZoneMap\\**"))
return FALSE;
}
if ((elen >= 11 && _wcsnicmp(exe->Buffer + elen - 11, L"msiexec.exe", 11) == 0) ||
(elen >= 20 && _wcsnicmp(exe->Buffer + elen - 20, L"TrustedInstaller.exe", 20) == 0)) {
if (WildMatchN(key->Buffer, klen, L"\\REGISTRY\\**\\CurrentVersion\\Installer\\**") ||
WildMatchN(key->Buffer, klen, L"\\REGISTRY\\**\\CurrentVersion\\Uninstall\\**") ||
WildMatchN(key->Buffer, klen, L"\\REGISTRY\\**\\SYSTEM\\CurrentControlSet\\Services\\**"))
return FALSE;
}
if (elen >= 12 && _wcsnicmp(exe->Buffer + elen - 12, L"schtasks.exe", 12) == 0) {
if (WildMatchN(key->Buffer, klen, L"\\REGISTRY\\**\\Windows NT\\CurrentVersion\\Schedule\\TaskCache\\**"))
return FALSE;
}
}
if (USOK(key)) {
if (MatchBlockReg(key))
return TRUE;
}
if (USOK(valueName)) {
SIZE_T n = valueName->Length / sizeof(WCHAR);
for (SIZE_T i = 0; g_BlockReg[i]; ++i) {
wchar_t* pat = g_BlockReg[i];
if (wcschr(pat, L'\\') || wcschr(pat, L'*') || wcschr(pat, L'?'))
continue;
size_t m = wcslen(pat);
if (n == m && _wcsnicmp(valueName->Buffer, pat, m) == 0)
return TRUE;
}
}
return FALSE;
}
BOOLEAN GetProcessImagePathByPid(HANDLE pid, PUNICODE_STRING ProcessImagePath)
{
PEPROCESS process = NULL;
NTSTATUS status = PsLookupProcessByProcessId(pid, &process);
if (!NT_SUCCESS(status))
return FALSE;
HANDLE h = NULL;
status = ObOpenObjectByPointer(process, OBJ_KERNEL_HANDLE, NULL, PROCESS_QUERY_LIMITED_INFORMATION, *PsProcessType, KernelMode, &h);
if (!NT_SUCCESS(status)) {
ObDereferenceObject(process);
return FALSE;
}
ULONG len = 0;
status = ZwQueryInformationProcess(h, ProcessImageFileName, NULL, 0, &len);
if (status != STATUS_INFO_LENGTH_MISMATCH || len == 0) {
ZwClose(h);
ObDereferenceObject(process);
return FALSE;
}
PVOID buf = ExAllocatePool2(POOL_FLAG_NON_PAGED, len, 'iPgN');
if (!buf) {
ZwClose(h);
ObDereferenceObject(process);
return FALSE;
}
status = ZwQueryInformationProcess(h, ProcessImageFileName, buf, len, &len);
if (NT_SUCCESS(status)) {
PUNICODE_STRING image = (PUNICODE_STRING)buf;
if (image->Buffer && image->Length > 0 && ProcessImagePath->MaximumLength >= image->Length + sizeof(WCHAR)) {
RtlCopyMemory(ProcessImagePath->Buffer, image->Buffer, image->Length);
ProcessImagePath->Length = image->Length;
ProcessImagePath->Buffer[image->Length / sizeof(WCHAR)] = 0;
ExFreePool2(buf, 'iPgN', NULL, 0);
ZwClose(h);
ObDereferenceObject(process);
return TRUE;
}
}
ExFreePool2(buf, 'iPgN', NULL, 0);
ZwClose(h);
ObDereferenceObject(process);
return FALSE;
}
BOOLEAN IsWhitelist(PUNICODE_STRING s)
{
if (MatchList(s, g_WhitelistExcept))
return FALSE;
return MatchList(s, g_Whitelist);
}
BOOLEAN MatchBlockReg(PUNICODE_STRING s)
{
return MatchList(s, g_BlockReg);
}
wchar_t* GetMatchedBlockRegRule(PUNICODE_STRING s)
{
return MatchListGetRule(s, g_BlockReg);
}
+8
View File
@@ -0,0 +1,8 @@
#pragma once
#include <ntifs.h>
wchar_t* GetMatchedBlockRegRule(PUNICODE_STRING s);
BOOLEAN MatchBlockReg(PUNICODE_STRING s);
BOOLEAN IsWhitelist(PUNICODE_STRING s);
BOOLEAN GetProcessImagePathByPid(HANDLE pid, PUNICODE_STRING ProcessImagePath);
BOOLEAN IsRegistryBlock(PUNICODE_STRING key, PUNICODE_STRING valueName, PUNICODE_STRING exe);
+37 -18
View File
@@ -1,8 +1,8 @@
# PYAS
Python antivirus software uses deep learning and behavioral monitoring to block threats!
Antivirus software written in Python and C that blocks threats through deep learning and behavioral monitoring!
![PYAS_UI](https://github.com/user-attachments/assets/68765836-7272-482f-b8cd-d8ba728d88ab)
<img width="2245" height="1477" alt="PYAS_UI" src="https://github.com/user-attachments/assets/87d40261-7655-49ad-a19c-1ffcca60584f" />
## Readme Language
@@ -34,32 +34,51 @@ The following lists the storage locations of all relevant code and other related
```
PYAS/
├── Engine/
│ ├── Models/ # Directory for ONNX AI models
│ └── Rules/ # Directory for YARA and network rules
│ ├── Models/
│ │ ├── convert.py # Convert executable files or other files to images
│ │ └── train.py # TensorFlow CNN model training complete code
│ │
│ └── Rules/
│ ├── rules.yar # Yara virus signature rule matching
│ └── rules.ips # IP network address rule matching
│
├── Plugins/
│ └── Filter/ # Windows kernel driver for security protection
│ └── Filter/
│ ├── DriverEntry.c # Main driver entry and initialization logic
│ ├── DriverEntry.h # Global driver definitions, constants, and functions
│ ├── DriverPipe.c # Kernel to user pipe logging implementation
│ ├── ProtectBoot.c # Disk boot sector write protection
│ ├── ProtectImage.c # Image load monitoring and shellcode detection
│ ├── ProtectInject.c # Process thread handle access control to prevent injection
│ ├── ProtectReg.c # Registry modification protection
│ ├── ProtectRules.c # White, block list, and matching logic for files registry
│ └── ProtectRules.h # Protection rule declarations
│
├── PYAS.py # Main application and GUI interface
├── PYAS_Config.py # Configuration handling and global parameters
├── PYAS_Engine.py # YARA and ONNX Scanning engine
├── PYAS_Interface.py # User interface definitions and widget logic
├── PYAS_Resource.py # Static picture resource management
├── PYAS_Version.py # Packaging and version info
└── ... # Other supplementary folders and files
├── PYAS.py # Main application entry point and UI to engine interface
├── PYAS_Config.py # Configuration loading, saving, and global parameters
├── PYAS_Engine.py # Core scanning engine: YARA, IP, ONNX model execution
├── PYAS_Interface.py # User interface components and event handling
├── PYAS_Resource.py # Static image and icon resource management
├── PYAS_Version.py # Version metadata for packaging and updates
└── ... # Other supplementary folders and files
```
## Program Architecture
PYAS antivirus software complete program flow architecture diagram.
<img width="23000" height="6000" alt="PYAS_Architecture" src="https://github.com/user-attachments/assets/3a7ce637-c2b3-4719-9658-07f286cfa879" />
## Packaged Releases
Packaged Releases Download: https://github.com/87owo/PYAS/releases
## Support System
| Config | Permissions | System version | Available memory | Available storage |
|-----------|---------------|----------------|------------------|-------------------|
| Minimum | Administrator | Windows 10 | 200MB | 100MB |
| Recommend | Administrator | Windows 10 | 300MB | 200MB |
| Optimal | Administrator | Windows 11 | 500MB | 200MB |
| Config | Permissions | System version | Processor | Memory | Storage |
|-----------|---------------|----------------------|-----------|--------|---------|
| Minimum | Administrator | >= Windows 10 (20H1) | 1 GHz | 200MB | 100MB |
| Recommend | Administrator | >= Windows 10 (21H2) | 3 GHz | 500MB | 200MB |
## Official Website
@@ -69,4 +88,4 @@ Open Source Website : https://github.com/87owo/PYAS
## Project License
https://github.com/87owo/PYAS/blob/main/LICENSE.md
https://github.com/87owo/PYAS/blob/main/LICENSE.txt
+37 -18
View File
@@ -1,8 +1,8 @@
# PYAS
以 Python 开发的杀毒软件,结合深度学习与行为监控来阻挡威胁!
使用 Python 和 C 编写的杀毒软件,并通过深度学习和行为监控阻止威胁!
![PYAS_UI](https://github.com/user-attachments/assets/68765836-7272-482f-b8cd-d8ba728d88ab)
<img width="2245" height="1477" alt="PYAS_UI" src="https://github.com/user-attachments/assets/87d40261-7655-49ad-a19c-1ffcca60584f" />
## 说明语言
@@ -34,32 +34,51 @@ pip install yara-python==4.5.4
```
PYAS/
├── Engine/
│ ├── Models/ # ONNX 深度学习模型目录
│ └── Rules/ # YARA 与网络规则目录
│ ├── Models/
│ │ ├── convert.py # 将可执行文件或其他文件转换为图片
│ │ └── train.py # TensorFlow CNN 模型训练完整代码
│ │
│ └── Rules/
│ ├── rules.yar # YARA 病毒特征码规则匹配
│ └── rules.ips # IP 网络地址规则匹配
│
├── Plugins/
│ └── Filter/ # 用于安全防护的 Windows 核心驱动
│ └── Filter/
│ ├── DriverEntry.c # 驱动主入口与初始化逻辑
│ ├── DriverEntry.h # 全局驱动定义、常量与函数
│ ├── DriverPipe.c # 内核与用户层的管道日志传输实现
│ ├── ProtectBoot.c # 磁盘引导区写入保护
│ ├── ProtectImage.c # 映像加载监控与 shellcode 检测
│ ├── ProtectInject.c # 进程与线程控制,防止注入
│ ├── ProtectReg.c # 注册表修改保护
│ ├── ProtectRules.c # 白名单、阻止名单与文件/注册表匹配逻辑
│ └── ProtectRules.h # 保护规则声明
│
├── PYAS.py # 主程式与图形界面 (GUI)
├── PYAS_Config.py # 组态处理与全域参数
├── PYAS_Engine.py # YARA 与 ONNX 扫描引擎
├── PYAS_Interface.py # 使用者介面定义与元件逻辑
├── PYAS_Resource.py # 静态图片资源管理
├── PYAS_Version.py # 打包与版本资讯
└── ... # 其他补充文件夹与文件
├── PYAS.py # 主应用程序入口点与 UI 到引擎的接口
├── PYAS_Config.py # 配置加载、保存与全局参数
├── PYAS_Engine.py # 核心扫描引擎:YARA、IP、ONNX 模型执行
├── PYAS_Interface.py # 用户界面组件与事件处理
├── PYAS_Resource.py # 静态图片与图标资源管理
├── PYAS_Version.py # 版本元数据,用于打包与更新
└── ... # 其他补充文件夹与文件
```
## 代码架构
PYAS 杀毒软件完整代码流程架构图。
<img width="23000" height="6000" alt="PYAS_Architecture" src="https://github.com/user-attachments/assets/3a7ce637-c2b3-4719-9658-07f286cfa879" />
## 安装版本
打包发行版下载:https://github.com/87owo/PYAS/releases
## 系统需求
| 配置需求 | 权限需求 | 系统需求 | 可用內存 | 可用储存空间 |
| ---- | ------- | ----------- | ----- | ------ |
| 最低 | 系统管理员 | Windows 10 | 200MB | 100MB |
| 建议 | 系统管理员 | Windows 10 | 300MB | 200MB |
| 最佳 | 系统管理员 | Windows 11 | 500MB | 200MB |
| 配置要求 | 权限 | 系统版本 | 处理器 | 可用内存空间 | 可用存储空间 |
| ------- | ----- | ------ | ----- | ------------ | ---------- |
| 最低配置 | 管理员 | >= Windows 10 (20H1) | 1 GHz | 200MB | 100MB |
| 推荐配置 | 管理员 | >= Windows 10 (21H2) | 3 GHz | 300MB | 200MB |
## 官方网站
@@ -69,4 +88,4 @@ PYAS/
## 授权条款
https://github.com/87owo/PYAS/blob/main/LICENSE.md
https://github.com/87owo/PYAS/blob/main/LICENSE.txt
+38 -19
View File
@@ -1,8 +1,8 @@
# PYAS
以 Python 開發的防毒軟體,結合深度學習與行為監控來阻擋威脅!
使用 Python 和 C 開發的防毒軟體,並透過深度學習和行為監控來阻止威脅!
![PYAS_UI](https://github.com/user-attachments/assets/68765836-7272-482f-b8cd-d8ba728d88ab)
<img width="2245" height="1477" alt="PYAS_UI" src="https://github.com/user-attachments/assets/87d40261-7655-49ad-a19c-1ffcca60584f" />
## 說明語言
@@ -34,32 +34,51 @@ pip install yara-python==4.5.4
```
PYAS/
├── Engine/
│ ├── Models/ # ONNX 深度學習模型目錄
│ └── Rules/ # YARA 與網路規則目錄
│ ├── Models/
│ │ ├── convert.py # 將可執行檔或其他檔案轉換為圖片
│ │ └── train.py # TensorFlow CNN 模型訓練完整程式碼
│ │
│ └── Rules/
│ ├── rules.yar # YARA 病毒特徵碼規則匹配
│ └── rules.ips # IP 網路位址規則匹配
│
├── Plugins/
│ └── Filter/ # 用於安全防護的 Windows 核心驅動程式
│ └── Filter/
│ ├── DriverEntry.c # 驅動主入口與初始化邏輯
│ ├── DriverEntry.h # 全域驅動定義、常數與函式
│ ├── DriverPipe.c # 核心層與使用者層的管道日誌傳輸實作
│ ├── ProtectBoot.c # 磁碟開機區寫入保護
│ ├── ProtectImage.c # 映像載入監控與 shellcode 偵測
│ ├── ProtectInject.c # 程序與執行緒控制,防止注入
│ ├── ProtectReg.c # 登錄檔修改保護
│ ├── ProtectRules.c # 白名單、封鎖清單與檔案/登錄匹配邏輯
│ └── ProtectRules.h # 保護規則宣告
│
├── PYAS.py # 主程式與圖形介面 (GUI)
├── PYAS_Config.py # 組態處理與全域參數
├── PYAS_Engine.py # YARA 與 ONNX 掃描引擎
├── PYAS_Interface.py # 使用者介面定義與元件邏輯
├── PYAS_Resource.py # 靜態圖片資源管理
├── PYAS_Version.py # 打包與版本資訊
└── ... # 其他補充資料夾與檔案
├── PYAS.py # 主應用程式入口點與 UI 到引擎的介面
├── PYAS_Config.py # 組態載入、儲存與全域參數
├── PYAS_Engine.py # 核心掃描引擎:YARA、IP、ONNX 模型執行
├── PYAS_Interface.py # 使用者介面元件與事件處理
├── PYAS_Resource.py # 靜態圖片與圖示資源管理
├── PYAS_Version.py # 版本中繼資料,用於打包與更新
└── ... # 其他補充資料夾與檔案
```
## 程式架構
PYAS 防毒軟體完整程式流程架構圖。
<img width="23000" height="6000" alt="PYAS_Architecture" src="https://github.com/user-attachments/assets/3a7ce637-c2b3-4719-9658-07f286cfa879" />
## 安裝版本
打包發行版下載:https://github.com/87owo/PYAS/releases
打包發行版下載 : https://github.com/87owo/PYAS/releases
## 系統需求
| 配置需求 | 權限需求 | 系統需求 | 可用記憶體 | 可用儲存空間 |
| ---- | ------- | ----------- | ----- | ------ |
| 最低 | 系統管理員 | Windows 10 | 200MB | 100MB |
| 建議 | 系統管理員 | Windows 10 | 300MB | 200MB |
| 最佳 | 系統管理員 | Windows 11 | 500MB | 200MB |
| 配置要求 | 權限 | 系統版本 | 處理器 | 可用記憶體空間 | 可用儲存空間 |
| ------- | ---- | ------- | ------ | ------------ | ----------- |
| 最低配置 | 管理員 | >= Windows 10 (20H1) | 1 GHz | 200MB | 100MB |
| 推薦配置 | 管理員 | >= Windows 10 (21H2) | 3 GHz | 300MB | 200MB |
## 官方網站
@@ -69,4 +88,4 @@ PYAS/
## 授權條款
https://github.com/87owo/PYAS/blob/main/LICENSE.md
https://github.com/87owo/PYAS/blob/main/LICENSE.txt