Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
949f74ab04 | ||
|
|
ef68a89b45 | ||
|
|
10ecb35cca | ||
|
|
696ac22f77 | ||
|
|
8d13f98030 | ||
|
|
1dddf13a9d | ||
|
|
855472239a | ||
|
|
dc5d317623 | ||
|
|
91011e9e2a | ||
|
|
bb09b75d3b | ||
|
|
b2f9adad66 | ||
|
|
0c2c84d2a9 | ||
|
|
1733e7cc86 | ||
|
|
831d9a9895 | ||
|
|
70ba3a629d | ||
|
|
29e9702d21 | ||
|
|
f8ef756bd4 | ||
|
|
233b28e8a5 | ||
|
|
da77c17be5 | ||
|
|
8dfa76822e | ||
|
|
4163991b66 | ||
|
|
78323c9a08 | ||
|
|
eb517e86f3 | ||
|
|
e24f3823cb | ||
|
|
fd3e8ee28a | ||
|
|
a980ea7bd6 | ||
|
|
20ce73c54f | ||
|
|
d8f22f7f28 | ||
|
|
591055edaf | ||
|
|
fbf0e06c04 | ||
|
|
9daf327e80 | ||
|
|
4441978e10 | ||
|
|
d8eb770735 | ||
|
|
cefbf79c6e | ||
|
|
fc8762094e | ||
|
|
801c3aadcc | ||
|
|
4296f1ec43 | ||
|
|
a7f469747c | ||
|
|
68d0352343 | ||
|
|
01e6d09f7c | ||
|
|
6582abfd4a | ||
|
|
f8f4b303d7 | ||
|
|
79f05a23a8 | ||
|
|
95845c5c85 | ||
|
|
cd1a24290e | ||
|
|
21261bfb17 | ||
|
|
79abf51cb8 | ||
|
|
e538b837d5 | ||
|
|
7b995e1223 | ||
|
|
c7826b58a3 | ||
|
|
5786dbdb75 | ||
|
|
0f42c19ec7 | ||
|
|
87d44a64f3 | ||
|
|
77dd4ace33 | ||
|
|
0907d71957 | ||
|
|
e7a30646e3 | ||
|
|
98d21b3391 | ||
|
|
35d9203b9c | ||
|
|
e6e384a7f7 | ||
|
|
7d954c14ae | ||
|
|
41388962e2 | ||
|
|
6d51f6b6a9 | ||
|
|
c7af9a3702 | ||
|
|
da7c61202c | ||
|
|
c24e872a33 | ||
|
|
d0809ec313 | ||
|
|
c1a796da38 | ||
|
|
98c27800e0 | ||
|
|
7a18eadd13 | ||
|
|
b07adb7b30 | ||
|
|
4d7c3cce4d | ||
|
|
4ff0ab9cd8 | ||
|
|
264dd50969 | ||
|
|
26d0ad1a6e | ||
|
|
90284018e5 | ||
|
|
46eeec16d4 | ||
|
|
083fb0dccc | ||
|
|
d46f145806 | ||
|
|
868eddfd2b | ||
|
|
8295e6bb5b | ||
|
|
424914b842 | ||
|
|
8c5027df0f | ||
|
|
0b7817d992 | ||
|
|
ca6c9bfd05 | ||
|
|
0a1abd8040 | ||
|
|
ed69a4fdf6 | ||
|
|
2ae19a6d4e | ||
|
|
404bc50dd4 | ||
|
|
cada5eeeaf | ||
|
|
5e9bd40e8b | ||
|
|
0788bab0dd | ||
|
|
4e8e0dbea7 | ||
|
|
b8c5279137 | ||
|
|
a3255b1681 | ||
|
|
f151379f8f |
No files matched your search
+52
-57
@@ -1,73 +1,68 @@
|
||||
from PIL import Image
|
||||
import numpy, pefile, os
|
||||
|
||||
def file_to_images(file_data, output_dir, file_name, target_size=(224, 224)):#
|
||||
wah = int(numpy.ceil(numpy.sqrt(len(file_data))))
|
||||
file_data = numpy.frombuffer(file_data, dtype=numpy.uint8)
|
||||
image_array = numpy.zeros((wah * wah,), dtype=numpy.uint8)
|
||||
image_array[:len(file_data)] = file_data
|
||||
image = Image.fromarray(image_array.reshape((wah, wah)), 'L')
|
||||
image = image.resize(target_size, Image.Resampling.NEAREST)
|
||||
image.save(os.path.join(output_dir, f"{file_name}.png"))
|
||||
####################################################################################################
|
||||
|
||||
def check_file_type(file_path):
|
||||
def preprocess_image(file_data, size, channels=1):
|
||||
width, height = size
|
||||
wah = int(numpy.ceil(numpy.sqrt(len(file_data) / channels)))
|
||||
arr = numpy.frombuffer(file_data, dtype=numpy.uint8)
|
||||
img = numpy.zeros(wah*wah*channels, dtype=numpy.uint8)
|
||||
img[:len(file_data)] = arr
|
||||
image = Image.fromarray(img.reshape((wah, wah)), 'L')
|
||||
return image.resize((width, height), Image.Resampling.NEAREST)
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def is_text_file(content, sample_size=1024):
|
||||
raw = content[:sample_size]
|
||||
if not raw:
|
||||
return False
|
||||
text_char = set(range(32, 127)) | {9, 10, 13}
|
||||
nontext = sum(b not in text_char for b in raw)
|
||||
return nontext / len(raw) < 0.15
|
||||
|
||||
def get_type(file_path):
|
||||
suffix = {".com", ".dll", ".drv", ".exe", ".ocx", ".scr", ".sys", ".mui", ".cpl"}
|
||||
|
||||
match_data = {}
|
||||
if not os.path.splitext(file_path)[-1].lower() in suffix:
|
||||
return match_data
|
||||
try:
|
||||
shell_section = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
|
||||
"cry", "tvm", "dec", "enc", "vmp", "upx", "aes", "lzma", "press",
|
||||
"pack", "enigma", "protect", "secur"]
|
||||
with pefile.PE(file_path, fast_load=True) as pe:
|
||||
for section in pe.sections:
|
||||
name = section.Name.rstrip(b'\x00').decode('latin1').lower()
|
||||
data = section.get_data()
|
||||
if data:
|
||||
match_data[name] = section.get_data()
|
||||
except pefile.PEFormatError:
|
||||
with open(file_path, 'rb') as f:
|
||||
file_content = f.read()
|
||||
if is_text_file(file_content):
|
||||
match_data[os.path.splitext(file_path)[-1].lower()] = file_content
|
||||
return match_data
|
||||
|
||||
unknown_section = ["asmstub", "base", "bss", "clr_uef", "cursors",
|
||||
"engine", "fio", "fothk", "h~;", "icapsec", "malloc_h", "miniex",
|
||||
"mssmixer", "ndr64", "nsys_wr", "obr", "wow", "wow64svc", "wpp_sf",
|
||||
"pad", "pgae", "poolmi", "proxy", "qihoo", "res", "retpol", "uedbg",
|
||||
"rwexec", "rygs", "s:@", "sanontcp", "segm", "test", "tracesup",
|
||||
"transit", "trs_age", "wisevec"]
|
||||
####################################################################################################
|
||||
|
||||
unimportant_section = ["viahwaes", "orpc", "nep", "ace", "extjmp",
|
||||
"no_bbt", "data", "page", "hexpthk"]
|
||||
|
||||
shells = shell_section + unimportant_section + unknown_section
|
||||
|
||||
ftype = str(f".{file_path.split('.')[-1]}").lower()
|
||||
|
||||
if ftype in [".bat", ".cmd", ".ps1", ".vbs", ".wsf", ".js", ".html"]:
|
||||
with open(file_path, 'rb') as f:
|
||||
return [f.read()]
|
||||
|
||||
match_data = []
|
||||
if ftype in [".com", ".exe", ".dll", ".sys", ".scr"]:
|
||||
with pefile.PE(file_path, fast_load=True) as pe:
|
||||
for section in pe.sections:
|
||||
section_name = section.Name.rstrip(b'\x00').decode('latin1')
|
||||
#if (section.Characteristics & 0x00000020 and not
|
||||
#any(shell in section_name.lower() for shell in shells)):
|
||||
if section.Characteristics & 0x00000020:
|
||||
match_data.append(section.get_data())
|
||||
return match_data
|
||||
return False
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return False
|
||||
|
||||
def batch_file_to_images(input_dir, output_dir):
|
||||
def file_to_images(input_dir, output_dir):
|
||||
for root, dirs, files in os.walk(input_dir):
|
||||
for file in files:
|
||||
try:
|
||||
file_path = os.path.join(root, file)
|
||||
file_data = check_file_type(file_path)
|
||||
if file_data:
|
||||
for i, data in enumerate(file_data, 1):
|
||||
print(i, file_path)
|
||||
relative_path = os.path.relpath(root, input_dir)
|
||||
output_path_dir = os.path.join(output_dir, relative_path)
|
||||
if not os.path.exists(output_path_dir):
|
||||
os.makedirs(output_path_dir)
|
||||
file_to_images(data, output_path_dir, f"{i}_{file}")
|
||||
for name, data in get_type(file_path).items():
|
||||
print(name, file_path)
|
||||
relative_path = os.path.relpath(root, input_dir)
|
||||
output_path_dir = os.path.join(output_dir, relative_path)
|
||||
if not os.path.exists(output_path_dir):
|
||||
os.makedirs(output_path_dir)
|
||||
image = preprocess_image(data, (224, 224))
|
||||
image.save(os.path.join(output_path_dir, f"{name}_{file}.png"))
|
||||
except Exception as e:
|
||||
print(e)
|
||||
pass
|
||||
|
||||
####################################################################################################
|
||||
|
||||
input_directory = input('Enter the folder path: ')
|
||||
output_directory = "./Image_File"
|
||||
batch_file_to_images(input_directory, output_directory)
|
||||
output_directory = "./Image_Output"
|
||||
file_to_images(input_directory, output_directory)
|
||||
input('Conversion Complete')
|
||||
@@ -1,5 +1,7 @@
|
||||
import os, hashlib
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def calc_sha256(path):
|
||||
with open(path, "rb") as f:
|
||||
return hashlib.sha256(f.read()).digest()
|
||||
@@ -25,5 +27,8 @@ def dedup_realtime(root):
|
||||
seen.add(h)
|
||||
print(f"deleted {deleted}")
|
||||
|
||||
####################################################################################################
|
||||
|
||||
if __name__ == "__main__":
|
||||
dedup_realtime(r".\Image_File")
|
||||
dedup_realtime(input("Input file path: "))
|
||||
input('Deduplicate Complete')
|
||||
+111
-60
@@ -2,15 +2,57 @@ import tensorflow as tf
|
||||
import os, tf2onnx, numpy, random
|
||||
from PIL import Image
|
||||
from tensorflow.keras import *
|
||||
from collections import Counter
|
||||
|
||||
####################################################################################################
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
tf.keras.mixed_precision.set_global_policy('mixed_float16')
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def load_dataset(data_dir, image_size=(224, 224), val_split=0.00001, batch_size=256, color_mode="grayscale"):
|
||||
channels = 1 if color_mode == "grayscale" else 3
|
||||
file_paths, labels, class_indices = get_file_list(data_dir)
|
||||
|
||||
combined = list(zip(file_paths, labels))
|
||||
random.shuffle(combined)
|
||||
file_paths[:], labels[:] = zip(*combined)
|
||||
|
||||
num_val = int(val_split * len(file_paths))
|
||||
train_files = file_paths[num_val:]
|
||||
train_labels = labels[num_val:]
|
||||
val_files = file_paths[:num_val]
|
||||
val_labels = labels[:num_val]
|
||||
num_classes = len(class_indices)
|
||||
|
||||
train_ds = tf.data.Dataset.from_tensor_slices((train_files, train_labels))
|
||||
train_ds = train_ds.map(lambda f, l: parse_fn(f, l, image_size, channels, num_classes), num_parallel_calls=tf.data.AUTOTUNE)
|
||||
train_ds = train_ds.batch(batch_size).prefetch(tf.data.AUTOTUNE)
|
||||
|
||||
val_ds = tf.data.Dataset.from_tensor_slices((val_files, val_labels))
|
||||
val_ds = val_ds.map(lambda f, l: parse_fn(f, l, image_size, channels, num_classes), num_parallel_calls=tf.data.AUTOTUNE)
|
||||
val_ds = val_ds.batch(batch_size).prefetch(tf.data.AUTOTUNE)
|
||||
|
||||
train_ds.class_indices = class_indices
|
||||
return train_ds, val_ds
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def parse_fn(filename, label, image_size, channels, num_classes):
|
||||
img = tf.io.read_file(filename)
|
||||
img = tf.image.decode_image(img, channels=channels, expand_animations=False)
|
||||
img = tf.cond(tf.reduce_all(tf.equal(tf.shape(img)[:2], image_size)), lambda: tf.cast(img, tf.float32), lambda: tf.image.resize(img, image_size))
|
||||
img = tf.cast(img, tf.float32) / 255.0
|
||||
label = tf.one_hot(label, depth=num_classes)
|
||||
return img, label
|
||||
|
||||
def get_file_list(directory):
|
||||
file_paths, labels, class_indices = [], [], {}
|
||||
for i, cls in enumerate(sorted([d for d in os.listdir(directory) if os.path.isdir(os.path.join(directory, d))])):
|
||||
class_indices[cls] = i
|
||||
cls_dir = os.path.join(directory, cls)
|
||||
|
||||
for root, _, files in os.walk(cls_dir):
|
||||
for file in files:
|
||||
if file.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif')):
|
||||
@@ -18,95 +60,104 @@ def get_file_list(directory):
|
||||
labels.append(i)
|
||||
return file_paths, labels, class_indices
|
||||
|
||||
def load_dataset(train_dir, val_dir, val_split=0.01, batch_size=128, color_mode="grayscale"):
|
||||
channels = 1 if color_mode == "grayscale" else 3
|
||||
if train_dir == val_dir:
|
||||
file_paths, labels, class_indices = get_file_list(train_dir)
|
||||
combined = list(zip(file_paths, labels))
|
||||
random.shuffle(combined)
|
||||
file_paths[:], labels[:] = zip(*combined)
|
||||
num_val = int(val_split * len(file_paths))
|
||||
train_files = file_paths[num_val:]
|
||||
train_labels = labels[num_val:]
|
||||
val_files = file_paths[:num_val]
|
||||
val_labels = labels[:num_val]
|
||||
else:
|
||||
train_files, train_labels, class_indices = get_file_list(train_dir)
|
||||
val_files, val_labels, _ = get_file_list(val_dir)
|
||||
num_classes = len(class_indices)
|
||||
####################################################################################################
|
||||
|
||||
def parse_fn(filename, label):
|
||||
img = tf.io.read_file(filename)
|
||||
img = tf.image.decode_image(img, channels=channels, expand_animations=False)
|
||||
img = tf.cast(img, tf.float32) / 255.0
|
||||
label = tf.one_hot(label, depth=num_classes)
|
||||
return img, label
|
||||
def multi_conv(x, strides):
|
||||
convs = []
|
||||
for k in [(1, 7), (1, 1), (3, 3), (5, 5)]:
|
||||
c = layers.DepthwiseConv2D(kernel_size=k, strides=strides, padding='same', activation='gelu')(x)
|
||||
convs.append(c)
|
||||
|
||||
train_ds = tf.data.Dataset.from_tensor_slices((train_files, train_labels))
|
||||
train_ds = train_ds.map(parse_fn, num_parallel_calls=tf.data.AUTOTUNE)
|
||||
train_ds = train_ds.batch(batch_size).prefetch(tf.data.AUTOTUNE)
|
||||
val_ds = tf.data.Dataset.from_tensor_slices((val_files, val_labels))
|
||||
val_ds = val_ds.map(parse_fn, num_parallel_calls=tf.data.AUTOTUNE)
|
||||
val_ds = val_ds.batch(batch_size).prefetch(tf.data.AUTOTUNE)
|
||||
train_ds.class_indices = class_indices
|
||||
return train_ds, val_ds
|
||||
x = layers.Concatenate()(convs)
|
||||
x = layers.BatchNormalization()(x)
|
||||
return layers.Activation('gelu')(x)
|
||||
|
||||
def gated_conv(x, strides):
|
||||
c = layers.DepthwiseConv2D(3, strides=strides, padding='same', activation='gelu')(x)
|
||||
g = layers.DepthwiseConv2D(3, strides=strides, padding='same', activation='sigmoid')(x)
|
||||
return layers.Multiply()([c, g])
|
||||
|
||||
def multi_conv(x, strides):
|
||||
convs = [layers.DepthwiseConv2D(kernel_size=k, strides=strides, padding='same')(x) for k in [1, 3, 5, 7]]
|
||||
x = layers.Concatenate()(convs)
|
||||
x = layers.BatchNormalization()(x)
|
||||
return layers.Activation('gelu')(x)
|
||||
|
||||
def se_block(x, reduction):
|
||||
def coordinate_attention(x, reduction):
|
||||
input_shape = tf.shape(x)
|
||||
h, w = input_shape[1], input_shape[2]
|
||||
filters = x.shape[-1]
|
||||
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)
|
||||
return layers.multiply([x, s])
|
||||
mip = max(8, filters // reduction)
|
||||
|
||||
x_h = layers.Lambda(lambda t: tf.reduce_mean(t, axis=2, keepdims=True))(x)
|
||||
x_w = layers.Lambda(lambda t: tf.reduce_mean(t, axis=1, keepdims=True))(x)
|
||||
x_w_t = layers.Permute((2, 1, 3))(x_w)
|
||||
|
||||
x_cat = layers.Concatenate(axis=1)([x_h, x_w_t])
|
||||
x_cat = layers.Conv2D(mip, 1, padding='valid', use_bias=False)(x_cat)
|
||||
x_cat = layers.BatchNormalization()(x_cat)
|
||||
x_cat = layers.Activation('gelu')(x_cat)
|
||||
|
||||
x_cat_h, x_cat_w = layers.Lambda(lambda t: tf.split(t[0], [t[1], t[2]], axis=1))([x_cat, h, w])
|
||||
x_h_sigmoid = layers.Conv2D(filters, 1, padding='valid', activation='sigmoid')(x_cat_h)
|
||||
x_cat_w = layers.Permute((2, 1, 3))(x_cat_w)
|
||||
x_w_sigmoid = layers.Conv2D(filters, 1, padding='valid', activation='sigmoid')(x_cat_w)
|
||||
|
||||
return layers.Multiply()([x, x_h_sigmoid, x_w_sigmoid])
|
||||
|
||||
def build_model(input_shape, num_classes):
|
||||
i = layers.Input(shape=input_shape)
|
||||
x = multi_conv(i, strides=1)
|
||||
x = multi_conv(x, strides=2)
|
||||
x = gated_conv(x, strides=2)
|
||||
x = multi_conv(x, strides=2)
|
||||
x = multi_conv(x, strides=2)
|
||||
x = multi_conv(x, strides=2)
|
||||
x = se_block(x, reduction=2)
|
||||
x = layers.GlobalAveragePooling2D()(x)
|
||||
x = multi_conv(x, strides=2)
|
||||
|
||||
x = coordinate_attention(x, reduction=4)
|
||||
x = layers.GlobalMaxPooling2D()(x)
|
||||
|
||||
x = layers.Dense(x.shape[-1] // 2, activation='gelu', dtype='float32')(x)
|
||||
o = layers.Dense(num_classes, activation='softmax', dtype='float32')(x)
|
||||
return models.Model(i, o)
|
||||
|
||||
def lr_scheduler(epoch, lr):
|
||||
return 1e-3 * (0.7 ** epoch)
|
||||
####################################################################################################
|
||||
|
||||
def calculate_lr_cosine_sq(epoch, total_epochs=25, lr_start=5e-4, lr_end=1e-6):
|
||||
cos_val = 0.5 * (1 + numpy.cos(epoch / total_epochs * numpy.pi))
|
||||
return lr_end + (lr_start - lr_end) * (cos_val ** 2)
|
||||
|
||||
def lr_scheduler(epoch):
|
||||
return calculate_lr_cosine_sq(epoch)
|
||||
|
||||
def categorical_focal_loss(gamma=2.0, alpha=0.25):
|
||||
def focal_loss(y_true, y_pred):
|
||||
y_pred = tf.clip_by_value(y_pred, tf.keras.backend.epsilon(), 1.0 - tf.keras.backend.epsilon())
|
||||
cross_entropy = -y_true * tf.math.log(y_pred)
|
||||
loss = alpha * tf.math.pow(1.0 - y_pred, gamma) * cross_entropy
|
||||
return tf.reduce_sum(loss, axis=-1)
|
||||
return focal_loss
|
||||
|
||||
class CustomModelCheckpoint(callbacks.Callback):
|
||||
def on_epoch_end(self, epoch, logs=False):
|
||||
models.save_model(self.model, f"PYAS_Model_Epoch_{epoch + 1}.h5")
|
||||
spec = (tf.TensorSpec((None,) + train_ds.image_shape, tf.float32),)
|
||||
model_proto, _ = tf2onnx.convert.from_keras(self.model, input_signature=spec, opset=18)
|
||||
model_proto, _ = tf2onnx.convert.from_keras(self.model, input_signature=spec, opset=17)
|
||||
with open(f"PYAS_Model_Epoch_{epoch + 1}.onnx", "wb") as f:
|
||||
f.write(model_proto.SerializeToString())
|
||||
|
||||
train_ds, val_ds = load_dataset(r'./Image_File', r'./Image_File')
|
||||
####################################################################################################
|
||||
|
||||
train_ds, val_ds = load_dataset(r'.\Image_File_Pefile')
|
||||
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:
|
||||
model = models.load_model('PYAS_Model_Epoch_0.h5')
|
||||
print("Load model from disk")
|
||||
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.")
|
||||
try:
|
||||
model = models.load_model('PYAS_Model_Epoch_0.h5')
|
||||
print("Load model from disk")
|
||||
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_focal_loss(gamma=2.0, alpha=0.25),
|
||||
metrics=['accuracy', metrics.Precision(name='precision'), metrics.Recall(name='recall'),
|
||||
metrics.FalsePositives(name='fp'), metrics.TrueNegatives(name='tn')])
|
||||
|
||||
model.fit(train_ds, epochs=25, callbacks=[CustomModelCheckpoint(), callbacks.LearningRateScheduler(lr_scheduler)], validation_data=val_ds)
|
||||
input('Training Complete')
|
||||
+25
-21
@@ -1,27 +1,31 @@
|
||||
PYAS Security Software Development License Agreement
|
||||
Last updated: 2025-08-15
|
||||
87owo Publicly Available Source Code License Agreement
|
||||
Last updated: 2025-12-19
|
||||
|
||||
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.
|
||||
1. License and Ownership
|
||||
- This software and its source code are source available for public view.
|
||||
- Access or execution of certain features may require an activation key.
|
||||
- 87owo reserves all legal rights, no intellectual property is transferred.
|
||||
- All project archives, source code, and binaries remain fully proprietary.
|
||||
|
||||
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.
|
||||
2. Use and Prohibitions
|
||||
- You may view, download, and modify the code for local and personal use.
|
||||
- Redistribution of any original or modified code requires prior consent.
|
||||
- Commercial hosting or SaaS deployment is prohibited without permission.
|
||||
- Reverse engineering, license removal, or illegal use is strictly barred.
|
||||
|
||||
3. License Components
|
||||
– All project script archives and executable files are proprietary.
|
||||
3. Data and Privacy
|
||||
- This project may collect operational data for optimization and analysis.
|
||||
- All collected data is strictly anonymized to ensure the user's privacy.
|
||||
- Transmission of information is encrypted to prevent unauthorized access.
|
||||
|
||||
4. Updates & Terms
|
||||
– Updates to new versions may include patches, enhancements, or modifications.
|
||||
– Continued use constitutes your acceptance of these features or terms.
|
||||
4. Updates and Terms
|
||||
- New releases may include critical patches, enhancements, or UI changes.
|
||||
- Continued use of these services constitutes acceptance of updated terms.
|
||||
- The author reserves the right to modify these license terms at any time.
|
||||
|
||||
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.
|
||||
5. Warranty and Liability
|
||||
- All services and assets are provided "as is" without any form of warranty.
|
||||
- 87owo is not liable for any direct or indirect damages from software use.
|
||||
- Users assume all risks regarding performance, data, and system integrity.
|
||||
|
||||
© 2020–2025 87owo (PYAS Security). All rights reserved.
|
||||
© 2020-2026 87owo (PYAS Security). All rights reserved.
|
||||
@@ -1,7 +1,7 @@
|
||||
import os, gc, re, sys, time, json, base64
|
||||
import os, gc, re, sys, time, json, shutil
|
||||
import ctypes, ctypes.wintypes, threading
|
||||
import requests, webbrowser, winreg, shutil
|
||||
import traceback, hashlib, msvcrt, pyperclip
|
||||
import requests, webbrowser, winreg, msvcrt
|
||||
import traceback, hashlib
|
||||
|
||||
from PYAS_Config import *
|
||||
from PYAS_Engine import *
|
||||
@@ -56,6 +56,21 @@ class SERVICE_STATUS(ctypes.Structure):
|
||||
("dwCheckPoint", ctypes.wintypes.DWORD),
|
||||
("dwWaitHint", ctypes.wintypes.DWORD),]
|
||||
|
||||
class PROCESS_BASIC_INFORMATION(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("Reserved1", ctypes.wintypes.LPVOID),
|
||||
("PebBaseAddress", ctypes.wintypes.LPVOID),
|
||||
("Reserved2", ctypes.wintypes.LPVOID * 2),
|
||||
("UniqueProcessId", ctypes.wintypes.LPVOID),
|
||||
("Reserved3", ctypes.wintypes.LPVOID)
|
||||
]
|
||||
|
||||
class UNICODE_STRING(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("Length", ctypes.wintypes.USHORT),
|
||||
("MaximumLength", ctypes.wintypes.USHORT),
|
||||
("Buffer", ctypes.c_void_p)]
|
||||
|
||||
####################################################################################################
|
||||
|
||||
class MainWindow_Controller(QMainWindow):
|
||||
@@ -89,6 +104,8 @@ class MainWindow_Controller(QMainWindow):
|
||||
self.python = sys.executable
|
||||
self.process_timer = QTimer(self)
|
||||
|
||||
self.sign = sign_scanner()
|
||||
self.sign.init_windll(["wintrust"])
|
||||
self.model = model_scanner()
|
||||
self.model.load_path(self.path_models)
|
||||
self.rule = rule_scanner()
|
||||
@@ -112,11 +129,11 @@ class MainWindow_Controller(QMainWindow):
|
||||
"traditional_switch", "simplified_switch", "english_switch",
|
||||
]
|
||||
self.pyas_default = {
|
||||
"version": "3.3.4",
|
||||
"version": "3.3.7",
|
||||
"product": "00000-00000-00000-00000-00000",
|
||||
"language": "english_switch",
|
||||
"theme": "white_switch",
|
||||
"sensitive": 95,
|
||||
"sensitive": 90,
|
||||
"process_switch": True,
|
||||
"document_switch": True,
|
||||
"system_switch": True,
|
||||
@@ -131,15 +148,18 @@ class MainWindow_Controller(QMainWindow):
|
||||
{"exe": "explorer.exe", "class": "", "title": ""},
|
||||
]
|
||||
self.block_replace = {
|
||||
"BOOT_BLOCK": "引導行為攔截",
|
||||
"REG_BLOCK": "註冊表行為攔截",
|
||||
"FILE_BLOCK": "檔案行為攔截",
|
||||
"RANSOM_BLOCK": "勒索行為攔截",
|
||||
"CLR_BLOCK": "托管行為攔截",
|
||||
"SHELLCODE_BLOCK": "殼碼行為攔截",
|
||||
"BOOT_BLOCK": "引導行為攔截",
|
||||
"REG_BLOCK": "註冊表行為攔截",
|
||||
"CLR_BLOCK": "執行環境攔截",
|
||||
"SHELLCODE_BLOCK": "殼碼加載攔截",
|
||||
"THREAD_BLOCK": "線程行為攔截",
|
||||
"INJECT_BLOCK": "注入行為攔截",
|
||||
"PROC_BLOCK": "進程行為攔截",
|
||||
"REMOTE_BLOCK": "遠控行為攔截",
|
||||
"SCREEN_BLOCK": "監控行為攔截",
|
||||
"KILL_ATTEMPT": "終止行為攔截",
|
||||
}
|
||||
|
||||
####################################################################################################
|
||||
@@ -167,7 +187,7 @@ class MainWindow_Controller(QMainWindow):
|
||||
####################################################################################################
|
||||
|
||||
def init_windll(self):
|
||||
for name in ["ntdll", "Psapi", "user32", "kernel32", "advapi32", "iphlpapi"]:
|
||||
for name in ["ntdll", "Psapi", "user32", "kernel32", "advapi32", "iphlpapi", "shell32"]:
|
||||
try:
|
||||
setattr(self, name.lower(), ctypes.WinDLL(name, use_last_error=True))
|
||||
except Exception as e:
|
||||
@@ -199,6 +219,12 @@ class MainWindow_Controller(QMainWindow):
|
||||
self.advapi32.CloseServiceHandle.argtypes = [ctypes.wintypes.HANDLE]
|
||||
self.advapi32.CloseServiceHandle.restype = ctypes.wintypes.BOOL
|
||||
|
||||
self.ntdll.NtQueryInformationProcess.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.ULONG, ctypes.c_void_p, ctypes.wintypes.ULONG, ctypes.POINTER(ctypes.wintypes.ULONG)]
|
||||
self.ntdll.NtQueryInformationProcess.restype = ctypes.wintypes.ULONG
|
||||
|
||||
self.shell32.CommandLineToArgvW.argtypes = [ctypes.wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_int)]
|
||||
self.shell32.CommandLineToArgvW.restype = ctypes.POINTER(ctypes.wintypes.LPWSTR)
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def save_config(self, file_path, config):
|
||||
@@ -266,11 +292,12 @@ class MainWindow_Controller(QMainWindow):
|
||||
self.last_widget = self.widgets.get("home_window")
|
||||
self.setup_theme_mapping()
|
||||
self.setup_process_menu()
|
||||
self.setup_scan_menu()
|
||||
|
||||
def create_shadow(self):
|
||||
shadow = QGraphicsDropShadowEffect(self)
|
||||
shadow.setOffset(0, 0)
|
||||
shadow.setBlurRadius(20)
|
||||
shadow.setBlurRadius(15)
|
||||
shadow.setColor(QColor(175, 175, 175))
|
||||
return shadow
|
||||
|
||||
@@ -330,7 +357,7 @@ class MainWindow_Controller(QMainWindow):
|
||||
def save_state(self, name, checked):
|
||||
self.pyas_config[name] = bool(checked)
|
||||
if name == "sensitive_switch":
|
||||
self.pyas_config["sensitive"] = 0 if checked else 95
|
||||
self.pyas_config["sensitive"] = 0 if checked else 90
|
||||
elif name == "extension_switch":
|
||||
pass
|
||||
elif name == "process_switch":
|
||||
@@ -348,7 +375,7 @@ class MainWindow_Controller(QMainWindow):
|
||||
elif self.install_system_driver():
|
||||
self.start_daemon_thread(self.pipe_server_thread)
|
||||
else:
|
||||
self.send_message("驅動防護啟用失敗", "warn", True)
|
||||
self.send_message("驅動防護啟用失敗,請重啟裝置來修復錯誤", "warn", True)
|
||||
elif name == "network_switch":
|
||||
if checked:
|
||||
self.start_daemon_thread(self.protect_net_thread)
|
||||
@@ -572,6 +599,8 @@ class MainWindow_Controller(QMainWindow):
|
||||
self.pyas_config["system_switch"] = False
|
||||
self.pyas_config["driver_switch"] = False
|
||||
self.pyas_config["network_switch"] = False
|
||||
|
||||
self.stop_button()
|
||||
self.stop_system_driver()
|
||||
|
||||
self.minimize_button()
|
||||
@@ -618,7 +647,8 @@ class MainWindow_Controller(QMainWindow):
|
||||
if not isinstance(message, str):
|
||||
message = str(message)
|
||||
if message and translate:
|
||||
message = self.trans(self.pyas_config["language"], message)
|
||||
lang = self.pyas_config.get("language", "english_switch")
|
||||
message = self.trans(lang, message)
|
||||
|
||||
m = mode.lower()
|
||||
if m == "quest":
|
||||
@@ -639,7 +669,7 @@ class MainWindow_Controller(QMainWindow):
|
||||
elif m == "save":
|
||||
select = QFileDialog.getSaveFileName(self, message)[0]
|
||||
|
||||
select = select or False
|
||||
select = select or None
|
||||
now = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
output = f"[{now}] | {mode} | {message} | {select}"
|
||||
log_widget = self.widgets.get("log_text")
|
||||
@@ -650,6 +680,8 @@ class MainWindow_Controller(QMainWindow):
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def invoke_method(self, obj, method, *args):
|
||||
q_args = []
|
||||
for arg in args:
|
||||
@@ -661,20 +693,32 @@ class MainWindow_Controller(QMainWindow):
|
||||
q_args.append(Q_ARG("QString", str(arg)))
|
||||
QMetaObject.invokeMethod(obj, method, Qt.QueuedConnection, *q_args)
|
||||
|
||||
def norm_path(self, path):
|
||||
if isinstance(path, (list, tuple, set)):
|
||||
t = type(path)
|
||||
return t(self.norm_path(p) for p in path)
|
||||
def norm_path(self, path, must_exist=True):
|
||||
if isinstance(path, list):
|
||||
return [p for p in (self.norm_path(x, must_exist) for x in path) if p]
|
||||
if isinstance(path, tuple):
|
||||
return tuple(p for p in (self.norm_path(x, must_exist) for x in path) if p)
|
||||
if isinstance(path, set):
|
||||
return {p for p in (self.norm_path(x, must_exist) for x in path) if p}
|
||||
if isinstance(path, str):
|
||||
return os.path.normpath(os.path.abspath(path))
|
||||
ap = os.path.normpath(os.path.abspath(path))
|
||||
return ap if (not must_exist or os.path.exists(ap)) else None
|
||||
return path
|
||||
|
||||
def path_equal(self, a, b):
|
||||
pa = self.norm_path(a, must_exist=False)
|
||||
pb = self.norm_path(b, must_exist=False)
|
||||
if not pa or not pb:
|
||||
return False
|
||||
return os.path.normcase(pa) == os.path.normcase(pb)
|
||||
|
||||
####################################################################################################
|
||||
|
||||
@Slot()
|
||||
def slot_scan_reset(self):
|
||||
count = len(self.virus_results)
|
||||
self.widgets["solve_button"].setVisible(count > 0)
|
||||
self.widgets["virus_list"].clear()
|
||||
self.widgets["solve_button"].hide()
|
||||
self.widgets["stop_button"].show()
|
||||
self.widgets["method_button"].hide()
|
||||
self.widgets["method_window"].hide()
|
||||
@@ -696,9 +740,9 @@ class MainWindow_Controller(QMainWindow):
|
||||
|
||||
@Slot(str)
|
||||
def slot_scan_result(self, msg):
|
||||
self.widgets["progress_text"].setText(msg)
|
||||
count = len(self.virus_results)
|
||||
self.widgets["solve_button"].setVisible(count > 0)
|
||||
self.widgets["progress_text"].setText(msg)
|
||||
self.widgets["stop_button"].hide()
|
||||
self.widgets["method_button"].show()
|
||||
self.send_message(msg, "notify", True)
|
||||
@@ -713,8 +757,9 @@ class MainWindow_Controller(QMainWindow):
|
||||
self.scan_start = time.time()
|
||||
self.last_widget = self.widgets.get("scan_window")
|
||||
self.scan_reset_signal.emit()
|
||||
self.progress_title_signal.emit(self.trans(self.pyas_config["language"], "正在掃描"))
|
||||
self.scan_progress_signal.emit(self.trans(self.pyas_config["language"], "正在初始化中"))
|
||||
|
||||
lang = self.pyas_config.get("language", "english_switch")
|
||||
self.scan_progress_signal.emit(self.trans(lang, "正在初始化中"))
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
@@ -748,21 +793,27 @@ class MainWindow_Controller(QMainWindow):
|
||||
if self.is_in_whitelist(norm_path):
|
||||
continue
|
||||
self.scan_count += 1
|
||||
|
||||
state = self.scan_engine(norm_path)
|
||||
if state:
|
||||
self.virus_results.append(norm_path)
|
||||
self.scan_add_virus_signal.emit(f"[{state}] > {norm_path}")
|
||||
|
||||
lang = self.pyas_config.get("language", "english_switch")
|
||||
self.progress_title_signal.emit(self.trans(lang, "正在掃描"))
|
||||
self.scan_progress_signal.emit(norm_path)
|
||||
gc.collect()
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
finally:
|
||||
elapsed = int(time.time() - self.scan_start)
|
||||
count = len(self.virus_results)
|
||||
elapsed = int(time.time() - self.scan_start)
|
||||
result = (
|
||||
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))
|
||||
lang = self.pyas_config.get("language", "english_switch")
|
||||
self.progress_title_signal.emit(self.trans(lang, "病毒掃描"))
|
||||
self.scan_result_signal.emit(self.trans(lang, result))
|
||||
|
||||
def yield_files(self, targets):
|
||||
if isinstance(targets, str):
|
||||
@@ -778,23 +829,26 @@ class MainWindow_Controller(QMainWindow):
|
||||
|
||||
def scan_engine(self, file_path):
|
||||
try:
|
||||
if self.sign.sign_verify(file_path):
|
||||
return False
|
||||
|
||||
label, level = self.model.model_scan(file_path)
|
||||
if label and level >= self.pyas_config.get("sensitive", 95):
|
||||
if label and level >= self.pyas_config.get("sensitive", 90):
|
||||
return f"{label}.{level}"
|
||||
|
||||
if self.pyas_config.get("extension_switch", False):
|
||||
label, level = self.rule.yara_scan(file_path)
|
||||
if label and level:
|
||||
return f"{label}.{level}"
|
||||
return False
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
return None
|
||||
return None
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def solve_button(self):
|
||||
deleted = 0
|
||||
started = False
|
||||
virus_list = self.widgets["virus_list"]
|
||||
start_ts = time.time()
|
||||
|
||||
@@ -802,40 +856,108 @@ class MainWindow_Controller(QMainWindow):
|
||||
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
|
||||
lang = self.pyas_config.get("language", "english_switch")
|
||||
self.progress_title_signal.emit(self.trans(lang, "正在刪除"))
|
||||
self.scan_progress_signal.emit(file_path)
|
||||
|
||||
try:
|
||||
os.remove(file_path)
|
||||
deleted += 1
|
||||
virus_list.takeItem(i)
|
||||
try:
|
||||
self.virus_results.remove(file_path)
|
||||
except ValueError:
|
||||
pass
|
||||
self.virus_results.remove(file_path)
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
QApplication.processEvents()
|
||||
remain = virus_list.count()
|
||||
|
||||
count = len(self.virus_results)
|
||||
self.widgets["solve_button"].setVisible(count > 0)
|
||||
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))
|
||||
f"剩餘 {count} 個病毒,共刪除 {deleted} 檔案,耗時 {elapsed} 秒"
|
||||
if count else f"未剩餘病毒,共刪除 {deleted} 檔案,耗時 {elapsed} 秒")
|
||||
lang = self.pyas_config.get("language", "english_switch")
|
||||
self.progress_title_signal.emit(self.trans(lang, "病毒掃描"))
|
||||
self.scan_result_signal.emit(self.trans(lang, result))
|
||||
|
||||
def stop_button(self):
|
||||
self.scan_running = False
|
||||
self.widgets["stop_button"].hide()
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def setup_scan_menu(self):
|
||||
widget = self.widgets.get("virus_list")
|
||||
if widget:
|
||||
widget.setContextMenuPolicy(Qt.CustomContextMenu)
|
||||
widget.customContextMenuRequested.connect(self.show_scan_menu)
|
||||
|
||||
def show_scan_menu(self, pos):
|
||||
widget = self.widgets.get("virus_list")
|
||||
if not widget:
|
||||
return
|
||||
item = widget.itemAt(pos)
|
||||
if not item:
|
||||
return
|
||||
|
||||
lang = self.pyas_config.get("language", "english_switch")
|
||||
menu = QMenu()
|
||||
copy_action = menu.addAction(self.trans(lang, "複製路徑"))
|
||||
del_action = menu.addAction(self.trans(lang, "刪除檔案"))
|
||||
white_action = menu.addAction(self.trans(lang, "增加白名單"))
|
||||
quarantine_action = menu.addAction(self.trans(lang, "增加隔離區"))
|
||||
act = menu.exec(widget.viewport().mapToGlobal(pos))
|
||||
|
||||
text = item.text()
|
||||
if ">" in text:
|
||||
path = text.split(">", 1)[1].strip()
|
||||
else:
|
||||
path = text.strip()
|
||||
|
||||
if act == copy_action:
|
||||
QGuiApplication.clipboard().setText(str(path or "").replace("/", "\\"))
|
||||
|
||||
elif act == del_action:
|
||||
file_path = self.norm_path(path)
|
||||
if file_path and self.send_message("您確定要刪除檔案嗎?", "quest"):
|
||||
try:
|
||||
os.remove(file_path)
|
||||
widget.takeItem(widget.row(item))
|
||||
self.virus_results.remove(file_path)
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
elif act == white_action:
|
||||
file_path = self.norm_path(path)
|
||||
if file_path and self.send_message("您確定要增加到白名單嗎?", "quest"):
|
||||
try:
|
||||
n = self.manage_named_list("white_list", [file_path], action="add", with_hash=True)
|
||||
self.send_message(f"成功增加到白名單,共 {n} 個檔案", "info", True)
|
||||
widget.takeItem(widget.row(item))
|
||||
self.virus_results.remove(file_path)
|
||||
except:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
elif act == quarantine_action:
|
||||
file_path = self.norm_path(path)
|
||||
if file_path and self.send_message("您確定要增加到隔離區嗎?", "quest"):
|
||||
try:
|
||||
n = self.manage_named_list("quarantine", [file_path], action="add", with_hash=True, lock_func=self.lock_file)
|
||||
self.send_message(f"成功增加到隔離區,共 {n} 個檔案", "info", True)
|
||||
widget.takeItem(widget.row(item))
|
||||
self.virus_results.remove(file_path)
|
||||
except:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
count = len(self.virus_results)
|
||||
self.widgets["solve_button"].setVisible(count > 0)
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def list_process(self):
|
||||
pe = self.get_process_entry()
|
||||
snapshot = self.kernel32.CreateToolhelp32Snapshot(0x00000002, 0)
|
||||
result, success = [], self.kernel32.Process32First(snapshot, ctypes.byref(pe))
|
||||
|
||||
while success:
|
||||
pid = pe.th32ProcessID
|
||||
name, file_path = (None, None)
|
||||
@@ -848,6 +970,7 @@ class MainWindow_Controller(QMainWindow):
|
||||
name = raw.decode("mbcs", errors="replace") or None
|
||||
except Exception:
|
||||
name = None
|
||||
|
||||
result.append((pid, name, file_path))
|
||||
success = self.kernel32.Process32Next(snapshot, ctypes.byref(pe))
|
||||
self.kernel32.CloseHandle(snapshot)
|
||||
@@ -858,6 +981,7 @@ class MainWindow_Controller(QMainWindow):
|
||||
self.proc_pid_map = [pid for pid, _, _ in procs]
|
||||
widget = self.widgets.get("manage_list")
|
||||
info_text = self.widgets.get("info_text")
|
||||
|
||||
if widget:
|
||||
model = QStringListModel([f"{name or 'None'} | {pid} | {file_path or 'None'}" for pid, name, file_path in procs])
|
||||
widget.setModel(model)
|
||||
@@ -879,6 +1003,7 @@ class MainWindow_Controller(QMainWindow):
|
||||
def start_process_timer(self):
|
||||
if hasattr(self, "process_timer") and self.process_timer.isActive():
|
||||
return
|
||||
|
||||
self.process_timer = QTimer(self)
|
||||
self.process_timer.timeout.connect(self.refresh_process)
|
||||
self.process_timer.start(0)
|
||||
@@ -900,19 +1025,49 @@ class MainWindow_Controller(QMainWindow):
|
||||
idx = widget.indexAt(pos)
|
||||
if not idx.isValid() or idx.row() >= len(self.proc_pid_map):
|
||||
return
|
||||
pid = self.proc_pid_map[idx.row()]
|
||||
|
||||
lang = self.pyas_config.get("language", "english_switch")
|
||||
menu = QMenu()
|
||||
kill_action = menu.addAction("結束進程")
|
||||
if menu.exec(widget.viewport().mapToGlobal(pos)) == kill_action:
|
||||
copy_action = menu.addAction(self.trans(lang, "複製路徑"))
|
||||
kill_action = menu.addAction(self.trans(lang, "結束進程"))
|
||||
white_action = menu.addAction(self.trans(lang, "增加白名單"))
|
||||
quarantine_action = menu.addAction(self.trans(lang, "增加隔離區"))
|
||||
act = menu.exec(widget.viewport().mapToGlobal(pos))
|
||||
|
||||
pid = self.proc_pid_map[idx.row()]
|
||||
name, file_path = self.get_exe_info(pid)
|
||||
|
||||
if act == copy_action:
|
||||
QGuiApplication.clipboard().setText(str(file_path or "").replace("/", "\\"))
|
||||
|
||||
elif act == kill_action:
|
||||
self.kill_process(pid)
|
||||
|
||||
elif act == white_action:
|
||||
file_path = self.norm_path(path)
|
||||
if file_path and self.send_message("您確定要增加到白名單嗎?", "quest"):
|
||||
try:
|
||||
n = self.manage_named_list("white_list", [file_path], action="add", with_hash=True)
|
||||
self.send_message(f"成功增加到白名單,共 {n} 個檔案", "info", True)
|
||||
except:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
elif act == quarantine_action:
|
||||
file_path = self.norm_path(path)
|
||||
if file_path and self.send_message("您確定要增加到隔離區嗎?", "quest"):
|
||||
try:
|
||||
n = self.manage_named_list("quarantine", [file_path], action="add", with_hash=True, lock_func=self.lock_file)
|
||||
self.send_message(f"成功增加到隔離區,共 {n} 個檔案", "info", True)
|
||||
except:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
def kill_process(self, pid):
|
||||
try:
|
||||
h = self.kernel32.OpenProcess(0x1F0FFF, False, pid)
|
||||
if h:
|
||||
file_path = self.norm_path(self.get_process_file(h))
|
||||
if hasattr(self, "file_pyas") and file_path == getattr(self, "file_pyas", None):
|
||||
self.close()
|
||||
if self.path_equal(file_path, self.file_pyas):
|
||||
self.close_button()
|
||||
else:
|
||||
self.kernel32.TerminateProcess(h, 0)
|
||||
self.kernel32.CloseHandle(h)
|
||||
@@ -997,6 +1152,7 @@ class MainWindow_Controller(QMainWindow):
|
||||
def repair_system_mbr(self):
|
||||
if not hasattr(self, "mbr_backup") or not self.mbr_backup:
|
||||
return
|
||||
|
||||
for drive, mbr_value in self.mbr_backup.items():
|
||||
drive_path = rf"\\.\PhysicalDrive{drive}"
|
||||
try:
|
||||
@@ -1015,9 +1171,11 @@ class MainWindow_Controller(QMainWindow):
|
||||
wallpaper = os.path.join(self.path_system, "web", "wallpaper", "Windows", "img0.jpg")
|
||||
if not os.path.exists(wallpaper):
|
||||
return
|
||||
|
||||
key = r"Control Panel\\Desktop"
|
||||
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key, 0, winreg.KEY_SET_VALUE) as reg:
|
||||
winreg.SetValueEx(reg, "Wallpaper", 0, winreg.REG_SZ, wallpaper)
|
||||
|
||||
theme_dir = os.path.join(self.path_appdata, "Microsoft", "Windows", "Themes")
|
||||
for fname in ["TranscodedWallpaper", "TranscodedWallpaper.tmp"]:
|
||||
fpath = os.path.join(theme_dir, fname)
|
||||
@@ -1026,6 +1184,7 @@ class MainWindow_Controller(QMainWindow):
|
||||
os.remove(fpath)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cache_dir = os.path.join(theme_dir, "CachedFiles")
|
||||
if os.path.exists(cache_dir):
|
||||
try:
|
||||
@@ -1135,11 +1294,12 @@ class MainWindow_Controller(QMainWindow):
|
||||
if self.send_message("請選擇要攔截的軟體彈窗", "quest", True):
|
||||
while True:
|
||||
QApplication.processEvents()
|
||||
title, class_name, process_name = self.get_window_info(self.user32.GetForegroundWindow())
|
||||
if process_name and not any(self.window_rule_match(item, process_name, class_name, title) for item in self.pass_windows):
|
||||
if self.send_message(f"您確定要攔截 {process_name} ({title}) 嗎?", "quest", True):
|
||||
if self.add_window_rule(self.pyas_config["block_list"], process_name, class_name, title):
|
||||
self.send_message(f"成功增加到彈窗攔截: {process_name} ({title})", "info", True)
|
||||
|
||||
title, class_name, proc_name = self.get_window_info(self.user32.GetForegroundWindow())
|
||||
if proc_name and not any(self.window_rule_match(item, proc_name, class_name, title) for item in self.pass_windows):
|
||||
if self.send_message(f"您確定要攔截 {proc_name} ({title}) 嗎?", "quest", True):
|
||||
if self.add_window_rule(self.pyas_config["block_list"], proc_name, class_name, title):
|
||||
self.send_message(f"成功增加到彈窗攔截: {proc_name} ({title})", "info", True)
|
||||
else:
|
||||
self.send_message("已存在彈窗攔截", "info", True)
|
||||
break
|
||||
@@ -1151,32 +1311,33 @@ class MainWindow_Controller(QMainWindow):
|
||||
if self.send_message("請選擇要取消攔截的軟體彈窗", "quest", True):
|
||||
while True:
|
||||
QApplication.processEvents()
|
||||
title, class_name, process_name = self.get_window_info(self.user32.GetForegroundWindow())
|
||||
if process_name and not any(self.window_rule_match(item, process_name, class_name, title) for item in self.pass_windows):
|
||||
if self.send_message(f"您確定要取消攔截 {process_name} ({title}) 嗎?", "quest", True):
|
||||
if self.remove_window_rule(self.pyas_config["block_list"], process_name, class_name, title):
|
||||
self.send_message(f"成功取消彈窗攔截: {process_name} ({title})", "info", True)
|
||||
|
||||
title, class_name, proc_name = self.get_window_info(self.user32.GetForegroundWindow())
|
||||
if proc_name and not any(self.window_rule_match(item, proc_name, class_name, title) for item in self.pass_windows):
|
||||
if self.send_message(f"您確定要取消攔截 {proc_name} ({title}) 嗎?", "quest", True):
|
||||
if self.remove_window_rule(self.pyas_config["block_list"], proc_name, class_name, title):
|
||||
self.send_message(f"成功取消彈窗攔截: {proc_name} ({title})", "info", True)
|
||||
else:
|
||||
self.send_message("未找到彈窗攔截", "info", True)
|
||||
break
|
||||
self.start_daemon_thread(self.popup_intercept_thread)
|
||||
|
||||
def window_rule_match(self, item, process_name, class_name, title):
|
||||
for k, v in zip(["exe", "class", "title"], [process_name, class_name, title]):
|
||||
def window_rule_match(self, item, proc_name, class_name, title):
|
||||
for k, v in zip(["exe", "class", "title"], [proc_name, class_name, title]):
|
||||
if item.get(k, "") and item.get(k, "") != v:
|
||||
return False
|
||||
return True
|
||||
|
||||
def add_window_rule(self, rule_list, process_name, class_name, title):
|
||||
if not any(self.window_rule_match(item, process_name, class_name, title) for item in rule_list):
|
||||
rule_list.append({"exe": process_name, "class": class_name, "title": title})
|
||||
def add_window_rule(self, rule_list, proc_name, class_name, title):
|
||||
if not any(self.window_rule_match(item, proc_name, class_name, title) for item in rule_list):
|
||||
rule_list.append({"exe": proc_name, "class": class_name, "title": title})
|
||||
self.save_config(self.file_config, self.pyas_config)
|
||||
return True
|
||||
return False
|
||||
|
||||
def remove_window_rule(self, rule_list, process_name, class_name, title):
|
||||
def remove_window_rule(self, rule_list, proc_name, class_name, title):
|
||||
before = len(rule_list)
|
||||
rule_list[:] = [item for item in rule_list if not self.window_rule_match(item, process_name, class_name, title)]
|
||||
rule_list[:] = [item for item in rule_list if not self.window_rule_match(item, proc_name, class_name, title)]
|
||||
if len(rule_list) < before:
|
||||
self.save_config(self.file_config, self.pyas_config)
|
||||
return True
|
||||
@@ -1190,12 +1351,26 @@ class MainWindow_Controller(QMainWindow):
|
||||
rules = self.pyas_config.get("block_list", [])
|
||||
if not rules:
|
||||
continue
|
||||
|
||||
for hWnd in self.get_all_windows():
|
||||
title, class_name, process_name = self.get_window_info(hWnd)
|
||||
if (not any(self.window_rule_match(item, process_name, class_name, title) for item in self.pass_windows) and
|
||||
any(self.window_rule_match(item, process_name, class_name, title) for item in rules)):
|
||||
title, class_name, proc_name = self.get_window_info(hWnd)
|
||||
if (not any(self.window_rule_match(item, proc_name, class_name, title) for item in self.pass_windows) and
|
||||
any(self.window_rule_match(item, proc_name, class_name, title) for item in rules)):
|
||||
closed = False
|
||||
|
||||
for msg in [0x0010, 0x0002, 0x0012, 0x0112]:
|
||||
self.user32.SendMessageW(hWnd, msg, 0xF060, 0)
|
||||
if self.user32.SendMessageW(hWnd, msg, 0xF060, 0) != 0:
|
||||
closed = True
|
||||
break
|
||||
|
||||
if not closed and proc_name:
|
||||
pid = ctypes.c_ulong()
|
||||
self.user32.GetWindowThreadProcessId(hWnd, ctypes.byref(pid))
|
||||
if pid.value:
|
||||
h = self.kernel32.OpenProcess(0x1F0FFF, False, pid.value)
|
||||
if h:
|
||||
self.kernel32.TerminateProcess(h, 0)
|
||||
self.kernel32.CloseHandle(h)
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
@@ -1219,73 +1394,78 @@ class MainWindow_Controller(QMainWindow):
|
||||
self.user32.GetClassNameW(hWnd, class_name, 256)
|
||||
pid = ctypes.c_ulong()
|
||||
self.user32.GetWindowThreadProcessId(hWnd, ctypes.byref(pid))
|
||||
process_name = ""
|
||||
|
||||
proc_name = ""
|
||||
try:
|
||||
process_name = self.get_process_name_by_pid(pid.value)
|
||||
proc_name = self.get_process_name(pid.value)
|
||||
except Exception:
|
||||
pass
|
||||
return str(title.value), str(class_name.value), process_name
|
||||
return str(title.value), str(class_name.value), proc_name
|
||||
|
||||
def get_process_name_by_pid(self, pid):
|
||||
def get_process_name(self, pid):
|
||||
name, file_path = self.get_exe_info(pid)
|
||||
if name:
|
||||
return name
|
||||
snapshot = self.kernel32.CreateToolhelp32Snapshot(0x00000002, 0)
|
||||
entry = PROCESSENTRY32()
|
||||
entry.dwSize = ctypes.sizeof(PROCESSENTRY32)
|
||||
name = ""
|
||||
|
||||
result = ""
|
||||
if self.kernel32.Process32First(snapshot, ctypes.byref(entry)):
|
||||
while True:
|
||||
if entry.th32ProcessID == pid:
|
||||
name = entry.szExeFile.decode("mbcs").rstrip("\x00")
|
||||
try:
|
||||
result = entry.szExeFile.decode("mbcs").rstrip("\x00")
|
||||
except Exception:
|
||||
result = ""
|
||||
break
|
||||
if not self.kernel32.Process32Next(snapshot, ctypes.byref(entry)):
|
||||
break
|
||||
self.kernel32.CloseHandle(snapshot)
|
||||
return name
|
||||
return result
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def whitelist_button(self):
|
||||
self.config_list("white_list")
|
||||
files = self.send_message("選擇檔案", "files", True)
|
||||
if files:
|
||||
if self.send_message("您確定要增加到白名單嗎?", "quest"):
|
||||
n = self.manage_named_list("white_list", files, action="add", with_hash=True)
|
||||
self.send_message(f"成功增加到白名單,共 {n} 個檔案", "info")
|
||||
if files and self.send_message("您確定要增加到白名單嗎?", "quest"):
|
||||
n = self.manage_named_list("white_list", files, action="add", with_hash=True)
|
||||
self.send_message(f"成功增加到白名單,共 {n} 個檔案", "info", True)
|
||||
|
||||
def whitelist_button_2(self):
|
||||
self.config_list("white_list")
|
||||
files = self.send_message("選擇檔案", "files", True)
|
||||
if files:
|
||||
if self.send_message("您確定要移除白名單嗎?", "quest"):
|
||||
n = self.manage_named_list("white_list", files, action="remove", with_hash=True)
|
||||
self.send_message(f"成功移除白名單,共 {n} 個檔案", "info")
|
||||
if files and self.send_message("您確定要移除白名單嗎?", "quest"):
|
||||
n = self.manage_named_list("white_list", files, action="remove", with_hash=True)
|
||||
self.send_message(f"成功移除白名單,共 {n} 個檔案", "info", True)
|
||||
|
||||
def quarantine_button(self):
|
||||
self.config_list("quarantine")
|
||||
files = self.send_message("選擇檔案", "files", True)
|
||||
if files:
|
||||
if self.send_message("您確定要增加到隔離區嗎?", "quest"):
|
||||
n = self.manage_named_list("quarantine", files, action="add", with_hash=True, lock_func=self.lock_file)
|
||||
if n > 0:
|
||||
self.send_message(f"成功增加到隔離區,共 {n} 個檔案", "info")
|
||||
if files and self.send_message("您確定要增加到隔離區嗎?", "quest"):
|
||||
n = self.manage_named_list("quarantine", files, action="add", with_hash=True, lock_func=self.lock_file)
|
||||
self.send_message(f"成功增加到隔離區,共 {n} 個檔案", "info", True)
|
||||
|
||||
def quarantine_button_2(self):
|
||||
self.config_list("quarantine")
|
||||
quarantine_dir = os.path.join(self.path_config, "quarantine")
|
||||
files = self.send_message("選擇檔案", "files", True)
|
||||
if files:
|
||||
if self.send_message("您確定要移除隔離區嗎?", "quest"):
|
||||
n = self.manage_named_list("quarantine", files, action="remove", with_hash=True, lock_func=self.lock_file)
|
||||
self.send_message(f"成功移除隔離區,共 {n} 個檔案", "info")
|
||||
if files and self.send_message("您確定要移除隔離區嗎?", "quest"):
|
||||
n = self.manage_named_list("quarantine", files, action="remove", with_hash=True, lock_func=self.lock_file)
|
||||
self.send_message(f"成功移除隔離區,共 {n} 個檔案", "info", True)
|
||||
|
||||
def add_to_quarantine(self, files):
|
||||
self.config_list("quarantine")
|
||||
return self.manage_named_list("quarantine", files, action="add", with_hash=True, lock_func=self.lock_file)
|
||||
|
||||
def is_in_whitelist(self, file_path):
|
||||
norm_path = self.norm_path(file_path)
|
||||
file_hash = self.calc_file_hash(norm_path)
|
||||
return any(item["file"] == norm_path and item["hash"] == file_hash
|
||||
for item in self.pyas_config.get("white_list", []))
|
||||
p = self.norm_path(file_path)
|
||||
if not p:
|
||||
return False
|
||||
file_hash = self.calc_file_hash(p)
|
||||
return any(os.path.normcase(item.get("file","")) == os.path.normcase(p) and
|
||||
item.get("hash","") == file_hash for item in self.pyas_config.get("white_list", []))
|
||||
|
||||
def init_whitelist(self):
|
||||
self.manage_named_list("white_list", [self.file_pyas], action="add", with_hash=True)
|
||||
@@ -1293,36 +1473,36 @@ class MainWindow_Controller(QMainWindow):
|
||||
####################################################################################################
|
||||
|
||||
def manage_named_list(self, list_key, files, action="add", with_hash=True, lock_func=None):
|
||||
target_list = self.config_list(list_key)
|
||||
files = files or []
|
||||
norm_paths = self.norm_path(files)
|
||||
norm_paths = self.norm_path(files or [], must_exist=True)
|
||||
if isinstance(norm_paths, str):
|
||||
norm_paths = [norm_paths]
|
||||
norm_paths = [norm_paths] if norm_paths else []
|
||||
|
||||
n = 0
|
||||
if action == "add":
|
||||
for path in norm_paths:
|
||||
QApplication.processEvents()
|
||||
file_hash = self.calc_file_hash(path) if with_hash else ""
|
||||
if not any(self.norm_path(item["file"]) == path and (not with_hash or item.get("hash", "") == file_hash) for item in target_list):
|
||||
if not any(self.norm_path(item["file"]) == path and
|
||||
(not with_hash or item.get("hash", "") == file_hash)
|
||||
for item in self.config_list(list_key)):
|
||||
if lock_func:
|
||||
try:
|
||||
lock_func(path, True)
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
target_list.append({"file": path, "hash": file_hash})
|
||||
self.config_list(list_key).append({"file": path, "hash": file_hash})
|
||||
n += 1
|
||||
|
||||
elif action == "remove":
|
||||
remove_list = [item for item in target_list if item["file"] in norm_paths]
|
||||
for item in remove_list:
|
||||
for item in [item for item in self.config_list(list_key)
|
||||
if self.norm_path(item["file"]) in norm_paths]:
|
||||
try:
|
||||
if lock_func:
|
||||
lock_func(item["file"], False)
|
||||
target_list.remove(item)
|
||||
self.config_list(list_key).remove(item)
|
||||
n += 1
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
if n:
|
||||
self.save_config(self.file_config, self.pyas_config)
|
||||
return n
|
||||
@@ -1341,7 +1521,15 @@ class MainWindow_Controller(QMainWindow):
|
||||
|
||||
def website_button(self):
|
||||
try:
|
||||
webbrowser.open("https://github.com/87owo/PYAS")
|
||||
webbrowser.open("https://pyas-security.com/antivirus")
|
||||
return True
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
return False
|
||||
|
||||
def cloud_button(self):
|
||||
try:
|
||||
webbrowser.open("https://pyas-security.com/analyze")
|
||||
return True
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
@@ -1422,30 +1610,31 @@ class MainWindow_Controller(QMainWindow):
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
def get_process_list(self):
|
||||
exist_process, pe = set(), self.get_process_entry()
|
||||
hSnapshot = self.kernel32.CreateToolhelp32Snapshot(0x00000002, 0)
|
||||
if self.kernel32.Process32First(hSnapshot, ctypes.byref(pe)):
|
||||
while True:
|
||||
exist_process.add(pe.th32ProcessID)
|
||||
if not self.kernel32.Process32Next(hSnapshot, ctypes.byref(pe)):
|
||||
break
|
||||
self.kernel32.CloseHandle(hSnapshot)
|
||||
return exist_process
|
||||
|
||||
def handle_new_process(self, pid):
|
||||
try:
|
||||
h = self.kernel32.OpenProcess(0x1F0FFF, False, pid)
|
||||
if not h:
|
||||
return
|
||||
file_path = self.norm_path(self.get_process_file(h))
|
||||
if file_path and os.path.exists(file_path) and not self.is_in_whitelist(file_path):
|
||||
self.suspend_process(h, True)
|
||||
state = self.scan_engine(file_path)
|
||||
if state:
|
||||
|
||||
self.suspend_process(h, True)
|
||||
cmdline = self.get_process_cmdline(h)
|
||||
paths = []
|
||||
for arg in self.split_commandline(cmdline):
|
||||
paths.extend(self.extract_paths_from_arg(arg))
|
||||
|
||||
seen = set()
|
||||
paths = [p for p in paths if p and (p not in seen and not seen.add(p))]
|
||||
for p in paths:
|
||||
file_path = self.norm_path(self.device_path_to_drive(p)) if p else ""
|
||||
if not file_path:
|
||||
continue
|
||||
if self.is_in_whitelist(file_path):
|
||||
continue
|
||||
if self.scan_engine(file_path):
|
||||
self.kernel32.TerminateProcess(h, 0)
|
||||
self.send_message(f"進程防護 | 靜態掃描攔截 | {pid} | {file_path} | None", "notify", True)
|
||||
self.suspend_process(h, False)
|
||||
|
||||
self.suspend_process(h, False)
|
||||
self.kernel32.CloseHandle(h)
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
@@ -1464,6 +1653,19 @@ class MainWindow_Controller(QMainWindow):
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def get_process_list(self):
|
||||
exist_process, pe = set(), self.get_process_entry()
|
||||
hSnapshot = self.kernel32.CreateToolhelp32Snapshot(0x00000002, 0)
|
||||
if self.kernel32.Process32First(hSnapshot, ctypes.byref(pe)):
|
||||
while True:
|
||||
exist_process.add(pe.th32ProcessID)
|
||||
if not self.kernel32.Process32Next(hSnapshot, ctypes.byref(pe)):
|
||||
break
|
||||
self.kernel32.CloseHandle(hSnapshot)
|
||||
return exist_process
|
||||
|
||||
def get_process_file(self, h_process):
|
||||
buf = ctypes.create_unicode_buffer(1024)
|
||||
if self.psapi.GetProcessImageFileNameW(h_process, buf, 1024):
|
||||
@@ -1488,6 +1690,73 @@ class MainWindow_Controller(QMainWindow):
|
||||
self.kernel32.CloseHandle(h)
|
||||
return name, file_path
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def get_process_cmdline(self, h):
|
||||
pbi = PROCESS_BASIC_INFORMATION()
|
||||
retlen = ctypes.wintypes.ULONG(0)
|
||||
status = self.ntdll.NtQueryInformationProcess(h, 0, ctypes.byref(pbi), ctypes.sizeof(pbi), ctypes.byref(retlen))
|
||||
if status != 0:
|
||||
return ""
|
||||
|
||||
pointer_size = ctypes.sizeof(ctypes.c_void_p)
|
||||
peb_address = int(pbi.PebBaseAddress) if pbi.PebBaseAddress else 0
|
||||
read_buf = (ctypes.c_ubyte * pointer_size)()
|
||||
lpNumberOfBytesRead = ctypes.c_size_t(0)
|
||||
offset_process_parameters = 0x20 if pointer_size == 8 else 0x10
|
||||
addr_pp = peb_address + offset_process_parameters
|
||||
if not addr_pp:
|
||||
return ""
|
||||
if not self.kernel32.ReadProcessMemory(h, ctypes.c_void_p(addr_pp), read_buf, pointer_size, ctypes.byref(lpNumberOfBytesRead)):
|
||||
return ""
|
||||
|
||||
proc_params_address = ctypes.c_void_p.from_buffer_copy(read_buf).value
|
||||
if not proc_params_address:
|
||||
return ""
|
||||
|
||||
offset_command_line = 0x70 if pointer_size == 8 else 0x40
|
||||
us = UNICODE_STRING()
|
||||
addr_cmd = int(proc_params_address) + offset_command_line
|
||||
if not self.kernel32.ReadProcessMemory(h, ctypes.c_void_p(addr_cmd), ctypes.byref(us), ctypes.sizeof(us), ctypes.byref(lpNumberOfBytesRead)):
|
||||
return ""
|
||||
if not us.Buffer or us.Length == 0:
|
||||
return ""
|
||||
|
||||
buf_len = int(us.Length // 2)
|
||||
buf = (ctypes.c_wchar * buf_len)()
|
||||
if not self.kernel32.ReadProcessMemory(h, ctypes.c_void_p(int(us.Buffer)), buf, us.Length, ctypes.byref(lpNumberOfBytesRead)):
|
||||
return ""
|
||||
return "".join(buf)
|
||||
|
||||
def split_commandline(self, cmdline):
|
||||
if not cmdline:
|
||||
return []
|
||||
|
||||
argc = ctypes.c_int(0)
|
||||
argv = self.shell32.CommandLineToArgvW(cmdline, ctypes.byref(argc))
|
||||
if not argv:
|
||||
return []
|
||||
|
||||
args = [argv[i] for i in range(argc.value)]
|
||||
self.kernel32.LocalFree(ctypes.cast(argv, ctypes.c_void_p))
|
||||
return args
|
||||
|
||||
def extract_paths_from_arg(self, arg):
|
||||
patterns = [
|
||||
r'([A-Za-z]:\\[^"\']+)',
|
||||
r'(\\\\[^"\']+)',
|
||||
r'(\.\\[^"\']+)',
|
||||
r'(\./[^"\']+)',
|
||||
r'([A-Za-z]:/[^"\']+)',
|
||||
r'([^\s]*\\[^\s]+)'
|
||||
]
|
||||
found = []
|
||||
for p in patterns:
|
||||
for m in re.finditer(p, arg):
|
||||
val = m.group(1).strip('"').strip("'")
|
||||
found.append(val)
|
||||
return list(dict.fromkeys(found))
|
||||
|
||||
####################################################################################################
|
||||
|
||||
def protect_file_thread(self):
|
||||
@@ -1499,17 +1768,20 @@ class MainWindow_Controller(QMainWindow):
|
||||
bytes_returned = ctypes.wintypes.DWORD()
|
||||
res = self.kernel32.ReadDirectoryChangesW(hDir, buffer, ctypes.sizeof(buffer), True,
|
||||
0x0000001F, ctypes.byref(bytes_returned), None, None)
|
||||
if not res:
|
||||
continue
|
||||
|
||||
if res:
|
||||
notify = FILE_NOTIFY_INFORMATION.from_buffer_copy(buffer)
|
||||
raw_filename = notify.FileName[:notify.FileNameLength // 2]
|
||||
file_path = self.norm_path(os.path.join(self.path_user, raw_filename))
|
||||
notify = FILE_NOTIFY_INFORMATION.from_buffer_copy(buffer)
|
||||
raw_filename = notify.FileName[:notify.FileNameLength // 2]
|
||||
if not raw_filename:
|
||||
continue
|
||||
|
||||
if notify.Action in [2, 3, 4] and not self.is_in_whitelist(file_path):
|
||||
state = self.scan_engine(file_path)
|
||||
if state:
|
||||
self.add_to_quarantine([file_path])
|
||||
self.send_message(f"檔案防護 | 靜態掃描攔截 | None | {file_path} | None", "notify", True)
|
||||
file_path = self.norm_path(os.path.join(self.path_user, raw_filename), must_exist=True)
|
||||
if file_path and notify.Action in [2, 3, 4] and not self.is_in_whitelist(file_path):
|
||||
state = self.scan_engine(file_path)
|
||||
if state:
|
||||
self.add_to_quarantine([file_path])
|
||||
self.send_message(f"檔案防護 | 靜態掃描攔截 | None | {file_path} | None", "notify", True)
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
self.kernel32.CloseHandle(hDir)
|
||||
@@ -1562,17 +1834,17 @@ class MainWindow_Controller(QMainWindow):
|
||||
def handle_new_connection(self, key):
|
||||
pid, remote_addr, remote_port = key
|
||||
try:
|
||||
h_process = self.kernel32.OpenProcess(0x1F0FFF, False, pid)
|
||||
if not h_process:
|
||||
h = self.kernel32.OpenProcess(0x1F0FFF, False, pid)
|
||||
if not h:
|
||||
return
|
||||
file_path = self.norm_path(self.get_process_file(h_process))
|
||||
remote_ip = f"{remote_addr & 0xFF}.{(remote_addr >> 8) & 0xFF}.{(remote_addr >> 16) & 0xFF}.{(remote_addr >> 24) & 0xFF}"
|
||||
|
||||
if file_path and os.path.exists(file_path) and not self.is_in_whitelist(file_path):
|
||||
file_path = self.norm_path(self.get_process_file(h))
|
||||
if 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.kernel32.TerminateProcess(h, 0)
|
||||
self.send_message(f"網路防護 | 規則列表攔截 | {pid} | {file_path} | {remote_ip}", "notify", True)
|
||||
self.kernel32.CloseHandle(h_process)
|
||||
self.kernel32.CloseHandle(h)
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
@@ -1662,11 +1934,12 @@ class MainWindow_Controller(QMainWindow):
|
||||
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)):
|
||||
file_path = self.norm_path(self.device_path_to_drive(raw_path))
|
||||
if not self.is_in_whitelist(file_path) and not self.sign.sign_verify(file_path):
|
||||
try:
|
||||
h = self.kernel32.OpenProcess(0x1F0FFF, False, int(pid.strip()))
|
||||
if h:
|
||||
self.kernel32.TerminateProcess(h, 0xC0000022)
|
||||
self.kernel32.TerminateProcess(h, 0)
|
||||
self.kernel32.CloseHandle(h)
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
+10
-9
@@ -71,9 +71,10 @@ translate_dict = {
|
||||
"沙箱":"Sandbox ", "虛擬":"Virtual ", "隔離":"Quarantine ", "時":"",
|
||||
"建立":"Create ","環境":"Environment ","沙箱":"Sandbox ","化":"", "表":"",
|
||||
"達":"Reached ", "上限":"Limit ", "區":"", "金鑰":"Key ", "產品":"Product ",
|
||||
"托管":"CLR ","殼碼":"Shellcode ","線程":"Thread ","注入":"Inject ",
|
||||
"運行庫":".NET CLR ","殼碼":"Shellcode ","線程":"Thread ","注入":"Inject ",
|
||||
"前往":"Go ","檢查":"Check ","可用":"Available ","靜態":"Static ",
|
||||
"版本":"Version ","是":"","剩餘":"Remain "," ":" "},
|
||||
"版本":"Version ","是":"","剩餘":"Remain ","遠控":"Remote ","監控":"Monitor ",
|
||||
" ":" "},
|
||||
|
||||
"white_switch": {
|
||||
"_white": "_black",},
|
||||
@@ -116,13 +117,13 @@ translate_dict = {
|
||||
"_white": "_black"
|
||||
},
|
||||
"black_switch": {
|
||||
"255, 255, 255": "55, 55, 55",
|
||||
"245, 245, 245": "75, 75, 75",
|
||||
"235, 235, 235": "65, 65, 65",
|
||||
"240, 240, 240": "80, 80, 80",
|
||||
"250, 250, 250": "90, 90, 90",
|
||||
"220, 255, 220": "80, 80, 80",
|
||||
"210, 255, 210": "90, 90, 90",
|
||||
"255, 255, 255": "20, 20, 20",
|
||||
"245, 245, 245": "40, 40, 40",
|
||||
"235, 235, 235": "30, 30, 30",
|
||||
"240, 240, 240": "70, 70, 70",
|
||||
"250, 250, 250": "80, 80, 80",
|
||||
"220, 255, 220": "70, 70, 70",
|
||||
"210, 255, 210": "80, 80, 80",
|
||||
"0, 0, 0": "255, 255, 255",
|
||||
"_black": "_white"
|
||||
}
|
||||
|
||||
+148
-84
@@ -1,5 +1,72 @@
|
||||
import os, yara, numpy, locale, pefile, onnxruntime
|
||||
import os, yara, numpy, base64, onnxruntime
|
||||
import ctypes, ctypes.wintypes, pefile
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
|
||||
####################################################################################################
|
||||
|
||||
class GUID(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("Data1", ctypes.wintypes.DWORD),
|
||||
("Data2", ctypes.wintypes.WORD),
|
||||
("Data3", ctypes.wintypes.WORD),
|
||||
("Data4", ctypes.c_ubyte * 8)]
|
||||
|
||||
class WINTRUST_FILE_INFO(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("cbStruct", ctypes.wintypes.DWORD),
|
||||
("pcwszFilePath", ctypes.wintypes.LPCWSTR),
|
||||
("hFile", ctypes.wintypes.HANDLE),
|
||||
("pgKnownSubject", ctypes.wintypes.LPVOID)]
|
||||
|
||||
class WINTRUST_DATA(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("cbStruct", ctypes.wintypes.DWORD),
|
||||
("pPolicyCallbackData", ctypes.wintypes.LPVOID),
|
||||
("pSIPClientData", ctypes.wintypes.LPVOID),
|
||||
("dwUIChoice", ctypes.wintypes.DWORD),
|
||||
("fdwRevocationChecks", ctypes.wintypes.DWORD),
|
||||
("dwUnionChoice", ctypes.wintypes.DWORD),
|
||||
("pFile", ctypes.POINTER(WINTRUST_FILE_INFO)),
|
||||
("dwStateAction", ctypes.wintypes.DWORD),
|
||||
("hWVTStateData", ctypes.wintypes.HANDLE),
|
||||
("pwszURLReference", ctypes.wintypes.LPCWSTR),
|
||||
("dwProvFlags", ctypes.wintypes.DWORD),
|
||||
("dwUIContext", ctypes.wintypes.DWORD),
|
||||
("pSignatureSettings", ctypes.wintypes.LPVOID)]
|
||||
|
||||
####################################################################################################
|
||||
|
||||
class sign_scanner:
|
||||
def __init__(self):
|
||||
self.verify = GUID(0x00AAC56B, 0xCD44, 0x11D0, (0x8C, 0xC2, 0x00, 0xC0, 0x4F, 0xC2, 0x95, 0xEE))
|
||||
|
||||
def init_windll(self, path):
|
||||
for name in path:
|
||||
try:
|
||||
setattr(self, name.lower(), ctypes.WinDLL(name, use_last_error=True))
|
||||
except Exception as e:
|
||||
self.send_message(e, "warn", False)
|
||||
|
||||
self.WinVerifyTrust = self.wintrust.WinVerifyTrust
|
||||
self.WinVerifyTrust.restype = ctypes.wintypes.LONG
|
||||
self.WinVerifyTrust.argtypes = [ctypes.wintypes.HWND, ctypes.POINTER(GUID), ctypes.c_void_p]
|
||||
|
||||
def is_sign(self, file_path):
|
||||
with pefile.PE(file_path, fast_load=True) as pe:
|
||||
sec_dir = pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']]
|
||||
return sec_dir.VirtualAddress != 0 and sec_dir.Size > 0
|
||||
|
||||
def sign_verify(self, file_path):
|
||||
fi = WINTRUST_FILE_INFO(ctypes.sizeof(WINTRUST_FILE_INFO), file_path, None, None)
|
||||
data = WINTRUST_DATA(ctypes.sizeof(WINTRUST_DATA), None, None, 2, 0, 1,
|
||||
ctypes.pointer(fi), 1, None, None, 0, 0, None)
|
||||
s = self.WinVerifyTrust(None, ctypes.byref(self.verify), ctypes.byref(data))
|
||||
data.dwStateAction = 2
|
||||
self.WinVerifyTrust(None, ctypes.byref(self.verify), ctypes.byref(data))
|
||||
return s == 0
|
||||
|
||||
####################################################################################################
|
||||
|
||||
class rule_scanner:
|
||||
def __init__(self):
|
||||
@@ -26,9 +93,8 @@ class rule_scanner:
|
||||
|
||||
def yara_scan(self, file_path):
|
||||
try:
|
||||
data = open(file_path, "rb").read() if isinstance(file_path, str) else file_path
|
||||
for rules in self.rules.values():
|
||||
matches = rules.match(data=data)
|
||||
matches = rules.match(filepath=file_path)
|
||||
if matches:
|
||||
rule_name = str(matches[0])
|
||||
label = rule_name.split("_")[0]
|
||||
@@ -38,19 +104,14 @@ class rule_scanner:
|
||||
except Exception:
|
||||
return False, False
|
||||
|
||||
####################################################################################################
|
||||
|
||||
class model_scanner:
|
||||
def __init__(self):
|
||||
self.models = {}
|
||||
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.model = None
|
||||
self.suffix = {".com", ".dll", ".drv", ".exe", ".ocx", ".scr", ".sys"}
|
||||
self.labels = ["Pefile/White", "Pefile/General"]
|
||||
self.detect_set = {"Pefile/General"}
|
||||
self.resize = (224, 224)
|
||||
|
||||
def load_path(self, path):
|
||||
@@ -61,84 +122,87 @@ class model_scanner:
|
||||
def load_file(self, file):
|
||||
if file.lower().endswith('.onnx'):
|
||||
try:
|
||||
self.models[file] = onnxruntime.InferenceSession(file)
|
||||
self.model = onnxruntime.InferenceSession(file)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def model_scan(self, file_path):
|
||||
def model_scan(self, file_path, full_output=False):
|
||||
if not self.model:
|
||||
return (False, False) if not full_output else ([], str(file_path), None)
|
||||
|
||||
sections = self.extract_sections(file_path)
|
||||
if not sections:
|
||||
return (False, False) if not full_output else ([], str(file_path), None)
|
||||
|
||||
images = [self.preprocess_image(data, self.resize) for data in sections.values()]
|
||||
if not images:
|
||||
return (False, False) if not full_output else ([], str(file_path), None)
|
||||
|
||||
arr = numpy.stack([numpy.asarray(img).astype('float32') / 255.0 for img in images])
|
||||
if arr.ndim == 3:
|
||||
arr = numpy.expand_dims(arr, axis=-1)
|
||||
|
||||
input_meta = self.model.get_inputs()[0]
|
||||
input_name = input_meta.name
|
||||
input_shape = input_meta.shape
|
||||
|
||||
if len(input_shape) == 4:
|
||||
if input_shape[1] in (1, 3) and input_shape[3] not in (1, 3):
|
||||
arr = arr.transpose(0, 3, 1, 2)
|
||||
try:
|
||||
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)
|
||||
|
||||
file_sections = self.get_type(file_path)
|
||||
if not file_sections:
|
||||
return False, False
|
||||
|
||||
batch_images = [self.preprocess_image(data, self.resize, channels) for data in file_sections.values()]
|
||||
arr = numpy.stack([numpy.asarray(img).astype('float32') / 255.0 for img in batch_images])
|
||||
if arr.ndim == 3:
|
||||
arr = arr[..., None]
|
||||
if shape[-1] in (1, 3):
|
||||
model_input = arr
|
||||
elif shape[1] in (1, 3):
|
||||
model_input = arr.transpose(0, 3, 1, 2)
|
||||
else:
|
||||
return False, False
|
||||
|
||||
input_name = model.get_inputs()[0].name
|
||||
predictions = model.run(None, {input_name: model_input})[0]
|
||||
|
||||
label_scores = {label: [] for label in self.labels}
|
||||
for pre_answers in predictions:
|
||||
for k, score in enumerate(pre_answers):
|
||||
label_scores[self.labels[k]].append(score)
|
||||
label_percentage = {label: (sum(scores)/len(scores))*100 for label, scores in label_scores.items() if scores}
|
||||
if not label_percentage:
|
||||
return False, False
|
||||
best_label, best_conf = max(label_percentage.items(), key=lambda x: x[1])
|
||||
if best_label in self.detect:
|
||||
return best_label, int(best_conf)
|
||||
return False, False
|
||||
probs = self.model.run(None, {input_name: arr})[0]
|
||||
except Exception:
|
||||
return False, False
|
||||
return (False, False) if not full_output else ([], str(file_path), None)
|
||||
|
||||
def preprocess_image(self, file_data, size, channels=1):
|
||||
results = []
|
||||
best_malicious = None
|
||||
|
||||
for name, pred, img in zip(sections.keys(), probs, images):
|
||||
idx = int(numpy.argmax(pred))
|
||||
label = self.labels[idx] if idx < len(self.labels) else f"Class_{idx}"
|
||||
conf = round(float(pred[idx]) * 100, 2)
|
||||
print(f"Section: {name} | Label: {label} | Confidence: {conf}%")
|
||||
|
||||
if full_output:
|
||||
results.append((name, label, conf, self.pil_to_base64(img)))
|
||||
if label in self.detect_set:
|
||||
if best_malicious is None or conf > best_malicious[1]:
|
||||
best_malicious = (label, int(conf))
|
||||
|
||||
if full_output:
|
||||
results.sort(key=lambda x: (x[1] not in self.detect_set, -x[2]))
|
||||
malicious_count = sum(1 for _, lbl, _, _ in results if lbl in self.detect_set)
|
||||
total = len(results)
|
||||
return results, str(file_path), f"{malicious_count}/{total}"
|
||||
|
||||
return best_malicious if best_malicious else (False, False)
|
||||
|
||||
def pil_to_base64(self, img):
|
||||
buf = BytesIO()
|
||||
img.save(buf, format='PNG')
|
||||
return base64.b64encode(buf.getvalue()).decode()
|
||||
|
||||
def preprocess_image(self, data, size, channels=1):
|
||||
width, height = size
|
||||
wah = int(numpy.ceil(numpy.sqrt(len(file_data) / channels)))
|
||||
arr = numpy.frombuffer(file_data, dtype=numpy.uint8)
|
||||
img = numpy.zeros(wah*wah*channels, dtype=numpy.uint8)
|
||||
img[:len(file_data)] = arr
|
||||
if channels == 1:
|
||||
image = Image.fromarray(img.reshape((wah, wah)), 'L')
|
||||
else:
|
||||
image = Image.fromarray(img.reshape((wah, wah, channels)), 'RGB')
|
||||
wah = int(numpy.ceil(numpy.sqrt(len(data) / channels)))
|
||||
arr = numpy.frombuffer(data, dtype=numpy.uint8)
|
||||
imgbuf = numpy.zeros(wah * wah * channels, dtype=numpy.uint8)
|
||||
imgbuf[:len(arr)] = arr
|
||||
image = Image.fromarray(imgbuf.reshape((wah, wah)), 'L')
|
||||
return image.resize((width, height), Image.Resampling.NEAREST)
|
||||
|
||||
def is_text_file(self, content, sample_size=1024):
|
||||
raw = content[:sample_size]
|
||||
if not raw:
|
||||
return False
|
||||
text_char = set(range(32, 127)) | {9, 10, 13}
|
||||
nontext = sum(b not in text_char for b in raw)
|
||||
return nontext / len(raw) < 0.15
|
||||
|
||||
def get_type(self, file_path):
|
||||
def extract_sections(self, file_path):
|
||||
match_data = {}
|
||||
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:
|
||||
sec = pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']]
|
||||
if bool(sec.VirtualAddress and sec.Size):
|
||||
return {}
|
||||
for section in pe.sections:
|
||||
name = section.Name.rstrip(b'\x00').decode('latin1').lower()
|
||||
if section.Characteristics & 0x00000020:
|
||||
match_data[name] = section.get_data()
|
||||
except pefile.PEFormatError:
|
||||
with open(file_path, 'rb') as f:
|
||||
file_content = f.read()
|
||||
if self.is_text_file(file_content):
|
||||
match_data[os.path.splitext(file_path)[-1].lower()] = file_content
|
||||
fpath_str = str(file_path)
|
||||
ext = os.path.splitext(fpath_str)[-1].lower()
|
||||
if ext in self.suffix:
|
||||
try:
|
||||
with pefile.PE(fpath_str, fast_load=True) as pe:
|
||||
for section in pe.sections:
|
||||
name = section.Name.rstrip(b'\x00').decode('latin1', errors='ignore').lower()
|
||||
data = section.get_data()
|
||||
if data:
|
||||
match_data[name] = data
|
||||
except Exception:
|
||||
pass
|
||||
return match_data
|
||||
+33
-30
@@ -1437,8 +1437,8 @@ class Ui_main_window(object):
|
||||
self.info_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:10pt; font-weight:400; font-style:normal;\">\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))
|
||||
"</style></head><body style=\" font-family:'PMingLiU'; font-size:10pt; font-weight:400; font-style:normal;\">\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; font-family:'MS Shell Dlg 2';\"><br /></p></body></html>", None))
|
||||
self.sensitive_title.setText(QCoreApplication.translate("main_window", u"\u589e\u5f37\u6a21\u5f0f", None))
|
||||
self.sensitive_text.setText(QCoreApplication.translate("main_window", u"\u6b64\u9078\u9805\u53ef\u4ee5\u589e\u5f37\u6383\u63cf\u5f15\u64ce", None))
|
||||
self.sensitive_switch.setText(QCoreApplication.translate("main_window", u"\u95dc\u9589", None))
|
||||
@@ -1477,39 +1477,42 @@ class Ui_main_window(object):
|
||||
"<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:'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-15</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">87owo Publicly Available Source Code 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-12-19</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 & Ownership</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 and 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"
|
||||
"rgin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - This software and its source code are source available for public view.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - Access or execution of certain features may require an activation key.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - 87owo reserves all legal rights, no intellectual property is transferred.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - All project archives, source code, and binaries remain fully 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;\">2. Use & 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 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=\" margin-top:0px; margin-bottom:0px; margin-left:0px; mar"
|
||||
"gin-right:0px; -qt-block-indent:0; text-indent:0px;\">2. Use and Prohibitions</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - You may view, download, and modify the code for local and personal use.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - Redistribution of any original or modified code requires prior consent.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - Commercial hosting or SaaS deployment is prohibited without permission.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - Reverse engineering, license removal, or illegal use is strictly barred.</p>\n"
|
||||
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-blo"
|
||||
"ck-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. Data and Privacy</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - This project may collect operational data for optimization and analysis.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - All collected data is strictly anonymized to ensure the user's privacy.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - Transmission of information is encrypted to prevent unauthorized access.</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 & 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=\" margin-top:0px; margin-bottom:0px; m"
|
||||
"argin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">4. Updates and Terms</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - New releases may include critical patches, enhancements, or UI changes.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - Continued use of these services constitutes acceptance of updated terms.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - The author reserves the right to modify these license terms at any time.</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 & 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 "as is," 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))
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">5. Warranty and Liabi"
|
||||
"lity</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - All services and assets are provided "as is" without any form of warranty.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - 87owo is not liable for any direct or indirect damages from software use.</p>\n"
|
||||
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> - Users assume all risks regarding performance, data, and system integrity.</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-2026 87owo (PYAS Security). All rights reserved.</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
@@ -2,7 +2,7 @@ import pyinstaller_versionfile
|
||||
|
||||
pyinstaller_versionfile.create_versionfile(
|
||||
output_file="versionfile.txt",
|
||||
version='3.3.4',
|
||||
version='3.3.7',
|
||||
company_name="PYAS Security",
|
||||
file_description="Python Antivirus Software",
|
||||
internal_name="PYAS",
|
||||
|
||||
@@ -12,6 +12,10 @@ BOOLEAN g_Unloading = FALSE;
|
||||
BOOLEAN g_CmRegActive = FALSE;
|
||||
EX_RUNDOWN_REF g_Rundown;
|
||||
PDEVICE_OBJECT g_GuardDevice = NULL;
|
||||
PDRIVER_OBJECT g_DriverObject = NULL;
|
||||
|
||||
PDEVICE_OBJECT g_MbrFilterTargets[MAX_MBR_TARGETS] = { 0 };
|
||||
ULONG g_MbrFilterCount = 0;
|
||||
|
||||
volatile LONG g_LogWorkCount = 0;
|
||||
static UNICODE_STRING g_DeviceName;
|
||||
@@ -34,23 +38,23 @@ static NTSTATUS CombinedDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp)
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
return IoCallDriver((PDEVICE_OBJECT)DeviceObject->DeviceExtension, 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);
|
||||
|
||||
return BootProtectDispatch(DeviceObject, Irp);
|
||||
}
|
||||
|
||||
static NTSTATUS AttachDiskFilters(PDRIVER_OBJECT DriverObject)
|
||||
@@ -58,6 +62,7 @@ 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;
|
||||
|
||||
@@ -72,12 +77,14 @@ static NTSTATUS AttachDiskFilters(PDRIVER_OBJECT DriverObject)
|
||||
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);
|
||||
@@ -85,24 +92,29 @@ static NTSTATUS AttachDiskFilters(PDRIVER_OBJECT DriverObject)
|
||||
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);
|
||||
@@ -112,21 +124,25 @@ static NTSTATUS AttachDiskFilters(PDRIVER_OBJECT DriverObject)
|
||||
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(RegistryPath);
|
||||
|
||||
|
||||
g_DriverObject = DriverObject;
|
||||
|
||||
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))
|
||||
if (!NT_SUCCESS(gs))
|
||||
return STATUS_DEVICE_BUSY;
|
||||
}
|
||||
|
||||
{
|
||||
LARGE_INTEGER t = KeQueryPerformanceCounter(NULL);
|
||||
g_DeviceName.Buffer = g_DeviceNameBuf;
|
||||
@@ -134,14 +150,18 @@ NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
|
||||
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))
|
||||
if (!NT_SUCCESS(status))
|
||||
return status;
|
||||
|
||||
|
||||
DriverObject->DriverUnload = DriverUnload;
|
||||
for (ULONG i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; ++i)
|
||||
for (ULONG i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; ++i)
|
||||
DriverObject->MajorFunction[i] = CombinedDispatch;
|
||||
|
||||
DriverObject->Flags |= 0x20;
|
||||
g_ControlDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
|
||||
|
||||
IoDeleteSymbolicLink(&g_SymLink);
|
||||
{
|
||||
UINT i = 0;
|
||||
@@ -157,50 +177,70 @@ NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
|
||||
if (!NT_SUCCESS(status)) {
|
||||
IoDeleteDevice(g_ControlDeviceObject);
|
||||
g_ControlDeviceObject = NULL;
|
||||
if (g_GuardDevice) {
|
||||
IoDeleteDevice(g_GuardDevice);
|
||||
g_GuardDevice = 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(®Alt, regAltBuf);
|
||||
|
||||
status = CmRegisterCallbackEx(RegistryProtectCallback, ®Alt, DriverObject, NULL, &g_CmRegHandle, NULL);
|
||||
if (NT_SUCCESS(status))
|
||||
if (NT_SUCCESS(status))
|
||||
g_CmRegActive = TRUE;
|
||||
}
|
||||
|
||||
InitImageProtect();
|
||||
InitInjectProtect();
|
||||
InitRemoteProtect();
|
||||
InitScreenProtect();
|
||||
InitProcessProtect();
|
||||
|
||||
InitFileProtect();
|
||||
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;
|
||||
}
|
||||
|
||||
UninitFileProtect();
|
||||
UninitInjectProtect();
|
||||
UninitImageProtect();
|
||||
UninitRemoteProtect();
|
||||
UninitScreenProtect();
|
||||
UninitProcessProtect();
|
||||
|
||||
ExWaitForRundownProtectionRelease(&g_Rundown);
|
||||
|
||||
if (InterlockedCompareExchange((volatile LONG*)&g_LogWorkCount, 0, 0) != 0) {
|
||||
KeWaitForSingleObject(&g_LogDrainEvent, Executive, KernelMode, FALSE, NULL);
|
||||
}
|
||||
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);
|
||||
@@ -209,6 +249,7 @@ VOID DriverUnload(PDRIVER_OBJECT DriverObject)
|
||||
}
|
||||
}
|
||||
g_MbrFilterCount = 0;
|
||||
|
||||
if (DiskDrvObj) {
|
||||
ObDereferenceObject(DiskDrvObj);
|
||||
DiskDrvObj = NULL;
|
||||
@@ -221,4 +262,4 @@ VOID DriverUnload(PDRIVER_OBJECT DriverObject)
|
||||
IoDeleteDevice(g_GuardDevice);
|
||||
g_GuardDevice = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,17 @@
|
||||
#include <ntifs.h>
|
||||
#include <ntstrsafe.h>
|
||||
#include <ntdddisk.h>
|
||||
#include <ntddscsi.h>
|
||||
#include <fltKernel.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_TERMINATE
|
||||
#define PROCESS_TERMINATE 0x0001
|
||||
#endif
|
||||
#ifndef PROCESS_CREATE_THREAD
|
||||
#define PROCESS_CREATE_THREAD 0x0002
|
||||
#endif
|
||||
@@ -28,7 +32,7 @@
|
||||
#define PROCESS_CREATE_PROCESS 0x0080
|
||||
#endif
|
||||
#ifndef PROCESS_SET_QUOTA
|
||||
#define PROCESS_SET_QUOTA 0x0100
|
||||
#define PROCESS_SET_QUota 0x0100
|
||||
#endif
|
||||
#ifndef PROCESS_SET_INFORMATION
|
||||
#define PROCESS_SET_INFORMATION 0x0200
|
||||
@@ -42,29 +46,50 @@
|
||||
#ifndef PROCESS_SET_LIMITED_INFORMATION
|
||||
#define PROCESS_SET_LIMITED_INFORMATION 0x2000
|
||||
#endif
|
||||
#ifndef THREAD_TERMINATE
|
||||
#define THREAD_TERMINATE 0x0001
|
||||
#endif
|
||||
#ifndef THREAD_SUSPEND_RESUME
|
||||
#define THREAD_SUSPEND_RESUME 0x0002
|
||||
#endif
|
||||
#ifndef THREAD_SET_CONTEXT
|
||||
#define THREAD_SET_CONTEXT 0x0010
|
||||
#endif
|
||||
#ifndef THREAD_IMPERSONATE
|
||||
#define THREAD_IMPERSONATE 0x0100
|
||||
#endif
|
||||
#ifndef THREAD_DIRECT_IMPERSONATION
|
||||
#define THREAD_DIRECT_IMPERSONATION 0x0200
|
||||
#endif
|
||||
#ifndef JOB_OBJECT_ASSIGN_PROCESS
|
||||
#define JOB_OBJECT_ASSIGN_PROCESS 0x0001
|
||||
#endif
|
||||
#ifndef JOB_OBJECT_TERMINATE
|
||||
#define JOB_OBJECT_TERMINATE 0x0008
|
||||
#endif
|
||||
#ifndef FILE_DISPOSITION_DELETE
|
||||
#define FILE_DISPOSITION_DELETE 0x00000001
|
||||
#endif
|
||||
#ifndef UINT
|
||||
typedef unsigned int UINT;
|
||||
#endif
|
||||
#define MAX_MBR_TARGETS 64
|
||||
|
||||
extern POBJECT_TYPE* PsJobType;
|
||||
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 POBJECT_TYPE* IoFileObjectType;
|
||||
extern FAST_MUTEX HookMutex;
|
||||
extern PDRIVER_OBJECT DiskDrvObj;
|
||||
extern PCSTR PsGetProcessImageFileName(PEPROCESS Process);
|
||||
extern EX_RUNDOWN_REF g_Rundown;
|
||||
extern PDEVICE_OBJECT g_GuardDevice;
|
||||
extern PDRIVER_OBJECT g_DriverObject;
|
||||
extern PFLT_FILTER g_FilterHandle;
|
||||
|
||||
NTSYSAPI PCSTR NTAPI PsGetProcessImageFileName(PEPROCESS Process);
|
||||
|
||||
typedef PVOID(NTAPI* _pyas_ExAllocatePool2)(ULONG, SIZE_T, ULONG);
|
||||
typedef VOID(NTAPI* _pyas_ExFreePool2)(PVOID, ULONG, PVOID, ULONG);
|
||||
@@ -74,14 +99,14 @@ 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);
|
||||
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");
|
||||
UNICODE_STRING n = RTL_CONSTANT_STRING(L"ExAllocatePoolWithTag");
|
||||
p1 = (_pyas_ExAllocatePoolWithTag)MmGetSystemRoutineAddress(&n);
|
||||
}
|
||||
if (p1)
|
||||
@@ -92,9 +117,10 @@ static __forceinline PVOID PYAS_ExAllocatePool2(ULONG f, SIZE_T s, ULONG t) {
|
||||
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");
|
||||
if (!p2) {
|
||||
UNICODE_STRING n = RTL_CONSTANT_STRING(L"ExFreePool2");
|
||||
p2 = (_pyas_ExFreePool2)MmGetSystemRoutineAddress(&n);
|
||||
}
|
||||
if (p2) {
|
||||
@@ -102,13 +128,13 @@ static __forceinline VOID PYAS_ExFreePool2(PVOID a, ULONG t, PVOID h, ULONG f) {
|
||||
return;
|
||||
}
|
||||
static _pyas_ExFreePoolWithTag p1 = 0;
|
||||
if (!p1) {
|
||||
if (!p1) {
|
||||
UNICODE_STRING n = RTL_CONSTANT_STRING(L"ExFreePoolWithTag");
|
||||
p1 = (_pyas_ExFreePoolWithTag)MmGetSystemRoutineAddress(&n);
|
||||
}
|
||||
if (p1) {
|
||||
if (p1) {
|
||||
p1(a, t);
|
||||
return;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,6 +145,12 @@ VOID DriverUnload(PDRIVER_OBJECT DriverObject);
|
||||
VOID SendPipeLog(PCSTR msg, SIZE_T len);
|
||||
VOID UninitImageProtect(VOID);
|
||||
VOID UninitInjectProtect(VOID);
|
||||
VOID UninitRemoteProtect(VOID);
|
||||
VOID UninitScreenProtect(VOID);
|
||||
VOID UninitProcessProtect(VOID);
|
||||
VOID UninitFileProtect(VOID);
|
||||
|
||||
VOID LogAnsi3(PCSTR tag, ULONG upid, PUNICODE_STRING s1, PUNICODE_STRING s2);
|
||||
|
||||
NTSYSAPI NTSTATUS NTAPI ZwQueryInformationProcess(
|
||||
_In_ HANDLE ProcessHandle,
|
||||
@@ -139,9 +171,17 @@ NTSTATUS ObReferenceObjectByName(
|
||||
OUT PVOID* Object
|
||||
);
|
||||
|
||||
NTSTATUS FileProtectDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp);
|
||||
NTSTATUS BootProtectDispatch(
|
||||
PDEVICE_OBJECT DeviceObject,
|
||||
PIRP Irp
|
||||
);
|
||||
|
||||
NTSTATUS RegistryProtectCallback(PVOID ctx, PVOID arg1, PVOID arg2);
|
||||
NTSTATUS InitImageProtect(VOID);
|
||||
NTSTATUS InitInjectProtect(VOID);
|
||||
NTSTATUS InitRemoteProtect(VOID);
|
||||
NTSTATUS InitScreenProtect(VOID);
|
||||
NTSTATUS InitProcessProtect(VOID);
|
||||
NTSTATUS InitFileProtect(VOID);
|
||||
|
||||
BOOLEAN GetProcessImagePathByPid(HANDLE pid, PUNICODE_STRING ProcessImagePath);
|
||||
@@ -1,4 +1,5 @@
|
||||
#include <ntifs.h>
|
||||
#include <ntstrsafe.h>
|
||||
#include "DriverEntry.h"
|
||||
|
||||
extern PDEVICE_OBJECT g_ControlDeviceObject;
|
||||
@@ -17,19 +18,20 @@ static VOID PipeLogWork(PDEVICE_OBJECT DeviceObject, PVOID Context)
|
||||
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)))
|
||||
{
|
||||
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)
|
||||
|
||||
if (InterlockedDecrement(&g_LogWorkCount) == 0) {
|
||||
KeSetEvent(&g_LogDrainEvent, IO_NO_INCREMENT, FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
VOID SendPipeLog(PCSTR msg, SIZE_T len)
|
||||
@@ -40,11 +42,9 @@ VOID SendPipeLog(PCSTR msg, SIZE_T len)
|
||||
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) {
|
||||
@@ -61,3 +61,20 @@ VOID SendPipeLog(PCSTR msg, SIZE_T len)
|
||||
InterlockedIncrement(&g_LogWorkCount);
|
||||
IoQueueWorkItem(ctx->Item, PipeLogWork, DelayedWorkQueue, ctx);
|
||||
}
|
||||
|
||||
VOID LogAnsi3(PCSTR tag, ULONG upid, PUNICODE_STRING s1, PUNICODE_STRING s2)
|
||||
{
|
||||
ANSI_STRING a1 = { 0 }, a2 = { 0 };
|
||||
CHAR buf[1024] = { 0 };
|
||||
|
||||
if (s1)
|
||||
RtlUnicodeStringToAnsiString(&a1, s1, TRUE);
|
||||
if (s2)
|
||||
RtlUnicodeStringToAnsiString(&a2, s2, TRUE);
|
||||
|
||||
RtlStringCchPrintfA(buf, RTL_NUMBER_OF(buf), "%s | %u | %s | %s", tag, upid, a1.Buffer ? a1.Buffer : "", a2.Buffer ? a2.Buffer : "");
|
||||
SendPipeLog(buf, strlen(buf));
|
||||
|
||||
RtlFreeAnsiString(&a1);
|
||||
RtlFreeAnsiString(&a2);
|
||||
}
|
||||
+139
-87
@@ -1,11 +1,86 @@
|
||||
#include <ntifs.h>
|
||||
#include "DriverEntry.h"
|
||||
#include "ProtectRules.h"
|
||||
#include "ProtectMatch.h"
|
||||
|
||||
PDEVICE_OBJECT g_MbrFilterTargets[MAX_MBR_TARGETS] = { 0 };
|
||||
ULONG g_MbrFilterCount = 0;
|
||||
#define PROTECTED_BOOT_AREA_SIZE (34 * 512)
|
||||
|
||||
NTSTATUS FileProtectDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp)
|
||||
static VOID GetExeNameForLog(HANDLE pid, PUNICODE_STRING exe)
|
||||
{
|
||||
if (!exe || !exe->Buffer || exe->MaximumLength == 0)
|
||||
return;
|
||||
|
||||
exe->Length = 0;
|
||||
if (KeGetCurrentIrql() == PASSIVE_LEVEL) {
|
||||
if (GetProcessImagePathByPid(pid, exe))
|
||||
return;
|
||||
}
|
||||
PEPROCESS eproc = PsGetCurrentProcess();
|
||||
PCSTR n = PsGetProcessImageFileName(eproc);
|
||||
size_t l = n ? strlen(n) : 0;
|
||||
|
||||
for (size_t i = 0; i < l && i < (exe->MaximumLength / sizeof(WCHAR)) - 1; i++)
|
||||
exe->Buffer[i] = (WCHAR)n[i];
|
||||
exe->Buffer[l] = 0;
|
||||
exe->Length = (USHORT)(l * sizeof(WCHAR));
|
||||
}
|
||||
|
||||
static BOOLEAN QueryDevName(PDEVICE_OBJECT dev, PUNICODE_STRING out)
|
||||
{
|
||||
if (KeGetCurrentIrql() > APC_LEVEL)
|
||||
return FALSE;
|
||||
|
||||
if (!dev || !out || !out->Buffer || out->MaximumLength == 0)
|
||||
return FALSE;
|
||||
|
||||
ULONG need = 0;
|
||||
NTSTATUS s = ObQueryNameString(dev, NULL, 0, &need);
|
||||
if (s != STATUS_INFO_LENGTH_MISMATCH || need == 0)
|
||||
return FALSE;
|
||||
|
||||
POBJECT_NAME_INFORMATION oni = (POBJECT_NAME_INFORMATION)ExAllocatePool2(POOL_FLAG_NON_PAGED, need, 'nOmD');
|
||||
if (!oni)
|
||||
return FALSE;
|
||||
|
||||
BOOLEAN ok = FALSE;
|
||||
s = ObQueryNameString(dev, oni, need, &need);
|
||||
if (NT_SUCCESS(s) && oni->Name.Buffer && oni->Name.Length && oni->Name.Length < out->MaximumLength) {
|
||||
RtlCopyMemory(out->Buffer, oni->Name.Buffer, oni->Name.Length);
|
||||
out->Length = (USHORT)oni->Name.Length;
|
||||
out->Buffer[out->Length / sizeof(WCHAR)] = 0;
|
||||
ok = TRUE;
|
||||
}
|
||||
ExFreePool2(oni, 'nOmD', NULL, 0);
|
||||
return ok;
|
||||
}
|
||||
|
||||
static BOOLEAN IsDangerousDiskIo(PIO_STACK_LOCATION s)
|
||||
{
|
||||
if (!s) return FALSE;
|
||||
|
||||
if (s->MajorFunction == IRP_MJ_DEVICE_CONTROL || s->MajorFunction == IRP_MJ_INTERNAL_DEVICE_CONTROL) {
|
||||
ULONG code = s->Parameters.DeviceIoControl.IoControlCode;
|
||||
if (code == IOCTL_DISK_SET_DRIVE_LAYOUT || code == IOCTL_DISK_SET_DRIVE_LAYOUT_EX) return TRUE;
|
||||
if (code == IOCTL_DISK_DELETE_DRIVE_LAYOUT) return TRUE;
|
||||
if (code == IOCTL_DISK_FORMAT_TRACKS || code == IOCTL_DISK_FORMAT_TRACKS_EX) return TRUE;
|
||||
if (code == IOCTL_DISK_SET_PARTITION_INFO || code == IOCTL_DISK_SET_PARTITION_INFO_EX) return TRUE;
|
||||
if (code == IOCTL_SCSI_PASS_THROUGH || code == IOCTL_SCSI_PASS_THROUGH_DIRECT) return TRUE;
|
||||
}
|
||||
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
static BOOLEAN IsBootSectorWrite(PIO_STACK_LOCATION s)
|
||||
{
|
||||
if (s->MajorFunction == IRP_MJ_WRITE) {
|
||||
LARGE_INTEGER offset = s->Parameters.Write.ByteOffset;
|
||||
if (offset.QuadPart < PROTECTED_BOOT_AREA_SIZE) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
NTSTATUS BootProtectDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp)
|
||||
{
|
||||
PDEVICE_OBJECT lower = (PDEVICE_OBJECT)DeviceObject->DeviceExtension;
|
||||
if (!lower) {
|
||||
@@ -14,110 +89,87 @@ NTSTATUS FileProtectDispatch(PDEVICE_OBJECT DeviceObject, PIRP Irp)
|
||||
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);
|
||||
NTSTATUS rs = IoCallDriver(lower, Irp);
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return st;
|
||||
return rs;
|
||||
}
|
||||
PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);
|
||||
if (stack->MajorFunction == IRP_MJ_POWER) {
|
||||
|
||||
PIO_STACK_LOCATION s = IoGetCurrentIrpStackLocation(Irp);
|
||||
|
||||
if (s->MajorFunction == IRP_MJ_POWER) {
|
||||
PoStartNextPowerIrp(Irp);
|
||||
IoSkipCurrentIrpStackLocation(Irp);
|
||||
NTSTATUS st = PoCallDriver(lower, Irp);
|
||||
NTSTATUS ps = PoCallDriver(lower, Irp);
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return st;
|
||||
return ps;
|
||||
}
|
||||
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;
|
||||
HANDLE pid = PsGetCurrentProcessId();
|
||||
ULONG upid = (ULONG)(ULONG_PTR)pid;
|
||||
|
||||
if (upid == 0 || upid == 4) {
|
||||
IoSkipCurrentIrpStackLocation(Irp);
|
||||
NTSTATUS ns = IoCallDriver(lower, Irp);
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return ns;
|
||||
}
|
||||
|
||||
BOOLEAN blocked = FALSE;
|
||||
WCHAR eb[512] = { 0 };
|
||||
UNICODE_STRING exe = { 0 };
|
||||
exe.Buffer = eb;
|
||||
exe.MaximumLength = sizeof(eb);
|
||||
|
||||
if (KeGetCurrentIrql() == PASSIVE_LEVEL) {
|
||||
GetExeNameForLog(pid, &exe);
|
||||
if (IsWhitelist(&exe)) {
|
||||
IoSkipCurrentIrpStackLocation(Irp);
|
||||
NTSTATUS ns2 = IoCallDriver(lower, Irp);
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return ns2;
|
||||
}
|
||||
}
|
||||
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));
|
||||
|
||||
if (lower->DeviceType == FILE_DEVICE_DISK) {
|
||||
if (IsDangerousDiskIo(s)) {
|
||||
blocked = TRUE;
|
||||
}
|
||||
|
||||
if (!blocked && IsBootSectorWrite(s)) {
|
||||
blocked = TRUE;
|
||||
}
|
||||
|
||||
if (blocked) {
|
||||
if (KeGetCurrentIrql() <= APC_LEVEL) {
|
||||
WCHAR db[512] = { 0 };
|
||||
UNICODE_STRING dev = { 0 };
|
||||
dev.Buffer = db;
|
||||
dev.MaximumLength = sizeof(db);
|
||||
QueryDevName(lower, &dev);
|
||||
|
||||
LogAnsi3("BOOT_BLOCK", upid, &exe, dev.Length ? &dev : &exe);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (blocked) {
|
||||
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);
|
||||
NTSTATUS rs2 = IoCallDriver(lower, Irp);
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return st;
|
||||
}
|
||||
return rs2;
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
#include <ntifs.h>
|
||||
#include <fltKernel.h>
|
||||
#include "DriverEntry.h"
|
||||
#include "ProtectMatch.h"
|
||||
|
||||
#pragma comment(lib, "FltMgr.lib")
|
||||
|
||||
PFLT_FILTER g_FilterHandle = NULL;
|
||||
extern PDRIVER_OBJECT g_DriverObject;
|
||||
EX_RUNDOWN_REF g_Rundown;
|
||||
|
||||
// 定義標誌以便在不同 IRQL 下安全操作
|
||||
#define MAX_PATH_LEN 512
|
||||
|
||||
// 獲取進程名稱 (僅在確定需要攔截時調用,減少性能開銷)
|
||||
static VOID GetExeNameSafe(HANDLE pid, PUNICODE_STRING exe)
|
||||
{
|
||||
if (!exe || !exe->Buffer || !exe->MaximumLength)
|
||||
return;
|
||||
|
||||
exe->Length = 0;
|
||||
|
||||
// 嘗試獲取短名稱 (最安全)
|
||||
PEPROCESS cur = PsGetCurrentProcess();
|
||||
PCSTR n = NULL;
|
||||
if (cur) n = PsGetProcessImageFileName(cur);
|
||||
|
||||
// 如果在 PASSIVE_LEVEL,嘗試獲取完整路徑 (用於精確白名單)
|
||||
// 注意:這裡依然有風險,但僅在攔截路徑執行
|
||||
if (KeGetCurrentIrql() == PASSIVE_LEVEL) {
|
||||
if (GetProcessImagePathByPid(pid, exe)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 降級方案:使用短名稱
|
||||
size_t l = n ? strlen(n) : 0;
|
||||
for (size_t i = 0; i < l && i < (exe->MaximumLength / sizeof(WCHAR)) - 1; i++)
|
||||
exe->Buffer[i] = (WCHAR)n[i];
|
||||
exe->Buffer[l] = 0;
|
||||
exe->Length = (USHORT)(l * sizeof(WCHAR));
|
||||
}
|
||||
|
||||
static BOOLEAN PreOpCheck(VOID)
|
||||
{
|
||||
if (g_Unloading)
|
||||
return FALSE;
|
||||
if (!ExAcquireRundownProtection(&g_Rundown))
|
||||
return FALSE;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static VOID PostOpRelease(VOID)
|
||||
{
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
}
|
||||
|
||||
static BOOLEAN IsDeleteOrRename(PFLT_CALLBACK_DATA Data)
|
||||
{
|
||||
FILE_INFORMATION_CLASS infoClass = Data->Iopb->Parameters.SetFileInformation.FileInformationClass;
|
||||
|
||||
if (infoClass == FileDispositionInformation) {
|
||||
PFILE_DISPOSITION_INFORMATION di = (PFILE_DISPOSITION_INFORMATION)Data->Iopb->Parameters.SetFileInformation.InfoBuffer;
|
||||
return di && di->DeleteFile;
|
||||
}
|
||||
if (infoClass == FileDispositionInformationEx) {
|
||||
PFILE_DISPOSITION_INFORMATION_EX dx = (PFILE_DISPOSITION_INFORMATION_EX)Data->Iopb->Parameters.SetFileInformation.InfoBuffer;
|
||||
return dx && (dx->Flags & FILE_DISPOSITION_DELETE);
|
||||
}
|
||||
if (infoClass == FileRenameInformation || infoClass == FileRenameInformationEx)
|
||||
return TRUE;
|
||||
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
static BOOLEAN IsWriteAccess(PFLT_CALLBACK_DATA Data)
|
||||
{
|
||||
// 如果是寫入操作,直接返回
|
||||
if (Data->Iopb->MajorFunction == IRP_MJ_WRITE)
|
||||
return TRUE;
|
||||
|
||||
// 如果是設置信息 (已經通過 IsDeleteOrRename 過濾),視為寫入(修改元數據)
|
||||
if (Data->Iopb->MajorFunction == IRP_MJ_SET_INFORMATION)
|
||||
return TRUE;
|
||||
|
||||
// 如果是創建/打開文件,檢查權限
|
||||
if (Data->Iopb->MajorFunction == IRP_MJ_CREATE) {
|
||||
ULONG access = Data->Iopb->Parameters.Create.SecurityContext->DesiredAccess;
|
||||
// 檢查是否包含寫入數據、追加數據、刪除、修改屬性等權限
|
||||
if (access & (FILE_WRITE_DATA | FILE_APPEND_DATA | DELETE |
|
||||
WRITE_DAC | WRITE_OWNER | GENERIC_WRITE | GENERIC_ALL)) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
static FLT_PREOP_CALLBACK_STATUS FilePreOp(
|
||||
_Inout_ PFLT_CALLBACK_DATA Data,
|
||||
_In_ PCFLT_RELATED_OBJECTS FltObjects,
|
||||
_Flt_CompletionContext_Outptr_ PVOID* CompletionContext
|
||||
)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(FltObjects);
|
||||
UNREFERENCED_PARAMETER(CompletionContext);
|
||||
|
||||
// 1. 基礎檢查 (Paging IO 不攔截)
|
||||
if (FlagOn(Data->Iopb->IrpFlags, IRP_PAGING_IO)) {
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
if (!PreOpCheck())
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
|
||||
// 2. 獲取 PID
|
||||
HANDLE pid = PsGetCurrentProcessId();
|
||||
ULONG upid = (ULONG)(ULONG_PTR)pid;
|
||||
|
||||
// 忽略 System (4) 和 Idle (0) 進程,避免系統崩潰
|
||||
if (upid == 0 || upid == 4) {
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
// 3. 檢查操作類型 (僅關心 Create, Write, SetInfo)
|
||||
BOOLEAN checkFile = (Data->Iopb->MajorFunction == IRP_MJ_CREATE || Data->Iopb->MajorFunction == IRP_MJ_WRITE);
|
||||
BOOLEAN checkSetInfo = (Data->Iopb->MajorFunction == IRP_MJ_SET_INFORMATION);
|
||||
|
||||
if (!checkFile && !checkSetInfo) {
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
if (checkSetInfo && !IsDeleteOrRename(Data)) {
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
// 4. 獲取文件名 (這一步最關鍵)
|
||||
PFLT_FILE_NAME_INFORMATION nameInfo = NULL;
|
||||
// 使用 QUERY_DEFAULT | NORMALIZED 確保獲取標準化路徑
|
||||
NTSTATUS status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &nameInfo);
|
||||
|
||||
if (!NT_SUCCESS(status)) {
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
status = FltParseFileNameInformation(nameInfo);
|
||||
if (!NT_SUCCESS(status)) {
|
||||
FltReleaseFileNameInformation(nameInfo);
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
// 5. 邏輯判斷 (優化順序:文件名白名單 -> 黑名單 -> 操作檢查 -> 進程白名單)
|
||||
|
||||
// A. 全局文件白名單 (例如 Windows 目錄下的某些操作)
|
||||
if (IsWhitelist(&nameInfo->Name)) {
|
||||
FltReleaseFileNameInformation(nameInfo);
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
// B. 黑名單匹配
|
||||
BOOLEAN hitFile = MatchBlockFile(&nameInfo->Name);
|
||||
// 勒索防護:必須在敏感目錄 且 有敏感後綴 (如 .txt, .doc)
|
||||
// 註:Updater.bat 產生 .txt,應命中這裡
|
||||
BOOLEAN hitRansom = MatchBlockRansom(&nameInfo->Name) && HasBlockedSuffix(&nameInfo->Name);
|
||||
|
||||
// 如果沒有命中任何規則,直接放行,節省資源
|
||||
if (!hitFile && !hitRansom) {
|
||||
FltReleaseFileNameInformation(nameInfo);
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
// C. 檢查是否為寫入行為 (讀取不攔截)
|
||||
if (!IsWriteAccess(Data)) {
|
||||
FltReleaseFileNameInformation(nameInfo);
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
// D. 到了這裡,說明命中規則且正在寫入,準備攔截
|
||||
// 這時候才去獲取進程名稱,檢查進程白名單
|
||||
WCHAR exe_buffer[MAX_PATH_LEN] = { 0 };
|
||||
UNICODE_STRING exe = { 0 };
|
||||
exe.Buffer = exe_buffer;
|
||||
exe.MaximumLength = sizeof(exe_buffer);
|
||||
|
||||
GetExeNameSafe(pid, &exe); // 獲取進程名
|
||||
|
||||
if (IsWhitelistExcept(&exe)) {
|
||||
// 進程在白名單中 (如 ntoskrnl, explorer 等)
|
||||
FltReleaseFileNameInformation(nameInfo);
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
// E. 執行攔截
|
||||
if (hitRansom) {
|
||||
LogAnsi3("RANSOM_BLOCK", upid, &exe, &nameInfo->Name);
|
||||
Data->IoStatus.Status = STATUS_ACCESS_DENIED;
|
||||
Data->IoStatus.Information = 0;
|
||||
FltReleaseFileNameInformation(nameInfo);
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_COMPLETE;
|
||||
}
|
||||
|
||||
if (hitFile) {
|
||||
LogAnsi3("FILE_BLOCK", upid, &exe, &nameInfo->Name);
|
||||
Data->IoStatus.Status = STATUS_ACCESS_DENIED;
|
||||
Data->IoStatus.Information = 0;
|
||||
FltReleaseFileNameInformation(nameInfo);
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_COMPLETE;
|
||||
}
|
||||
|
||||
// 默認放行
|
||||
FltReleaseFileNameInformation(nameInfo);
|
||||
PostOpRelease();
|
||||
return FLT_PREOP_SUCCESS_NO_CALLBACK;
|
||||
}
|
||||
|
||||
static NTSTATUS FilterUnloadCallback(FLT_FILTER_UNLOAD_FLAGS Flags)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(Flags);
|
||||
g_Unloading = TRUE;
|
||||
ExWaitForRundownProtectionRelease(&g_Rundown);
|
||||
if (g_FilterHandle != NULL) {
|
||||
FltUnregisterFilter(g_FilterHandle);
|
||||
g_FilterHandle = NULL;
|
||||
}
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
static NTSTATUS FilterInstanceSetup(
|
||||
_In_ PCFLT_RELATED_OBJECTS FltObjects,
|
||||
_In_ FLT_INSTANCE_SETUP_FLAGS Flags,
|
||||
_In_ DEVICE_TYPE VolumeDeviceType,
|
||||
_In_ FLT_FILESYSTEM_TYPE VolumeFilesystemType
|
||||
)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(FltObjects);
|
||||
UNREFERENCED_PARAMETER(Flags);
|
||||
UNREFERENCED_PARAMETER(VolumeDeviceType);
|
||||
UNREFERENCED_PARAMETER(VolumeFilesystemType);
|
||||
// 自動附加到所有卷
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
static VOID FilterInstanceTeardownStart(
|
||||
_In_ PCFLT_RELATED_OBJECTS FltObjects,
|
||||
_In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
|
||||
)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(FltObjects);
|
||||
UNREFERENCED_PARAMETER(Flags);
|
||||
}
|
||||
|
||||
static VOID FilterInstanceTeardownComplete(
|
||||
_In_ PCFLT_RELATED_OBJECTS FltObjects,
|
||||
_In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
|
||||
)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(FltObjects);
|
||||
UNREFERENCED_PARAMETER(Flags);
|
||||
}
|
||||
|
||||
const FLT_OPERATION_REGISTRATION Callbacks[] = {
|
||||
{ IRP_MJ_CREATE, 0, FilePreOp, NULL },
|
||||
{ IRP_MJ_WRITE, 0, FilePreOp, NULL },
|
||||
{ IRP_MJ_SET_INFORMATION, 0, FilePreOp, NULL },
|
||||
{ IRP_MJ_OPERATION_END }
|
||||
};
|
||||
|
||||
const FLT_REGISTRATION FilterRegistration = {
|
||||
sizeof(FLT_REGISTRATION),
|
||||
FLT_REGISTRATION_VERSION,
|
||||
0,
|
||||
NULL,
|
||||
Callbacks,
|
||||
FilterUnloadCallback,
|
||||
FilterInstanceSetup,
|
||||
NULL,
|
||||
FilterInstanceTeardownStart,
|
||||
FilterInstanceTeardownComplete,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
NTSTATUS InitFileProtect(VOID)
|
||||
{
|
||||
ExInitializeRundownProtection(&g_Rundown);
|
||||
|
||||
if (!g_DriverObject)
|
||||
return STATUS_UNSUCCESSFUL;
|
||||
|
||||
NTSTATUS status = FltRegisterFilter(g_DriverObject, &FilterRegistration, &g_FilterHandle);
|
||||
if (!NT_SUCCESS(status))
|
||||
return status;
|
||||
|
||||
status = FltStartFiltering(g_FilterHandle);
|
||||
if (!NT_SUCCESS(status)) {
|
||||
FltUnregisterFilter(g_FilterHandle);
|
||||
g_FilterHandle = NULL;
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
VOID UninitFileProtect(VOID)
|
||||
{
|
||||
g_Unloading = TRUE;
|
||||
ExWaitForRundownProtectionRelease(&g_Rundown);
|
||||
if (g_FilterHandle != NULL) {
|
||||
FltUnregisterFilter(g_FilterHandle);
|
||||
g_FilterHandle = NULL;
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,15 @@
|
||||
#include <ntifs.h>
|
||||
#include "DriverEntry.h"
|
||||
#include "ProtectRules.h"
|
||||
#include "ProtectMatch.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) {
|
||||
static BOOLEAN CheckVadExec(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)
|
||||
@@ -45,7 +21,8 @@ static BOOLEAN CheckStackVAD(PVOID a) {
|
||||
return (mbi.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)) != 0;
|
||||
}
|
||||
|
||||
static BOOLEAN CheckShellcodeWalkStack(ULONG h) {
|
||||
static BOOLEAN WalkForShellcode(ULONG h)
|
||||
{
|
||||
#define MAXWALK 20
|
||||
PVOID frames[MAXWALK] = { 0 };
|
||||
ULONG c = RtlWalkFrameChain(frames, MAXWALK, 1);
|
||||
@@ -58,99 +35,88 @@ static BOOLEAN CheckShellcodeWalkStack(ULONG h) {
|
||||
|
||||
for (ULONG i = 0; i < d; i++) {
|
||||
PVOID p = frames[i];
|
||||
if (p && CheckStackVAD(p))
|
||||
if (p && CheckVadExec(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))
|
||||
if (p && CheckVadExec(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)
|
||||
if (g_Unloading)
|
||||
return;
|
||||
if (ProcessId == (HANDLE)0 || ProcessId == (HANDLE)4)
|
||||
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)) {
|
||||
|
||||
WCHAR eb[512] = { 0 };
|
||||
UNICODE_STRING exe = { 0 };
|
||||
exe.Buffer = eb;
|
||||
exe.MaximumLength = sizeof(eb);
|
||||
exe.Length = 0;
|
||||
|
||||
if (!GetProcessImagePathByPid(ProcessId, &exe)) {
|
||||
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));
|
||||
for (size_t i = 0; i < l && i < RTL_NUMBER_OF(eb) - 1; i++)
|
||||
eb[i] = (WCHAR)n[i];
|
||||
eb[l] = 0;
|
||||
exe.Length = (USHORT)(l * sizeof(WCHAR));
|
||||
}
|
||||
if (exeName.Length & 1) exeName.Length--;
|
||||
if (exe.Length & 1) exe.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));
|
||||
size_t elen = exe.Length / sizeof(WCHAR);
|
||||
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) ||
|
||||
(elen >= 10 && _wcsnicmp(exe.Buffer + elen - 10, L"sppsvc.exe", 10) == 0)) {
|
||||
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));
|
||||
if (IsWhitelist(&exe)) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return;
|
||||
}
|
||||
if (FullImageName && FullImageName->Buffer) {
|
||||
if (MatchClrFromNonFramework(FullImageName)) {
|
||||
LogAnsi3("CLR_BLOCK", (ULONG)(ULONG_PTR)ProcessId, &exe, FullImageName);
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (WalkForShellcode(8)) {
|
||||
UNICODE_STRING none = RTL_CONSTANT_STRING(L"None");
|
||||
LogAnsi3("SHELLCODE_BLOCK", (ULONG)(ULONG_PTR)ProcessId, &exe, &none);
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return;
|
||||
}
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
}
|
||||
|
||||
NTSTATUS InitImageProtect(VOID) {
|
||||
NTSTATUS InitImageProtect(VOID)
|
||||
{
|
||||
NTSTATUS s = PsSetLoadImageNotifyRoutine(ImageLoadNotify);
|
||||
if (NT_SUCCESS(s))
|
||||
g_ImageNotifyEnabled = TRUE;
|
||||
return s;
|
||||
}
|
||||
|
||||
VOID UninitImageProtect(VOID) {
|
||||
VOID UninitImageProtect(VOID)
|
||||
{
|
||||
if (g_ImageNotifyEnabled) {
|
||||
PsRemoveLoadImageNotifyRoutine(ImageLoadNotify);
|
||||
g_ImageNotifyEnabled = FALSE;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#include <ntifs.h>
|
||||
#include "DriverEntry.h"
|
||||
#include "ProtectRules.h"
|
||||
#include "ProtectMatch.h"
|
||||
|
||||
static PVOID g_ObRegHandle = NULL;
|
||||
static POB_OPERATION_REGISTRATION g_ObOps = NULL;
|
||||
@@ -11,22 +11,22 @@ static OB_PREOP_CALLBACK_STATUS PreProcessCallback(PVOID RegistrationContext, PO
|
||||
UNREFERENCED_PARAMETER(RegistrationContext);
|
||||
if (g_Unloading)
|
||||
return OB_PREOP_SUCCESS;
|
||||
if (!Info || Info->KernelHandle)
|
||||
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))
|
||||
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;
|
||||
return OB_PREOP_SUCCESS;
|
||||
}
|
||||
HANDLE target = PsGetProcessId((PEPROCESS)Info->Object);
|
||||
if (target == cur) {
|
||||
if (target == cur) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return OB_PREOP_SUCCESS;
|
||||
}
|
||||
@@ -35,9 +35,9 @@ static OB_PREOP_CALLBACK_STATUS PreProcessCallback(PVOID RegistrationContext, PO
|
||||
PCSTR tn = PsGetProcessImageFileName((PEPROCESS)Info->Object);
|
||||
if (tn && (_stricmp(tn, "lsass.exe") == 0))
|
||||
mask |= PROCESS_VM_READ;
|
||||
|
||||
|
||||
if ((*desired & mask) == 0) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return OB_PREOP_SUCCESS;
|
||||
}
|
||||
BOOLEAN logok = (KeGetCurrentIrql() == PASSIVE_LEVEL);
|
||||
@@ -45,31 +45,27 @@ static OB_PREOP_CALLBACK_STATUS PreProcessCallback(PVOID RegistrationContext, PO
|
||||
UNICODE_STRING cexe = { 0 }, texe = { 0 };
|
||||
cexe.Buffer = cbuf; cexe.MaximumLength = sizeof(cbuf);
|
||||
texe.Buffer = tbuf; texe.MaximumLength = sizeof(tbuf);
|
||||
|
||||
if (logok)
|
||||
|
||||
if (logok)
|
||||
GetProcessImagePathByPid(cur, &cexe);
|
||||
if (logok && IsWhitelist(&cexe)) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return OB_PREOP_SUCCESS;
|
||||
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++)
|
||||
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));
|
||||
LogAnsi3("INJECT_BLOCK", (ULONG)(ULONG_PTR)cur, &cexe, &texe);
|
||||
}
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return OB_PREOP_SUCCESS;
|
||||
@@ -78,29 +74,29 @@ static OB_PREOP_CALLBACK_STATUS PreProcessCallback(PVOID RegistrationContext, PO
|
||||
static OB_PREOP_CALLBACK_STATUS PreThreadCallback(PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION Info)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(RegistrationContext);
|
||||
if (!Info || Info->KernelHandle)
|
||||
if (!Info || Info->KernelHandle)
|
||||
return OB_PREOP_SUCCESS;
|
||||
if (Info->Object == NULL)
|
||||
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))
|
||||
if (!ExAcquireRundownProtection(&g_Rundown))
|
||||
return OB_PREOP_SUCCESS;
|
||||
|
||||
|
||||
HANDLE cur = PsGetCurrentProcessId();
|
||||
if (cur == (HANDLE)0 || cur == (HANDLE)4) {
|
||||
if (cur == (HANDLE)0 || cur == (HANDLE)4) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return OB_PREOP_SUCCESS;
|
||||
return OB_PREOP_SUCCESS;
|
||||
}
|
||||
HANDLE owner = PsGetThreadProcessId((PETHREAD)Info->Object);
|
||||
if (owner == cur) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return OB_PREOP_SUCCESS;
|
||||
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);
|
||||
if ((*desired & tmask) == 0) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return OB_PREOP_SUCCESS;
|
||||
}
|
||||
BOOLEAN logok = (KeGetCurrentIrql() == PASSIVE_LEVEL);
|
||||
@@ -108,47 +104,41 @@ static OB_PREOP_CALLBACK_STATUS PreThreadCallback(PVOID RegistrationContext, POB
|
||||
UNICODE_STRING cexe = { 0 };
|
||||
cexe.Buffer = cbuf;
|
||||
cexe.MaximumLength = sizeof(cbuf);
|
||||
|
||||
if (logok)
|
||||
|
||||
if (logok)
|
||||
GetProcessImagePathByPid(cur, &cexe);
|
||||
if (logok && IsWhitelist(&cexe)) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return OB_PREOP_SUCCESS;
|
||||
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));
|
||||
UNICODE_STRING tnone = RTL_CONSTANT_STRING(L"None");
|
||||
LogAnsi3("THREAD_BLOCK", (ULONG)(ULONG_PTR)cur, &cexe, &tnone);
|
||||
}
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return OB_PREOP_SUCCESS;
|
||||
}
|
||||
|
||||
NTSTATUS InitInjectProtect(VOID)
|
||||
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);
|
||||
|
||||
RtlInitUnicodeString(&obAlt, L"385000");
|
||||
|
||||
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;
|
||||
@@ -156,14 +146,14 @@ NTSTATUS InitInjectProtect(VOID)
|
||||
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);
|
||||
@@ -175,7 +165,7 @@ NTSTATUS InitInjectProtect(VOID)
|
||||
|
||||
VOID UninitInjectProtect(VOID)
|
||||
{
|
||||
if (g_ObRegHandle) {
|
||||
if (g_ObRegHandle) {
|
||||
ObUnRegisterCallbacks(g_ObRegHandle);
|
||||
g_ObRegHandle = NULL;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
#include <ntifs.h>
|
||||
#include "DriverEntry.h"
|
||||
#include "ProtectRules.h"
|
||||
#include "ProtectMatch.h"
|
||||
|
||||
static __forceinline BOOLEAN USOK(PUNICODE_STRING s)
|
||||
{
|
||||
return s && s->Buffer && s->Length;
|
||||
}
|
||||
|
||||
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 (!USOK(s) || !list)
|
||||
return FALSE;
|
||||
|
||||
SIZE_T s_len = s->Length / sizeof(WCHAR);
|
||||
for (SIZE_T i = 0; list[i]; ++i) {
|
||||
wchar_t* pat = list[i];
|
||||
if (wcschr(pat, L'*') || wcschr(pat, L'?')) {
|
||||
if (WildMatchN(s->Buffer, s_len, pat))
|
||||
return TRUE;
|
||||
}
|
||||
else {
|
||||
SIZE_T pat_len = wcslen(pat);
|
||||
if (s_len >= pat_len && _wcsnicmp(s->Buffer, pat, pat_len) == 0) {
|
||||
if (s_len == pat_len || s->Buffer[s_len - pat_len - 1] == L'\\') {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
if (s_len >= pat_len && _wcsnicmp(s->Buffer + s_len - pat_len, pat, pat_len) == 0) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
static wchar_t* MatchListGetRule(PUNICODE_STRING s, wchar_t** list)
|
||||
{
|
||||
if (!USOK(s) || !list)
|
||||
return 0;
|
||||
|
||||
SIZE_T s_len = s->Length / sizeof(WCHAR);
|
||||
for (SIZE_T i = 0; list[i]; ++i) {
|
||||
wchar_t* pat = list[i];
|
||||
if (wcschr(pat, L'*') || wcschr(pat, L'?')) {
|
||||
if (WildMatchN(s->Buffer, s_len, pat))
|
||||
return pat;
|
||||
}
|
||||
else {
|
||||
SIZE_T pat_len = wcslen(pat);
|
||||
if (s_len >= pat_len && _wcsnicmp(s->Buffer, pat, pat_len) == 0) {
|
||||
if (s_len == pat_len || s->Buffer[s_len - pat_len - 1] == L'\\') {
|
||||
return pat;
|
||||
}
|
||||
}
|
||||
if (s_len >= pat_len && _wcsnicmp(s->Buffer + s_len - pat_len, pat, pat_len) == 0) {
|
||||
return pat;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static BOOLEAN StrStrIW(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++) {
|
||||
if (_wcsnicmp(s + i, sub, m) == 0)
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
static BOOLEAN EndsWithNameUS(PUNICODE_STRING s, const wchar_t* name)
|
||||
{
|
||||
if (!USOK(s) || !name)
|
||||
return FALSE;
|
||||
|
||||
SIZE_T n = s->Length / sizeof(WCHAR);
|
||||
SIZE_T m = wcslen(name);
|
||||
return n >= m && _wcsnicmp(s->Buffer + (n - m), name, m) == 0;
|
||||
}
|
||||
|
||||
BOOLEAN IsRegistryBlock(PUNICODE_STRING key, PUNICODE_STRING valueName, PUNICODE_STRING exe)
|
||||
{
|
||||
if (USOK(key) && WildMatchN(key->Buffer, key->Length / sizeof(WCHAR), L"\\REGISTRY\\MACHINE\\SYSTEM\\ControlSet001\\Services\\**"))
|
||||
return FALSE;
|
||||
|
||||
if (USOK(exe) && IsWhitelist(exe))
|
||||
return FALSE;
|
||||
|
||||
if (USOK(exe) && USOK(key)) {
|
||||
if ((EndsWithNameUS(exe, L"services.exe") || EndsWithNameUS(exe, L"svchost.exe") || EndsWithNameUS(exe, L"sc.exe")) &&
|
||||
WildMatchN(key->Buffer, key->Length / sizeof(WCHAR), L"\\REGISTRY\\**\\SYSTEM\\CurrentControlSet\\Services\\**"))
|
||||
return FALSE;
|
||||
|
||||
if ((EndsWithNameUS(exe, L"powershell.exe") || EndsWithNameUS(exe, L"pwsh.exe")) &&
|
||||
(WildMatchN(key->Buffer, key->Length / sizeof(WCHAR), L"\\REGISTRY\\**\\CurrentVersion\\Internet Settings\\ZoneMap\\**") ||
|
||||
WildMatchN(key->Buffer, key->Length / sizeof(WCHAR), L"\\REGISTRY\\**\\CurrentVersion\\Internet Settings\\ZoneMap") ||
|
||||
WildMatchN(key->Buffer, key->Length / sizeof(WCHAR), L"\\REGISTRY\\**\\CurrentVersion\\Notifications\\Data\\**") ||
|
||||
WildMatchN(key->Buffer, key->Length / sizeof(WCHAR), L"\\REGISTRY\\**\\CurrentVersion\\Notifications\\Data")))
|
||||
return FALSE;
|
||||
|
||||
if ((EndsWithNameUS(exe, L"msiexec.exe") || EndsWithNameUS(exe, L"TrustedInstaller.exe")) &&
|
||||
(WildMatchN(key->Buffer, key->Length / sizeof(WCHAR), L"\\REGISTRY\\**\\CurrentVersion\\Installer\\**") ||
|
||||
WildMatchN(key->Buffer, key->Length / sizeof(WCHAR), L"\\REGISTRY\\**\\CurrentVersion\\Uninstall\\**") ||
|
||||
WildMatchN(key->Buffer, key->Length / sizeof(WCHAR), L"\\REGISTRY\\**\\SYSTEM\\CurrentControlSet\\Services\\**")))
|
||||
return FALSE;
|
||||
|
||||
if (EndsWithNameUS(exe, L"schtasks.exe") && WildMatchN(key->Buffer, key->Length / sizeof(WCHAR), L"\\REGISTRY\\**\\Windows NT\\CurrentVersion\\Schedule\\TaskCache\\**"))
|
||||
return FALSE;
|
||||
}
|
||||
if (USOK(key) && MatchBlockReg(key))
|
||||
return TRUE;
|
||||
|
||||
if (USOK(valueName)) {
|
||||
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'?') && _wcsnicmp(valueName->Buffer, pat, wcslen(pat)) == 0)
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
BOOLEAN GetProcessImagePathByPid(HANDLE pid, PUNICODE_STRING ProcessImagePath)
|
||||
{
|
||||
PEPROCESS process = NULL;
|
||||
PVOID buf = NULL;
|
||||
HANDLE h = NULL;
|
||||
NTSTATUS status;
|
||||
ULONG len = 0;
|
||||
|
||||
status = PsLookupProcessByProcessId(pid, &process);
|
||||
if (!NT_SUCCESS(status))
|
||||
return FALSE;
|
||||
|
||||
status = ObOpenObjectByPointer(process, OBJ_KERNEL_HANDLE, NULL, PROCESS_QUERY_LIMITED_INFORMATION, *PsProcessType, KernelMode, &h);
|
||||
if (!NT_SUCCESS(status))
|
||||
goto cleanup;
|
||||
|
||||
status = ZwQueryInformationProcess(h, ProcessImageFileName, NULL, 0, &len);
|
||||
if (status != STATUS_INFO_LENGTH_MISMATCH || len == 0)
|
||||
goto cleanup;
|
||||
|
||||
buf = ExAllocatePool2(POOL_FLAG_NON_PAGED, len, 'iPgN');
|
||||
if (!buf)
|
||||
goto cleanup;
|
||||
|
||||
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;
|
||||
status = TRUE;
|
||||
}
|
||||
else {
|
||||
status = FALSE;
|
||||
}
|
||||
}
|
||||
else {
|
||||
status = FALSE;
|
||||
}
|
||||
cleanup:
|
||||
if (buf)
|
||||
ExFreePool2(buf, 'iPgN', NULL, 0);
|
||||
if (h)
|
||||
ZwClose(h);
|
||||
if (process)
|
||||
ObDereferenceObject(process);
|
||||
return NT_SUCCESS(status);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
BOOLEAN MatchBlockFile(PUNICODE_STRING s)
|
||||
{
|
||||
return MatchList(s, g_BlockFile);
|
||||
}
|
||||
|
||||
BOOLEAN MatchBlockRansom(PUNICODE_STRING s)
|
||||
{
|
||||
return MatchList(s, g_BlockRansom);
|
||||
}
|
||||
|
||||
wchar_t* GetMatchedBlockFileRule(PUNICODE_STRING s)
|
||||
{
|
||||
return MatchListGetRule(s, g_BlockFile);
|
||||
}
|
||||
|
||||
BOOLEAN HasBlockedSuffix(PUNICODE_STRING s)
|
||||
{
|
||||
if (!USOK(s)) {
|
||||
return FALSE;
|
||||
}
|
||||
for (SIZE_T i = 0; g_Blocksuffix[i]; ++i) {
|
||||
if (EndsWithNameUS(s, g_Blocksuffix[i])) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
BOOLEAN MatchRemoteSuspectBin(PUNICODE_STRING img)
|
||||
{
|
||||
if (!USOK(img))
|
||||
return FALSE;
|
||||
|
||||
for (SIZE_T i = 0; g_RemoteSuspectBins[i]; ++i)
|
||||
if (EndsWithNameUS(img, g_RemoteSuspectBins[i]))
|
||||
return TRUE;
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
BOOLEAN MatchRemoteCommand(PUNICODE_STRING cmd, PUNICODE_STRING img)
|
||||
{
|
||||
if (!USOK(cmd))
|
||||
return FALSE;
|
||||
|
||||
const wchar_t* s = cmd->Buffer;
|
||||
for (SIZE_T i = 0; g_RemoteCmdIndicatorsHttp[i]; ++i)
|
||||
if (StrStrIW(s, g_RemoteCmdIndicatorsHttp[i]))
|
||||
return TRUE;
|
||||
|
||||
for (SIZE_T i = 0; g_RemoteCmdIndicatorsGeneric[i]; ++i)
|
||||
if (StrStrIW(s, g_RemoteCmdIndicatorsGeneric[i]))
|
||||
return TRUE;
|
||||
|
||||
if (USOK(img) && EndsWithNameUS(img, L"cmd.exe")) {
|
||||
for (SIZE_T i = 0; g_RemoteCmdFromCmdExe[i]; ++i)
|
||||
if (StrStrIW(s, g_RemoteCmdFromCmdExe[i]))
|
||||
return TRUE;
|
||||
}
|
||||
if (USOK(img) && EndsWithNameUS(img, L"rundll32.exe")) {
|
||||
for (SIZE_T i = 0; g_RemoteCmdFromRundll32Exe[i]; ++i)
|
||||
if (StrStrIW(s, g_RemoteCmdFromRundll32Exe[i]))
|
||||
return TRUE;
|
||||
}
|
||||
if (USOK(img) && EndsWithNameUS(img, L"regsvr32.exe") && StrStrIW(s, L"/i:") && StrStrIW(s, L"http"))
|
||||
return TRUE;
|
||||
|
||||
if (USOK(img) && EndsWithNameUS(img, L"mshta.exe")) {
|
||||
for (SIZE_T i = 0; g_RemoteCmdFromMshtaExe[i]; ++i)
|
||||
if (StrStrIW(s, g_RemoteCmdFromMshtaExe[i]))
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
BOOLEAN MatchScreenCapModule(PUNICODE_STRING mod)
|
||||
{
|
||||
if (!USOK(mod))
|
||||
return FALSE;
|
||||
|
||||
for (SIZE_T i = 0; g_ScreenCapModules[i]; ++i)
|
||||
if (EndsWithNameUS(mod, g_ScreenCapModules[i]))
|
||||
return TRUE;
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
BOOLEAN MatchSuspiciousProcPath(PUNICODE_STRING img)
|
||||
{
|
||||
if (!USOK(img))
|
||||
return FALSE;
|
||||
|
||||
const wchar_t* s = img->Buffer;
|
||||
if (StrStrIW(s, L"\\Users\\")) {
|
||||
for (SIZE_T i = 0; g_ScreenUserSubdirs[i]; ++i)
|
||||
if (StrStrIW(s, g_ScreenUserSubdirs[i]))
|
||||
return TRUE;
|
||||
}
|
||||
for (SIZE_T i = 0; g_ScreenOtherProcNeedles[i]; ++i)
|
||||
if (StrStrIW(s, g_ScreenOtherProcNeedles[i]))
|
||||
return TRUE;
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
BOOLEAN MatchClrFromNonFramework(PUNICODE_STRING fullImageName)
|
||||
{
|
||||
if (!USOK(fullImageName))
|
||||
return FALSE;
|
||||
|
||||
const wchar_t* s = fullImageName->Buffer;
|
||||
return (StrStrIW(s, L"\\clr.dll") || StrStrIW(s, L"\\mscorwks.dll")) && !StrStrIW(s, L"\\Windows\\Microsoft.NET\\") && !StrStrIW(s, L"\\Framework");
|
||||
}
|
||||
|
||||
BOOLEAN IsWhitelistExcept(PUNICODE_STRING img)
|
||||
{
|
||||
if (!USOK(img))
|
||||
return FALSE;
|
||||
|
||||
return MatchList(img, g_WhitelistExcept);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include <ntifs.h>
|
||||
|
||||
wchar_t* GetMatchedBlockRegRule(PUNICODE_STRING s);
|
||||
wchar_t* GetMatchedBlockFileRule(PUNICODE_STRING s);
|
||||
BOOLEAN GetProcessImagePathByPid(HANDLE pid, PUNICODE_STRING ProcessImagePath);
|
||||
|
||||
BOOLEAN IsWhitelist(PUNICODE_STRING s);
|
||||
BOOLEAN IsWhitelistExcept(PUNICODE_STRING img);
|
||||
|
||||
BOOLEAN MatchBlockReg(PUNICODE_STRING s);
|
||||
BOOLEAN IsRegistryBlock(PUNICODE_STRING key, PUNICODE_STRING valueName, PUNICODE_STRING exe);
|
||||
|
||||
BOOLEAN MatchBlockFile(PUNICODE_STRING s);
|
||||
BOOLEAN MatchBlockRansom(PUNICODE_STRING s);
|
||||
BOOLEAN HasBlockedSuffix(PUNICODE_STRING s);
|
||||
|
||||
BOOLEAN MatchRemoteSuspectBin(PUNICODE_STRING img);
|
||||
BOOLEAN MatchRemoteCommand(PUNICODE_STRING cmd, PUNICODE_STRING img);
|
||||
|
||||
BOOLEAN MatchScreenCapModule(PUNICODE_STRING mod);
|
||||
BOOLEAN MatchSuspiciousProcPath(PUNICODE_STRING img);
|
||||
BOOLEAN MatchClrFromNonFramework(PUNICODE_STRING fullImageName);
|
||||
@@ -0,0 +1,125 @@
|
||||
#include <ntifs.h>
|
||||
#include <ntstrsafe.h>
|
||||
#include "DriverEntry.h"
|
||||
|
||||
typedef union _PS_PROTECTION {
|
||||
UCHAR Level;
|
||||
struct {
|
||||
UCHAR Type : 3;
|
||||
UCHAR Audit : 1;
|
||||
UCHAR Signer : 4;
|
||||
} Flags;
|
||||
} PS_PROTECTION, * PPS_PROTECTION;
|
||||
|
||||
static PVOID g_PsSetProcessProtection = NULL;
|
||||
static HANDLE g_ProtectedPid = NULL;
|
||||
static PVOID g_ObCookie = NULL;
|
||||
|
||||
static NTSTATUS SetPPL31(_In_ PEPROCESS proc)
|
||||
{
|
||||
if (!proc || !g_PsSetProcessProtection)
|
||||
return STATUS_PROCEDURE_NOT_FOUND;
|
||||
|
||||
PS_PROTECTION p = { 0 };
|
||||
p.Level = 0x31;
|
||||
((VOID(NTAPI*)(PEPROCESS, PS_PROTECTION))g_PsSetProcessProtection)(proc, p);
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
static OB_PREOP_CALLBACK_STATUS ObPreOperation(
|
||||
_In_ PVOID RegistrationContext,
|
||||
_Inout_ POB_PRE_OPERATION_INFORMATION info
|
||||
)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(RegistrationContext);
|
||||
|
||||
if (!info || info->KernelHandle)
|
||||
return OB_PREOP_SUCCESS;
|
||||
|
||||
if (info->ObjectType == *PsProcessType) {
|
||||
PEPROCESS proc = (PEPROCESS)info->Object;
|
||||
HANDLE pid = PsGetProcessId(proc);
|
||||
if (g_ProtectedPid && pid == g_ProtectedPid && PsGetCurrentProcessId() != g_ProtectedPid) {
|
||||
ACCESS_MASK* mask = (info->Operation == OB_OPERATION_HANDLE_CREATE)
|
||||
? &info->Parameters->CreateHandleInformation.DesiredAccess
|
||||
: &info->Parameters->DuplicateHandleInformation.DesiredAccess;
|
||||
|
||||
if (*mask & PROCESS_TERMINATE) {
|
||||
LogAnsi3("KILL_ATTEMPT",
|
||||
(ULONG)(ULONG_PTR)PsGetCurrentProcessId(),
|
||||
NULL, NULL);
|
||||
*mask &= ~(PROCESS_TERMINATE | PROCESS_VM_WRITE | PROCESS_CREATE_THREAD);
|
||||
}
|
||||
}
|
||||
}
|
||||
return OB_PREOP_SUCCESS;
|
||||
}
|
||||
|
||||
static VOID ProcessNotify(
|
||||
_In_opt_ PEPROCESS Process,
|
||||
_In_ HANDLE Pid,
|
||||
_In_opt_ PPS_CREATE_NOTIFY_INFO CreateInfo
|
||||
)
|
||||
{
|
||||
UNICODE_STRING target = RTL_CONSTANT_STRING(L"\\??\\C:\\PYAS.exe");
|
||||
if (CreateInfo) {
|
||||
if (Process && CreateInfo->ImageFileName &&
|
||||
RtlEqualUnicodeString(CreateInfo->ImageFileName, &target, TRUE)) {
|
||||
|
||||
NTSTATUS st = SetPPL31(Process);
|
||||
UNREFERENCED_PARAMETER(st);
|
||||
|
||||
InterlockedExchangePointer((PVOID*)&g_ProtectedPid, Pid);
|
||||
LogAnsi3("PROC_PPL", (ULONG)(ULONG_PTR)Pid, (PUNICODE_STRING)CreateInfo->ImageFileName, NULL);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (g_ProtectedPid && Pid == g_ProtectedPid) {
|
||||
InterlockedExchangePointer((PVOID*)&g_ProtectedPid, NULL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
NTSTATUS InitProcessProtect(VOID)
|
||||
{
|
||||
UNICODE_STRING n = RTL_CONSTANT_STRING(L"PsSetProcessProtection");
|
||||
g_PsSetProcessProtection = MmGetSystemRoutineAddress(&n);
|
||||
|
||||
static OB_OPERATION_REGISTRATION ops[1];
|
||||
RtlZeroMemory(ops, sizeof(ops));
|
||||
ops[0].ObjectType = PsProcessType;
|
||||
ops[0].Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE;
|
||||
ops[0].PreOperation = ObPreOperation;
|
||||
ops[0].PostOperation = NULL;
|
||||
|
||||
UNICODE_STRING alt = RTL_CONSTANT_STRING(L"321000");
|
||||
OB_CALLBACK_REGISTRATION reg;
|
||||
RtlZeroMemory(®, sizeof(reg));
|
||||
reg.Version = OB_FLT_REGISTRATION_VERSION;
|
||||
reg.OperationRegistrationCount = 1;
|
||||
reg.OperationRegistration = ops;
|
||||
reg.RegistrationContext = NULL;
|
||||
reg.Altitude = alt;
|
||||
|
||||
NTSTATUS s = ObRegisterCallbacks(®, &g_ObCookie);
|
||||
if (!NT_SUCCESS(s)) {
|
||||
g_ObCookie = NULL;
|
||||
return s;
|
||||
}
|
||||
s = PsSetCreateProcessNotifyRoutineEx(ProcessNotify, FALSE);
|
||||
if (!NT_SUCCESS(s)) {
|
||||
ObUnRegisterCallbacks(g_ObCookie);
|
||||
g_ObCookie = NULL;
|
||||
return s;
|
||||
}
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
VOID UninitProcessProtect(VOID)
|
||||
{
|
||||
if (g_ObCookie) {
|
||||
ObUnRegisterCallbacks(g_ObCookie);
|
||||
g_ObCookie = NULL;
|
||||
}
|
||||
PsSetCreateProcessNotifyRoutineEx(ProcessNotify, TRUE);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
#include <ntifs.h>
|
||||
#include "ProtectRules.h"
|
||||
#include "DriverEntry.h"
|
||||
#include "ProtectMatch.h"
|
||||
|
||||
static BOOLEAN QueryRegPathFromObject(PVOID KeyObject, PUNICODE_STRING OutPath, POBJECT_NAME_INFORMATION* OutInfo)
|
||||
{
|
||||
@@ -8,11 +8,11 @@ static BOOLEAN QueryRegPathFromObject(PVOID KeyObject, PUNICODE_STRING OutPath,
|
||||
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);
|
||||
@@ -28,36 +28,35 @@ static BOOLEAN QueryRegPathFromObject(PVOID KeyObject, PUNICODE_STRING OutPath,
|
||||
NTSTATUS RegistryProtectCallback(PVOID ctx, PVOID arg1, PVOID arg2)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(ctx);
|
||||
if (g_Unloading)
|
||||
if (g_Unloading)
|
||||
return STATUS_SUCCESS;
|
||||
if (!ExAcquireRundownProtection(&g_Rundown))
|
||||
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;
|
||||
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)
|
||||
if (canQuery)
|
||||
QueryRegPathFromObject(s->Object, &checkReg, &nameInfo);
|
||||
}
|
||||
else if (type == RegNtPreDeleteValueKey) {
|
||||
@@ -68,7 +67,7 @@ NTSTATUS RegistryProtectCallback(PVOID ctx, PVOID arg1, PVOID arg2)
|
||||
}
|
||||
else if (type == RegNtPreDeleteKey) {
|
||||
PREG_DELETE_KEY_INFORMATION d = (PREG_DELETE_KEY_INFORMATION)arg2;
|
||||
if (canQuery)
|
||||
if (canQuery)
|
||||
QueryRegPathFromObject(d->Object, &checkReg, &nameInfo);
|
||||
}
|
||||
else if (type == RegNtPreRenameKey) {
|
||||
@@ -78,12 +77,12 @@ NTSTATUS RegistryProtectCallback(PVOID ctx, PVOID arg1, PVOID arg2)
|
||||
}
|
||||
else if (type == RegNtPreCreateKeyEx) {
|
||||
PREG_CREATE_KEY_INFORMATION c = (PREG_CREATE_KEY_INFORMATION)arg2;
|
||||
if (c->CompleteName)
|
||||
if (c->CompleteName)
|
||||
checkReg = *c->CompleteName;
|
||||
}
|
||||
else if (type == RegNtPreReplaceKey) {
|
||||
PREG_REPLACE_KEY_INFORMATION rk = (PREG_REPLACE_KEY_INFORMATION)arg2;
|
||||
if (canQuery)
|
||||
if (canQuery)
|
||||
QueryRegPathFromObject(rk->Object, &checkReg, &nameInfo);
|
||||
}
|
||||
else if (type == RegNtPreSaveKey) {
|
||||
@@ -93,7 +92,7 @@ NTSTATUS RegistryProtectCallback(PVOID ctx, PVOID arg1, PVOID arg2)
|
||||
}
|
||||
else if (type == RegNtPreRestoreKey) {
|
||||
PREG_RESTORE_KEY_INFORMATION res = (PREG_RESTORE_KEY_INFORMATION)arg2;
|
||||
if (canQuery)
|
||||
if (canQuery)
|
||||
QueryRegPathFromObject(res->Object, &checkReg, &nameInfo);
|
||||
}
|
||||
else if (type == RegNtPreLoadKey) {
|
||||
@@ -101,11 +100,11 @@ NTSTATUS RegistryProtectCallback(PVOID ctx, PVOID arg1, PVOID arg2)
|
||||
if (lk->KeyName)
|
||||
checkReg = *lk->KeyName;
|
||||
}
|
||||
|
||||
if (checkReg.Buffer || (valueName && valueName->Buffer)) {
|
||||
GetProcessImagePathByPid(pid, &exe);
|
||||
|
||||
if (canQuery)
|
||||
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;
|
||||
}
|
||||
@@ -113,7 +112,7 @@ NTSTATUS RegistryProtectCallback(PVOID ctx, PVOID arg1, PVOID arg2)
|
||||
if (nameInfo)
|
||||
ExFreePool2(nameInfo, 'rgeR', NULL, 0);
|
||||
if (need_log)
|
||||
SendPipeLog(logbuf, strlen(logbuf));
|
||||
LogAnsi3("REG_BLOCK", (ULONG)(ULONG_PTR)pid, &exe, &checkReg);
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return status;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#include <ntifs.h>
|
||||
#include "DriverEntry.h"
|
||||
#include "ProtectMatch.h"
|
||||
|
||||
static BOOLEAN g_RemoteNotifyEnabled = FALSE;
|
||||
|
||||
static VOID ProcessNotifyEx(PEPROCESS Process, HANDLE ProcessId, PPS_CREATE_NOTIFY_INFO CreateInfo)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(Process);
|
||||
UNREFERENCED_PARAMETER(ProcessId);
|
||||
|
||||
if (!CreateInfo)
|
||||
return;
|
||||
if (g_Unloading)
|
||||
return;
|
||||
if (KeGetCurrentIrql() != PASSIVE_LEVEL)
|
||||
return;
|
||||
if (!ExAcquireRundownProtection(&g_Rundown))
|
||||
return;
|
||||
|
||||
HANDLE ppid = CreateInfo->CreatingThreadId.UniqueProcess;
|
||||
if (ppid == (HANDLE)0 || ppid == (HANDLE)4) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return;
|
||||
}
|
||||
UNICODE_STRING parent = { 0 };
|
||||
WCHAR pbuf[512] = { 0 };
|
||||
parent.Buffer = pbuf;
|
||||
parent.MaximumLength = sizeof(pbuf);
|
||||
|
||||
if (!GetProcessImagePathByPid(ppid, &parent)) {
|
||||
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(pbuf) - 1; i++)
|
||||
pbuf[i] = (WCHAR)n[i];
|
||||
pbuf[l] = 0;
|
||||
parent.Length = (USHORT)(l * sizeof(WCHAR));
|
||||
}
|
||||
if (IsWhitelist(&parent)) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return;
|
||||
}
|
||||
UNICODE_STRING img = { 0 };
|
||||
if (CreateInfo->ImageFileName)
|
||||
img = *CreateInfo->ImageFileName;
|
||||
UNICODE_STRING cmd = { 0 };
|
||||
if (CreateInfo->CommandLine)
|
||||
cmd = *CreateInfo->CommandLine;
|
||||
|
||||
BOOLEAN suspect = FALSE;
|
||||
if (MatchRemoteSuspectBin(&img) && MatchRemoteCommand(&cmd, &img))
|
||||
suspect = TRUE;
|
||||
|
||||
if (suspect) {
|
||||
CreateInfo->CreationStatus = STATUS_ACCESS_DENIED;
|
||||
if (cmd.Buffer && cmd.Length)
|
||||
LogAnsi3("REMOTE_BLOCK", (ULONG)(ULONG_PTR)ppid, &parent, &cmd);
|
||||
else if (img.Buffer && img.Length)
|
||||
LogAnsi3("REMOTE_BLOCK", (ULONG)(ULONG_PTR)ppid, &parent, &img);
|
||||
else {
|
||||
UNICODE_STRING none = RTL_CONSTANT_STRING(L"None");
|
||||
LogAnsi3("REMOTE_BLOCK", (ULONG)(ULONG_PTR)ppid, &parent, &none);
|
||||
}
|
||||
}
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
}
|
||||
|
||||
NTSTATUS InitRemoteProtect(VOID)
|
||||
{
|
||||
NTSTATUS s = PsSetCreateProcessNotifyRoutineEx(ProcessNotifyEx, FALSE);
|
||||
if (NT_SUCCESS(s))
|
||||
g_RemoteNotifyEnabled = TRUE;
|
||||
return s;
|
||||
}
|
||||
|
||||
VOID UninitRemoteProtect(VOID)
|
||||
{
|
||||
if (g_RemoteNotifyEnabled) {
|
||||
PsSetCreateProcessNotifyRoutineEx(ProcessNotifyEx, TRUE);
|
||||
g_RemoteNotifyEnabled = FALSE;
|
||||
}
|
||||
}
|
||||
+98
-223
@@ -1,9 +1,7 @@
|
||||
#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",
|
||||
@@ -15,25 +13,18 @@ wchar_t* g_Whitelist[] = {
|
||||
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*\\ntoskrnl.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",
|
||||
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\lsass.exe",
|
||||
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\csrss.exe",
|
||||
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\smss.exe",
|
||||
L"\\Device\\HarddiskVolume*\\Windows\\Sys*\\wininit.exe",
|
||||
NULL
|
||||
};
|
||||
|
||||
@@ -47,7 +38,7 @@ wchar_t* g_AttachDisk[] = {
|
||||
};
|
||||
|
||||
wchar_t* g_BlockFile[] = {
|
||||
L"\\DosDevices\\**",
|
||||
L"\\Device\\Harddisk*\\DR*",
|
||||
L"\\Device\\Harddisk*\\Partition\\**",
|
||||
L"\\Device\\HarddiskVolume*\\Boot\\**",
|
||||
L"\\Device\\HarddiskVolume*\\EFI\\**",
|
||||
@@ -55,9 +46,9 @@ wchar_t* g_BlockFile[] = {
|
||||
L"\\Device\\HarddiskVolume*\\Recovery\\**",
|
||||
L"\\Device\\HarddiskVolume*\\System Volume Information\\**",
|
||||
L"\\Device\\HarddiskVolume*\\Windows\\**",
|
||||
L"\\Device\\HarddiskVolume*\\ProgramData\\PYAS\\**",
|
||||
L"\\Device\\HarddiskVolume*\\$*\\**",
|
||||
|
||||
L"\\Device\\HarddiskVolume*\\ProgramData\\PYAS\\**",
|
||||
L"**\\PYAS.exe",
|
||||
L"**\\CON**",
|
||||
L"**\\PRN**",
|
||||
L"**\\AUX**",
|
||||
@@ -76,6 +67,20 @@ wchar_t* g_BlockRansom[] = {
|
||||
L"\\Device\\HarddiskVolume*\\Users\\*\\Music\\**",
|
||||
L"\\Device\\HarddiskVolume*\\Users\\*\\Pictures\\**",
|
||||
L"\\Device\\HarddiskVolume*\\Users\\*\\Videos\\**",
|
||||
L"\\Device\\HarddiskVolume*\\Users\\*\\OneDrive\\**",
|
||||
NULL
|
||||
};
|
||||
|
||||
wchar_t* g_Blocksuffix[] = {
|
||||
L".exe", L".dll", L".sys", L".com", L".scr",
|
||||
L".zip", L".7z", L".rar", L".tar", L".gz",
|
||||
L".js", L".bat", L".cmd", L".ps1", L".vbs",
|
||||
L".ppt", L".pptx", L".wps", L".txt", L".rtf",
|
||||
L".pdf", L".xls", L".xlsx", L".doc", L".docx",
|
||||
L".jpg", L".jpeg", L".png", L".webp", L".gif",
|
||||
L".mp3", L".wav", L".aac", L".ogg", L".flac",
|
||||
L".mp4", L".avi", L".mov", L".wmv", L".mkv",
|
||||
L".aux", L".cur", L".mui", L".ttf", L".efi",
|
||||
NULL
|
||||
};
|
||||
|
||||
@@ -83,30 +88,10 @@ 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",
|
||||
@@ -181,7 +166,6 @@ wchar_t* g_BlockReg[] = {
|
||||
L"CmdLine",
|
||||
L"SetupType",
|
||||
L"AutoReboot",
|
||||
L"Shell",
|
||||
L"Userinit",
|
||||
L"UIHost",
|
||||
L"Debugger",
|
||||
@@ -195,197 +179,88 @@ wchar_t* g_BlockReg[] = {
|
||||
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);
|
||||
}
|
||||
wchar_t* g_RemoteSuspectBins[] = {
|
||||
L"powershell.exe",
|
||||
L"pwsh.exe",
|
||||
L"wscript.exe",
|
||||
L"cscript.exe",
|
||||
L"mshta.exe",
|
||||
L"rundll32.exe",
|
||||
L"regsvr32.exe",
|
||||
L"cmd.exe",
|
||||
L"bitsadmin.exe",
|
||||
L"msbuild.exe",
|
||||
L"installutil.exe",
|
||||
L"wmic.exe",
|
||||
NULL
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
wchar_t* g_RemoteCmdIndicatorsHttp[] = {
|
||||
L"http://",
|
||||
L"https://",
|
||||
NULL
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
wchar_t* g_RemoteCmdIndicatorsGeneric[] = {
|
||||
L"-enc",
|
||||
L"-e",
|
||||
L"-encodedcommand",
|
||||
L"frombase64string(",
|
||||
L"iex(",
|
||||
L"downloadstring(",
|
||||
NULL
|
||||
};
|
||||
|
||||
static __forceinline BOOLEAN USOK(PUNICODE_STRING s)
|
||||
{
|
||||
return s && s->Buffer && s->Length;
|
||||
}
|
||||
wchar_t* g_RemoteCmdFromCmdExe[] = {
|
||||
L"powershell",
|
||||
L"pwsh",
|
||||
L"mshta",
|
||||
L"rundll32",
|
||||
L"wscript",
|
||||
L"cscript",
|
||||
NULL
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
wchar_t* g_RemoteCmdFromRundll32Exe[] = {
|
||||
L".dll,",
|
||||
L"javascript:",
|
||||
L"http",
|
||||
NULL
|
||||
};
|
||||
|
||||
BOOLEAN GetProcessImagePathByPid(HANDLE pid, PUNICODE_STRING ProcessImagePath)
|
||||
{
|
||||
PEPROCESS process = NULL;
|
||||
NTSTATUS status = PsLookupProcessByProcessId(pid, &process);
|
||||
if (!NT_SUCCESS(status))
|
||||
return FALSE;
|
||||
wchar_t* g_RemoteCmdRegsvr32Need[] = {
|
||||
L"/i:",
|
||||
NULL
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
wchar_t* g_RemoteCmdFromMshtaExe[] = {
|
||||
L"http://",
|
||||
L"https://",
|
||||
NULL
|
||||
};
|
||||
|
||||
BOOLEAN IsWhitelist(PUNICODE_STRING s)
|
||||
{
|
||||
if (MatchList(s, g_WhitelistExcept))
|
||||
return FALSE;
|
||||
return MatchList(s, g_Whitelist);
|
||||
}
|
||||
wchar_t* g_ScreenCapModules[] = {
|
||||
L"windows.graphics.capture.dll",
|
||||
L"dxgi.dll",
|
||||
L"d3d11.dll",
|
||||
L"dwmapi.dll",
|
||||
L"dcomp.dll",
|
||||
L"mfreadwrite.dll",
|
||||
L"mfplat.dll",
|
||||
L"opengl32.dll",
|
||||
L"gdi32full.dll",
|
||||
L"win32u.dll",
|
||||
NULL
|
||||
};
|
||||
|
||||
BOOLEAN MatchBlockReg(PUNICODE_STRING s)
|
||||
{
|
||||
return MatchList(s, g_BlockReg);
|
||||
}
|
||||
wchar_t* g_ScreenUserSubdirs[] = {
|
||||
L"\\AppData\\",
|
||||
L"\\Temp\\",
|
||||
L"\\Downloads\\",
|
||||
NULL
|
||||
};
|
||||
|
||||
wchar_t* GetMatchedBlockRegRule(PUNICODE_STRING s)
|
||||
{
|
||||
return MatchListGetRule(s, g_BlockReg);
|
||||
}
|
||||
wchar_t* g_ScreenOtherProcNeedles[] = {
|
||||
L"\\ProgramData\\",
|
||||
NULL
|
||||
};
|
||||
@@ -1,8 +1,25 @@
|
||||
#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);
|
||||
extern wchar_t* g_Whitelist[];
|
||||
extern wchar_t* g_WhitelistExcept[];
|
||||
|
||||
extern wchar_t* g_AttachDisk[];
|
||||
extern wchar_t* g_BlockFile[];
|
||||
extern wchar_t* g_BlockRansom[];
|
||||
extern wchar_t* g_Blocksuffix[];
|
||||
|
||||
extern wchar_t* g_BlockReg[];
|
||||
|
||||
extern wchar_t* g_RemoteSuspectBins[];
|
||||
|
||||
extern wchar_t* g_RemoteCmdIndicatorsHttp[];
|
||||
extern wchar_t* g_RemoteCmdIndicatorsGeneric[];
|
||||
extern wchar_t* g_RemoteCmdFromCmdExe[];
|
||||
extern wchar_t* g_RemoteCmdFromRundll32Exe[];
|
||||
extern wchar_t* g_RemoteCmdRegsvr32Need[];
|
||||
extern wchar_t* g_RemoteCmdFromMshtaExe[];
|
||||
|
||||
extern wchar_t* g_ScreenCapModules[];
|
||||
extern wchar_t* g_ScreenUserSubdirs[];
|
||||
extern wchar_t* g_ScreenOtherProcNeedles[];
|
||||
@@ -0,0 +1,67 @@
|
||||
#include <ntifs.h>
|
||||
#include "DriverEntry.h"
|
||||
#include "ProtectMatch.h"
|
||||
|
||||
static BOOLEAN g_ScreenImgCb = FALSE;
|
||||
|
||||
static VOID ImageLoadNotify(PUNICODE_STRING FullImageName, HANDLE ProcessId, PIMAGE_INFO ImageInfo)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(ImageInfo);
|
||||
if (g_Unloading)
|
||||
return;
|
||||
if (KeGetCurrentIrql() != PASSIVE_LEVEL)
|
||||
return;
|
||||
if (!ExAcquireRundownProtection(&g_Rundown))
|
||||
return;
|
||||
if (!FullImageName || !FullImageName->Buffer || FullImageName->Length == 0) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return;
|
||||
}
|
||||
|
||||
UNICODE_STRING proc = { 0 };
|
||||
WCHAR pbuf[512] = { 0 };
|
||||
proc.Buffer = pbuf;
|
||||
proc.MaximumLength = sizeof(pbuf);
|
||||
|
||||
if (!GetProcessImagePathByPid(ProcessId, &proc)) {
|
||||
PEPROCESS eproc = NULL;
|
||||
if (NT_SUCCESS(PsLookupProcessByProcessId(ProcessId, &eproc))) {
|
||||
PCSTR n = PsGetProcessImageFileName(eproc);
|
||||
SIZE_T l = n ? strlen(n) : 0;
|
||||
for (SIZE_T i = 0; i < l && i < RTL_NUMBER_OF(pbuf) - 1; i++)
|
||||
pbuf[i] = (WCHAR)n[i];
|
||||
pbuf[l] = 0;
|
||||
proc.Length = (USHORT)(l * sizeof(WCHAR));
|
||||
ObDereferenceObject(eproc);
|
||||
}
|
||||
}
|
||||
if (proc.Length == 0) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return;
|
||||
}
|
||||
if (IsWhitelist(&proc)) {
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
return;
|
||||
}
|
||||
|
||||
BOOLEAN suspicious = MatchSuspiciousProcPath(&proc);
|
||||
if (suspicious && MatchScreenCapModule(FullImageName))
|
||||
LogAnsi3("SCREEN_BLOCK", (ULONG)(ULONG_PTR)ProcessId, &proc, FullImageName);
|
||||
|
||||
ExReleaseRundownProtection(&g_Rundown);
|
||||
}
|
||||
|
||||
NTSTATUS InitScreenProtect(VOID)
|
||||
{
|
||||
NTSTATUS s = PsSetLoadImageNotifyRoutine(ImageLoadNotify);
|
||||
if (NT_SUCCESS(s)) g_ScreenImgCb = TRUE;
|
||||
return s;
|
||||
}
|
||||
|
||||
VOID UninitScreenProtect(VOID)
|
||||
{
|
||||
if (g_ScreenImgCb) {
|
||||
PsRemoveLoadImageNotifyRoutine(ImageLoadNotify);
|
||||
g_ScreenImgCb = FALSE;
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,6 @@ Antivirus software written in Python and C that blocks threats through deep lear
|
||||
|
||||
<img width="2245" height="1477" alt="PYAS_UI" src="https://github.com/user-attachments/assets/87d40261-7655-49ad-a19c-1ffcca60584f" />
|
||||
|
||||
## Readme Language
|
||||
|
||||
English : https://github.com/87owo/PYAS/blob/main/README.md
|
||||
|
||||
繁體中文 : https://github.com/87owo/PYAS/blob/main/README_zh_TW.md
|
||||
|
||||
简体中文 : https://github.com/87owo/PYAS/blob/main/README_zh_CN.md
|
||||
|
||||
## Requirements
|
||||
|
||||
Python 3.10 is recommended. Other Python versions may require different pip commands.
|
||||
@@ -63,15 +55,115 @@ PYAS/
|
||||
└── ... # Other supplementary folders and files
|
||||
```
|
||||
|
||||
## Program Architecture
|
||||
## Architecture diagram
|
||||
|
||||
PYAS antivirus software complete program flow architecture diagram.
|
||||
PYAS Security antivirus software general architecture diagram.
|
||||
|
||||
<img width="23000" height="6000" alt="PYAS_Architecture" src="https://github.com/user-attachments/assets/3a7ce637-c2b3-4719-9658-07f286cfa879" />
|
||||
```mermaid
|
||||
graph TD
|
||||
%% Global Styles
|
||||
classDef ui fill:#e1f5fe,stroke:#01579b,stroke-width:2px;
|
||||
classDef logic fill:#fff9c4,stroke:#fbc02d,stroke-width:2px;
|
||||
classDef engine fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px;
|
||||
classDef thread fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px;
|
||||
classDef kernel fill:#ffebee,stroke:#c62828,stroke-width:2px;
|
||||
classDef data fill:#eceff1,stroke:#455a64,stroke-width:2px,stroke-dasharray: 5 5;
|
||||
|
||||
## Packaged Releases
|
||||
User((User))
|
||||
|
||||
Packaged Releases Download: https://github.com/87owo/PYAS/releases
|
||||
subgraph Presentation_Layer ["Presentation Layer (View)"]
|
||||
direction TB
|
||||
UI_Static["PYAS_Interface.py<br/>(Ui_main_window Class)"]:::ui
|
||||
UI_Controller["PYAS.py<br/>(MainWindow_Controller Class)"]:::ui
|
||||
TrayIcon["System Tray Icon"]:::ui
|
||||
|
||||
User <--> UI_Controller
|
||||
UI_Static --- UI_Controller
|
||||
UI_Controller --- TrayIcon
|
||||
end
|
||||
|
||||
subgraph Core_Logic_Layer ["Core Logic & Controller"]
|
||||
direction TB
|
||||
Init_Env["Initialization<br/>(init_environ, init_variable,<br/>init_windll)"]:::logic
|
||||
Config_Mgr["Configuration Manager<br/>(load_config, save_config)"]:::logic
|
||||
|
||||
subgraph System_Tools ["System Tools"]
|
||||
Sys_Repair["System Repair<br/>(repair_system_mbr,<br/>repair_system_image, etc.)"]:::logic
|
||||
Sys_Clean["System Cleaner<br/>(clean_button, traverse_temp)"]:::logic
|
||||
Proc_Mgr["Process Manager<br/>(list_process, kill_process)"]:::logic
|
||||
List_Mgr["List Manager<br/>(manage_named_list:<br/>Whitelist/Quarantine)"]:::logic
|
||||
end
|
||||
|
||||
UI_Controller --> Init_Env
|
||||
Init_Env --> Config_Mgr
|
||||
UI_Controller --> System_Tools
|
||||
end
|
||||
|
||||
subgraph Protection_Layer ["Real-time Protection Threads (Daemons)"]
|
||||
direction TB
|
||||
Thread_Proc["Process Guard Thread<br/>(protect_proc_thread)<br/>[WMI/Snapshot]"]:::thread
|
||||
Thread_File["File Guard Thread<br/>(protect_file_thread)<br/>[ReadDirectoryChangesW]"]:::thread
|
||||
Thread_Net["Network Guard Thread<br/>(protect_net_thread)<br/>[GetExtendedTcpTable]"]:::thread
|
||||
Thread_Sys["System Guard Thread<br/>(protect_system_thread)<br/>[Reg/MBR Check]"]:::thread
|
||||
Thread_Popup["Popup Blocker Thread<br/>(popup_intercept_thread)<br/>[EnumWindows]"]:::thread
|
||||
Thread_Pipe["Driver IPC Thread<br/>(pipe_server_thread)<br/>[NamedPipe Server]"]:::thread
|
||||
|
||||
Init_Env --> Thread_Proc
|
||||
Init_Env --> Thread_File
|
||||
Init_Env --> Thread_Net
|
||||
Init_Env --> Thread_Sys
|
||||
Init_Env --> Thread_Popup
|
||||
Init_Env --> Thread_Pipe
|
||||
end
|
||||
|
||||
subgraph Engine_Layer ["Detection Engine (PYAS_Engine.py)"]
|
||||
direction TB
|
||||
Scan_Worker["Scan Worker<br/>(scan_worker / scan_engine)"]:::engine
|
||||
|
||||
subgraph Scanners
|
||||
Sign_Check["Signature Scanner<br/>(sign_scanner)<br/>[WinVerifyTrust]"]:::engine
|
||||
AI_Model["AI Model Scanner<br/>(model_scanner)<br/>[ONNX/ResNet]"]:::engine
|
||||
Yara_Rules["Rule Scanner<br/>(rule_scanner)<br/>[Yara/IP Lists]"]:::engine
|
||||
end
|
||||
|
||||
Thread_Proc --> Scan_Worker
|
||||
Thread_File --> Scan_Worker
|
||||
Thread_Net --> Scan_Worker
|
||||
UI_Controller -->|Manual Scan| Scan_Worker
|
||||
|
||||
Scan_Worker --> Sign_Check
|
||||
Scan_Worker --> AI_Model
|
||||
Scan_Worker --> Yara_Rules
|
||||
end
|
||||
|
||||
subgraph Kernel_OS_Layer ["Windows Kernel & Driver"]
|
||||
direction TB
|
||||
WinAPI["Windows API (ctypes)<br/>(kernel32, user32, ntdll,<br/>advapi32, iphlpapi, psapi)"]:::kernel
|
||||
Driver_Sys["Kernel Driver<br/>(PYAS_Driver.sys)"]:::kernel
|
||||
OS_FS["File System (NTFS)"]:::kernel
|
||||
OS_Net["Network Stack"]:::kernel
|
||||
|
||||
Init_Env -- Load DLLs --> WinAPI
|
||||
Thread_File -- Monitor --> OS_FS
|
||||
Thread_Net -- Monitor --> OS_Net
|
||||
Thread_Proc -- Suspend/Kill --> WinAPI
|
||||
|
||||
Thread_Pipe <==>|"Named Pipe IPC<br/>(\\.\pipe\PYAS_Output_Pipe)"| Driver_Sys
|
||||
Driver_Sys -- Callback/Block --> WinAPI
|
||||
end
|
||||
|
||||
subgraph Data_Persistence ["Data & Resources"]
|
||||
Config_File[("Config.json")]:::data
|
||||
Model_Files[("Model Files<br/>(.onnx)")]:::data
|
||||
Rule_Files[("Rule Files<br/>(.yar)")]:::data
|
||||
Quarantine_Dir[("/Quarantine/")]:::data
|
||||
|
||||
Config_Mgr <--> Config_File
|
||||
AI_Model <--> Model_Files
|
||||
Yara_Rules <--> Rule_Files
|
||||
List_Mgr <--> Quarantine_Dir
|
||||
end
|
||||
```
|
||||
|
||||
## Support System
|
||||
|
||||
@@ -80,12 +172,24 @@ Packaged Releases Download: https://github.com/87owo/PYAS/releases
|
||||
| Minimum | Administrator | >= Windows 10 (20H1) | 1 GHz | 200MB | 100MB |
|
||||
| Recommend | Administrator | >= Windows 10 (21H2) | 3 GHz | 500MB | 200MB |
|
||||
|
||||
## Packaged Releases
|
||||
|
||||
Download the installer. If it is incompatible with your system, you can repackage it yourself.
|
||||
|
||||
Packaged Download: https://github.com/87owo/PYAS/releases
|
||||
|
||||
## Official Website
|
||||
|
||||
Official Website : https://pyantivirus.wixsite.com/pyas
|
||||
If you are interested in this project, you can visit the website to see other related content.
|
||||
|
||||
Open Source Website : https://github.com/87owo/PYAS
|
||||
Source Available : https://github.com/87owo/PYAS
|
||||
|
||||
Official Website : https://pyas-security.com/antivirus
|
||||
|
||||
## Project License
|
||||
|
||||
https://github.com/87owo/PYAS/blob/main/LICENSE.txt
|
||||
For any questions, needs, or bug feedback, please contact us through the following website.
|
||||
|
||||
Source Issues : https://github.com/87owo/PYAS/issues
|
||||
|
||||
Official Email : mailto:service.pyas@gmail.com
|
||||
@@ -1,91 +0,0 @@
|
||||
# PYAS
|
||||
|
||||
使用 Python 和 C 编写的杀毒软件,并通过深度学习和行为监控阻止威胁!
|
||||
|
||||
<img width="2245" height="1477" alt="PYAS_UI" src="https://github.com/user-attachments/assets/87d40261-7655-49ad-a19c-1ffcca60584f" />
|
||||
|
||||
## 说明语言
|
||||
|
||||
English : https://github.com/87owo/PYAS/blob/main/README.md
|
||||
|
||||
繁體中文 : https://github.com/87owo/PYAS/blob/main/README_zh_TW.md
|
||||
|
||||
简体中文 : https://github.com/87owo/PYAS/blob/main/README_zh_CN.md
|
||||
|
||||
## 安装需求
|
||||
|
||||
建议使用 Python 3.10。其他版本的 Python 可能需要不同的 pip 指令。
|
||||
|
||||
```
|
||||
pip install numpy==1.26.4
|
||||
pip install onnxruntime==1.18.1
|
||||
pip install pefile==2023.2.7
|
||||
pip install Pillow==11.0.0
|
||||
pip install pyperclip==1.9.0
|
||||
pip install PySide6==6.9.1
|
||||
pip install requests==2.32.4
|
||||
pip install yara-python==4.5.4
|
||||
```
|
||||
|
||||
## 文件讯息
|
||||
|
||||
以下列出所有相关代码与文件的存放位置。
|
||||
|
||||
```
|
||||
PYAS/
|
||||
├── Engine/
|
||||
│ ├── Models/
|
||||
│ │ ├── convert.py # 将可执行文件或其他文件转换为图片
|
||||
│ │ └── train.py # TensorFlow CNN 模型训练完整代码
|
||||
│ │
|
||||
│ └── Rules/
|
||||
│ ├── rules.yar # YARA 病毒特征码规则匹配
|
||||
│ └── rules.ips # IP 网络地址规则匹配
|
||||
│
|
||||
├── Plugins/
|
||||
│ └── Filter/
|
||||
│ ├── DriverEntry.c # 驱动主入口与初始化逻辑
|
||||
│ ├── DriverEntry.h # 全局驱动定义、常量与函数
|
||||
│ ├── DriverPipe.c # 内核与用户层的管道日志传输实现
|
||||
│ ├── ProtectBoot.c # 磁盘引导区写入保护
|
||||
│ ├── ProtectImage.c # 映像加载监控与 shellcode 检测
|
||||
│ ├── ProtectInject.c # 进程与线程控制,防止注入
|
||||
│ ├── ProtectReg.c # 注册表修改保护
|
||||
│ ├── ProtectRules.c # 白名单、阻止名单与文件/注册表匹配逻辑
|
||||
│ └── ProtectRules.h # 保护规则声明
|
||||
│
|
||||
├── 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 (20H1) | 1 GHz | 200MB | 100MB |
|
||||
| 推荐配置 | 管理员 | >= Windows 10 (21H2) | 3 GHz | 300MB | 200MB |
|
||||
|
||||
## 官方网站
|
||||
|
||||
官方网站 : https://pyantivirus.wixsite.com/pyas
|
||||
|
||||
开源网站 : https://github.com/87owo/PYAS
|
||||
|
||||
## 授权条款
|
||||
|
||||
https://github.com/87owo/PYAS/blob/main/LICENSE.txt
|
||||
@@ -1,91 +0,0 @@
|
||||
# PYAS
|
||||
|
||||
使用 Python 和 C 開發的防毒軟體,並透過深度學習和行為監控來阻止威脅!
|
||||
|
||||
<img width="2245" height="1477" alt="PYAS_UI" src="https://github.com/user-attachments/assets/87d40261-7655-49ad-a19c-1ffcca60584f" />
|
||||
|
||||
## 說明語言
|
||||
|
||||
English : https://github.com/87owo/PYAS/blob/main/README.md
|
||||
|
||||
繁體中文 : https://github.com/87owo/PYAS/blob/main/README_zh_TW.md
|
||||
|
||||
简体中文 : https://github.com/87owo/PYAS/blob/main/README_zh_CN.md
|
||||
|
||||
## 安裝需求
|
||||
|
||||
建議使用 Python 3.10。其他版本的 Python 可能需要不同的 pip 指令。
|
||||
|
||||
```
|
||||
pip install numpy==1.26.4
|
||||
pip install onnxruntime==1.18.1
|
||||
pip install pefile==2023.2.7
|
||||
pip install Pillow==11.0.0
|
||||
pip install pyperclip==1.9.0
|
||||
pip install PySide6==6.9.1
|
||||
pip install requests==2.32.4
|
||||
pip install yara-python==4.5.4
|
||||
```
|
||||
|
||||
## 檔案資訊
|
||||
|
||||
以下列出所有相關程式碼與文件的存放位置。
|
||||
|
||||
```
|
||||
PYAS/
|
||||
├── Engine/
|
||||
│ ├── Models/
|
||||
│ │ ├── convert.py # 將可執行檔或其他檔案轉換為圖片
|
||||
│ │ └── train.py # TensorFlow CNN 模型訓練完整程式碼
|
||||
│ │
|
||||
│ └── Rules/
|
||||
│ ├── rules.yar # YARA 病毒特徵碼規則匹配
|
||||
│ └── rules.ips # IP 網路位址規則匹配
|
||||
│
|
||||
├── Plugins/
|
||||
│ └── Filter/
|
||||
│ ├── DriverEntry.c # 驅動主入口與初始化邏輯
|
||||
│ ├── DriverEntry.h # 全域驅動定義、常數與函式
|
||||
│ ├── DriverPipe.c # 核心層與使用者層的管道日誌傳輸實作
|
||||
│ ├── ProtectBoot.c # 磁碟開機區寫入保護
|
||||
│ ├── ProtectImage.c # 映像載入監控與 shellcode 偵測
|
||||
│ ├── ProtectInject.c # 程序與執行緒控制,防止注入
|
||||
│ ├── ProtectReg.c # 登錄檔修改保護
|
||||
│ ├── ProtectRules.c # 白名單、封鎖清單與檔案/登錄匹配邏輯
|
||||
│ └── ProtectRules.h # 保護規則宣告
|
||||
│
|
||||
├── 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 (20H1) | 1 GHz | 200MB | 100MB |
|
||||
| 推薦配置 | 管理員 | >= Windows 10 (21H2) | 3 GHz | 300MB | 200MB |
|
||||
|
||||
## 官方網站
|
||||
|
||||
官方網站 : https://pyantivirus.wixsite.com/pyas
|
||||
|
||||
開源網站 : https://github.com/87owo/PYAS
|
||||
|
||||
## 授權條款
|
||||
|
||||
https://github.com/87owo/PYAS/blob/main/LICENSE.txt
|
||||
Reference in new issue
Block a user