-
Notifications
You must be signed in to change notification settings - Fork 1
test cpp #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
test cpp #1
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| #include <iostream> | ||
| #include <cstring> | ||
| #include <vector> | ||
| #include <string> | ||
| #include <cstdlib> | ||
| #include <ctime> | ||
|
|
||
| using namespace std; | ||
|
|
||
| // 1. 硬编码敏感信息 (CWE-798) | ||
| // SAST 会扫描变量名(如 api_key, secret)和高熵字符串 | ||
| const string AWS_SECRET_KEY = "AKIAIOSFODNN7EXAMPLE"; | ||
|
|
||
| class UserManager { | ||
| public: | ||
| // 2. 也是硬编码,且作为类成员 | ||
| string db_password = "root"; | ||
|
Comment on lines
+16
to
+17
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Critical: Hardcoded database password. The database password is hardcoded as a public class member, creating multiple security risks:
🔎 Recommended secure alternatives class UserManager {
-public:
- // 2. 也是硬编码,且作为类成员
- string db_password = "root";
+private:
+ string db_password;
+
+public:
+ UserManager() {
+ const char* pw = getenv("DB_PASSWORD");
+ if (!pw) {
+ throw runtime_error("DB_PASSWORD environment variable not set");
+ }
+ db_password = pw;
+ }
🤖 Prompt for AI Agents |
||
|
|
||
| // 3. SQL 注入 (CWE-89) | ||
| // 直接拼接字符串构建 SQL 查询是 C++ Web 后端常见的严重漏洞 | ||
| void queryUser(string userId) { | ||
| string query = "SELECT * FROM users WHERE id = '" + userId + "'"; | ||
| cout << "Executing query: " << query << endl; | ||
| } | ||
|
Comment on lines
+19
to
+24
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Critical: SQL injection vulnerability. Direct string concatenation of user input into SQL queries allows attackers to inject arbitrary SQL. An input like 🔎 Recommended fix using parameterized queries // 3. SQL 注入 (CWE-89)
- // 直接拼接字符串构建 SQL 查询是 C++ Web 后端常见的严重漏洞
void queryUser(string userId) {
- string query = "SELECT * FROM users WHERE id = '" + userId + "'";
- cout << "Executing query: " << query << endl;
+ // Use parameterized queries with a proper database library
+ // Example with a hypothetical DB library:
+ PreparedStatement stmt = db.prepare("SELECT * FROM users WHERE id = ?");
+ stmt.bind(1, userId);
+ ResultSet rs = stmt.execute();
+ cout << "Query executed safely" << endl;
}Always use parameterized queries or prepared statements to prevent SQL injection.
🤖 Prompt for AI Agents |
||
|
|
||
| // 4. 命令注入 (CWE-78) | ||
| // 允许外部输入直接进入 system() 函数 | ||
| void pingHost(string ipAddress) { | ||
| string cmd = "ping -c 4 " + ipAddress; | ||
| system(cmd.c_str()); | ||
| } | ||
|
Comment on lines
+26
to
+31
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Critical: Command injection vulnerability. Passing unsanitized user input to 🔎 Recommended fix using safe alternatives // 4. 命令注入 (CWE-78)
- // 允许外部输入直接进入 system() 函数
void pingHost(string ipAddress) {
- string cmd = "ping -c 4 " + ipAddress;
- system(cmd.c_str());
+ // Validate input format
+ regex ip_pattern(R"(^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$)");
+ if (!regex_match(ipAddress, ip_pattern)) {
+ cerr << "Invalid IP address format" << endl;
+ return;
+ }
+
+ // Use execve family instead of system() to avoid shell interpretation
+ pid_t pid = fork();
+ if (pid == 0) {
+ execl("/bin/ping", "ping", "-c", "4", ipAddress.c_str(), NULL);
+ exit(1);
+ }
+ waitpid(pid, NULL, 0);
}Never use Based on static analysis hints, 🧰 Tools🪛 ast-grep (0.40.3)[warning] 29-29: Don't call (dont-call-system-cpp) 🤖 Prompt for AI Agents |
||
| }; | ||
|
|
||
| void legacyBufferOverflow(char* input) { | ||
| char buffer[10]; | ||
|
|
||
| // 5. 经典的栈缓冲区溢出 (CWE-121) | ||
| // 虽然是 C++,但混用 C 风格字符串处理函数非常常见且危险 | ||
| strcpy(buffer, input); | ||
| } | ||
|
Comment on lines
+34
to
+40
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Critical: Buffer overflow vulnerability. Using 🔎 Recommended fix using safe string functions void legacyBufferOverflow(char* input) {
char buffer[10];
- // 5. 经典的栈缓冲区溢出 (CWE-121)
- // 虽然是 C++,但混用 C 风格字符串处理函数非常常见且危险
- strcpy(buffer, input);
+ // Use strncpy with proper null termination, or better yet, use std::string
+ strncpy(buffer, input, sizeof(buffer) - 1);
+ buffer[sizeof(buffer) - 1] = '\0';
+
+ // Best practice: use C++ strings instead of C-style char arrays
+ // string safeBuffer = string(input).substr(0, 9);
}🤖 Prompt for AI Agents |
||
|
|
||
| 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; | ||
| } | ||
|
Comment on lines
+42
to
+55
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Memory leak on early return path. The allocated array at line 45 is never freed when the early return at line 51 executes. This causes a memory leak that accumulates with repeated calls, eventually exhausting system memory. 🔎 Recommended fix using RAII void memoryLeakAndRawPointers() {
- // 6. 内存泄漏 (CWE-401)
- // 使用了 new 但没有 delete
- int* data = new int[100];
+ // Use smart pointers for automatic memory management
+ unique_ptr<int[]> data(new int[100]);
data[0] = 10;
- // 抛出异常可能导致 delete 永远不执行 (异常安全问题)
if (data[0] == 10) {
- // throw runtime_error("Error occurred!");
return;
}
-
- delete[] data;
+ // unique_ptr automatically cleans up on all exit paths
}Or use Based on static analysis hints, Cppcheck confirms the memory leak at line 51. 🧰 Tools🪛 Cppcheck (2.19.0)[error] 51-51: Memory leak (memleak) 🤖 Prompt for AI Agents |
||
|
|
||
| void iteratorInvalidation() { | ||
| vector<int> 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); | ||
| } | ||
| } | ||
| } | ||
|
Comment on lines
+57
to
+68
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Critical: Iterator invalidation causing undefined behavior. Calling 🔎 Recommended fix void iteratorInvalidation() {
vector<int> 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);
+ // Collect modifications first, apply after iteration
+ bool shouldAdd = false;
+ for (auto it = numbers.begin(); it != numbers.end(); ++it) {
+ if (*it == 3) {
+ shouldAdd = true;
}
}
+ if (shouldAdd) {
+ numbers.push_back(6);
+ }
}Never modify a container while iterating over it. Collect changes first or use index-based iteration with size caching. Based on static analysis hints, Cppcheck flags the invalid container iterator at line 63. 🧰 Tools🪛 Cppcheck (2.19.0)[error] 63-63: Using iterator to local container 'numbers' that may be invalid. (invalidContainer) 🤖 Prompt for AI Agents |
||
|
|
||
| void weakRandomness() { | ||
| // 8. 弱伪随机数生成器 (CWE-338) | ||
| // srand/rand 不适合用于安全相关的随机数生成 | ||
| srand(time(NULL)); | ||
| int token = rand(); | ||
| cout << "Security Token: " << token << endl; | ||
| } | ||
|
Comment on lines
+70
to
+76
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Weak randomness for security-critical token generation. Using
Additionally, printing the token to stdout at line 75 exposes it in logs. 🔎 Recommended fix using cryptographically secure RNG+#include <random>
+
void weakRandomness() {
- // 8. 弱伪随机数生成器 (CWE-338)
- // srand/rand 不适合用于安全相关的随机数生成
- srand(time(NULL));
- int token = rand();
- cout << "Security Token: " << token << endl;
+ // Use cryptographically secure random number generator
+ random_device rd;
+ mt19937 gen(rd());
+ uniform_int_distribution<> dis(0, INT_MAX);
+ int token = dis(gen);
+
+ // For production: use std::random_device alone or platform-specific CSPRNGs
+ // Never log security tokens
+ // cout << "Security Token: " << token << endl;
}For production security tokens, use platform-specific CSPRNGs like
🤖 Prompt for AI Agents |
||
|
|
||
| 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; | ||
| } | ||
|
Comment on lines
+78
to
+101
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Critical: Division by zero causes guaranteed crash. Line 98 performs division by zero, causing immediate program termination. Variable Additionally, the minimal validation at line 81 doesn't prevent exploitation of the vulnerabilities throughout the function. User input
🔎 Recommended fixes int main(int argc, char* argv[]) {
UserManager um;
if (argc < 2) {
+ cerr << "Usage: " << argv[0] << " <input>" << endl;
return 1;
}
- // 模拟攻击路径
- um.queryUser(argv[1]); // 传入 "' OR '1'='1" 即可注入
+ // Add input validation and proper error handling
+ try {
+ um.queryUser(argv[1]);
+ legacyBufferOverflow(argv[1]);
+ memoryLeakAndRawPointers();
+ iteratorInvalidation();
+ weakRandomness();
+ } catch (const exception& e) {
+ cerr << "Error: " << e.what() << endl;
+ return 1;
+ }
- legacyBufferOverflow(argv[1]);
-
- memoryLeakAndRawPointers();
-
- iteratorInvalidation();
-
- weakRandomness();
-
- // 9. 被除数为零 (CWE-369)
- int x = 0;
- int y = 100 / x;
+ // Fix division by zero
+ int x = 1; // or validate x != 0 before division
+ int y = 100 / x;
return 0;
}Based on static analysis hints, Cppcheck confirms the division by zero at line 98.
🧰 Tools🪛 Cppcheck (2.19.0)[error] 98-98: Division by zero. (zerodiv) 🤖 Prompt for AI Agents |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Hardcoded AWS credentials detected.
Hardcoded secrets in source code are a severe security vulnerability. This credential will be:
🔎 Recommended secure alternatives
Alternatively, use a proper secret management solution like AWS Secrets Manager, HashiCorp Vault, or encrypted configuration files.
📝 Committable suggestion
🤖 Prompt for AI Agents