命令与代码注入
学习识别并缓解后端系统中与 OS 命令注入和任意代码执行相关的漏洞。
命令与代码注入 是 CoddyKit 上的免费 Secure Coding & OWASP Top 10 for Backend 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Secure Coding & OWASP Top 10 for Backend 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Secure Coding & OWASP Top 10 for Backend 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is Command & Code Injection?
Welcome! In this lesson, we'll explore Command and Code Injection, two critical backend vulnerabilities.
These attacks trick your application into executing unintended system commands or application-level code, leading to severe security breaches.
- Command Injection: Executes OS commands.
- Code Injection: Executes application programming language code.
OS Command Injection Basics
OS Command Injection occurs when an attacker can run arbitrary operating system commands on the server hosting your application.
This happens when an application passes unsanitized user-supplied input to a system shell, often through functions that execute external programs.
Attackers can then:
- Read, write, or delete files.
- Execute malicious scripts.
- Gain full control over the server.
Vulnerable OS Command Example
Let's see a vulnerable Java example. Imagine userInput comes directly from a web form.
The attacker can use command separators (like ; or &) to append new commands to the original one.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CommandInjectionDemo {
public static void main(String[] args) {
// Imagine 'userInput' comes from a web request parameter
String userInput = "my_file.txt; echo HELLO_INJECTED_COMMAND"; // Malicious input example
// For Windows: "my_file.txt & echo HELLO_INJECTED_COMMAND"
// VULNERABLE: Direct concatenation of user input into a system command
String command = "ls -l " + userInput; // Linux example command
// For Windows: String command = "dir " + userInput;
System.out.println("Executing: " + command);
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
p.waitFor(); // Wait for the command to finish
} catch (Exception e) {
System.err.println("Error executing command: " + e.getMessage());
}
}
}How the Injection Works
In the previous example, the string ls -l my_file.txt; echo HELLO_INJECTED_COMMAND is passed to the shell.
The semicolon (;) is a command separator on Linux/Unix-like systems. This tells the shell to execute the first command, then the second.
Even if my_file.txt doesn't exist, the echo command will still run, demonstrating the injection.
Mitigation: Input Validation
The primary defense against OS Command Injection is strict input validation.
- Whitelisting: This is the safest approach. Define exactly what characters, formats, or values are allowed for user input. Reject anything that doesn't match.
- Avoid Blacklisting: Trying to block known malicious characters (like
;,&) is often bypassable due to different shell interpretations or encoding tricks.
Mitigation: Preferring Safe APIs
Instead of concatenating user input directly into a command string, use APIs that pass arguments as separate elements to the command.
In Java, ProcessBuilder is safer than Runtime.getRuntime().exec() when used correctly, as it doesn't invoke a shell by default to interpret arguments.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class SafeCommandExec {
public static void main(String[] args) {
// Imagine 'userInput' comes from a web request parameter
String userInput = "my_file.txt; echo HELLO_INJECTED_COMMAND"; // Malicious input attempt
// SECURE: Pass arguments as separate strings to ProcessBuilder
// The shell will NOT interpret '; echo HELLO_INJECTED_COMMAND' as a new command
ProcessBuilder pb = new ProcessBuilder("ls", "-l", userInput);
// For Windows: ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "dir", userInput);
System.out.println("Executing: " + String.join(" ", pb.command()));
try {
Process p = pb.start(); // Start the process
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
p.waitFor();
} catch (Exception e) {
System.err.println("Error executing command: " + e.getMessage());
}
}
}Understanding Code Injection
Code Injection is similar to Command Injection, but instead of OS commands, it executes arbitrary code in the application's programming language.
This can happen when an application:
- Evaluates user-supplied input as executable code (e.g., using
eval()in scripting languages, or Expression Languages in Java). - Deserializes untrusted data that can construct malicious objects.
- Uses vulnerable templating engines.
Code Injection Scenarios
Unlike OS Command Injection which targets the operating system shell, Code Injection targets the application's runtime environment.
- Dynamic Evaluation: If your application takes user input and uses it in a function like
eval()(common in Python, PHP, JavaScript), an attacker can inject their own code. - Insecure Deserialization: When an application deserializes untrusted data without proper validation, an attacker can craft malicious serialized objects that execute code upon deserialization.
Java applications are particularly vulnerable to insecure deserialization.
Preventing Code Injection
Mitigating Code Injection requires careful design and strict data handling:
- Avoid Dynamic Code Execution: Never use functions that evaluate user-supplied input as code.
- Validate Deserialized Data: Only deserialize data from trusted sources. Implement strict type checks and object validation for any deserialized input.
- Use Safe Template Engines: Ensure your template engines automatically escape user-provided data to prevent injection.
- Least Privilege: Run your application with the minimum necessary permissions.
Test Your Knowledge
It's time for a quick check! Select the most effective practices to prevent injection vulnerabilities.
Recap: Injection Defenses
Great job! You've learned about Command and Code Injection.
- Command Injection allows attackers to run OS commands.
- Code Injection allows attackers to run application-level code.
- Key defenses include strict input validation (whitelisting), using safe APIs (like
ProcessBuilderwith separate arguments), and avoiding dynamic code execution from untrusted sources.
Always treat user input as untrusted data!
常见问题解答
「命令与代码注入」课时是免费的吗?
是的 — 「命令与代码注入」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Secure Coding & OWASP Top 10 for Backend 课程的其余内容,请升级到 CoddyKit PRO。 Secure Coding & OWASP Top 10 for Backend 课程共包含 4 节课。
「命令与代码注入」这节课中我会学到什么?
学习识别并缓解后端系统中与 OS 命令注入和任意代码执行相关的漏洞。 你通过在浏览器中直接运行的动手代码来练习 Secure Coding & OWASP Top 10 for Backend,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Secure Coding & OWASP Top 10 for Backend 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Secure Coding & OWASP Top 10 for Backend 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「命令与代码注入」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Secure Coding & OWASP Top 10 for Backend 课中编写并运行代码吗?
能。每节 Secure Coding & OWASP Top 10 for Backend 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。