Blog | G5 Cyber Security

API Key Reset on HTTP

TL;DR

Automatically invalidate API keys if they are detected being sent over insecure HTTP connections to prevent compromise. This guide shows how to implement this using a reverse proxy (like Nginx) and your application’s key management.

Solution Guide

  1. Understand the Risk: Sending API keys via HTTP means they can be intercepted by anyone monitoring the network. This is especially dangerous on public Wi-Fi or untrusted networks.
  2. Reverse Proxy Configuration (Nginx Example): Use a reverse proxy to enforce HTTPS and check for insecure connections.
    • Edit your Nginx configuration file (usually /etc/nginx/nginx.conf or in the sites-available directory).
    • Add a block to redirect HTTP requests to HTTPS:
      server {
        listen 80;
        server_name example.com;
        return 301 https://$host$request_uri;
      }
      
    • Configure your proxy pass to forward requests to your application server.
  3. Key Management Integration: Your application needs a way to identify and invalidate keys sent over HTTP. There are several approaches:
    • Request Header Check: If the X-Forwarded-Proto header is set to `http`, it indicates an insecure connection.
      # Example in Python (Flask)
      from flask import request
      
      @app.route('/api/data')
      def get_data():
        if request.headers.get('X-Forwarded-Proto') == 'http':
          # Invalidate the API key
          invalidate_key(request.headers.get('Authorization'))
          return "API Key invalidated due to insecure connection", 403
        else:
          # Process request as normal
          return "Data retrieved successfully"
      
    • IP Address Logging: Log the IP addresses of clients connecting via HTTP. Regularly scan these logs and invalidate keys associated with those IPs.

      This is less precise but can be useful if you don’t have access to request headers.

    • Key Usage Tracking: Track when a key is used, including the protocol (HTTP or HTTPS). Invalidate keys that are used over HTTP after a short period.

      Requires more application-level logic but provides better control.

  4. Invalidation Process: Implement a function to invalidate API keys. This might involve:
    • Removing the key from your database.
    • Adding the key to a blacklist.
    • Revoking the key’s permissions in your authentication system.
  5. Testing: Thoroughly test the solution.
    • Attempt to use an API key over HTTP and verify it is invalidated.
    • Ensure that keys used over HTTPS continue to function normally.
    • Check your logs for accurate recording of insecure connections.
  6. Monitoring: Continuously monitor your application’s logs for attempts to use API keys over HTTP.

    Set up alerts to notify you of any suspicious activity.

Exit mobile version