mintrt 0.1.0

Security-featured runtime for lua.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//     <<*>> Revenge of snowflake.
//     -^v-  SASWE
//     @ This source code is licensed under a dual license model:
//       1. MPL-2.0 for non-commercial use only
//       2. Commercial License for commercial use
//       See LICENSE and LICENSE_COMMERCIAL files for details.
use std::collections::HashMap;
use log::{info, warn};
use serde::{Deserialize, Serialize};
use env_modify::{LuaApis, SHookApis, S_YNHookTask};
use crate::config::entity_ro;

pub mod env_modify;
pub(crate) mod check_exec;
pub mod detailed_restrict;
mod deep_extern_hook;

//默认移除:
pub static DEFAULT_DENY_MODULES_LIST: [&str; 3] = [
    "debug", "package", "require"
];
//这两个应该公开
//作者有权自己特许危险的模块和 api,但是用户必须得到说明,并且有权不使用(必须)和随时禁用(非必须)
pub static DEFAULT_PRECISION_DENY_CONFIG: &[(&str, &[&str])] = &[
    ("string", &["dump"]),
];
//重复工作,ai完成
/// 风险等级分类
#[derive(Debug, Clone, PartialEq)]
pub enum RiskLevel {
    Critical, // 致命风险 - 必须禁用或严格限制
    High,     // 高风险 - 需要特殊权限
    Medium,   // 中等风险 - 需要监控和限制
}

/// 权限类型枚举 - 对应所有危险的 Lua API
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Permission {
    // ========== 致命风险 (Critical) ==========
    // global 模块
    Dofile,      // 执行任意 Lua 文件
    Load,        // 将字符串加载为函数(执行任意代码)
    Loadfile,    // 从文件加载函数
    Require,     // 加载任意模块

    // os 模块
    OsExecute,   // 执行系统命令
    OsExit,      // 终止进程
    OsGetenv,    // 获取环境变量
    OsRemove,    // 删除文件
    OsRename,    // 重命名文件
    OsSetenv,    // 设置环境变量

    // io 模块
    IoOpen,      // 打开任意文件
    IoRead,      // 读取文件内容
    IoWrite,     // 写入文件内容
    IoPopen,     // 打开系统进程

    // debug 模块
    DebugGetinfo,     // 获取函数信息
    DebugGetlocal,    // 获取局部变量
    DebugGetmetatable,// 获取元表
    DebugGetregistry, // 获取注册表
    DebugGetupvalue,  // 获取闭包上值
    DebugGetuservalue,// 获取用户值
    DebugSethook,     // 设置钩子
    DebugSetlocal,    // 设置局部变量
    DebugSetupvalue,  // 设置闭包上值
    DebugSetuservalue,// 设置用户值

    // package 模块
    PackageLoadlib,   // 加载动态库(最高风险)

    // ========== 高风险 (High) ==========
    PackagePath,      // 模块路径
    PackageLoaded,    // 已加载模块
    PackagePreload,   // 预加载模块
    PackageSearchpath,// 搜索模块路径

    // ========== 中等风险 (Medium) ==========
    MathRandom,       // 随机数生成
    MathRandomseed,   // 随机数种子
    StringDump,       // 生成字节码
}

impl Permission {
    /// 获取权限对应的风险等级
    pub fn risk_level(&self) -> RiskLevel {
        match self {
            // 必须注意,严格限制,默认禁止
            Permission::Dofile | Permission::Load | Permission::Loadfile |
            Permission::Require | Permission::OsExecute | Permission::OsExit |
            Permission::OsGetenv | Permission::OsRemove | Permission::OsRename |
            Permission::OsSetenv | Permission::IoOpen | Permission::IoRead |
            Permission::IoWrite | Permission::IoPopen |
            Permission::DebugGetinfo | Permission::DebugGetlocal |
            Permission::DebugGetmetatable | Permission::DebugGetregistry |
            Permission::DebugGetupvalue | Permission::DebugGetuservalue |
            Permission::DebugSethook | Permission::DebugSetlocal |
            Permission::DebugSetupvalue | Permission::DebugSetuservalue |
            Permission::PackageLoadlib => RiskLevel::Critical,

            // 稍加限制
            Permission::PackagePath | Permission::PackageLoaded |
            Permission::PackagePreload | Permission::PackageSearchpath => RiskLevel::High,

            // 不限制
            Permission::MathRandom | Permission::MathRandomseed |
            Permission::StringDump => RiskLevel::Medium,
        }
    }
    //安全限制:显式允许,日志warn(hook函数实现),不限制的仅仅提示 warn
    //还需要处理 HashMap 做的显式允许表

    /*
    /// 检查权限是否应该被允许(需要额外的白名单配置)
    pub fn should_check_whitelist(&self) -> bool {
        matches!(self.risk_level(), RiskLevel::Critical | RiskLevel::High)
    }*/

