베타 Shoulder는 베타 버전입니다 — 결과가 가끔 잘못될 수 있습니다. 여러분의 피드백이 다음에 무엇을 고칠지 결정합니다. 피드백 공유
💥

Uncontrolled Resource Consumption

🛡️ 8 개의 규칙이 이를 탐지합니다

Uncontrolled Resource Consumption

The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.

Limited resources include memory, file system storage, database connection pool entries, and CPU. If an attacker can trigger the allocation of these limited resources, but the number or size of the resources is not controlled, then the attacker could cause a denial of service.

보급률
높음
자주 악용됨
영향
보통
검토 권장
예방
문서화됨
8개의 수정 예시
2 예방
2 예방

이 취약점을 수정하는 방법

8개의 Shoulder 탐지 규칙을 기반으로 한 Resource Exhaustion 예방 전략.

LLM Denial of Service MEDIUM

Set MaxTokens limits, validate input length, and configure timeouts for LLM API calls

+13 -3 go
  func handler(w http.ResponseWriter, r *http.Request) {
      var req ChatRequest
      json.NewDecoder(r.Body).Decode(&req)
-     resp, _ := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
-         Model:    "gpt-4",
-         Messages: []openai.ChatCompletionMessage{{Content: req.Message}},
+ 
+     message := req.Message
+     if len(message) > 2000 {
+         message = message[:2000]
+     }
+ 
+     ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
+     defer cancel()
+ 
+     resp, _ := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
+         Model:     "gpt-4",
+         Messages:  []openai.ChatCompletionMessage{{Content: message}},
+         MaxTokens: 500,
      })
      json.NewEncoder(w).Encode(resp)
  }
  
Missing Request Size Limits MEDIUM

Use http.MaxBytesReader to limit request body size before reading

+6 -1 go
  func handler(w http.ResponseWriter, r *http.Request) {
-     body, _ := io.ReadAll(r.Body)
+     r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024)
+     body, err := io.ReadAll(r.Body)
+     if err != nil {
+         http.Error(w, "Request too large", 413)
+         return
+     }
      process(body)
  }
  
Denial of Service via Resource Exhaustion MEDIUM

Limit goroutines with semaphore, set HTTP timeouts, and validate allocation sizes

+5 -2 go
  func process(items []string) {
-     for _, item := range items {
-         go func(i string) {
+     sem := make(chan struct{}, 100)
+     for _, item := range items {
+         sem <- struct{}{}
+         go func(i string) {
+             defer func() { <-sem }()
              expensiveOperation(i)
          }(item)
      }
  }
  
LLM Denial of Service MEDIUM

Set max_tokens limits and validate input length before LLM API calls

+5 -3 javascript
- const response = await openai.chat.completions.create({
-   model: 'gpt-4',
-   messages: [{ role: 'user', content: req.body.message }]
+ const message = req.body.message.substring(0, 2000);
+ const response = await openai.chat.completions.create({
+   model: 'gpt-4',
+   messages: [{ role: 'user', content: message }],
+   max_tokens: 500
  });
  
Denial of Service via Unbounded Child Processes MEDIUM

Configure timeout and maxBuffer for child process execution to prevent resource exhaustion

+4 -1 javascript
- const { stdout } = await execPromise(`ping -c 4 ${domain}`);
+ const { stdout } = await execPromise(`ping -c 4 ${domain}`, {
+   timeout: 5000,
+   maxBuffer: 1024 * 100
+ });
  
Missing Resource Limits MEDIUM

Define CPU and memory resource limits to prevent resource exhaustion and denial of service

+7 -2 yaml
  apiVersion: v1
  kind: Pod
  spec:
    containers:
    - name: app
      image: nginx:1.25
-     ports:
-       - containerPort: 80
+     resources:
+       requests:
+         memory: "128Mi"
+         cpu: "250m"
+       limits:
+         memory: "256Mi"
+         cpu: "500m"
  
LLM Denial of Service MEDIUM

Set max_tokens limits, validate input length, and configure timeouts for LLM API calls

+11 -5 python
- @app.route('/chat', methods=['POST'])
- def chat():
-     response = openai.chat.completions.create(
-         model='gpt-4',
-         messages=[{'role': 'user', 'content': request.json['message']}]
+ MAX_INPUT_LENGTH = 2000
+ MAX_OUTPUT_TOKENS = 500
+ 
+ @app.route('/chat', methods=['POST'])
+ def chat():
+     message = request.json['message'][:MAX_INPUT_LENGTH]
+     response = openai.chat.completions.create(
+         model='gpt-4',
+         messages=[{'role': 'user', 'content': message}],
+         max_tokens=MAX_OUTPUT_TOKENS,
+         timeout=30
      )
      return jsonify(response.choices[0].message.content)
  
Resource Exhaustion / Denial of Service MEDIUM

Set size limits on file reads, bound loop iterations, and add timeouts

+8 -5 python
- from flask import request
- 
- @app.route('/upload', methods=['POST'])
- def upload():
-     content = request.files['file'].read()
+ from flask import Flask, request
+ 
+ app = Flask(__name__)
+ app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024  # 10 MB
+ 
+ @app.route('/upload', methods=['POST'])
+ def upload():
+     content = request.files['file'].read(10 * 1024 * 1024)
      return process(content)
  
3 탐지
3 탐지

코드에서 취약점 찾기

Shoulder를 사용하여 코드에서 Uncontrolled Resource Consumption 패턴을 스캔하세요. 8 규칙.

터미널
# Scan with Shoulder CLI
npx @shoulderdev/cli trust --cwe=400

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

탐지 규칙 (8)

4 경고 신호
4 경고 신호

코드 리뷰에서 주의할 점

이 패턴은 잠재적인 Uncontrolled Resource Consumption 취약점을 나타냅니다. 코드 리뷰와 보안 감사 중에 찾아보세요.

🟡
LLM API call lacks resource limits go-llm-denial-of-service
🟡
AI/LLM API calls lacking token limits or input validation that could enable denial of service go-llm-denial-of-service
🟡
Unbounded resource usage can lead to DoS go-resource-exhaustion
🟡
AI/LLM API calls that lack token limits, potentially enabling denial of service attacks javascript-llm-denial-of-service
🟡
child process execution (exec, spawn) without proper resource limits javascript-unbounded-exec-dos
🟡
Container is missing resource limits. kubernetes-missing-resource-limits
🟡
containers missing resource limits kubernetes-missing-resource-limits
🟡
operations that can cause resource exhaustion: unbounded loops on user input, reading entire large f python-resource-exhaustion
🔍

코드베이스를 스캔하세요: Uncontrolled Resource Consumption

Shoulder CLI는 전체 코드베이스에서 취약한 패턴을 찾아냅니다.