Blog | G5 Cyber Security

GIF Image DOS Attack Prevention

TL;DR

Large or maliciously crafted GIF images can cause a denial-of-service (DoS) attack by consuming excessive client-side resources. This guide explains how to mitigate this risk.

Solution Guide

  1. Understand the Problem: GIFs, unlike JPEGs and PNGs, are decoded entirely on the client’s browser. A very large GIF or one with many frames can take a long time to process, freezing the browser or causing it to crash.
  2. Image Size Limits (Server-Side): Implement limits on the maximum allowed file size for uploaded images. This is your first line of defence.
    • For PHP: You can check $_FILES['image']['size'] before saving the image.
    • Example PHP code:
       2048000) {
        echo 'Image too large!';
        exit;
      }
      ?>
  3. Image Dimension Limits (Server-Side): Limit the maximum width and height of uploaded images. Large dimensions contribute to larger file sizes.
    • Use image processing libraries like GD or ImageMagick on your server to check these values before saving.
       1000 || $height > 800) {
          echo 'Image dimensions too large!';
          exit;
      }
      ?>
  4. GIF Optimisation (Server-Side): Automatically optimise uploaded GIFs to reduce their file size and number of frames.
    • Tools like ImageMagick can be used for this. Consider reducing the colour palette or removing unnecessary frames.
  5. Content Security Policy (CSP): Implement a CSP to restrict where images can be loaded from, reducing the risk of malicious GIFs being injected.
    • Add a header like this to your web server configuration:
      Content-Security-Policy: img-src 'self'

      This only allows images from the same domain as your website.

  6. Client-Side Validation (JavaScript): Add client-side validation to check image size and dimensions before uploading, providing a better user experience.
    • Example JavaScript:
      const fileInput = document.getElementById('imageUpload');
      fileInput.addEventListener('change', function() {
        if (this.files[0].size > 2048000) {
          alert('Image too large!');
          this.value = ''; // Clear the selected file
        }
      });
  7. Lazy Loading: Implement lazy loading for images, so they are only loaded when they come into view.
    • This can help prevent a large number of GIFs from being processed at once.
  8. Regular Security Audits: Regularly scan your website and server for vulnerabilities, including potential image-related attacks.
Exit mobile version