बीटा Shoulder बीटा में है — परिणाम कभी-कभी गलत हो सकते हैं। आपकी प्रतिक्रिया तय करती है कि हम आगे क्या ठीक करें। प्रतिक्रिया साझा करें

Improper Control of Generation of Code ('Code Injection')

🛡️ 10 नियम इसे पहचानते हैं

Improper Control of Generation of Code ('Code Injection')

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.

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.

व्यापकता
उच्च
बार-बार शोषित
प्रभाव
क्रिटिकल
6 क्रिटिकल गंभीरता वाले नियम
रोकथाम
प्रलेखित
10 फिक्स उदाहरण
2 रोकथाम
2 रोकथाम

इस भेद्यता को कैसे ठीक करें

10 Shoulder डिटेक्शन नियमों पर आधारित Code Injection के लिए रोकथाम रणनीतियाँ।

Code Injection via os/exec CRITICAL

Pass user input as template data, never use template.HTML with unsanitized input

+4 -4 go
  package main
  
  import (
      "html/template"
      "net/http"
  )
  
  func handler(w http.ResponseWriter, r *http.Request) {
      userContent := r.FormValue("content")
-     // Vulnerable: user input cast to template.HTML bypasses escaping
-     unsafe := template.HTML("<div>" + userContent + "</div>")
-     tmpl, _ := template.New("page").Parse(`<html>{{.}}</html>`)
-     tmpl.Execute(w, unsafe)
+     // Safe: pass as template data, html/template auto-escapes
+     data := struct{ Content string }{Content: userContent}
+     tmpl, _ := template.New("page").Parse(`<html><div>{{.Content}}</div></html>`)
+     tmpl.Execute(w, data)
  }
  
LLM Insecure Output Handling HIGH

Validate and sanitize LLM outputs before using in dangerous operations like exec or SQL

+6 -1 go
  resp, _ := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
      Messages: []openai.ChatCompletionMessage{{Content: "Generate command for: " + task}},
  })
  cmd := resp.Choices[0].Message.Content
- exec.Command("bash", "-c", cmd).Run()
+ 
+ validCommands := map[string]bool{"ls": true, "pwd": true, "date": true}
+ if !validCommands[cmd] {
+     return fmt.Errorf("invalid command: %s", cmd)
+ }
+ exec.Command(cmd).Run()
  
Server-Side Template Injection CRITICAL

Use predefined templates and pass user input as template data, never as template code

+9 -5 go
  package main
  
  import (
      "html/template"
      "net/http"
  )
  
- func handler(w http.ResponseWriter, r *http.Request) {
-     tmplStr := r.FormValue("template")
-     // Vulnerable: user input parsed as template code
-     tmpl, _ := template.New("page").Parse(tmplStr)
-     tmpl.Execute(w, nil)
+ // Safe: template is predefined, not from user input
+ var pageTmpl = template.Must(template.ParseFiles("templates/page.html"))
+ 
+ func handler(w http.ResponseWriter, r *http.Request) {
+     name := r.FormValue("name")
+     // Safe: user input passed as data, not template code
+     pageTmpl.Execute(w, map[string]string{
+         "name": name,
+     })
  }
  
Code Injection via eval() and Function constructor CRITICAL

Replace eval/Function constructor with safe alternatives like JSON.parse or predefined function maps

+11 -4 javascript
  const express = require('express');
  const app = express();
  
- app.post('/calculate', (req, res) => {
-   const expression = req.body.expression;
-   const result = eval(expression);
-   res.json({ result });
+ const operations = {
+   add: (a, b) => a + b,
+   subtract: (a, b) => a - b,
+   multiply: (a, b) => a * b,
+ };
+ 
+ app.post('/calculate', (req, res) => {
+   const { op, a, b } = req.body;
+   const fn = operations[op];
+   if (!fn) return res.status(400).json({ error: 'Invalid operation' });
+   res.json({ result: fn(Number(a), Number(b)) });
  });
  
TypeScript Unsafe Decorator Usage HIGH

Use static values for decorator parameters and avoid eval(), global modifications, or user input in decorators

+16 -14 javascript
- function DynamicRole(roleExpression: string) {
-   return function (target: any, key: string, desc: PropertyDescriptor) {
-     const original = desc.value;
-     desc.value = function (...args: any[]) {
-       if (eval(roleExpression)) {
-         return original.apply(this, args);
-       }
-       throw new Error('Unauthorized');
-     };
-   };
- }
- 
- class AdminController {
-   @DynamicRole("user.role === 'admin'")
+ 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.currentUser?.role)) {
+         throw new Error('Unauthorized');
+       }
+       return original.apply(this, args);
+     };
+   };
+ }
+ 
+ class AdminController {
+   @RequireRole(Role.Admin)
    deleteUser() { /* ... */ }
  }
  
