feat: client-side ClamAV scanning for encrypted rooms (Issue #19)

Synapse's own check_media_file_for_spam module can never see E2EE
attachment content - only the client ever holds the decryption key.
Adds two hooks that call a self-hosted scan service
(https://axion1337.chat/_scan, deployed separately in the gitops repo):

- DecryptFile.ts: scans every decrypted attachment (image/audio/video/
  file all funnel through this one function via MediaEventHelper)
  before returning it as a Blob.
- ContentMessages.ts: scans plaintext before encryption/upload in
  uploadFile(), the shared function behind all attachment uploads
  (main file, thumbnails, voice messages), regardless of room
  encryption state.

New ContentScanRejectedError surfaces through the existing error-
rendering paths (MediaProcessingError, upload failure dialog) using
the same pattern as DecryptError/DownloadError/UploadFailedError.

Live-tested: EICAR blocked pre-upload in encrypted rooms and DMs;
receive-side hook also blocks EICAR sent by an unpatched client
(app.element.io), confirming it isn't just self-protection for our
own uploads. Fails open on scanner errors so an outage can't block
all uploads/downloads.
This commit is contained in:
Thore Cimbal
2026-07-29 12:00:00 +00:00
parent 44305556c3
commit 42285021cb
8 changed files with 134 additions and 19 deletions
+63
View File
@@ -0,0 +1,63 @@
/*
Copyright 2026 aXion1337
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
// Client-side ClamAV scanning (Issue #19 extension): Synapse's own server-side spam-checker
// module can never see E2EE attachment content - only a cooperating client can, since only
// the client ever holds the room's decryption key. This calls a small self-hosted scan
// service (same ClamAV instance the server-side module uses) directly from the browser, both
// before encrypting/uploading a file and after downloading/decrypting one - see
// ContentMessages.ts (send) and DecryptFile.ts (receive) for the two call sites.
import { logger } from "matrix-js-sdk/src/logger";
export class ContentScanRejectedError extends Error {
public readonly signature: string;
public constructor(signature: string) {
super(`Blocked by content scanner: ${signature}`);
this.name = "ContentScanRejectedError";
this.signature = signature;
}
}
/**
* Scans plaintext bytes against the self-hosted ClamAV scan service.
* Fails open (resolves normally) on any network/scanner-side error, matching the same
* fail-open policy as the server-side Synapse module - a scanner outage should not block
* uploads or downloads site-wide.
* @throws {ContentScanRejectedError} if the scanner positively identifies the content as infected.
*/
export async function scanContent(data: ArrayBuffer | ArrayBufferView, accessToken: string): Promise<void> {
let response: Response;
try {
response = await fetch("/_scan", {
method: "POST",
headers: { Authorization: `Bearer ${accessToken}` },
body: data as BodyInit,
});
} catch (e) {
logger.warn("Content scan request failed (scanner unreachable?) - allowing through", e);
return;
}
if (!response.ok) {
logger.warn("Content scan request failed with status", response.status, "- allowing through");
return;
}
let result: { clean: boolean; signature?: string };
try {
result = await response.json();
} catch (e) {
logger.warn("Content scan response was not valid JSON - allowing through", e);
return;
}
if (result.clean === false) {
throw new ContentScanRejectedError(result.signature ?? "unknown");
}
}
+21 -5
View File
@@ -13,6 +13,8 @@ import { type EncryptedFile, type MediaEventInfo } from "matrix-js-sdk/src/types
import { mediaFromContent } from "../customisations/Media";
import { getBlobSafeMimeType } from "./blobs";
import { MatrixClientPeg } from "../MatrixClientPeg";
import { scanContent, ContentScanRejectedError } from "./ContentScanner";
export class DownloadError extends Error {
public constructor(e: Error) {
@@ -30,6 +32,8 @@ export class DecryptError extends Error {
}
}
export { ContentScanRejectedError };
/**
* Decrypt a file attached to a matrix event.
* @param {EncryptedFile} file The encrypted file information taken from the matrix event.
@@ -55,19 +59,31 @@ export async function decryptFile(file?: EncryptedFile, info?: MediaEventInfo):
throw new DownloadError(e as Error);
}
let dataArray: ArrayBuffer;
let mimetype: string;
try {
// Decrypt the array buffer using the information taken from the event content.
const dataArray = await encrypt.decryptAttachment(responseData, file!);
// Turn the array into a Blob and give it the correct MIME-type.
dataArray = await encrypt.decryptAttachment(responseData, file!);
// IMPORTANT: we must not allow scriptable mime-types into Blobs otherwise
// they introduce XSS attacks if the Blob URI is viewed directly in the
// browser (e.g. by copying the URI into a new tab or window.)
// See warning at top of file.
const mimetype = getBlobSafeMimeType(info?.mimetype?.split(";")[0].trim() ?? "");
return new Blob([dataArray], { type: mimetype });
mimetype = getBlobSafeMimeType(info?.mimetype?.split(";")[0].trim() ?? "");
} catch (e) {
throw new DecryptError(e as Error);
}
// Issue #19 extension: Synapse's own media scanner never sees this content (it's
// ciphertext to the server) - this is the one place in the whole app where decrypted
// plaintext for *every* attachment type first exists, so scanning here covers all of
// them in one spot. Deliberately outside the try/catch above: a scan rejection is a
// distinct outcome from a decrypt failure, not wrapped as a DecryptError.
const accessToken = MatrixClientPeg.safeGet()?.getAccessToken();
if (accessToken) {
await scanContent(dataArray, accessToken);
}
// Turn the array into a Blob and give it the correct MIME-type.
return new Blob([dataArray], { type: mimetype });
}