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 件の Shoulder 検出ルールに基づく Resource Exhaustion の予防策。
Set MaxTokens limits, validate input length, and configure timeouts for LLM API calls
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) }
Use http.MaxBytesReader to limit request body size before reading
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) }
Limit goroutines with semaphore, set HTTP timeouts, and validate allocation sizes
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) } }
Set max_tokens limits and validate input length before LLM API calls
- 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 });
Configure timeout and maxBuffer for child process execution to prevent resource exhaustion
- const { stdout } = await execPromise(`ping -c 4 ${domain}`); + const { stdout } = await execPromise(`ping -c 4 ${domain}`, { + timeout: 5000, + maxBuffer: 1024 * 100 + });
Define CPU and memory resource limits to prevent resource exhaustion and denial of service
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"
Set max_tokens limits, validate input length, and configure timeouts for LLM API calls
- @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)
Set size limits on file reads, bound loop iterations, and add timeouts
- 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)
コードの脆弱性を見つける
Shoulderを使用してコードのUncontrolled Resource Consumptionパターンをスキャンしましょう。 8 ルール.
# Scan with Shoulder CLI npx @shoulderdev/cli trust --cwe=400 # Or scan entire project npx @shoulderdev/cli trust .
検出ルール (8)
コードレビューで注目すべき点
これらのパターンはUncontrolled Resource Consumptionの潜在的な脆弱性を示しています。コードレビューとセキュリティ監査中に探してください。
コードベースをスキャン: Uncontrolled Resource Consumption
Shoulder CLI はコードベース全体から脆弱なパターンを見つけます。