Blog | G5 Cyber Security

Secure Custom HTML Emails

TL;DR

Allowing users to create custom HTML emails is risky. It opens doors for phishing attacks and malware distribution. This guide explains how to mitigate those risks through input sanitisation, content security policy (CSP), email client compatibility testing, link checking, and monitoring.

1. Understand the Risks

Users can inject malicious code into HTML emails, even without intending to. Common threats include:

2. Input Sanitisation – The First Line of Defence

Never trust user input directly. Sanitize all HTML before it’s used in an email.

  1. Whitelist Approach: Define a strict set of allowed HTML tags and attributes. Remove everything else. This is the most secure method, but can be restrictive.
  2. Blacklist Approach (Discouraged): Attempting to block dangerous tags/attributes is unreliable as attackers constantly find new ways around filters.
  3. HTML Purifier: A popular PHP library for robust HTML sanitisation. Other languages have similar libraries. Example usage:
    purify($user_submitted_html);
    echo $clean_html;
    ?>
  4. JavaScript Stripping: Remove all JavaScript, even within allowed tags.
  5. CSS Inline Styles Only: Allow only inline CSS styles (e.g., <p style="color: blue;">). Disable external stylesheets and embedded <style> blocks.

3. Content Security Policy (CSP)

Use CSP to tell email clients which resources are allowed to load within the email.

  1. Meta Tag: Add a meta tag in the <head> of your HTML email:
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'none'; style-src 'unsafe-inline'">
    
    • ‘self’: Allows resources from the same domain.
    • script-src ‘none’: Disables all JavaScript execution. Crucial!
    • style-src ‘unsafe-inline’: Allows inline CSS styles (necessary if you allow them in sanitisation). Be cautious with this; consider removing it if possible.

4. Email Client Compatibility Testing

Different email clients render HTML differently. Test your emails thoroughly.

5. Link Checking

Verify all links within the HTML email.

6. Monitoring and Reporting

Continuously monitor for suspicious activity.

Exit mobile version