T09 · Insecure Skill Coding Practices
- Location
beautify.py:56- Finding
Unbounded Image Processing Can Cause Resource Exhaustion
- Content
View full analysis
Image.Image: """创建垂直渐变背景(高性能版本)""" base = Image.new('RGB', (width, height)) r1, g1, b1 = hex_to_rgb(color_top) r2, g2, b2 = hex_to_rgb(color_bottom) pixels = base.load() for y in range(height): ratio = y / max(height - 1, 1) r = int(r1 + (r2 - r1) * ratio) g = int(g1 + (g2 - g1) * ratio) b = int(b1 + (b2 - b1) * ratio) for x in range(width): pixels[x, y] = (r, g, b) return base ``` The dimensions supplied to this function originate from the input image without application-level bounds: ```python original = Image.open(input_path) img_w, img_h = original.size # Calculate background dimensions bg_w = img_w + PADDING * 2 ``` The resulting dimensions are then used directly: ```python background = create_gradient(bg_w, bg_h, *GRADIENT_COLORS).convert('RGBA') ``` ### Technical Analysis The application accepts image dimensions without enforcing maximum width, height, total decoded pixels, input file size, memory consumption, or processing time. It allocates a full-size RGB gradient and subsequently creates additional RGBA images, masks, and converted copies. The gradient implementation also performs an interpreted Python loop for every output pixel. Its processing complexity is proportional to `width × height`, while memory consumption includes several full-resolution image buffers. A sufficiently large or highly compressed image can therefore cause substantial CPU and memory consumption. Pillow provides decompression-bomb protections, but the application does not establish its own ex ...[truncated 1228 chars]- Remediation
View remediation
MAX_WIDTH or img_h > MAX_HEIGHT or img_w * img_h > MAX_PIXELS ): raise ValueError("Input image dimensions exceed allowed limits") ``` 2. Enforce a maximum input file size before opening the image. 3. Treat Pillow decompression-bomb warnings as validation errors and retain a deliberate `Image.MAX_IMAGE_PIXELS` policy. 4. Call `original.load()` inside controlled exception handling so decoding failures occur before expensive output allocation. 5. Enforce execution time and memory limits at the worker or container level. 6. Replace the per-pixel Python loop with a bounded, optimized Pillow or array-based gradient implementation. 7. Validate the calculated output dimensions separately because padding and optional text increase the allocation size. ]]>
