Skip to main content

adk_site/
scan.rs

1//! Server-code refusal and content sniffing (spec 3.5 A-I1, §7.8.1 "Server code").
2//!
3//! A release containing a server-executable file or a server-side include directive is
4//! refused, and no flag overrides it. [`scan_file`] is the one rule set the release
5//! builder, the launch gate and the media pipeline share:
6//!
7//! | Rule | Refuses |
8//! |------|---------|
9//! | Extension | `.php`, `.phtml`, `.phar`, `.cgi`, `.pl`, `.py`, `.asp`, `.aspx`, `.jsp`, `.shtml` and their variants, in any position of the file name (`shell.php.jpg`) |
10//! | File name | `.htaccess`, `.htpasswd`, `.user.ini`, `php.ini`, `web.config` |
11//! | Directive | `<!--#include` and the other SSI directives, `<?php`, `<?=`, `<%@`, `<%=`, `<%!`, `<%--` in markup |
12//! | Shebang | Any file starting with `#!` |
13//! | Sniffing | ELF, PE, Mach-O and Java class files whatever their name; `<?php` and SSI `include`/`exec` inside any binary file (polyglots) |
14
15use serde::{Deserialize, Serialize};
16
17/// Extensions a web server may execute (A-I1), lower case, without the dot.
18pub const REFUSED_EXTENSIONS: &[&str] = &[
19    "php", "php3", "php4", "php5", "php7", "php8", "phtml", "pht", "phps", "phar", "cgi", "fcgi",
20    "pl", "py", "asp", "aspx", "ascx", "ashx", "asmx", "axd", "cer", "jsp", "jspx", "jsw", "jsv",
21    "jspf", "shtml", "shtm", "stm", "cfm", "cfml", "cfc",
22];
23
24/// File names that configure a web server to execute or rewrite (A-I1), lower case.
25pub const REFUSED_FILE_NAMES: &[&str] =
26    &[".htaccess", ".htpasswd", ".user.ini", "php.ini", "web.config"];
27
28/// SSI directive names after `<!--#`.
29const SSI_DIRECTIVES: &[&str] = &[
30    "include", "exec", "echo", "config", "set", "if", "elif", "else", "endif", "fsize", "flastmod",
31    "printenv",
32];
33
34/// Extensions served as markup that a server may parse for directives.
35const MARKUP_EXTENSIONS: &[&str] = &["html", "htm", "xhtml", "xht", "xml", "svg", "svgz"];
36
37/// Extensions of data a server serves as is: directives inside them are text, so a
38/// Markdown twin quoting `<?php` in a code block is not refused.
39const DATA_TEXT_EXTENSIONS: &[&str] =
40    &["md", "markdown", "txt", "json", "jsonld", "css", "js", "mjs", "csv", "map", "webmanifest"];
41
42/// Why a file was refused (A-I1).
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase", tag = "kind")]
45#[non_exhaustive]
46pub enum ServerCodeKind {
47    /// The file name carries an executable extension.
48    Extension {
49        /// The extension.
50        extension: String,
51    },
52    /// The file name is a server configuration file.
53    FileName {
54        /// The file name.
55        name: String,
56    },
57    /// A server-side include directive (`<!--#include …`).
58    SsiDirective {
59        /// The directive.
60        directive: String,
61    },
62    /// A PHP open tag.
63    PhpTag,
64    /// An ASP or JSP tag.
65    AspTag,
66    /// The file starts with `#!`.
67    Shebang,
68    /// The content is a native or JVM executable.
69    Executable {
70        /// The sniffed format.
71        format: String,
72    },
73}
74
75/// One A-I1 finding: a file and why it is refused.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78pub struct ServerCodeFinding {
79    /// The file's path in the release, `/`-separated, without a leading slash.
80    pub path: String,
81    /// Why it is refused.
82    #[serde(flatten)]
83    pub kind: ServerCodeKind,
84    /// The byte offset of a directive or tag in the content.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub offset: Option<usize>,
87}
88
89/// A content type recognised from a file's first bytes.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92#[non_exhaustive]
93pub enum Sniffed {
94    /// PNG image.
95    Png,
96    /// JPEG image.
97    Jpeg,
98    /// GIF image.
99    Gif,
100    /// WebP image.
101    Webp,
102    /// AVIF or HEIF image.
103    Avif,
104    /// ICO icon.
105    Ico,
106    /// PDF document.
107    Pdf,
108    /// ZIP archive (also JAR, DOCX, EPUB).
109    Zip,
110    /// gzip stream.
111    Gzip,
112    /// MP4 or QuickTime video.
113    Mp4,
114    /// WebM or Matroska video.
115    Webm,
116    /// MP3 audio.
117    Mp3,
118    /// Ogg container.
119    Ogg,
120    /// WOFF or WOFF2 font.
121    Woff,
122    /// WebAssembly module.
123    Wasm,
124    /// ELF executable.
125    Elf,
126    /// Windows PE executable.
127    Pe,
128    /// Mach-O executable.
129    MachO,
130    /// Java class file.
131    JavaClass,
132    /// Text starting with `#!`.
133    Script,
134    /// SVG image (text).
135    Svg,
136    /// HTML (text).
137    Html,
138}
139
140impl Sniffed {
141    /// The media type for this format.
142    pub fn content_type(self) -> &'static str {
143        match self {
144            Self::Png => "image/png",
145            Self::Jpeg => "image/jpeg",
146            Self::Gif => "image/gif",
147            Self::Webp => "image/webp",
148            Self::Avif => "image/avif",
149            Self::Ico => "image/x-icon",
150            Self::Pdf => "application/pdf",
151            Self::Zip => "application/zip",
152            Self::Gzip => "application/gzip",
153            Self::Mp4 => "video/mp4",
154            Self::Webm => "video/webm",
155            Self::Mp3 => "audio/mpeg",
156            Self::Ogg => "audio/ogg",
157            Self::Woff => "font/woff2",
158            Self::Wasm => "application/wasm",
159            Self::Elf | Self::Pe | Self::MachO | Self::JavaClass => "application/octet-stream",
160            Self::Script => "text/x-script",
161            Self::Svg => "image/svg+xml",
162            Self::Html => "text/html",
163        }
164    }
165
166    /// Whether the format is a native or JVM executable.
167    pub fn is_executable(self) -> bool {
168        matches!(self, Self::Elf | Self::Pe | Self::MachO | Self::JavaClass | Self::Script)
169    }
170
171    /// Whether the format is a raster image the media pipeline can re-encode.
172    pub fn is_raster_image(self) -> bool {
173        matches!(self, Self::Png | Self::Jpeg | Self::Gif | Self::Webp)
174    }
175}
176
177/// Recognises a file's format from its first bytes.
178///
179/// # Example
180///
181/// ```rust
182/// use adk_site::scan::{Sniffed, sniff};
183///
184/// assert_eq!(sniff(b"\x89PNG\r\n\x1a\n...."), Some(Sniffed::Png));
185/// assert_eq!(sniff(b"\x7fELF\x02\x01"), Some(Sniffed::Elf));
186/// assert_eq!(sniff(b"plain text"), None);
187/// ```
188pub fn sniff(bytes: &[u8]) -> Option<Sniffed> {
189    let starts = |magic: &[u8]| bytes.starts_with(magic);
190    if starts(b"\x89PNG\r\n\x1a\n") {
191        return Some(Sniffed::Png);
192    }
193    if starts(b"\xff\xd8\xff") {
194        return Some(Sniffed::Jpeg);
195    }
196    if starts(b"GIF87a") || starts(b"GIF89a") {
197        return Some(Sniffed::Gif);
198    }
199    if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
200        return Some(Sniffed::Webp);
201    }
202    if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" {
203        let brand = &bytes[8..12];
204        return Some(match brand {
205            b"avif" | b"avis" | b"heic" | b"heix" | b"mif1" | b"msf1" => Sniffed::Avif,
206            _ => Sniffed::Mp4,
207        });
208    }
209    if starts(b"\x00\x00\x01\x00") {
210        return Some(Sniffed::Ico);
211    }
212    if starts(b"%PDF-") {
213        return Some(Sniffed::Pdf);
214    }
215    if starts(b"PK\x03\x04") || starts(b"PK\x05\x06") {
216        return Some(Sniffed::Zip);
217    }
218    if starts(b"\x1f\x8b") {
219        return Some(Sniffed::Gzip);
220    }
221    if starts(b"\x1a\x45\xdf\xa3") {
222        return Some(Sniffed::Webm);
223    }
224    if starts(b"ID3") || (bytes.len() >= 2 && bytes[0] == 0xff && bytes[1] & 0xe0 == 0xe0) {
225        return Some(Sniffed::Mp3);
226    }
227    if starts(b"OggS") {
228        return Some(Sniffed::Ogg);
229    }
230    if starts(b"wOFF") || starts(b"wOF2") {
231        return Some(Sniffed::Woff);
232    }
233    if starts(b"\x00asm") {
234        return Some(Sniffed::Wasm);
235    }
236    if starts(b"\x7fELF") {
237        return Some(Sniffed::Elf);
238    }
239    if starts(b"MZ") {
240        return Some(Sniffed::Pe);
241    }
242    if starts(b"\xfe\xed\xfa\xce")
243        || starts(b"\xfe\xed\xfa\xcf")
244        || starts(b"\xce\xfa\xed\xfe")
245        || starts(b"\xcf\xfa\xed\xfe")
246    {
247        return Some(Sniffed::MachO);
248    }
249    // 0xCAFEBABE is also a Mach-O universal binary; both are refused.
250    if starts(b"\xca\xfe\xba\xbe") {
251        return Some(Sniffed::JavaClass);
252    }
253    if starts(b"#!") {
254        return Some(Sniffed::Script);
255    }
256    let head = &bytes[..bytes.len().min(512)];
257    let text = String::from_utf8_lossy(head).trim_start_matches('\u{feff}').to_ascii_lowercase();
258    let text = text.trim_start();
259    if text.starts_with("<svg") || (text.starts_with("<?xml") && text.contains("<svg")) {
260        return Some(Sniffed::Svg);
261    }
262    if text.starts_with("<!doctype html") || text.starts_with("<html") {
263        return Some(Sniffed::Html);
264    }
265    None
266}
267
268/// The lower-case extensions of a file name after its first dot: `a.php.jpg` gives
269/// `["php", "jpg"]`. A leading dot is part of the name, not an extension.
270fn name_extensions(name: &str) -> Vec<String> {
271    let trimmed = name.trim_start_matches('.');
272    trimmed.split('.').skip(1).map(str::to_ascii_lowercase).collect()
273}
274
275fn file_name(path: &str) -> &str {
276    path.rsplit('/').next().unwrap_or(path)
277}
278
279fn find_ci(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
280    if needle.is_empty() || haystack.len() < needle.len() {
281        return None;
282    }
283    (from..=haystack.len() - needle.len())
284        .find(|&i| haystack[i..i + needle.len()].eq_ignore_ascii_case(needle))
285}
286
287/// Finds SSI directives (`<!--#name`) in `bytes`; `only` restricts the names.
288fn ssi_directives(bytes: &[u8], only: Option<&[&str]>) -> Vec<(usize, String)> {
289    let mut found = Vec::new();
290    let mut from = 0;
291    while let Some(at) = find_ci(bytes, b"<!--#", from) {
292        let rest = &bytes[at + 5..];
293        let name: String = rest
294            .iter()
295            .skip_while(|b| b.is_ascii_whitespace())
296            .take_while(|b| b.is_ascii_alphabetic())
297            .map(|b| (*b as char).to_ascii_lowercase())
298            .collect();
299        let listed = only.unwrap_or(SSI_DIRECTIVES);
300        if listed.contains(&name.as_str()) {
301            found.push((at, name));
302        }
303        from = at + 5;
304    }
305    found
306}
307
308/// Scans one release file for server code (A-I1) and returns every finding; an empty
309/// list means the file may ship.
310///
311/// # Example
312///
313/// ```rust
314/// use adk_site::scan::{ServerCodeKind, scan_file};
315///
316/// assert!(scan_file("index.html", b"<!doctype html><p>hello</p>").is_empty());
317/// let findings = scan_file("index.html", b"<p><!--#include virtual=\"/x\" --></p>");
318/// assert!(matches!(findings[0].kind, ServerCodeKind::SsiDirective { .. }));
319/// assert!(!scan_file("uploads/shell.php.jpg", b"").is_empty());
320/// ```
321pub fn scan_file(path: &str, bytes: &[u8]) -> Vec<ServerCodeFinding> {
322    let mut findings = Vec::new();
323    let mut push = |kind: ServerCodeKind, offset: Option<usize>| {
324        findings.push(ServerCodeFinding { path: path.to_string(), kind, offset });
325    };
326    let name = file_name(path);
327    let lower_name = name.to_ascii_lowercase();
328    if REFUSED_FILE_NAMES.contains(&lower_name.as_str()) {
329        push(ServerCodeKind::FileName { name: name.to_string() }, None);
330    }
331    let extensions = name_extensions(name);
332    for extension in &extensions {
333        if REFUSED_EXTENSIONS.contains(&extension.as_str()) {
334            push(ServerCodeKind::Extension { extension: extension.clone() }, None);
335        }
336    }
337    let sniffed = sniff(bytes);
338    match sniffed {
339        Some(Sniffed::Script) => push(ServerCodeKind::Shebang, Some(0)),
340        Some(format @ (Sniffed::Elf | Sniffed::Pe | Sniffed::MachO | Sniffed::JavaClass)) => push(
341            ServerCodeKind::Executable { format: format!("{format:?}").to_lowercase() },
342            Some(0),
343        ),
344        _ => {}
345    }
346    let last_extension = extensions.last().map(String::as_str).unwrap_or("");
347    let is_text = std::str::from_utf8(bytes).is_ok();
348    let is_markup = MARKUP_EXTENSIONS.contains(&last_extension)
349        || matches!(sniffed, Some(Sniffed::Html | Sniffed::Svg));
350    let is_data_text = DATA_TEXT_EXTENSIONS.contains(&last_extension) && !is_markup;
351    if is_markup || (is_text && !is_data_text) {
352        for (at, directive) in ssi_directives(bytes, None) {
353            push(ServerCodeKind::SsiDirective { directive }, Some(at));
354        }
355        for tag in [b"<?php".as_slice(), b"<?="] {
356            if let Some(at) = find_ci(bytes, tag, 0) {
357                push(ServerCodeKind::PhpTag, Some(at));
358            }
359        }
360        for tag in [b"<%@".as_slice(), b"<%=", b"<%!", b"<%--"] {
361            if let Some(at) = find_ci(bytes, tag, 0) {
362                push(ServerCodeKind::AspTag, Some(at));
363                break;
364            }
365        }
366    } else if !is_text {
367        // Binary files: only markers too long to occur by chance, so an image with a
368        // webshell in its comment block (a polyglot) is caught without false positives.
369        if let Some(at) = find_ci(bytes, b"<?php", 0) {
370            push(ServerCodeKind::PhpTag, Some(at));
371        }
372        for (at, directive) in ssi_directives(bytes, Some(&["include", "exec"])) {
373            push(ServerCodeKind::SsiDirective { directive }, Some(at));
374        }
375    }
376    findings
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    #[test]
384    fn every_listed_extension_is_refused() {
385        for extension in REFUSED_EXTENSIONS {
386            let findings = scan_file(&format!("a/b/file.{extension}"), b"");
387            assert_eq!(findings.len(), 1, "{extension}");
388            let upper = scan_file(&format!("file.{}", extension.to_uppercase()), b"");
389            assert_eq!(upper.len(), 1, "{extension} upper case");
390        }
391    }
392
393    #[test]
394    fn double_extensions_and_config_files_are_refused() {
395        assert!(!scan_file("uploads/shell.php.jpg", b"\xff\xd8\xff").is_empty());
396        assert!(!scan_file(".htaccess", b"Options +Includes").is_empty());
397        assert!(!scan_file("sub/.HTACCESS", b"").is_empty());
398        assert!(!scan_file("web.config", b"<configuration/>").is_empty());
399        assert!(scan_file(".well-known/security.txt", b"Contact: mailto:a@b.c").is_empty());
400    }
401
402    #[test]
403    fn directives_in_markup_are_refused_and_quoted_text_is_not() {
404        let html = b"<html><body><!--#exec cmd=\"id\" --></body></html>";
405        assert_eq!(
406            scan_file("index.html", html)[0].kind,
407            ServerCodeKind::SsiDirective { directive: "exec".into() }
408        );
409        assert_eq!(scan_file("p.htm", b"<p><?php echo 1; ?></p>")[0].kind, ServerCodeKind::PhpTag);
410        assert_eq!(scan_file("p.html", b"<%@ page %>")[0].kind, ServerCodeKind::AspTag);
411        // Escaped in HTML, verbatim in a Markdown twin or a JSON machine view: inert data.
412        assert!(scan_file("p.html", b"<code>&lt;?php echo 1; ?&gt;</code>").is_empty());
413        assert!(scan_file("p/index.md", b"```php\n<?php echo 1;\n```\n").is_empty());
414        assert!(scan_file("p/index.awp.json", br#"{"body":"<?php"}"#).is_empty());
415        // An XML declaration is not a PHP tag.
416        assert!(scan_file("sitemap.xml", b"<?xml version=\"1.0\"?><urlset/>").is_empty());
417        // A comment is not a directive.
418        assert!(scan_file("a.html", b"<!-- # not a directive -->").is_empty());
419    }
420
421    #[test]
422    fn executables_are_sniffed_whatever_their_name() {
423        for (bytes, format) in [
424            (b"\x7fELF\x02\x01\x01".as_slice(), "elf"),
425            (b"MZ\x90\x00", "pe"),
426            (b"\xcf\xfa\xed\xfe", "macho"),
427            (b"\xca\xfe\xba\xbe", "javaclass"),
428        ] {
429            let findings = scan_file("images/logo.png", bytes);
430            assert_eq!(findings[0].kind, ServerCodeKind::Executable { format: format.into() });
431        }
432        assert_eq!(scan_file("notes.txt", b"#!/bin/sh\nid\n")[0].kind, ServerCodeKind::Shebang);
433    }
434
435    #[test]
436    fn polyglot_images_are_refused() {
437        let mut jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00".to_vec();
438        jpeg.extend_from_slice(b"\xff\xfe\x00\x20<?php system($_GET['c']); ?>");
439        jpeg.extend_from_slice(&[0x80; 64]);
440        assert_eq!(scan_file("uploads/photo.jpg", &jpeg)[0].kind, ServerCodeKind::PhpTag);
441        let clean = [0xff, 0xd8, 0xff, 0xe0, 0x3c, 0x25, 0x40, 0x80, 0x3c, 0x3f, 0x3d];
442        assert!(scan_file("uploads/photo.jpg", &clean).is_empty(), "short markers in binary");
443    }
444}