1use serde::{Deserialize, Serialize};
16
17pub 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
24pub const REFUSED_FILE_NAMES: &[&str] =
26 &[".htaccess", ".htpasswd", ".user.ini", "php.ini", "web.config"];
27
28const SSI_DIRECTIVES: &[&str] = &[
30 "include", "exec", "echo", "config", "set", "if", "elif", "else", "endif", "fsize", "flastmod",
31 "printenv",
32];
33
34const MARKUP_EXTENSIONS: &[&str] = &["html", "htm", "xhtml", "xht", "xml", "svg", "svgz"];
36
37const DATA_TEXT_EXTENSIONS: &[&str] =
40 &["md", "markdown", "txt", "json", "jsonld", "css", "js", "mjs", "csv", "map", "webmanifest"];
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase", tag = "kind")]
45#[non_exhaustive]
46pub enum ServerCodeKind {
47 Extension {
49 extension: String,
51 },
52 FileName {
54 name: String,
56 },
57 SsiDirective {
59 directive: String,
61 },
62 PhpTag,
64 AspTag,
66 Shebang,
68 Executable {
70 format: String,
72 },
73}
74
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78pub struct ServerCodeFinding {
79 pub path: String,
81 #[serde(flatten)]
83 pub kind: ServerCodeKind,
84 #[serde(skip_serializing_if = "Option::is_none")]
86 pub offset: Option<usize>,
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92#[non_exhaustive]
93pub enum Sniffed {
94 Png,
96 Jpeg,
98 Gif,
100 Webp,
102 Avif,
104 Ico,
106 Pdf,
108 Zip,
110 Gzip,
112 Mp4,
114 Webm,
116 Mp3,
118 Ogg,
120 Woff,
122 Wasm,
124 Elf,
126 Pe,
128 MachO,
130 JavaClass,
132 Script,
134 Svg,
136 Html,
138}
139
140impl Sniffed {
141 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 pub fn is_executable(self) -> bool {
168 matches!(self, Self::Elf | Self::Pe | Self::MachO | Self::JavaClass | Self::Script)
169 }
170
171 pub fn is_raster_image(self) -> bool {
173 matches!(self, Self::Png | Self::Jpeg | Self::Gif | Self::Webp)
174 }
175}
176
177pub 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 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
268fn 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
287fn 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
308pub 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 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 assert!(scan_file("p.html", b"<code><?php echo 1; ?></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 assert!(scan_file("sitemap.xml", b"<?xml version=\"1.0\"?><urlset/>").is_empty());
417 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}