Files
ipal-kit/src/modules/forms/attachments/fileChecks.ts
T

197 lines
7.8 KiB
TypeScript

import type { FormFileType } from './fileTypes.js'
import { fileExtensions } from './fileTypes.js'
/**
* Content checks for form files — by the bytes, never by the name or the
* browser's MIME type alone. They stop the wrong KIND of file. They are not an
* antivirus: a well-formed PDF or DOC can still be malicious (attachments.scan).
*/
const startsWith = (bytes: Uint8Array, signature: readonly number[], offset = 0) =>
bytes.length >= offset + signature.length && signature.every((b, i) => bytes[offset + i] === b)
const ascii = (text: string) => [...text].map((c) => c.charCodeAt(0))
const OLE = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]
const ZIP = [0x50, 0x4b, 0x03, 0x04]
/** How many leading bytes `signatureMatches` needs. */
export const SIGNATURE_BYTES = 16
/** Programs, whatever they are named: Windows (MZ), Linux (ELF), macOS (Mach-O), scripts (#!). */
export function looksExecutable(bytes: Uint8Array): boolean {
return (
startsWith(bytes, [0x4d, 0x5a]) ||
startsWith(bytes, [0x7f, 0x45, 0x4c, 0x46]) ||
startsWith(bytes, [0xfe, 0xed, 0xfa, 0xce]) ||
startsWith(bytes, [0xfe, 0xed, 0xfa, 0xcf]) ||
startsWith(bytes, [0xce, 0xfa, 0xed, 0xfe]) ||
startsWith(bytes, [0xcf, 0xfa, 0xed, 0xfe]) ||
startsWith(bytes, [0xca, 0xfe, 0xba, 0xbe]) ||
startsWith(bytes, ascii('#!'))
)
}
/**
* First-bytes check for a built-in type key; `undefined` for a key without one
* (a project's own type — its `detect` runs on the whole file instead).
*/
export function signatureMatches(key: string, head: Uint8Array): boolean | undefined {
switch (key) {
case 'doc':
case 'xls':
return startsWith(head, OLE)
case 'docx':
case 'odt':
case 'xlsx':
return startsWith(head, ZIP)
case 'jpg':
return startsWith(head, [0xff, 0xd8, 0xff])
case 'pdf':
return startsWith(head, ascii('%PDF-'))
case 'png':
return startsWith(head, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
case 'rtf':
return startsWith(head, ascii('{\\rtf'))
case 'webp':
return startsWith(head, ascii('RIFF')) && startsWith(head, ascii('WEBP'), 8)
default:
return undefined
}
}
type ZipEntry = { encrypted: boolean; name: string }
const u16 = (b: Uint8Array, o: number) => b[o] | (b[o + 1] << 8)
const u32 = (b: Uint8Array, o: number) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0
/**
* Entry names from a ZIP's central directory — read WITHOUT unpacking anything,
* so a zip bomb costs nothing. `null` when the archive has no readable directory.
*/
export function zipEntries(bytes: Uint8Array, maxEntries = 5000): null | ZipEntry[] {
// End-of-central-directory record: in the last 22 bytes + up to 64 KB of comment.
const min = Math.max(0, bytes.length - 22 - 0xffff)
let eocd = -1
for (let i = bytes.length - 22; i >= min; i--) {
if (bytes[i] === 0x50 && bytes[i + 1] === 0x4b && bytes[i + 2] === 0x05 && bytes[i + 3] === 0x06) {
eocd = i
break
}
}
if (eocd < 0) {return null}
const count = u16(bytes, eocd + 10)
let offset = u32(bytes, eocd + 16)
if (count > maxEntries) {return null}
const entries: ZipEntry[] = []
const decoder = new TextDecoder()
for (let i = 0; i < count; i++) {
if (offset + 46 > bytes.length || u32(bytes, offset) !== 0x02014b50) {return null}
const flags = u16(bytes, offset + 8)
const nameLength = u16(bytes, offset + 28)
const extraLength = u16(bytes, offset + 30)
const commentLength = u16(bytes, offset + 32)
if (offset + 46 + nameLength > bytes.length) {return null}
entries.push({ name: decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)), encrypted: (flags & 1) === 1 })
offset += 46 + nameLength + extraLength + commentLength
}
return entries
}
/** Entries a container of this type must have. */
const REQUIRED_ENTRIES: Record<string, string[]> = {
docx: ['[Content_Types].xml', 'word/document.xml'],
odt: ['mimetype', 'content.xml'],
xlsx: ['[Content_Types].xml', 'xl/workbook.xml'],
}
const RISKY_ENTRY = /\.(?:bat|cmd|com|dll|exe|hta|jar|js|lnk|msi|ps1|scr|sh|vbs)$/i
const indexOfBytes = (bytes: Uint8Array, needle: readonly number[]) => {
outer: for (let i = 0; i <= bytes.length - needle.length; i++) {
for (let j = 0; j < needle.length; j++) {
if (bytes[i + j] !== needle[j]) {continue outer}
}
return i
}
return -1
}
const utf16 = (text: string) => [...text].flatMap((c) => [c.charCodeAt(0), 0])
/**
* VBA macros in a legacy Office file: the macro storage holds a stream named
* `_VBA_PROJECT` (Word: Macros/VBA/_VBA_PROJECT, Excel: _VBA_PROJECT_CUR), and
* the compound file's directory stores names as UTF-16. BEST-EFFORT — it finds
* ordinary macro-enabled documents, not one built to hide.
*/
export function oleHasMacros(bytes: Uint8Array): boolean {
return indexOfBytes(bytes, utf16('_VBA_PROJECT')) >= 0
}
/** PDF features that run code or carry other files — a plain byte search (attachments.strictPdf). */
export function pdfHasActiveContent(bytes: Uint8Array): boolean {
return ['/JavaScript', '/JS ', '/JS(', '/Launch', '/EmbeddedFile', '/OpenAction'].some((token) => indexOfBytes(bytes, ascii(token)) >= 0)
}
export type FileRefusal =
/** The name: no extension the field allows, a double extension, a blocked extension. */
| 'content'
/** The bytes are not what the extension claims. */
| 'name'
/** The right container, but with something refused inside (macros, encryption, a program). */
| 'signature'
/**
* Name check, before any byte of the file: the last extension must belong to
* one of the allowed types (else `type`: simply another format), and NO
* extension of the name may be a risky one ("cv.pdf.exe", "cv.exe.pdf") unless
* the project allowed it, nor a second known one ("cv.pdf.docx") — else `refused`.
*/
export function matchFileType(
name: string,
allowed: readonly string[],
types: Record<string, FormFileType>,
risky: ReadonlySet<string>,
): { key: string; type: FormFileType } | { refused: 'refused' | 'type' } {
const extensions = fileExtensions(name.split(/[/\\]/).pop() ?? '')
const last = extensions.at(-1)
// A program, an archive, a macro-enabled file — refused as such, not as "another format".
if (extensions.some((e) => risky.has(e))) {return { refused: 'refused' }}
if (!last) {return { refused: 'type' }}
// "cv.pdf.docx": an extra extension that names another known type hides what the file is.
const known = new Set(Object.values(types).flatMap((t) => t.extensions))
if (extensions.slice(0, -1).some((e) => known.has(e))) {return { refused: 'refused' }}
for (const key of allowed) {
const type = types[key]
if (type?.extensions.includes(last)) {return { type, key }}
}
return { refused: 'type' }
}
/** Whole-file check, once the file is in memory. Returns the refusal, or null when it passes. */
export async function checkFileContent(
key: string,
type: FormFileType,
bytes: Uint8Array,
{ strictPdf = false }: { strictPdf?: boolean } = {},
): Promise<FileRefusal | null> {
if (bytes.length === 0 || looksExecutable(bytes)) {return 'signature'}
const signature = signatureMatches(key, bytes.subarray(0, SIGNATURE_BYTES))
if (signature === false) {return 'signature'}
if (type.detect && !(await type.detect(bytes))) {return 'signature'}
const required = REQUIRED_ENTRIES[key]
if (required) {
const entries = zipEntries(bytes)
if (!entries) {return 'signature'}
const names = new Set(entries.map((e) => e.name))
if (required.some((name) => !names.has(name))) {return 'signature'}
if (entries.some((e) => e.encrypted || /vbaProject\.bin$/i.test(e.name) || RISKY_ENTRY.test(e.name))) {return 'content'}
}
if ((key === 'doc' || key === 'xls') && oleHasMacros(bytes)) {return 'content'}
if (key === 'pdf' && strictPdf && pdfHasActiveContent(bytes)) {return 'content'}
return null
}