diff --git a/buggy_script.py b/buggy_script.py new file mode 100644 index 0000000..42a4e92 --- /dev/null +++ b/buggy_script.py @@ -0,0 +1,48 @@ +import time + +# 1. 逻辑/语法错误:函数定义缺少冒号,且缩进不规范 +def calculate_discount(price, discount) + final_price = price * (1 - discount) + return final_price # 缩进错误 + +# 2. 陷阱:使用可变对象(列表)作为默认参数 +def add_item_to_cart(item, cart=[]): + cart.append(item) + return cart + +class User: + # 3. 拼写错误:初始化方法写成了 _init_ 而不是 __init__ + def _init_(self, name, age): + self.name = name + self.age = age + + def greet(self): + # 4. 类型错误:尝试将字符串和整数直接连接 + print("Hello, I am " + self.name + " and I am " + self.age + " years old.") + +def main(): + print("Welcome to the shop!") + + # 5. 逻辑错误:运算符误用 (^ 在 Python 中是异或,不是幂运算) + square_area = 10 ^ 2 + print(f"Area calculation check: {square_area}") + + # 6. 语法错误:在 if 条件中使用了赋值运算符 (=) 而不是比较运算符 (==) + user_input = "yes" + if user_input = "yes": + print("User agreed.") + + # 7. 运行时错误:IndexError (索引越界) + items = ["Apple", "Banana", "Orange"] + for i in range(len(items) + 1): + print(f"Item {i}: {items[i]}") + + # 8. 运行时错误:ZeroDivisionError (除以零) + count = 0 + total = 100 + average = total / count + print("Average: " + average) + +# 9. 拼写错误:name 变量拼写错误 +if __name__ == "__main__": + mian() \ No newline at end of file diff --git a/cpp_security_test.cpp b/cpp_security_test.cpp new file mode 100644 index 0000000..0b4f8d3 --- /dev/null +++ b/cpp_security_test.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include + +#define BUFFER_SIZE 10 + +void bufferOverflowVuln(const char* input) { + char buffer[BUFFER_SIZE]; + strcpy(buffer, input); + std::cout << "Vulnerable Buffer: " << buffer << std::endl; +} + +void memoryLeakVuln() { + int* data = new int[100]; + if (data == nullptr) return; + + data[0] = 1; + std::cout << "Memory allocated and leaked." << std::endl; +} + +int integerOverflowVuln(int a, int b) { + return a + b; +} + +void formatStringVuln(const char* logMessage) { + printf(logMessage); + printf("\n"); +} + +void bufferOverflowSafe(const char* input) { + char buffer[BUFFER_SIZE]; + strncpy(buffer, input, BUFFER_SIZE - 1); + buffer[BUFFER_SIZE - 1] = '\0'; + std::cout << "Safe Buffer: " << buffer << std::endl; +} + +int main_cwe_test(int argc, char** argv) { + if (argc < 2) { + std::cerr << "Usage: " << argv[0] << " " << std::endl; + return 1; + } + + const char* user_input = argv[1]; + + bufferOverflowVuln(user_input); + memoryLeakVuln(); + int result = integerOverflowVuln(2147483647, 1); + formatStringVuln(user_input); + + bufferOverflowSafe(user_input); + + return 0; +} \ No newline at end of file diff --git a/test.go b/test.go new file mode 100644 index 0000000..bdbc29a --- /dev/null +++ b/test.go @@ -0,0 +1,172 @@ +package main + +import ( + "fmt" + "io/ioutil" // 已弃用的包 + "log" + "os" + "strings" + "time" + "unsafe" // 不安全的操作 +) + +var globalVar int // 未使用的全局变量 + +// 过长的函数(圈复杂度高) +func processData(data string) error { + if data == "" { + return fmt.Errorf("empty data") + } else if len(data) > 100 { + return fmt.Errorf("data too long") + } else { + parts := strings.Split(data, ",") + for i, part := range parts { + if i%2 == 0 { + if len(part) > 10 { + part = part[:10] + } else { + if part == "test" { + fmt.Println("found test") + } + } + } else { + switch part { + case "a": + fmt.Println("a") + case "b": + fmt.Println("b") + case "c": + fmt.Println("c") + case "d": + fmt.Println("d") + default: + fmt.Println("default") + } + } + } + } + return nil +} + +// 未处理的错误 +func readFile(filename string) string { + data, _ := ioutil.ReadFile(filename) // 错误未处理 + return string(data) +} + +// 拼写错误的参数名 +func printMessage(mesage string) { // 参数名拼写错误 + fmt.Println(mesage) +} + +// 返回未导出的类型 +type myError struct { // 未导出的类型 + msg string +} + +func (e *myError) Error() string { + return e.msg +} + +func createError() error { + return &myError{msg: "error"} // 返回未导出的类型 +} + +// 冗余的代码 +func redundantCode() { + var s string = "hello" // 冗余的类型声明 + fmt.Println(s) + + var i int + i = 10 // 可以合并声明和赋值 + fmt.Println(i) + + if true { // 总是为true的条件 + fmt.Println("always true") + } +} + +// 使用不安全操作 +func unsafeOperation() { + var x int = 42 + ptr := unsafe.Pointer(&x) + fmt.Printf("Pointer: %v\n", ptr) +} + +// 未使用的参数 +func unusedParameter(unused string) int { // 未使用的参数 + return 42 +} + +// 魔法数字 +func calculate() int { + return 100 * 24 * 60 * 60 // 魔法数字 +} + +// 冗长的函数调用链 +func longChain() { + fmt.Println(strings.ToUpper(strings.TrimSpace(strings.Replace("hello world", "world", "golang", -1)))) +} + +// 空的错误检查 +func emptyErrorCheck() { + err := processData("test") + if err != nil { // 空的错误检查 + // 什么也不做 + } +} + +// defer 在循环中 +func deferInLoop() { + for i := 0; i < 10; i++ { + file, _ := os.Create(fmt.Sprintf("test%d.txt", i)) + defer file.Close() // defer在循环中 + file.WriteString("test") + } +} + +// 可能的竞态条件 +var counter int + +func incrementCounter() { + counter++ // 非原子操作 +} + +// 使用 time.Sleep 而不是 context +func waitForCondition() { + time.Sleep(5 * time.Second) // 应该使用context + fmt.Println("done waiting") +} + +// 过长的行 +func veryLongFunctionNameWithManyParameters(param1 string, param2 int, param3 bool, param4 float64, param5 []string) (result string, err error) { + // 这是一个非常长的行,超过了通常的代码风格指南建议的80或120字符限制,应该被分解成多行以提高可读性。 + return "result", nil +} + +// 主函数 +func main() { + fmt.Println("Starting application...") + + // 调用各种有问题的函数 + processData("test,data,example,hello,world,foo,bar,baz") + readFile("nonexistent.txt") + printMessage("Hello") + redundantCode() + unsafeOperation() + unusedParameter("test") + result := calculate() + fmt.Printf("Result: %d\n", result) + longChain() + emptyErrorCheck() + deferInLoop() + + // 启动goroutine但没有同步 + go incrementCounter() + + waitForCondition() + + veryLongFunctionNameWithManyParameters("param1", 123, true, 3.14, []string{"a", "b", "c"}) + + log.Println("Application finished") +} diff --git a/test.php b/test.php new file mode 100644 index 0000000..dfbfbf7 --- /dev/null +++ b/test.php @@ -0,0 +1,198 @@ + 18) { + if ($user['country'] === 'US') { + if ($user['subscription'] === 'premium') { + if ($verbose) { + echo "Processing premium US user over 18\n"; + } + $result[] = $user; + } elseif ($user['subscription'] === 'basic') { + if ($verbose) { + echo "Processing basic US user over 18\n"; + } + $result[] = $user; + } else { + if ($verbose) { + echo "Skipping non-standard subscription\n"; + } + } + } elseif ($user['country'] === 'CA') { + if ($verbose) { + echo "Processing Canadian user over 18\n"; + } + $result[] = $user; + } else { + if ($verbose) { + echo "Skipping non-US/CA user over 18\n"; + } + } + } else { + if ($verbose) { + echo "Skipping user under 18\n"; + } + } + } + + // 注释掉的代码 (Commented Code) + /* + $oldResult = []; + foreach ($users as $u) { + $oldResult[] = $u['id']; + } + */ + + // 不必要的全局变量使用 + global $globalCounter; + $globalCounter++; + + // 避免使用 @ 抑制错误 + $fileContent = @file_get_contents('non_existent_file.txt'); + + // 未处理的异常 + try { + $date = new DateTime('invalid date'); + } catch (Exception $e) { + // 空catch块 + } + + // 可疑的魔法数字 + if (count($result) > 10) { + // ... + } + + // 返回临时变量 + return $result; + } + + // 函数参数过多 (Excessive Parameter List) + public function createUser( + string $firstName, + string $lastName, + string $email, + string $phone, + string $address, + string $city, + string $state, + string $zipCode, + string $country, + bool $isActive = true, + bool $isAdmin = false + ): array { + // 函数体为空 (Empty Function Body) + } + + // 过深的嵌套 (Depth of Inheritance Tree) + public function nestedIfExample(int $value): string + { + if ($value > 0) { + if ($value < 10) { + if ($value % 2 === 0) { + if ($value !== 4) { + return "Special case"; + } else { + return "Even number"; + } + } else { + return "Odd number"; + } + } else { + return "Large number"; + } + } else { + return "Non-positive"; + } + } +} + +// 未使用的类 (Unused Code Rules) +class UnusedClass +{ + public function doSomething() + { + echo "I'm never called!"; + } +} + +// 匿名类 (Anonymous Class) +$anonymous = new class { + public function greet() + { + echo "Hello from anonymous class!"; + } +}; + +// 未使用的函数 (Unused Code Rules) +function unusedFunction(): void +{ + echo "This function is never called"; +} + +// 主程序逻辑 +$manager = new UserManager(); +$users = [ + ['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com', 'age' => 25, 'country' => 'US', 'subscription' => 'premium', 'active' => true], + ['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com', 'age' => 17, 'country' => 'UK', 'subscription' => 'free', 'active' => true], + ['id' => 3, 'name' => 'Charlie', 'email' => 'charlie@example.com', 'age' => 30, 'country' => 'CA', 'subscription' => 'basic', 'active' => false], +]; + +// 忽略返回值 (Unused Result) +$manager->processUserData($users, true); + +// 使用 eval (Security Issue) +eval('$x = 5 + 3;'); + +// 直接输出敏感信息 +echo "Debug mode is " . ($debugMode ? 'ON' : 'OFF'); + +// 结束 +?> diff --git a/vulnerable.cpp b/vulnerable.cpp new file mode 100644 index 0000000..8636ba3 --- /dev/null +++ b/vulnerable.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +#include +#include +#include + +using namespace std; + +// 1. 硬编码敏感信息 (CWE-798) +// SAST 会扫描变量名(如 api_key, secret)和高熵字符串 +const string AWS_SECRET_KEY = "AKIAIOSFODNN7EXAMPLE"; + +class UserManager { +public: + // 2. 也是硬编码,且作为类成员 + string db_password = "root"; + + // 3. SQL 注入 (CWE-89) + // 直接拼接字符串构建 SQL 查询是 C++ Web 后端常见的严重漏洞 + void queryUser(string userId) { + string query = "SELECT * FROM users WHERE id = '" + userId + "'"; + cout << "Executing query: " << query << endl; + } + + // 4. 命令注入 (CWE-78) + // 允许外部输入直接进入 system() 函数 + void pingHost(string ipAddress) { + string cmd = "ping -c 4 " + ipAddress; + system(cmd.c_str()); + } +}; + +void legacyBufferOverflow(char* input) { + char buffer[10]; + + // 5. 经典的栈缓冲区溢出 (CWE-121) + // 虽然是 C++,但混用 C 风格字符串处理函数非常常见且危险 + strcpy(buffer, input); +} + +void memoryLeakAndRawPointers() { + // 6. 内存泄漏 (CWE-401) + // 使用了 new 但没有 delete + int* data = new int[100]; + data[0] = 10; + + // 抛出异常可能导致 delete 永远不执行 (异常安全问题) + if (data[0] == 10) { + // throw runtime_error("Error occurred!"); + return; + } + + delete[] data; +} + +void iteratorInvalidation() { + vector numbers = {1, 2, 3, 4, 5}; + + // 7. 迭代器失效 (CWE-835/Logic Error) + // 在遍历 vector 时进行 push_back 会导致底层数组重新分配, + // 从而使迭代器失效,导致未定义行为或崩溃。 + for (auto it = numbers.begin(); it != numbers.end(); ++it) { + if (*it == 3) { + numbers.push_back(6); + } + } +} + +void weakRandomness() { + // 8. 弱伪随机数生成器 (CWE-338) + // srand/rand 不适合用于安全相关的随机数生成 + srand(time(NULL)); + int token = rand(); + cout << "Security Token: " << token << endl; +} + +int main(int argc, char* argv[]) { + UserManager um; + + if (argc < 2) { + return 1; + } + + // 模拟攻击路径 + um.queryUser(argv[1]); // 传入 "' OR '1'='1" 即可注入 + + legacyBufferOverflow(argv[1]); + + memoryLeakAndRawPointers(); + + iteratorInvalidation(); + + weakRandomness(); + + // 9. 被除数为零 (CWE-369) + int x = 0; + int y = 100 / x; + + return 0; +} diff --git a/xxtest.c b/xxtest.c new file mode 100644 index 0000000..0c6ccb1 --- /dev/null +++ b/xxtest.c @@ -0,0 +1,68 @@ +#include +#include +#include + +// 1. 硬编码凭证 (Hardcoded Credentials) +// SAST工具会扫描特定的变量名(如 password, key)和字符串比较 +void check_admin(char *input_pass) { + if (strcmp(input_pass, "SuperSecretAdminPassword123") == 0) { + printf("Access Granted!\n"); + } +} + +// 2. 内存泄漏 (Memory Leak) & 空指针解引用 (Null Pointer Dereference) +void memory_issues() { + char *ptr = (char *)malloc(50); + + // 错误:没有检查 malloc 是否返回 NULL 就直接使用 + ptr[0] = 'A'; + + // 错误:函数结束前没有调用 free(ptr),导致内存泄漏 + return; +} + +// 3. 释放后使用 (Use After Free) & 双重释放 (Double Free) +void heap_corruption() { + char *data = (char *)malloc(10); + free(data); + + // 错误:内存已被释放,但再次写入数据 + strcpy(data, "Hello"); + + // 错误:再次释放同一块内存 + free(data); +} + +void risky_processing(char *user_input) { + char buffer[10]; + + // 4. 栈缓冲区溢出 (Stack Buffer Overflow) + // 如果 user_input 长度超过 10,会覆盖栈内存 + strcpy(buffer, user_input); + + // 5. 格式化字符串漏洞 (Format String Vulnerability) + // 如果 user_input 包含 "%s" 或 "%n" 等格式符,会导致崩溃或内存泄露 + printf(user_input); +} + +int main(int argc, char *argv[]) { + char local_buf[100]; + + // 6. 使用了被废弃且极其危险的函数 (Use of Deprecated/Unsafe Function) + // gets() 不检查缓冲区长度,是导致缓冲区溢出的头号杀手 + printf("Enter specific text: "); + gets(local_buf); + + if (argc > 1) { + risky_processing(argv[1]); + check_admin(argv[1]); + } + + memory_issues(); + heap_corruption(); + + // 7. 逻辑错误/死代码 (Unreachable Code) + return 0; + + printf("This line will never run."); +}