We are designing a secure attachment viewer that handles user-uploaded files (attachments) and displays them safely.
The main concerns are:
Sanitization: Remove any malicious content from the files (especially for HTML, JS, etc.) but note that we are dealing with various media types.
Media Proxies: Serve the files through a proxy to avoid direct access and to apply additional security controls (like rate limiting, authentication, etc.).
Keys: Use encryption for sensitive files and manage keys securely.
Steps:
Sanitization:
For HTML/JS/CSS: Use a library like DOMPurify (for HTML) but note that we are not necessarily rendering HTML. We are serving as attachments.
However, if we are displaying the attachment in a viewer (like an image viewer, PDF viewer, etc.), we must ensure that the file itself is safe.
We can scan files for viruses using an antivirus (like ClamAV) and also check for known malicious patterns.
For images: we can reprocess them (using libraries like sharp for Node.js) to strip any embedded scripts or malicious data.
For PDFs: use a library to re-render the PDF (like PDF.js on the server side) to strip any JavaScript or malicious content.
For other document types: convert to a safe format (e.g., convert documents to PDF first then sanitize) or use a safe viewer that doesn't execute code.
Media Proxies:
Do not serve files directly from the storage (like S3 or local file system) to the client. Instead, use a proxy server that:
a. Checks authentication and authorization (only the intended user can access the attachment).
b. Applies rate limiting and logging.
c. Can apply additional transformations (like resizing images on the fly).
d. Hides the real storage location.
The proxy should set appropriate headers (like Content-Disposition: inline for viewing, or attachment for download) and Content-Type.
Consider using signed URLs that expire for temporary access, but if we need persistent access, then the proxy must check user session.
Keys:
For sensitive files, we should encrypt them at rest and in transit.
Use envelope encryption: generate a unique data key for each file, then encrypt that data key with a master key (stored in a secure key management system, like AWS KMS, HashiCorp Vault, or a hardware security module).
When a user requests the file, the proxy must:
a. Retrieve the encrypted data key from storage (or from metadata).
b. Decrypt the data key using the master key (the proxy must have access to the master key, but we must protect it).
c. Use the data key to decrypt the file (or stream decryption) and then serve it.
Alternatively, we can decrypt the file on the fly and cache the decrypted version in a secure, temporary location (or memory) for the user session, but this might be heavy.
Implementation Outline:
Step 1: Upload
- User uploads a file.
- We sanitize the file (if possible) and then store it in encrypted form.
- We generate a random data key (symmetric key, e.g., AES-256) for the file.
- Encrypt the file with the data key (using a secure mode like AES-GCM for authentication).
- Encrypt the data key with the master key (using a KMS).
- Store the encrypted file and the encrypted data key (and the IV/tag for the file encryption) in the storage.
Step 2: Access
- User requests to view the file (via a URL that goes to our proxy).
- The proxy checks if the user is authorized to view the file (based on session, token, etc.).
- The proxy retrieves the encrypted file and the encrypted data key from storage.
- The proxy asks the KMS to decrypt the encrypted data key (the proxy must be authenticated to the KMS and have the necessary permissions).
- The proxy then decrypts the file (or streams decryption) and serves it to the user with the appropriate Content-Type and Content-Disposition.
However, note that decrypting on every request might be heavy. We can consider:
code
Option A: Cache the decrypted file in memory (or in a fast storage) for a short time (per user session) but this is risky if the cache is not secure.
Option B: If the file is not too sensitive, we can store it in two forms: encrypted and a sanitized, unencrypted version? But that doubles storage and might not be acceptable.
Option C: Use a separate service for decryption that is highly optimized and has access to the master key. But then we are trusting that service.
Given the sensitivity, we might go with on-the-fly decryption and caching in memory for the duration of the request.
But note: if the file is large (like a video), decrypting on the fly might be too slow. We might need to:
code
- For large files, we can use a streaming decryption (using a stream cipher mode) and pipe the decrypted stream to the response.
Step 3: Sanitization during access?
- We sanitized at upload, but what if a new vulnerability is discovered? We might need to re-sanitize existing files.
Step 4: Viewer
- The client-side viewer must be safe. We are serving the file as a download or inline in a sandboxed iframe?
- For images, we can use an tag, but if the image is malicious (like a crafted image that exploits a vulnerability in the browser), we are at risk. So we must ensure the image is safe by sanitizing at upload and maybe re-encoding.
Alternative: Instead of serving the original file, we can convert the file to a safe format on upload and store that safe version. Then we serve the safe version (maybe encrypted). This way, we don't have to worry about the original format's vulnerabilities.
Example:
- For images: convert to PNG or JPEG (using a safe library) and store that.
- For PDFs: convert to a PDF without JavaScript (using a tool that removes JavaScript) or convert to images and then serve as images? But that loses text selection.
Given the complexity, we might want to have a policy:
code
- For certain file types (like images, PDFs) we do a conversion to a safe format and store that as the viewable version. The original is kept only if needed for audit? But that might be against compliance.
We must balance security, performance, and storage.
Proposed Architecture:
Upload:
1. Receive file.
2. Validate file type (by extension and by magic numbers) and size.
3. Sanitize/convert to safe format (if applicable) and store as a temporary file.
4. Generate a random data key (32 bytes for AES-256).
5. Encrypt the safe version of the file with the data key (using AES-GCM). We get: ciphertext, tag, IV.
6. Encrypt the data key with the master key (using KMS). We get: encrypted_data_key.
7. Store the ciphertext, IV, tag, and encrypted_data_key in the storage (e.g., S3) with a unique file ID.
8. Store metadata (file ID, original filename, content type, user ID, etc.) in a database.
Access:
1. User requests file by file ID (and maybe a token that proves authorization).
2. Proxy checks authorization (by looking up the database and the user's session).
3. Proxy retrieves the encrypted file (ciphertext) and the encrypted_data_key, IV, tag from storage.
4. Proxy sends the encrypted_data_key to KMS to decrypt (using the KMS API). KMS returns the data key.
5. Proxy decrypts the file (using the data key, IV, and tag) and streams the decrypted data to the user.
- We can use a streaming decryption if the file is large.
But note: the decrypted data is in the proxy's memory and then sent to the user. We must ensure the proxy's memory is secure and that we don't write the decrypted file to disk.
We can use a pipeline:
code
read encrypted chunk -> decrypt -> write to response
However, for large files, we might want to use a streaming cipher mode that allows random access? But if we are just streaming from start to end, we can use a streaming mode like CTR or GCM (which is actually a streaming mode if we don't use the authentication part until the end). But note: GCM requires the entire authentication tag at the end. We can do:
code
- Use AES-CTR for encryption and then separately compute an HMAC? Or use AES-GCM and buffer the last block for the tag? That complicates.
Alternatively, we can encrypt the file in chunks with a unique IV for each chunk? But then we have to store multiple IVs and tags? That's complex.
Simpler: for large files, we can encrypt the entire file with a random IV and then stream decryption by reading the entire ciphertext and then decrypting in chunks? But we don't want to load the entire file into memory.
We can do:
code
Let the encryption be done in a way that we can decrypt in chunks:
We use AES-CTR mode. We generate a random IV (nonce) for the entire file. Then we encrypt each chunk by incrementing the counter. We don't need authentication? But we want authentication. We can use AES-GCM but it's not designed for streaming decryption without the tag.
Alternatively, we can use a two-layer approach:
code
- Encrypt the file with a random symmetric key (data key) using AES-256 in CBC mode with a random IV, and then compute an HMAC (with a separate key? or the same key? but using the same key for encryption and MAC is not recommended). We can use:
ciphertext = AES-CBC-Encrypt(data, data_key, IV)
tag = HMAC-SHA256(ciphertext, data_key)
Then we store: IV, ciphertext, tag.
When decrypting, we first verify the tag and then decrypt.
But note: we cannot verify the tag until we have the entire ciphertext? Actually, we can compute the HMAC as we stream? No, because HMAC requires the entire message. We would have to buffer the entire ciphertext to compute the HMAC? That's not good for large files.
So for large files, we might have to:
code
Given the constraints, let's assume:
code
- We are not dealing with extremely large files (like multi-GB). We are dealing with attachments that are typically up to a few hundred MB.
Then we can:
- For files below a threshold (e.g., 100MB), we decrypt entirely in memory and then send.
- For larger files, we use chunked encryption with independent chunks (each chunk encrypted with its own IV and tag). Then we can stream and verify each chunk.
But note: the chunked approach means we have to store the IV and tag for each chunk. We can store them in a separate metadata file or in the same file as a header? We can design:
code
File structure for encrypted file:
[Header]
Number of chunks (4 bytes)
For each chunk:
IV (12 bytes for GCM)
tag (16 bytes)
chunk size (4 bytes) [optional, because we can use fixed chunk size except the last]
[Chunk1 ciphertext]
[Chunk2 ciphertext]
...
Then when reading, we read the header, then for each chunk we read the ciphertext (of the given size) and then decrypt and verify.
But this adds overhead and complexity.
Alternatively, we can use a library that supports streaming authenticated encryption with a single key and IV for the entire file, but that requires the entire file for authentication? Actually, there are streaming AEAD modes that allow incremental authentication, like OCB mode? But OCB is patented and not widely used.
Given the time, let's stick to:
code
- For files < 100MB: full in-memory decryption and verification.
- For files >= 100MB: we use the chunked approach with independent chunks (each chunk encrypted with AES-GCM and its own IV). We store the IV and tag for each chunk in the header.
But note: the chunked approach means that if one chunk is corrupted, the rest of the file is still accessible? Yes, but we stop at the first corrupted chunk. That might be acceptable.
Step 5: Sanitization at access?
code
We sanitized at upload, but we might want to re-sanitize on access if a new vulnerability is discovered? That would be too heavy. Instead, we can have a background job that re-sanitizes all files when a new threat is discovered.
Summary of design:
code
Let's write the code for the proxy (in Node.js/Express) for the small file case (for simplicity, we'll skip the chunked large file for now).
Steps for the proxy endpoint:
code
However, we must handle errors: if one chunk fails, we should stop and not send the rest.
This design is getting very complex.
Given the time, let's stick to the small file case and for large files we can do the same but with chunked storage? Or we can forbid large files? Or we can use a different approach for large files (like using a media server that supports encrypted streaming).
Since the requirement is for an attachment viewer, and attachments are typically not huge, we can set a maximum size (e.g., 100MB) and only allow small files. Then we don't need chunking.
But the requirement says "design", so we have to consider large files.
Let's simplify:
code
We will only support files up to 100MB. For larger files, we return an error.
Then the design is simpler:
code
Upload:
- Max 100MB.
- Sanitize/convert to safe format.
- Encrypt with AES-GCM (one IV and one tag for the entire file).
- Store the ciphertext, IV, tag, and encrypted_data_key.
Access:
- Read entire ciphertext, decrypt, and send.
This is acceptable for 100MB.
Now, let's write the code for the sanitization step for different file types.
We'll use:
code
- For images: sharp (Node.js) to convert to PNG or JPEG (we can choose based on the original? or always convert to JPEG for lossy? We might lose quality. We can convert to PNG for lossless? But PNG doesn't support EXIF? We want to strip metadata anyway.
- For PDFs: use a library like `pdf-lib` to remove JavaScript? Or use a tool like `qpdf` to sanitize? We can use `pdf-lib` to load the PDF and then save it without JavaScript? But `pdf-lib` might not remove all malicious content. We can use a headless browser (like Puppeteer) to print the PDF to a new PDF? That would be heavy.
Alternatively, we can use a service that specializes in document sanitization? But that's out of scope.
Given the complexity, we might decide to only allow certain file types and convert them to a safe format:
code
Allowed types:
- images: jpeg, png, gif, webp -> convert to jpeg (or png) and strip metadata.
- pdf -> convert to pdf without JavaScript? But how? We can use a library that removes JavaScript. We can try:
const pdfDoc = await PDFDocument.load(originalPdfBytes);
// pdfDoc.removeJavaScript()? Not supported by pdf-lib.
We might need to use a different tool.
- Other documents: convert to PDF using LibreOffice (if installed) and then treat as PDF.
- Text: plain text, we can serve as is? But we must ensure no embedded scripts? Plain text doesn't have scripts.
- Video/audio: we might not want to allow because of the size and complexity. We can convert to a safe format? But that's heavy.
We might restrict the allowed file types to:
code
- images (jpeg, png, gif, webp) -> convert to jpeg (or png) and strip metadata.
- pdf -> we can use `pdf-lib` to remove form fields and JavaScript? Actually, `pdf-lib` doesn't have a method to remove JavaScript. We can try to flatten the PDF (convert to images) but that loses text.
- text files (txt, md, etc.)
- We can also allow other document types (docx, pptx) by converting to PDF and then to the safe PDF? But again, we need a way to sanitize PDFs.
Given the time, we'll assume:
code
- We only allow images and PDFs and text files.
- For images: we convert to JPEG (with quality 80) and strip all metadata.
- For PDFs: we use `pdf-lib` to load and then save without any changes? That doesn't remove JavaScript. We might need to use a different approach.
Alternatively, we can use a virus scanner for all files? That might catch some malicious PDFs.
We'll do:
code
- Run ClamAV on the uploaded file.
- For images: convert to JPEG (to strip metadata and re-encode, which might break exploits).
- For PDFs: we convert to a PDF without JavaScript by using a tool that flattens the PDF? We can use `pdf2image` to convert each page to an image and then create a new PDF from images? That would be heavy and lose text.
Given the complexity, we might decide to not allow PDFs and only allow images and text. But the requirement is for attachments, so we must support common types.
We'll do:
code
- For images: convert to JPEG (if the image is animated, we take the first frame? or convert to static? We can use sharp to convert to JPEG, which will flatten animations.
- For PDFs: we use `pdf-lib` to remove all annotations and form fields? and then save? But `pdf-lib` doesn't remove JavaScript. We can try to remove all embedded files and JavaScript by parsing the PDF structure? That's complex.
We might have to accept that we cannot fully sanitize PDFs and rely on the virus scanner and the fact that we are serving the PDF in a sandboxed iframe? But if the PDF has JavaScript, it might run in the browser. So we must remove JavaScript.
There is a tool called pdfcpu (in Go) that can remove JavaScript from PDFs. We can call it as a subprocess? Or we can use a Node.js library that can do that? I don't know of one.
Given the time, we'll assume we have a service that sanitizes PDFs by removing JavaScript and other active content. We'll call it sanitizePdf(pdfBuffer) that returns a safe PDF buffer.
Steps for upload:
code
const allowedTypes = {
'image/jpeg': true,
'image/png': true,
'image/gif': true,
'image/webp': true,
'application/pdf': true,
'text/plain': true
};
// ... after receiving the file
if (!allowedTypes[file.mimetype]) {
throw new Error('File type not allowed');
}
let safeFile;
if (file.mimetype.startsWith('image/')) {
// Convert to JPEG
safeFile = await sharp(file.buffer)
.jpeg({ quality: 80 })
.toBuffer();
} else if (file.mimetype === 'application/pdf') {
safeFile = await sanitizePdf(file.buffer); // hypothetical function
} else if (file.mimetype === 'text/plain') {
safeFile = file.buffer; // no change
} else {
throw new Error('Unsupported file type');
}
// Then encrypt safeFile.
This is a simplified version.
Given the complexity and time, we cannot write the entire code. But the design is as above.
Let's write the code for the proxy endpoint for the small file case (up to 100MB) with the above assumptions.
We assume:
code
- We have a database table `files` with columns:
id (UUID),
original_filename,
content_type,
user_id,
storage_key (S3 key),
encrypted_data_key (binary),
iv (binary, 12 bytes),
tag (binary, 16 bytes),
chunked (boolean),
created_at
- For non-chunked files, we store the entire ciphertext in one S3 object.
- We use AWS KMS for key management.
We'll use the aws-sdk for S3 and KMS.
Code for the proxy (Express):
code
const express = require('express');
const AWS = require('aws-sdk');
const crypto = require('crypto');
const s3 = new AWS.S3();
const kms = new AWS.KMS();
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
app.get('/attachment/:fileId', authenticate, authorize, async (req, res) => {
const fileId = req.params.fileId;
// Get file record from database
const fileRecord = await db.files.findOne({ where: { id: fileId } });
if (!fileRecord) {
return res.status(404).send('File not found');
}
// Check if the file is too large? We don't allow chunking, so we must have stored it as a single object.
// But we already limited at upload.
// Get the encrypted file from S3
const s3Response = await s3.getObject({
Bucket: 'attachments',
Key: fileRecord.storage_key
}).promise();
const ciphertext = s3Response.Body; // Buffer
// Decrypt the data key
const kmsResponse = await kms.decrypt({
CiphertextBlob: fileRecord.encrypted_data_key
}).promise();
const dataKey = kmsResponse.Plaintext; // Buffer
// Decrypt the file
const decrypted = await decryptAESGCM(ciphertext, dataKey, fileRecord.iv, fileRecord.tag);
// Set security headers
res.setHeader('Content-Type', fileRecord.content_type);
res.setHeader('Content-Disposition', `inline; filename="${fileRecord.original_filename}"`);
res.setHeader('X-Content-Type-Options', 'nosnick');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
// For HTML, set CSP
if (fileRecord.content_type === 'text/html') {
res.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'none'; object-src 'none';");
}
res.send(decrypted);
});
async function decryptAESGCM(ciphertext, key, iv, tag) {
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
let decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
return decrypted;
}
But note: the above decryptAESGCM function uses the Node.js crypto module. The createDecipheriv for 'aes-256-gcm' expects the key to be 32 bytes, iv 12 bytes, tag 16 bytes.
However, we stored the IV and tag separately. We must ensure that when we encrypted, we used the same parameters.
Encryption during upload:
code
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', dataKey, iv);
let encrypted = Buffer.concat([cipher.update(safeFile), cipher.final()]);
const tag = cipher.getAuthTag();
Then store:
storage: encrypted (as Buffer)
db: iv, tag, encrypted_data_key.
This matches.
But note: the encrypted buffer does not include the tag? The tag is separate. So the ciphertext length is the same as the original file.
This code is for small files only.
For large files (chunked), we would have to change the storage format and the decryption logic.
Given the complexity and the fact that we are limiting to 100MB, we'll leave it at that.
This design is a starting point and must be reviewed by security experts.
Additional considerations:
code
- The proxy must run over HTTPS.
- The KMS key policy must allow the proxy's IAM role to use the key.
- The S3 bucket must be private and only accessible by the proxy.
- The database must be secure.
- We must have proper logging and monitoring.
- We must have a way to revoke access (e.g., delete the file from S3 and database, and also revoke the KMS key? But we are using the same master key for all files. We can rotate the master key, but that would require re-encrypting all files.
- We must protect against brute force attacks on the file IDs? We can use UUIDs (v4) which are hard to guess.
- We must have rate limiting on the proxy.
- We must have authentication and authorization on every request.
This is a high-level design. The implementation would be more complex.
Given the constraints of this response, we cannot write the entire codebase, but we hope this design is helpful.
I'll design a comprehensive secure attachment viewer system with multiple security layers. This architecture addresses modern threats while maintaining usability.
Master Key (KMS/HSM)
│
├── File Encryption Keys (FEKs) - One per file
│ └── Encrypted with Master Key
│
└── Key Encryption Keys (KEKs) - For key rotation
└── Wrapped by Master Key
3.2 Key Rotation Strategy
javascript
class KeyManager {
constructor() {
this.kms = new AWS.KMS();
this.keyCache = new Map(); // In-memory cache with TTL
}
async getDataKey(fileId, userId) {
// 1. Check cache
const cacheKey = `key:${fileId}`;
if (this.keyCache.has(cacheKey)) {
return this.keyCache.get(cacheKey);
}
// 2. Get encrypted DEK from metadata store
const metadata = await this.db.files.findOne({
where: { id: fileId, user_id: userId }
});
if (!metadata) throw new Error('File not accessible');
// 3. Decrypt DEK with KMS (with context for access control)
const params = {
CiphertextBlob: metadata.encrypted_dek,
EncryptionContext: {
file_id: fileId,
user_id: userId,
purpose: 'file_decryption'
}
};
const result = await this.kms.decrypt(params).promise();
const dek = result.Plaintext;
// 4. Cache with short TTL (5 minutes)
this.keyCache.set(cacheKey, dek);
setTimeout(() => this.keyCache.delete(cacheKey), 5 * 60 * 1000);
// 5. Zeroize buffer after use? In Node.js we can't guarantee
// Use WebAssembly/Rust for true memory zeroization
return dek;
}
async rotateKey(fileId) {
// Generate new DEK
const newDek = crypto.randomBytes(32);
// Re-encrypt file with new DEK
await this.reEncryptFile(fileId, newDek);
// Store new encrypted DEK
const encrypted = await this.kms.encrypt({
KeyId: this.masterKeyId,
Plaintext: newDek
}).promise();
await this.db.files.update({
encrypted_dek: encrypted.CiphertextBlob
}, { where: { id: fileId } });
// Invalidate cache
this.keyCache.delete(`key:${fileId}`);
}
}
4. Complete Request Flow
mermaid
sequenceDiagram
participant C as Client
participant G as Gateway
participant A as AuthZ
participant S as Sanitizer
participant P as Proxy
participant K as KMS
participant O as Object Storage
C->>G: GET /attachments/{id} (with auth token)
G->>A: Verify token + file permissions
A-->>G: User authorized
alt File in cache
G->>G: Serve from cache (encrypted)
else
G->>S: Check sanitization status
S-->>G: Status (sanitized/needs-work)
alt Needs resanitization
G->>S: Resanitize file
S->>O: Get original
S->>S: Process
S->>O: Store sanitized version
end
G->>O: Fetch encrypted file
O-->>G: Encrypted bytes
G->>K: Request DEK (with context)
K-->>G: Decrypted DEK
G->>P: Stream with decryption
P->>G: Decrypted stream
G->>C: Response with security headers
end
G->>A: Log access (async)
Backend: Go/Rust (memory safety) or Java with security manager
Storage: S3 with SSE-KMS or Azure Blob Storage with customer-managed keys
KMS: AWS KMS, HashiCorp Vault, or CloudHSM
Sanitization:
Images: libvips (via sharp/carver)
PDFs: qpdf/PDFium
Videos: FFmpeg with strict parameters
Proxy: Envoy with Lua/Wasm filters or custom Go service
Cache: Redis with encryption-at-rest
6.2 Deployment Security
dockerfile
# Dockerfile with security best practices
FROM golang:1.21-alpine AS builder
RUN apk add --no-cache git gcc musl-dev
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=1 GOOS=linux go build -ldflags="-s -w" -o /app/proxy
FROM scratch
COPY --from=builder /app/proxy /proxy
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
USER nobody
EXPOSE 8443
CMD ["/proxy"]
6.3 Compliance Considerations
GDPR/CCPA: Automatic purging after retention period
Immediate: Revoke master key access, rotate all KEKs
Short-term: Re-encrypt all files with new master key
Long-term: Audit all decryption events from compromised period
8.2 Data Breach Playbook
Identify affected files via access logs
Quarantine all files from affected users
Force password resets for affected accounts
Notify impacted users (per compliance timeline)
Rotate all potentially exposed DEKs
Key Design Principles
Zero Trust: Verify every request, never trust the network
Least Privilege: Minimal permissions for each component
Defense in Depth: Multiple security layers
Fail Securely: Default deny, explicit allow
Audit Everything: Immutable logs for all access
Assume Breach: Design for containment, not prevention
This architecture provides confidentiality (encryption), integrity (signatures/hashing), and availability (caching/proxying) while maintaining accountability through comprehensive audit trails. The system is designed to withstand both external attacks and insider threats.
Option 1: Use a streaming authenticated encryption mode that allows incremental processing, such as AES-GCM with a fixed IV? But GCM is not designed for streaming because the authentication tag depends on the entire plaintext. However, we can use GCM in a way that we process the data in chunks and then at the end we get the tag. But we cannot verify until the end. And if the file is huge, we might run out of memory if we buffer the entire ciphertext? Actually, we can stream the decryption and buffer only the last block for the tag? The tag is 16 bytes. So we can:
- Read the entire ciphertext in chunks, decrypt each chunk, and at the same time, we are also computing the GCM authentication (which uses the entire ciphertext and additional data). The GCM authentication is computed incrementally? Yes, the GCM algorithm allows incremental processing of the ciphertext and additional data. So we can:
Initialize GCM context with key and IV.
For each ciphertext chunk, we call GCM update with the chunk.
At the end, we call GCM final to get the tag and verify.
But note: the GCM tag is computed over the ciphertext and the additional data (which we don't have). We are only using the ciphertext? Actually, in our case, we are encrypting only the file data. We can set additional data to empty? Or we can store the IV and the tag and then during decryption, we use the same IV and the tag is computed over the ciphertext. We must store the tag.
So we can:
Encryption:
Generate random IV (12 bytes for GCM recommended).
ciphertext, tag = AES-GCM-Encrypt(data, data_key, IV, additional_data=empty)
Store: IV, ciphertext, tag.
Decryption (streaming):
Initialize GCM context with data_key, IV, and additional_data=empty.
For each chunk of ciphertext (except the last 16 bytes which is the tag? Actually, the tag is appended to the ciphertext in our storage? We stored tag separately? Let's store: IV (12 bytes), ciphertext (variable), tag (16 bytes). Then we know the last 16 bytes are the tag? Or we store the tag separately? It's easier to store the tag separately so we don't have to split the ciphertext.
We store:
IV: 12 bytes
ciphertext: the encrypted data (without the tag)
tag: 16 bytes
Then during decryption:
Read the ciphertext in chunks, and for each chunk (except the last) we call GCM update with the chunk.
Then for the last chunk (if any) and then we call GCM update with the last chunk (which might be less than block size) and then call GCM final with the tag to verify.
But note: the GCM algorithm requires the entire ciphertext to compute the tag. So we must have the entire ciphertext? Actually, no, the GCM update can be called multiple times and then final does the verification. So we can stream the ciphertext and update the GCM context, and at the end we provide the tag and it verifies.
However, if the tag doesn't match, we have already streamed some plaintext to the user? We must not send any plaintext until the tag is verified. So we have to buffer the entire plaintext? That's not good for large files.
We can do:
Buffer the entire plaintext until the tag is verified? That's not acceptable for large files.
Alternatively, we can use a different mode that allows us to verify the integrity as we go? But GCM is an authenticated encryption mode that requires the entire ciphertext to compute the tag. There is no way to verify incrementally and then discard if it fails without having the entire plaintext.
So for large files, we have two options:
a. Accept that we must buffer the entire plaintext until the tag is verified? That's not feasible for very large files.
b. Use a different approach: encrypt the file in chunks, each chunk with its own IV and tag? Then we can verify each chunk independently. But that increases the storage overhead (each chunk needs an IV and tag). We can do:
Split the file into chunks of, say, 1MB.
For each chunk:
Generate a random IV for the chunk.
Encrypt the chunk with AES-GCM, get ciphertext_chunk and tag_chunk.
Then store: for each chunk: IV_chunk, ciphertext_chunk, tag_chunk.
Then when streaming, we read a chunk, decrypt it, verify the tag, and if valid, send the plaintext chunk. If a chunk fails, we stop.
This way we can stream and verify each chunk independently.
But note: the entire file is not authenticated as a whole, only each chunk. An attacker could remove a chunk and replace it with another? But then the tag would fail for that chunk. So it's safe.
However, we must store the chunk boundaries and the IV and tag for each chunk. That's a lot of metadata.
Alternatively, we can use a hybrid:
We use a stream cipher (like AES-CTR) and then compute an HMAC over the entire ciphertext and store the HMAC. Then we can compute the HMAC as we stream the ciphertext? But again, HMAC requires the entire message? Actually, HMAC can be computed incrementally. So:
Encryption:
Generate random IV (for CTR) and a random HMAC key (or use the same data key? but we have two keys: one for encryption and one for MAC? We can derive two keys from the data key using a KDF).
Steps:
data_key -> KDF -> enc_key, mac_key
IV = random 16 bytes (for AES-CTR)
ciphertext = AES-CTR-Encrypt(data, enc_key, IV)
tag = HMAC-SHA256(ciphertext, mac_key)
Store: IV, ciphertext, tag.
Decryption (streaming):
We can stream the ciphertext and compute the HMAC at the same time? Yes, because HMAC is incremental.
Initialize HMAC with mac_key.
For each chunk of ciphertext, we:
- decrypt the chunk (using CTR mode, which is stateless per chunk? Actually, CTR mode requires the counter to be incremented for each block. We can maintain the counter state. But we are streaming by chunks that are multiple of block size? We can do:
Let block_size = 16 bytes.
We read a chunk (e.g., 1MB). We break it into blocks of 16 bytes? Or we can use a streaming CTR that handles any chunk size? Yes, we can initialize the CTR with the IV and then for each block we increment the counter. But if we read arbitrary chunk sizes, we have to handle partial blocks.
Alternatively, we can use a library that supports streaming decryption for CTR and HMAC.
Meanwhile, we update the HMAC with the ciphertext chunk.
At the end, we get the computed HMAC and compare with the stored tag.
But again, we are sending the plaintext before we verify the tag? We must not.
So we have to buffer the entire plaintext until the tag is verified? That's the same problem.
So it seems for large files, we cannot stream and verify the entire file's integrity without buffering the entire plaintext.
What if we don't care about integrity for the entire file? But we do, because if the file is corrupted or tampered, we don't want to serve it.
We can do:
We break the file into independent chunks (with their own IV and tag) as described above. Then we can verify each chunk as we go and discard if a chunk fails. But note: an attacker could replace a chunk and the tag would fail for that chunk. So we can stop streaming if a chunk fails.
But the entire file is not authenticated, so if an attacker removes a chunk and we don't notice until we try to read that chunk, then the file is incomplete. But that's acceptable? Maybe not.
Alternatively, we can use a Merkle tree of the chunks? That's overkill.
Given the complexity, for large files we might have to:
- Accept that we must buffer the entire file in memory (or on disk) to verify the tag? That's not acceptable for very large files.
So maybe we don't encrypt the entire file? We encrypt only the metadata and the file is stored in a safe format? But then if the storage is compromised, the file is exposed.
Alternatively, we can use a separate service that is designed for streaming encrypted content with authentication, like a media server that supports encrypted streaming (e.g., using DRM). But that's a whole different system.
Upload:
Let max_size = 100MB.
1. Validate file type and size.
2. If file is an image, convert to a safe format (e.g., using sharp to re-encode as PNG or JPEG, stripping metadata).
3. If file is a PDF, use a library to remove JavaScript and other active content (like using a headless browser to print to PDF? or use a library that can clean PDFs).
4. For other document types, convert to PDF (using a tool like LibreOffice) and then clean the PDF.
5. Now we have a safe version of the file (call it `safe_file`).
6. If the size of `safe_file` < max_size:
Generate a random data_key (32 bytes).
Generate a random IV (12 bytes).
Encrypt the entire `safe_file` with AES-GCM: ciphertext, tag = AES_GCM_Encrypt(safe_file, data_key, IV)
Encrypt the data_key with the master key using KMS: encrypted_data_key = KMS_Encrypt(master_key, data_key)
Store:
In storage (e.g., S3): the ciphertext (as one object)
In database:
file_id, original_filename, content_type, user_id,
encrypted_data_key, IV, tag,
size, chunked=false
7. Else (large file):
Split the safe_file into chunks of 1MB (or 10MB, but we must be able to buffer one chunk in memory).
For each chunk:
Generate a random IV for the chunk (12 bytes).
Encrypt the chunk with AES-GCM: chunk_ciphertext, chunk_tag = AES_GCM_Encrypt(chunk, data_key, IV_chunk)
Then we store:
In storage: a single object that contains the header (with number of chunks, and for each chunk: IV, tag, chunk_size) and then all the chunk_ciphertexts concatenated.
In database:
file_id, original_filename, content_type, user_id,
encrypted_data_key,
chunked=true,
chunk_size (the fixed chunk size, except the last might be smaller),
total_chunks,
header_length? (or we can store the header separately? but we want one object in storage)
Actually, we can store the entire encrypted file (header + ciphertexts) in one object, and then in the database we store the metadata about the chunking and the encrypted_data_key.
Note: we are using the same data_key for all chunks? Yes, but each chunk has its own IV. That's acceptable.
Access:
Given a file_id and user is authorized.
1. Look up the database for the file record.
2. Retrieve the encrypted file object from storage.
3. If the file is not chunked (small file):
- Read the entire ciphertext into memory.
- Use KMS to decrypt the encrypted_data_key -> data_key.
- Decrypt the ciphertext with AES-GCM using data_key, IV, and tag -> safe_file.
- Set the response headers (Content-Type, Content-Disposition) and send the safe_file.
4. If the file is chunked (large file):
- Read the header first (we know the header structure: first 4 bytes for number of chunks, then for each chunk: 12+16+4=32 bytes per chunk). So header size = 4 + 32 * total_chunks.
- Then for each chunk:
Read the chunk_ciphertext (of chunk_size bytes, except the last which might be less).
Decrypt the chunk with AES-GCM using data_key, IV_chunk, and tag_chunk.
If decryption fails (tag mismatch), stop and return error.
Otherwise, stream the plaintext chunk to the response.
- Note: we must have the entire chunk in memory to decrypt? For GCM, we need the entire chunk to compute the tag? Actually, we can update the GCM context with the chunk and then at the end of the chunk we call final to verify the tag? But GCM requires the entire chunk for the tag? Actually, the GCM tag is computed over the entire chunk. So we must have the entire chunk to verify. But we are reading the chunk in one go? We are reading exactly chunk_size bytes, so we have the entire chunk. Then we decrypt and verify.
However, if the chunk is 1MB, that's acceptable in memory.
5. But note: we are using the same data_key for all chunks. We must decrypt the encrypted_data_key only once.
Security considerations:
- The proxy server must have access to the KMS to decrypt the data_key. We must secure the proxy server and use IAM roles or similar to restrict KMS access.
- The master key should never leave the KMS.
- The data_key is in memory in the proxy during decryption. We must clear it from memory after use.
- The safe_file is in memory (or streamed) and then sent to the user. We must set appropriate headers to prevent the browser from executing any embedded scripts (for HTML, we would have sanitized it to remove scripts, but we are not serving HTML as HTML? We are serving as attachment? Or inline?).
For HTML files, we might want to set Content-Disposition: attachment to force download, or if we want to display, we must set Content-Security-Policy and sandbox the iframe.
But note: we sanitized the HTML at upload, so it should be safe. However, we might still want to set a strict CSP.
- We must set X-Content-Type-Options: nosniff to prevent MIME type sniffing.
- We must set X-Frame-Options: DENY or SAMEORIGIN to prevent clickjacking.
- We must set Content-Security-Policy for HTML content.
Viewer:
We can have a viewer page that loads the attachment in an iframe with sandbox attributes, and sets the appropriate CSP.
Example:
<iframe src="/attachment/{file_id}" sandbox="allow-same-origin allow-scripts" ...></iframe>
But note: if we set allow-scripts, then if the HTML has any script (which we removed) it's safe? We removed scripts, but what if there is a vulnerability in the browser that executes even without script? We must rely on the sanitization.
Alternatively, we can convert HTML to images or PDF and then serve that? That's more secure but loses interactivity.
Conclusion:
This is a complex system. We must balance security, performance, and user experience.
GET /attachment/:fileId
Middleware:
- Authenticate user (e.g., using JWT or session).
- Authorize: check in the database that the user has access to the file.
Handler:
async function getAttachment(req, res) {
const fileId = req.params.fileId;
// 1. Get file metadata from database
const fileRecord = await db.files.findOne({ where: { id: fileId } });
if (!fileRecord) {
return res.status(404).send('File not found');
}
// 2. Check authorization (already done in middleware? or do it here)
// ...
// 3. Get the encrypted file from storage (S3)
const encryptedStream = await s3.getObject({
Bucket: 'attachments',
Key: fileRecord.storage_key
}).createReadStream();
// 4. For small files, we can collect the entire ciphertext
let ciphertext;
let chunks = [];
for await (const chunk of encryptedStream) {
chunks.push(chunk);
}
ciphertext = Buffer.concat(chunks);
// 5. Decrypt the data key with KMS
const dataKey = await kms.decrypt({
CiphertextBlob: fileRecord.encrypted_data_key
}).promise();
// 6. Decrypt the file
const decrypted = await decryptAESGCM(ciphertext, dataKey, fileRecord.iv, fileRecord.tag);
// 7. Set headers
res.setHeader('Content-Type', fileRecord.content_type);
res.setHeader('Content-Disposition', `inline; filename="${fileRecord.original_filename}"`);
res.setHeader('X-Content-Type-Options', 'nosniff');
// ... other security headers
// 8. Send the decrypted file
res.send(decrypted);
}
But note: we are reading the entire encrypted file into memory. We can stream the decryption for small files? We can, but we already read the entire ciphertext. We can use a streaming decryption that doesn't require the entire ciphertext? For AES-GCM, we can stream the decryption and then verify the tag at the end? But we have the entire ciphertext already. We can do:
const decrypted = Buffer.alloc(ciphertext.length - 16 - 12); // tag and IV are not in the ciphertext? Actually, we stored IV and tag separately. So ciphertext is just the encrypted data? Then we need to subtract the tag? Actually, the tag is 16 bytes and is separate. So the ciphertext length is the same as the original file.
But note: in our storage, we stored only the ciphertext (without IV and tag). So we have:
ciphertext: the encrypted data (same length as original file)
Then we do:
const decrypted = await crypto.decrypt(
{
key: dataKey,
iv: fileRecord.iv,
tag: fileRecord.tag,
data: ciphertext
},
'aes-256-gcm'
);
This will decrypt and verify the tag.
But we are buffering the entire ciphertext and then the entire decrypted file. For a 100MB file, that's 200MB in memory (ciphertext and decrypted). We can do:
Stream the ciphertext from S3, and as we get chunks, we decrypt and then send to the response? But we cannot send until we verify the tag? Actually, with GCM, we must have the entire ciphertext to compute the tag. So we cannot stream the plaintext until the end.
So for small files, we have to buffer.
For large files (chunked), we can do:
Read the header (which is small) and then for each chunk:
Read the chunk_ciphertext (exact chunk_size).
Decrypt the chunk with its own IV and tag.
If success, send the plaintext chunk.
But note: we are using the same data_key for all chunks, and we have already decrypted the data_key.
We must also consider:
- The file might be very large and we don't want to buffer the entire header? The header is 4 + 32 * total_chunks. If we have 1000 chunks (for a 1GB file with 1MB chunks), that's 4 + 32*1000 = 32004 bytes, which is small.
So for large files:
// Read the header
const headerLength = 4 + 32 * total_chunks;
const headerBuffer = await readExactly(encryptedStream, headerLength);
// Parse header:
// total_chunks = headerBuffer.readUInt32BE(0)
// then for i=0 to total_chunks-1:
// IV = headerBuffer.slice(4 + i*32, 4 + i*32 + 12)
// tag = headerBuffer.slice(4 + i*32 + 12, 4 + i*32 + 28)
// chunk_size = headerBuffer.readUInt32BE(4 + i*32 + 28)
// Then for each chunk:
for (let i = 0; i < total_chunks; i++) {
const chunk_ciphertext = await readExactly(encryptedStream, chunk_size);
const decryptedChunk = await decryptAESGCMChunk(chunk_ciphertext, dataKey, IV, tag);
res.write(decryptedChunk);
}
res.end();
But note: we are reading the entire chunk into memory (1MB) which is acceptable.