# Improper Control of Generation of Code ('Code Injection') (CWE-94) The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. **Stack:** Go - Prevalence: 높음 자주 악용됨 - Impact: 치명적 6개의 치명적 심각도 규칙 - Prevention: 문서화됨 10개의 수정 예시 **OWASP:** Injection (A03:2021-Injection) - #3 ## Description When software allows a user's input to contain code syntax, it might be possible for an attacker to craft the code in such a way that it will alter the intended control flow of the software. Such an alteration could lead to arbitrary code execution. ## Prevention 3개의 Shoulder 탐지 규칙을 기반으로 한 Code Injection 예방 전략. ### Go Pass user input as template data, never use template.HTML with unsanitized input Validate and sanitize LLM outputs before using in dangerous operations like exec or SQL Use predefined templates and pass user input as template data, never as template code ## Warning Signs - [HIGH] LLM output flows to ... without validation - [HIGH] LLM outputs used directly in dangerous operations like command execution or SQL queries without vali - [CRITICAL] user input flowing to template functions that bypass HTML escaping ## Consequences - 승인되지 않은 코드 실행 - 애플리케이션 데이터 읽기 - 애플리케이션 데이터 수정 ## Mitigations - eval()이나 동등한 함수의 사용을 피하도록 코드를 리팩터링하세요 - 엄격한 경계를 강제하는 샌드박스에서 코드를 실행하세요 - 가능한 경우 정적 타입 검사를 사용하세요 ## Detection - Total rules: 10 - Critical: 6 - Languages: go, javascript, typescript, python ## Rules by Language ### Go (3 rules) - **Code Injection via os/exec** [CRITICAL]: Detects user input flowing to template functions that bypass HTML escaping. - Remediation: Pass user input as template data instead of using template.HTML. ```go data := struct{ Content string }{Content: userInput} tmpl.Execute(w, data) ``` Learn more: https://shoulder.dev/learn/go/cwe-94/code-injection - **LLM Insecure Output Handling** [HIGH]: Detects LLM outputs used directly in dangerous operations like command execution or SQL queries without validation. - Remediation: Validate LLM outputs against an allowlist before using in dangerous operations. ```go if !validCommands[output] { return errors.New("invalid command") } ``` Learn more: https://shoulder.dev/learn/go/cwe-94/llm-insecure-output-handling - **Server-Side Template Injection** [CRITICAL]: User input passed directly to template.Parse without sanitization. - Remediation: Use predefined templates and pass user data as template variables. ```go tmpl := template.Must(template.ParseFiles("page.html")) tmpl.Execute(w, map[string]string{ "name": userInput, // Safe - passed as data, not template code }) ``` Learn more: https://shoulder.dev/learn/go/cwe-94/ssti