    /// 获取权限的风险描述
    pub fn description(&self) -> &'static str {
        match self {
            // Global
            Permission::Dofile => "执行任意 Lua 文件",
            Permission::Load => "将字符串加载为函数(执行任意代码)",
            Permission::Loadfile => "从文件加载函数(执行任意文件)",
            Permission::Require => "加载任意模块",

            // OS
            Permission::OsExecute => "执行任意系统命令(如 rm -rf /)",
            Permission::OsExit => "终止当前进程",
            Permission::OsGetenv => "获取环境变量(如 PASSWORD、API_KEY)",
            Permission::OsRemove => "删除任意文件(包括系统文件)",
            Permission::OsRename => "重命名任意文件(包括系统文件)",
            Permission::OsSetenv => "设置环境变量(如 LD_PRELOAD)",

            // IO
            Permission::IoOpen => "打开任意文件(包括 /etc/passwd)",
            Permission::IoRead => "读取任意文件内容",
            Permission::IoWrite => "写入任意文件内容",
            Permission::IoPopen => "打开系统进程(类似 execute)",

            // Debug
            Permission::DebugGetinfo => "获取函数信息(包括闭包、上下文)",
            Permission::DebugGetlocal => "获取局部变量(包括敏感变量)",
            Permission::DebugGetmetatable => "获取元表(修改对象行为)",
            Permission::DebugGetregistry => "获取注册表(Lua 内部数据结构)",
            Permission::DebugGetupvalue => "获取闭包上值(包括敏感数据)",
            Permission::DebugGetuservalue => "获取用户值(自定义数据)",
            Permission::DebugSethook => "设置钩子(修改运行时行为)",
            Permission::DebugSetlocal => "设置局部变量(修改运行时状态)",
            Permission::DebugSetupvalue => "设置闭包上值(修改闭包状态)",
            Permission::DebugSetuservalue => "设置用户值(修改自定义数据)",

            // Package
            Permission::PackageLoadlib => "加载动态库(执行任意 C 代码)",
            Permission::PackagePath => "获取/修改模块路径",
            Permission::PackageLoaded => "获取已加载模块",
            Permission::PackagePreload => "预加载模块",
            Permission::PackageSearchpath => "搜索模块路径",

            // Math & String
            Permission::MathRandom => "生成随机数",
            Permission::MathRandomseed => "设置随机数种子",
            Permission::StringDump => "生成字节码(可能用于代码注入)",
        }
    }

    /// 获取权限所属模块
    pub fn module(&self) -> &'static str {
        match self {
            Permission::Dofile | Permission::Load | Permission::Loadfile |
            Permission::Require => "global",

            Permission::OsExecute | Permission::OsExit | Permission::OsGetenv |
            Permission::OsRemove | Permission::OsRename | Permission::OsSetenv => "os",

            Permission::IoOpen | Permission::IoRead | Permission::IoWrite |
            Permission::IoPopen => "io",

            Permission::DebugGetinfo | Permission::DebugGetlocal |
            Permission::DebugGetmetatable | Permission::DebugGetregistry |
            Permission::DebugGetupvalue | Permission::DebugGetuservalue |
            Permission::DebugSethook | Permission::DebugSetlocal |
            Permission::DebugSetupvalue | Permission::DebugSetuservalue => "debug",

            Permission::PackageLoadlib | Permission::PackagePath |
            Permission::PackageLoaded | Permission::PackagePreload |
            Permission::PackageSearchpath => "package",

            Permission::MathRandom | Permission::MathRandomseed => "math",
            Permission::StringDump => "string",
        }
    }

    pub fn query_auth(func_name: &str) -> Option<Permission> {
        match func_name {
            "dofile" => Some(Permission::Dofile),
            "load" => Some(Permission::Load),
            "loadfile" => Some(Permission::Loadfile),
            "require" => Some(Permission::Require),

            "execute" => Some(Permission::OsExecute),
            "exit" => Some(Permission::OsExit),
            "getenv" => Some(Permission::OsGetenv),
            "remove" => Some(Permission::OsRemove),
            "rename" => Some(Permission::OsRename),
            "setenv" => Some(Permission::OsSetenv),

            "open" => Some(Permission::IoOpen),
            "read" => Some(Permission::IoRead),
            "write" => Some(Permission::IoWrite),
            "popen" => Some(Permission::IoPopen),

            "getinfo" => Some(Permission::DebugGetinfo),
            "getlocal" => Some(Permission::DebugGetlocal),
            "getmetatable" => Some(Permission::DebugGetmetatable),
            "getregistry" => Some(Permission::DebugGetregistry),
            "getupvalue" => Some(Permission::DebugGetupvalue),
            "getuservalue" => Some(Permission::DebugGetuservalue),
            "sethook" => Some(Permission::DebugSethook),
            "setlocal" => Some(Permission::DebugSetlocal),
            "setupvalue" => Some(Permission::DebugSetupvalue),
            "setuservalue" => Some(Permission::DebugSetuservalue),

            "loadlib" => Some(Permission::PackageLoadlib),
            "path" => Some(Permission::PackagePath),
            "loaded" => Some(Permission::PackageLoaded),
            "preload" => Some(Permission::PackagePreload),
            "searchpath" => Some(Permission::PackageSearchpath),

            "random" => Some(Permission::MathRandom),
            "randomseed" => Some(Permission::MathRandomseed),
            "dump" => Some(Permission::StringDump),

            _ => None,
        }
    }


    /// 获取 API 名称
    pub fn api_name(&self) -> &'static str {
        match self {
            Permission::Dofile => "dofile",
            Permission::Load => "load",
            Permission::Loadfile => "loadfile",
            Permission::Require => "require",

            Permission::OsExecute => "execute",
            Permission::OsExit => "exit",
            Permission::OsGetenv => "getenv",
            Permission::OsRemove => "remove",
            Permission::OsRename => "rename",
            Permission::OsSetenv => "setenv",

            Permission::IoOpen => "open",
            Permission::IoRead => "read",
            Permission::IoWrite => "write",
            Permission::IoPopen => "popen",

            Permission::DebugGetinfo => "getinfo",
            Permission::DebugGetlocal => "getlocal",
            Permission::DebugGetmetatable => "getmetatable",
            Permission::DebugGetregistry => "getregistry",
            Permission::DebugGetupvalue => "getupvalue",
            Permission::DebugGetuservalue => "getuservalue",
            Permission::DebugSethook => "sethook",
            Permission::DebugSetlocal => "setlocal",
            Permission::DebugSetupvalue => "setupvalue",
            Permission::DebugSetuservalue => "setuservalue",

            Permission::PackageLoadlib => "loadlib",
            Permission::PackagePath => "path",
            Permission::PackageLoaded => "loaded",
            Permission::PackagePreload => "preload",
            Permission::PackageSearchpath => "searchpath",

            Permission::MathRandom => "random",
            Permission::MathRandomseed => "randomseed",
            Permission::StringDump => "dump",
        }
    }
}