Code Injection via eval/exec CRITICAL

Use ast.literal_eval() for safe evaluation or avoid eval/exec entirely

+10 -6 python
- from flask import request
- 
- @app.route('/calc')
- def calculate():
-     expression = request.args.get('expr')
-     result = eval(expression)
+ import ast
+ from flask import request, abort
+ 
+ @app.route('/calc')
+ def calculate():
+     expression = request.args.get('expr', '')
+     try:
+         result = ast.literal_eval(expression)
+     except (ValueError, SyntaxError):
+         abort(400, 'Invalid expression')
      return str(result)
  
Dangerous Function Usage CRITICAL

Replace eval/exec with ast.literal_eval, JSON parsing, or subprocess with shell=False

+7 -6 python
- from flask import request
- 
- @app.route('/calculate')
- def calculate():
-     expr = request.args.get('expr')
-     result = eval(expr)
+ import ast
+ from flask import request
+ 
+ @app.route('/calculate')
+ def calculate():
+     expr = request.args.get('expr')
+     result = ast.literal_eval(expr)
      return {'result': result}
  
LLM Insecure Output Handling HIGH

Validate and sanitize LLM outputs with Pydantic before using in dangerous operations like eval, exec, or SQL

+18 -6 python
- response = openai.chat.completions.create(
-     model='gpt-4',
-     messages=[{'role': 'user', 'content': user_request}]
- )
- generated_code = response.choices[0].message.content
- result = eval(generated_code)
+ from pydantic import BaseModel, validator
+ import re
+ 
+ class ValidatedOutput(BaseModel):
+     expression: str
+ 
+     @validator('expression')
+     def validate_expression(cls, v):
+         if not re.fullmatch(r'[a-zA-Z0-9\s\+\-\*\/\(\)\.]+', v):
+             raise ValueError('Invalid expression format')
+         return v
+ 
+ response = openai.chat.completions.create(
+     model='gpt-4',
+     messages=[{'role': 'user', 'content': user_request}]
+ )
+ validated = ValidatedOutput(expression=response.choices[0].message.content)
+ result = process_validated_expression(validated.expression)
  

मुख्य अभ्यास

  • 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
  • avoided or heavily restricted
  • 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, exec, compile) - Command execution (os
3 पहचान
3 पहचान

अपने कोड में भेद्यताएँ खोजें

Improper Control of Generation of Code ('Code Injection') पैटर्न के लिए अपने कोडबेस को स्कैन करने के लिए Shoulder का उपयोग करें। 10 नियम.

टर्मिनल
# Scan with Shoulder CLI
npx @shoulderdev/cli trust --cwe=94

# Or scan entire project
npx @shoulderdev/cli trust .

पहचान नियम (10)

4 चेतावनी संकेत
4 चेतावनी संकेत

कोड समीक्षा में किन बातों पर ध्यान दें

ये पैटर्न संभावित Improper Control of Generation of Code ('Code Injection') भेद्यताओं का संकेत देते हैं। कोड समीक्षा और सुरक्षा ऑडिट के दौरान इन्हें देखें।

🟠
LLM output flows to ... without validation go-llm-insecure-output-handling
🟠
LLM outputs used directly in dangerous operations like command execution or SQL queries without vali go-llm-insecure-output-handling
🟠
LLM/AI outputs being used directly in dangerous operations without proper validation or sanitization javascript-llm-insecure-output-handling
🟠
Decorator '...' executes unsafe code or accesses global state. This can lead to code injection or unauthorized access. typescript-unsafe-decorator
🔴
user input flowing to template functions that bypass HTML escaping go-code-injection
🔴
user input flowing to code execution functions like eval() or Function constructor javascript-code-injection
🔴
untrusted user input flowing into code evaluation functions (eval, exec, compile) python-code-injection
🔴
usage of dangerous Python functions that can lead to arbitrary code execution: eval(), exec(), compi python-dangerous-functions
🔍

अपने कोडबेस को इसके लिए स्कैन करें: Improper Control of Generation of Code ('Code Injection')

Shoulder CLI आपके पूरे कोडबेस में भेद्य पैटर्न खोजता है।