# 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