명령어 및 코드 삽입
백엔드 시스템에서 OS 명령어 삽입 및 임의 코드 실행과 관련된 취약점을 식별하고 완화하는 방법을 학습합니다.
명령어 및 코드 삽입은(는) CoddyKit의 무료 Secure Coding & OWASP Top 10 for Backend 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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!
자주 묻는 질문
“명령어 및 코드 삽입” 강의는 무료인가요?
네 — “명령어 및 코드 삽입” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Secure Coding & OWASP Top 10 for Backend 강의 전체를 잠금 해제할 수 있습니다. Secure Coding & OWASP Top 10 for Backend 강의에는 총 4개의 강의가 포함되어 있습니다.
“명령어 및 코드 삽입”에서 뭘 배우나요?
백엔드 시스템에서 OS 명령어 삽입 및 임의 코드 실행과 관련된 취약점을 식별하고 완화하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Secure Coding & OWASP Top 10 for Backend을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Secure Coding & OWASP Top 10 for Backend을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Secure Coding & OWASP Top 10 for Backend은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“명령어 및 코드 삽입” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Secure Coding & OWASP Top 10 for Backend 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Secure Coding & OWASP Top 10 for Backend 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.