# Improper Input Validation (CWE-20) The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. **Stack:** Python - Prevalence: 高 频繁被利用 - Impact: 高 6 条严重级别为高的规则 - Prevention: 已记录 13 个修复示例 **OWASP:** Broken Access Control (A01:2021-Broken Access Control) - #1 ## Description Input validation is a frequently-used technique for checking potentially dangerous inputs in order to ensure that the inputs are safe for processing within the code, or when communicating with other components. When software does not validate input properly, an attacker is able to craft the input in a form that is not expected by the rest of the application. ## Prevention 基于 2 条 Shoulder 检测规则的 Improper Input Validation 预防策略。 ### Python Use Pydantic models with Field validators instead of raw Request objects Validate business-critical inputs with range constraints using Pydantic or manual checks ## Warning Signs - [MEDIUM] FastAPI endpoints that accept raw Request objects instead of Pydantic models - [MEDIUM] business-critical input values (discount, refund, quantity, price) that are used in operations witho ## Consequences - 执行未授权代码 - 修改应用程序数据 - 拒绝服务 (DoS) - 读取应用程序数据 ## Mitigations - 假定所有输入都是恶意的。采用只接受已知良好输入的验证策略 - 进行输入验证时,考虑所有可能相关的属性 - 不要仅依赖于查找恶意或畸形输入 ## Detection - Total rules: 13 - Languages: python, go, javascript, typescript ## Rules by Language ### Python (2 rules) - **FastAPI Missing Request Validation** [MEDIUM]: Detects FastAPI endpoints that accept raw Request objects instead of Pydantic models. This bypasses FastAPI's automatic validation and can lead to type confusion and injection vulnerabilities. - Remediation: Use Pydantic models instead of raw Request objects for automatic validation. ```python from pydantic import BaseModel, EmailStr, Field class UserCreate(BaseModel): username: str = Field(min_length=3, max_length=50) email: EmailStr @app.post("/users") async def create_user(user: UserCreate): return {"user": user} ``` Learn more: https://shoulder.dev/learn/python/cwe-20/missing-validation - **Business Logic Input Validation** [MEDIUM]: Detects business-critical input values (discount, refund, quantity, price) that are used in operations without proper validation. Missing validation can lead to financial fraud, inventory errors, or business logic bypass. - Remediation: Validate business-critical inputs with range constraints using Pydantic. ```python from pydantic import BaseModel, Field class DiscountRequest(BaseModel): discount: float = Field(..., ge=0, le=100) quantity: int = Field(..., gt=0) @app.post('/apply-discount') async def apply_discount_route(request: DiscountRequest): apply_discount(request.discount) ``` Learn more: https://shoulder.dev/learn/python/cwe-20/input-validation