# 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:** JavaScript - 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 예방 전략. ### Key Practices - treated as untrusted input since: - Prompt injection attacks can manipulate AI responses - LLMs can hallucinate and produce unexpected outputs - Model behavior may change between versions Dangerous operations include: - Code execution (eval, Function, vm ### JavaScript Replace eval/Function constructor with safe alternatives like JSON.parse or predefined function maps Validate and sanitize LLM outputs before using in dangerous operations like eval or SQL Use static values for decorator parameters and avoid eval(), global modifications, or user input in decorators ## Warning Signs - [HIGH] LLM/AI outputs being used directly in dangerous operations without proper validation or sanitization - [HIGH] Decorator '...' executes unsafe code or accesses global state. This can lead to code injection or unauthorized access. - [CRITICAL] user input flowing to code execution functions like eval() or Function constructor ## Consequences - 승인되지 않은 코드 실행 - 애플리케이션 데이터 읽기 - 애플리케이션 데이터 수정 ## Mitigations - eval()이나 동등한 함수의 사용을 피하도록 코드를 리팩터링하세요 - 엄격한 경계를 강제하는 샌드박스에서 코드를 실행하세요 - 가능한 경우 정적 타입 검사를 사용하세요 ## Detection - Total rules: 10 - Critical: 6 - Languages: go, javascript, typescript, python ## Rules by Language ### Typescript (3 rules) - **Code Injection via eval() and Function constructor** [CRITICAL]: Detects user input flowing to code execution functions like eval() or Function constructor. - Remediation: Use JSON.parse for data or predefined function maps instead of eval(). ```javascript const data = JSON.parse(userInput); // Or use a function map const ops = { add: (a,b) => a+b }; ops[action]?.(x, y); ``` Learn more: https://shoulder.dev/learn/javascript/cwe-94/code-injection - **LLM Insecure Output Handling** [HIGH]: Detects LLM/AI outputs being used directly in dangerous operations without proper validation or sanitization. OWASP LLM02 - Insecure Output Handling. LLM outputs should be treated as untrusted input since: - Prompt injection attacks can manipulate AI responses - LLMs can hallucinate and produce unexpected outputs - Model behavior may change between versions Dangerous operations include: - Code execution (eval, Function, vm.runInContext) - Command execution (exec, spawn, execSync) - SQL queries - Remediation: Validate LLM outputs against expected formats before using in dangerous operations. ```javascript const content = response.choices[0].message.content; if (!/^[a-zA-Z0-9\s]+$/.test(content)) { throw new Error('Invalid format'); } ``` Learn more: https://shoulder.dev/learn/javascript/cwe-94/llm-insecure-output-handling - **TypeScript Unsafe Decorator Usage** [HIGH]: Decorators that use eval(), modify global state, or accept user input as parameters enable code injection, prototype pollution, and authorization bypass. - Remediation: Use static values for decorator parameters and avoid eval/global modifications. ```typescript enum Role { Admin = 'admin', User = 'user' } function RequireRole(...roles: Role[]) { return function(target: any, key: string, desc: PropertyDescriptor) { const original = desc.value; desc.value = function(...args: any[]) { if (!roles.includes(this.user?.role)) { throw new Error('Unauthorized'); } return original.apply(this, args); }; }; } ``` Learn more: https://shoulder.dev/learn/typescript/cwe-94/unsafe-decorator ### Javascript (2 rules) - **Code Injection via eval() and Function constructor** [CRITICAL]: Detects user input flowing to code execution functions like eval() or Function constructor. - Remediation: Use JSON.parse for data or predefined function maps instead of eval(). ```javascript const data = JSON.parse(userInput); // Or use a function map const ops = { add: (a,b) => a+b }; ops[action]?.(x, y); ``` Learn more: https://shoulder.dev/learn/javascript/cwe-94/code-injection - **LLM Insecure Output Handling** [HIGH]: Detects LLM/AI outputs being used directly in dangerous operations without proper validation or sanitization. OWASP LLM02 - Insecure Output Handling. LLM outputs should be treated as untrusted input since: - Prompt injection attacks can manipulate AI responses - LLMs can hallucinate and produce unexpected outputs - Model behavior may change between versions Dangerous operations include: - Code execution (eval, Function, vm.runInContext) - Command execution (exec, spawn, execSync) - SQL queries - Remediation: Validate LLM outputs against expected formats before using in dangerous operations. ```javascript const content = response.choices[0].message.content; if (!/^[a-zA-Z0-9\s]+$/.test(content)) { throw new Error('Invalid format'); } ``` Learn more: https://shoulder.dev/learn/javascript/cwe-94/llm-insecure-output-handling