/// 安全授权结构
struct SAuthority {
    info: String,
    permission: Permission,
    enabled: bool,
}

/// 安全控制表 - 管理所有权限
pub type SAuthBasicCtrl = HashMap<Permission, bool>;
///留空直接禁用
pub type SDetailedAccessAllow = HashMap<String, Vec<String>>;
/// 处理授权解释
pub type SAnnounceClaim = HashMap<&'static str, String>;

/// 获取默认安全配置(全部禁用致命和高风险权限)
pub fn get_default_auth_config() -> SAuthBasicCtrl {
    let mut config = SAuthBasicCtrl::new();

    // 默认禁用所有致命风险权限
    config.insert(Permission::Dofile, false);
    config.insert(Permission::Load, false);
    config.insert(Permission::Loadfile, false);
    config.insert(Permission::Require, false);

    config.insert(Permission::OsExecute, false);
    config.insert(Permission::OsExit, false);
    config.insert(Permission::OsGetenv, false);
    config.insert(Permission::OsRemove, false);
    config.insert(Permission::OsRename, false);
    config.insert(Permission::OsSetenv, false);

    config.insert(Permission::IoOpen, false);
    config.insert(Permission::IoRead, false);
    config.insert(Permission::IoWrite, false);
    config.insert(Permission::IoPopen, false);

    config.insert(Permission::DebugGetinfo, false);
    config.insert(Permission::DebugGetlocal, false);
    config.insert(Permission::DebugGetmetatable, false);
    config.insert(Permission::DebugGetregistry, false);
    config.insert(Permission::DebugGetupvalue, false);
    config.insert(Permission::DebugGetuservalue, false);
    config.insert(Permission::DebugSethook, false);
    config.insert(Permission::DebugSetlocal, false);
    config.insert(Permission::DebugSetupvalue, false);
    config.insert(Permission::DebugSetuservalue, false);

    config.insert(Permission::PackageLoadlib, false);

    // 默认禁用高风险权限
    config.insert(Permission::PackagePath, false);
    config.insert(Permission::PackageLoaded, false);
    config.insert(Permission::PackagePreload, false);
    config.insert(Permission::PackageSearchpath, false);

    // 中等风险权限默认启用但受限
    config.insert(Permission::MathRandom, true);
    config.insert(Permission::MathRandomseed, true);
    config.insert(Permission::StringDump, false);

    config
}

pub fn get_authorized_auth_config(changes: SAuthBasicCtrl) -> SAuthBasicCtrl {
    let mut default = get_default_auth_config();
    for (permission, enabled) in changes {
        default.insert(permission, enabled);
    }
    default
}

