Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

fix: sanitize email HTML output

Stamina939132c0c0566
diff --git a/src/Filee.Engines/Email/EmlConverter.cs b/src/Filee.Engines/Email/EmlConverter.cs
index 3ce96ab2..8615857a 100644
--- a/src/Filee.Engines/Email/EmlConverter.cs
+++ b/src/Filee.Engines/Email/EmlConverter.cs
@@ -10,6 +10,8 @@ using System.IO.Compression;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
+using AngleSharp.Dom;
+using AngleSharp.Html.Parser;
using Filee.Core.Conversion;
using Filee.Engines.Infrastructure;
using MimeKit;
@@ -119,12 +121,9 @@ public sealed partial class EmlConverter : IConverter
string body;
if (message.HtmlBody is { } html)
{
- html = RemoveScripts(InlinePictures(html, message));
- // Keep the style sheets of the message's own <head>, and the content of its <body>.
- foreach (Match style in StyleBlock().Matches(html))
- styles.Append(style.Value);
- var match = BodyContent().Match(html);
- body = match.Success ? match.Groups[1].Value : HeadBlock().Replace(html, "");
+ var safe = SafeHtml(InlinePictures(html, message));
+ body = safe.Body;
+ styles.Append(safe.Styles);
}
else
{
@@ -133,6 +132,7 @@ public sealed partial class EmlConverter : IConverter
var sb = new StringBuilder();
sb.Append("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n");
+ sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'\">\n");
sb.Append($"<title>{WebUtility.HtmlEncode(message.Subject ?? "")}</title>\n");
sb.Append("<style>\n.filee-mail-headers { border-collapse: collapse; margin: 0 0 12px 0; font-family: sans-serif; font-size: 14px; }\n")
.Append(".filee-mail-headers th { text-align: left; vertical-align: top; padding: 2px 16px 2px 0; color: #555; font-weight: 600; }\n")
@@ -170,8 +170,50 @@ public sealed partial class EmlConverter : IConverter
});
}
- /// <summary>A converted page is opened in a browser: scripts of the message are not carried over.</summary>
- private static string RemoveScripts(string html) => ScriptBlock().Replace(html, "");
+ /// <summary>Keep readable mail markup while dropping browser-active elements, attributes and remote images.</summary>
+ private static (string Body, string Styles) SafeHtml(string html)
+ {
+ var document = new HtmlParser().ParseDocument(html);
+ foreach (var element in document.QuerySelectorAll("script, noscript, iframe, object, embed, applet, frame, frameset, portal, form, input, button, textarea, select, option, meta, link, base, svg, math, template, video, audio, source, track").ToArray())
+ element.Parent?.RemoveChild(element);
+
+ foreach (var element in document.QuerySelectorAll("*").ToArray())
+ {
+ foreach (var attribute in element.Attributes.ToArray())
+ {
+ var name = attribute.Name;
+ if (SafeHtmlAttributes.Contains(name)
+ || name == "alt" && element.LocalName == "img"
+ || name == "href" && element.LocalName == "a" && SafeLink(attribute.Value)
+ || name == "src" && element.LocalName == "img" && SafeInlineImage(attribute.Value))
+ continue;
+ element.RemoveAttribute(name);
+ }
+ }
+
+ var styles = string.Concat(document.QuerySelectorAll("style").Select(element => element.OuterHtml));
+ foreach (var style in document.Body?.QuerySelectorAll("style").ToArray() ?? [])
+ style.Parent?.RemoveChild(style);
+ return (document.Body?.InnerHtml ?? "", styles);
+ }
+
+ private static readonly HashSet<string> SafeHtmlAttributes = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "class", "id", "title", "lang", "dir", "style", "align", "width", "height", "colspan", "rowspan",
+ "cellpadding", "cellspacing", "border",
+ };
+
+ private static bool SafeLink(string value) => value.StartsWith('#')
+ || Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https" or "mailto";
+
+ private static bool SafeInlineImage(string value) =>
+ value.StartsWith("data:image/png;base64,", StringComparison.OrdinalIgnoreCase)
+ || value.StartsWith("data:image/jpeg;base64,", StringComparison.OrdinalIgnoreCase)
+ || value.StartsWith("data:image/jpg;base64,", StringComparison.OrdinalIgnoreCase)
+ || value.StartsWith("data:image/gif;base64,", StringComparison.OrdinalIgnoreCase)
+ || value.StartsWith("data:image/webp;base64,", StringComparison.OrdinalIgnoreCase)
+ || value.StartsWith("data:image/bmp;base64,", StringComparison.OrdinalIgnoreCase)
+ || value.StartsWith("data:image/avif;base64,", StringComparison.OrdinalIgnoreCase);
// ───────────────────────── Text ─────────────────────────
@@ -263,9 +305,6 @@ public sealed partial class EmlConverter : IConverter
// ───────────────────────── Patterns ─────────────────────────
- [GeneratedRegex("<body[^>]*>(.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]
- private static partial Regex BodyContent();
-
[GeneratedRegex("<head[^>]*>.*?</head>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]
private static partial Regex HeadBlock();
diff --git a/tests/Filee.Engines.Tests/EmlTests.cs b/tests/Filee.Engines.Tests/EmlTests.cs
index 107be91f..f1dbf7f3 100644
--- a/tests/Filee.Engines.Tests/EmlTests.cs
+++ b/tests/Filee.Engines.Tests/EmlTests.cs
@@ -50,7 +50,9 @@ public class EmlTests(EngineFixture fx) : IClassFixture<EngineFixture>
using var logo = new MagickImage(MagickColors.Teal, 16, 16);
var png = logo.ToByteArray(MagickFormat.Png);
const string Html = "<html><head><style>p { color: #C00000; }</style></head><body><p>안녕하세요. 자료를 보냅니다.</p>" +
- "<img src=\"cid:logo@filee\" alt=\"logo\"><script>alert('x')</script></body></html>";
+ "<img src=\"cid:logo@filee\" alt=\"logo\"><script>alert('x')</script>" +
+ "<img src=\"https://tracker.example/pixel\" onerror=\"alert('x')\">" +
+ "<a href=\"javascript:alert('x')\">bad link</a><svg onload=\"alert('x')\"></svg></body></html>";
var eml = string.Join("\r\n",
$"From: {EncodedWord("보낸이", "EUC-KR")} <[email protected]>",
@@ -125,6 +127,12 @@ public class EmlTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Contains("src=\"data:image/png;base64,", html);
Assert.DoesNotContain("cid:", html);
Assert.DoesNotContain("<script", html);
+ Assert.DoesNotContain("onerror", html);
+ Assert.DoesNotContain("onload", html);
+ Assert.DoesNotContain("tracker.example", html);
+ Assert.DoesNotContain("javascript:", html);
+ Assert.DoesNotContain("<svg", html);
+ Assert.Contains("Content-Security-Policy", html);
}
[Fact]