/// 生成完整的 Hook 任务列表
/// 输入:开发者定义的权限修改
/// 返回:(要禁用的 API 列表,要 Hook 的 API 列表)
pub fn generate_basic_ctrl_hook_task(auth: &SAuthBasicCtrl) -> S_YNHookTask {
    let mut deny_list: LuaApis = HashMap::new();
    let mut hook_callbacks: SHookApis = HashMap::new();

    // ========== 致命风险 - 直接禁用 ==========
    // Global 模块
    deny_list.insert("global".to_string(), vec![
        "dofile".to_string(),
        "load".to_string(),
        "loadfile".to_string(),
        "require".to_string(),
    ]);

    // OS 模块
    deny_list.insert("os".to_string(), vec![
        "execute".to_string(),
        "exit".to_string(),
        "getenv".to_string(),
        "remove".to_string(),
        "rename".to_string(),
        "setenv".to_string(),
    ]);

    // IO 模块
    deny_list.insert("io".to_string(), vec![
        "open".to_string(),
        "read".to_string(),
        "write".to_string(),
        "popen".to_string(),
    ]);

    // Debug 模块
    deny_list.insert("debug".to_string(), vec![
        "getinfo".to_string(),
        "getlocal".to_string(),
        "getmetatable".to_string(),
        "getregistry".to_string(),
        "getupvalue".to_string(),
        "getuservalue".to_string(),
        "sethook".to_string(),
        "setlocal".to_string(),
        "setupvalue".to_string(),
        "setuservalue".to_string(),
    ]);

    // Package 模块
    deny_list.insert("package".to_string(), vec![
        "loadlib".to_string(),
    ]);

    // ========== Hook 限制 ==========
    // Math 模块
    hook_callbacks.insert("random".to_string(), (math_random_hook, true));
    hook_callbacks.insert("randomseed".to_string(), (math_randomseed_hook, true));
    
    // 为禁用的 API 添加 Hook(用于日志记录)
    for (module, apis) in &deny_list  {
        for api in apis {
            // 安全地获取权限状态
            let if_enabled = Permission::query_auth(api)
                .and_then(|p| auth.get(&p).copied())//闭包探路
                .unwrap_or(false);
            
            // 根据权限状态选择不同的 hook 函数
            let hook_fn = if if_enabled {
                security_hook_allowed
            } else {
                security_hook_denied
            };
            
            hook_callbacks.insert(api.clone(), (hook_fn, if_enabled));
        }
    }
    // String 模块
    deny_list.insert("string".to_string(), vec![
        "dump".to_string(),
    ]);

    //常规安全限制 hook

    (deny_list, hook_callbacks)
}

// Hook 回调函数实现
fn math_random_hook(whole_api:&str) {
    // 在这里可以实现随机数范围检查逻辑
    // 例如:限制返回值在 1-1000 之间
    let _ = whole_api;
    warn!("[Security Hook] math.random called");
}

fn math_randomseed_hook(whole_api:&str) {
    // 在这里实现随机数种子检查逻辑
    // 例如:限制种子值在 1-1000 之间
    let _ = whole_api;
    warn!("[Security Hook] math.randomseed called - seed validation applied");
}

// 通用的安全 Hook 函数(允许调用)
fn security_hook_allowed(api_name: &str) {
    warn!("[Security Hook] {} called and was allowed.", api_name);
}

// 通用的安全 Hook 函数(拒绝调用)
fn security_hook_denied(api_name: &str) {
    warn!("[Security Hook] {} called and was rejected as an error.", api_name);
}




/// 打印安全审计报告
pub fn security_audit_log(config: &SAuthBasicCtrl) {
    let mut critical_count = 0;
    let mut high_count = 0;
    let mut medium_count = 0;

    for (permission, enabled) in config.iter() {
        let status = if *enabled { "ENABLED" } else { "DISABLED" };
        let risk = permission.risk_level();

        match risk {
            RiskLevel::Critical => {
                critical_count += 1;
                println!("[CRITICAL][{}] {} - {} [{}]",
                         permission.module(), permission.api_name(),
                         permission.description(), status);
            },
            RiskLevel::High => {
                high_count += 1;
                println!("[HIGH]    [{}] {} - {} [{}]",
                         permission.module(), permission.api_name(),
                         permission.description(), status);
            },
            RiskLevel::Medium => {
                medium_count += 1;
                println!("[MEDIUM]  [{}] {} - {} [{}]",
                         permission.module(), permission.api_name(),
                         permission.description(), status);
            },
        }
    }

    info!("\n=== Security ===");
    info!("Critical: {}, High: {}, Medium: {}", critical_count, high_count, medium_count);
    info!("Total permissions controlled: {}", config.len());
}