balrog~ ELF file analysis tool to be used after firmware extraction |
| git clone https://github.com/djnnvx/balrog.git |
| log | files | refs | archive | README |
rules.rs (55237B)
1 use crate::graph::{CallSite, Graph, Val}; 2 use crate::load::Binary; 3 use serde::Serialize; 4 use std::collections::{HashMap, HashSet}; 5 6 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Serialize, clap::ValueEnum)] 7 #[serde(rename_all = "lowercase")] 8 pub enum Class { 9 Exec, 10 Ipc, 11 Tls, 12 Fmt, 13 Mem, 14 Auth, 15 Priv, 16 Path, 17 Wdt, 18 } 19 20 pub const ORDER: &[Class] = &[ 21 Class::Exec, 22 Class::Ipc, 23 Class::Tls, 24 Class::Fmt, 25 Class::Mem, 26 Class::Auth, 27 Class::Priv, 28 Class::Path, 29 Class::Wdt, 30 ]; 31 32 impl Class { 33 fn base(self) -> i32 { 34 match self { 35 Class::Exec => 50, 36 Class::Ipc => 45, 37 Class::Tls => 45, 38 Class::Fmt => 45, 39 Class::Mem => 35, 40 Class::Auth => 30, 41 Class::Priv => 30, 42 Class::Path => 20, 43 Class::Wdt => 25, 44 } 45 } 46 pub fn tag(self) -> &'static str { 47 match self { 48 Class::Exec => "exec", 49 Class::Ipc => "ipc", 50 Class::Tls => "tls", 51 Class::Fmt => "fmt", 52 Class::Mem => "mem", 53 Class::Auth => "auth", 54 Class::Priv => "priv", 55 Class::Path => "path", 56 Class::Wdt => "wdt", 57 } 58 } 59 } 60 61 pub const SHELL: &[&str] = &[ 62 "system", 63 "popen", 64 "wordexp", 65 "twsystem", 66 "CsteSystem", 67 "bstar_system", 68 "___system", 69 "doShell", 70 "cgi_deal_popen", 71 "ExeCmd", 72 "ExecShell", 73 "exec_shell_popen", 74 "exec_shell_popen_str", 75 "exec_shell_async", 76 "exec_shell_sync", 77 "exec_shell_sync2", 78 "execFormatCmd", 79 "exec_cmd", 80 "tp_systemEx", 81 "pegaSystem", 82 "SLIBCSystem", 83 "SLIBCExec", 84 "SLIBCExecv", 85 "SLIBCPopen", 86 "smbrun", 87 "smbrun_no_sanitize", 88 "smbrunsecret", 89 "afprun", 90 "popen_utf8", 91 "do_system", 92 "safe_system", 93 "_backexec", 94 "execRoot_bg2", 95 "ugs_execRoot_shell", 96 "prctl_runCommandInShellWithTimeout", 97 "safe_popen", 98 "qid_sys_execute_update_script", 99 ]; 100 pub const SHELL_ARG1: &[&str] = &["SLIBCExecl"]; 101 pub const EVAL: &[&str] = &[ 102 "zend_eval_string", 103 "zend_eval_stringl", 104 "zend_eval_string_ex", 105 "PyRun_SimpleString", 106 "PyRun_SimpleStringFlags", 107 "PyRun_String", 108 "PyRun_StringFlags", 109 "Py_CompileString", 110 "PyEval_EvalCode", 111 ]; 112 pub const PRINTF_EXEC: &[&str] = &["doSystem", "doSystemCmd", "sysprintf", "lxmldbc_system"]; 113 pub const ARGV_EXEC: &[&str] = &[ 114 "execl", 115 "execlp", 116 "execle", 117 "execv", 118 "execvp", 119 "execvpe", 120 "execve", 121 "posix_spawn", 122 "posix_spawnp", 123 "_eval", 124 "_cpu_eval", 125 "_cpu_mask_eval", 126 "fm_exec", 127 ]; 128 pub const UNBOUNDED: &[(&str, usize, Option<usize>)] = &[ 129 ("strcpy", 0, None), 130 ("strcat", 0, None), 131 ("stpcpy", 0, None), 132 ("sprintf", 0, Some(1)), 133 ("vsprintf", 0, Some(1)), 134 ("gets", 0, None), 135 ("wcscpy", 0, None), 136 ("wcscat", 0, None), 137 ("getwd", 0, None), 138 ("__sprintf_chk", 0, Some(3)), 139 ("__vsprintf_chk", 0, Some(3)), 140 ("__strcpy_chk", 0, None), 141 ("__strcat_chk", 0, None), 142 ]; 143 pub const SIZED: &[(&str, usize)] = &[ 144 ("memcpy", 2), 145 ("memmove", 2), 146 ("strncpy", 2), 147 ("strncat", 2), 148 ("bcopy", 2), 149 ("mempcpy", 2), 150 ("stpncpy", 2), 151 ("wcsncpy", 2), 152 ("wmemcpy", 2), 153 ("strlcpy", 2), 154 ("strlcat", 2), 155 ("__memcpy_chk", 2), 156 ("__memmove_chk", 2), 157 ]; 158 pub const FORTIFY_BOUND: &[(&str, usize)] = &[ 159 ("__sprintf_chk", 2), 160 ("__vsprintf_chk", 2), 161 ("__strcpy_chk", 2), 162 ("__strcat_chk", 2), 163 ("__memcpy_chk", 3), 164 ("__memmove_chk", 3), 165 ("__snprintf_chk", 3), 166 ("__vsnprintf_chk", 3), 167 ]; 168 pub const FORMAT: &[(&str, usize)] = &[ 169 ("printf", 0), 170 ("syslog", 1), 171 ("fprintf", 1), 172 ("vsyslog", 1), 173 ("asprintf", 1), 174 ("vasprintf", 1), 175 ("vprintf", 0), 176 ("vfprintf", 1), 177 ("snprintf", 2), 178 ("vsnprintf", 2), 179 ("dprintf", 1), 180 ("vdprintf", 1), 181 ("g_strdup_printf", 0), 182 ("setproctitle", 0), 183 ("err", 1), 184 ("errx", 1), 185 ("verr", 1), 186 ("verrx", 1), 187 ("warn", 0), 188 ("warnx", 0), 189 ("vwarn", 0), 190 ("vwarnx", 0), 191 ("__printf_chk", 1), 192 ("__fprintf_chk", 2), 193 ("__syslog_chk", 2), 194 ("__snprintf_chk", 4), 195 ("__vsnprintf_chk", 4), 196 ]; 197 pub const SCANF: &[(&str, usize)] = &[ 198 ("scanf", 0), 199 ("fscanf", 1), 200 ("sscanf", 1), 201 ("__isoc99_scanf", 0), 202 ("__isoc99_fscanf", 1), 203 ("__isoc99_sscanf", 1), 204 ("vscanf", 0), 205 ("vfscanf", 1), 206 ("vsscanf", 1), 207 ]; 208 pub const PRIVOPS: &[&str] = &[ 209 "setuid", 210 "setgid", 211 "seteuid", 212 "setegid", 213 "setresuid", 214 "setresgid", 215 "setreuid", 216 "setregid", 217 "setfsuid", 218 "setfsgid", 219 "setgroups", 220 "initgroups", 221 "umask", 222 ]; 223 pub const TEMPFILE: &[&str] = &["mktemp", "tmpnam", "tmpnam_r", "tempnam"]; 224 pub const WEAK_RANDOM: &[&str] = &[ 225 "rand", 226 "random", 227 "rand_r", 228 "drand48", 229 "lrand48", 230 "mrand48", 231 "RAND_pseudo_bytes", 232 ]; 233 pub const SEED: &[&str] = &["srand", "srandom", "srand48", "seed48"]; 234 pub const WEAK_CRYPTO: &[&str] = &[ 235 "MD5", 236 "MD5_Init", 237 "MD4", 238 "SHA1_Init", 239 "EVP_md5", 240 "EVP_md4", 241 "EVP_sha1", 242 "mbedtls_md5", 243 "mbedtls_sha1", 244 "RC4", 245 "RC4_set_key", 246 "EVP_rc4", 247 "EVP_des_cbc", 248 "EVP_des_ecb", 249 "DES_set_key", 250 "DES_ecb_encrypt", 251 "EVP_rc2_cbc", 252 "EVP_bf_cbc", 253 "mbedtls_des_setkey_enc", 254 "EVP_aes_128_ecb", 255 "EVP_aes_192_ecb", 256 "EVP_aes_256_ecb", 257 ]; 258 pub const OLD_TLS: &[&str] = &[ 259 "SSLv2_method", 260 "SSLv3_method", 261 "SSLv3_client_method", 262 "SSLv3_server_method", 263 "TLSv1_method", 264 "TLSv1_client_method", 265 "TLSv1_1_method", 266 ]; 267 pub const VERIFY_MODE: &[&str] = &[ 268 "SSL_CTX_set_verify", 269 "SSL_set_verify", 270 "wolfSSL_CTX_set_verify", 271 "wolfSSL_set_verify", 272 ]; 273 pub const DESER: &[&str] = &[ 274 "soap_get", 275 "soap_serve", 276 "soap_begin_recv", 277 "xmlReadMemory", 278 "xmlParseMemory", 279 "xmlReadDoc", 280 "XML_Parse", 281 "d2i_X509", 282 "PEM_read_bio_X509", 283 ]; 284 pub const UNTRUSTED_INPUTS: &[&str] = &[ 285 "recv", 286 "recvfrom", 287 "recvmsg", 288 "recvmmsg", 289 "read", 290 "accept", 291 "accept4", 292 "getenv", 293 "fgets", 294 "getline", 295 "__getdelim", 296 "fread", 297 "SSL_read", 298 "BIO_read", 299 "json_tokener_parse", 300 "json_tokener_parse_ex", 301 "json_object_from_file", 302 "cJSON_Parse", 303 "cJSON_ParseWithLength", 304 "blobmsg_data", 305 "blobmsg_parse", 306 "soap_get", 307 "websGetVar", 308 "websDecodeUrl", 309 "FCGX_GetParam", 310 "hdf_get_value", 311 "config_get", 312 "find_val", 313 "get_cgi", 314 "httpGetEnv", 315 "nvram_get", 316 "nvram_safe_get", 317 "_nvram_get", 318 "nvram_get_int", 319 "nvram_get_buf", 320 "nvram_bufget", 321 "nvram_getf", 322 "nvram_get_adv", 323 "envram_get", 324 "envram_getf", 325 "apmib_get", 326 "artblock_get", 327 "artblock_safe_get", 328 "acosNvramConfig_get", 329 "acos_nvram_get", 330 "WAN_ith_CONFIG_GET", 331 "uci_lookup_option_string", 332 "uci_lookup_option", 333 "Uci_Get_Str", 334 "GetValue", 335 "acosNvramConfig_read", 336 "bcm_nvram_get", 337 "wlcsm_nvram_get", 338 "dni_nvram_get", 339 "PTI_nvram_get", 340 "CGI_Find_Parameter", 341 "getcgivars", 342 "getcgi", 343 "mg_get_var", 344 "webGetVar", 345 "websGetVarString", 346 "cmsObj_get", 347 "cJSON_GetObjectItem", 348 "cJSON_GetObjectItemCaseSensitive", 349 ]; 350 pub const PEERCRED: &[&str] = &["getsockopt", "getpeereid", "getpeername", "SO_PEERCRED"]; 351 352 pub const SANITIZERS: &[&str] = &[ 353 "canonicalize_file_name", 354 "strtol", 355 "strtoul", 356 "strtoll", 357 "strtoull", 358 "strtoimax", 359 "strtoumax", 360 "inet_pton", 361 "inet_aton", 362 "inet_ntop", 363 "fnmatch", 364 "g_shell_quote", 365 "quote_for_shell", 366 "secure_getenv", 367 ]; 368 pub const BOUNDED: &[&str] = &[ 369 "snprintf", 370 "vsnprintf", 371 "strlcpy", 372 "strlcat", 373 "strncpy", 374 "strncat", 375 "strnlen", 376 "stpecpy", 377 "strscpy", 378 "__snprintf_chk", 379 "__strcpy_chk", 380 "__memcpy_chk", 381 ]; 382 pub const CT_COMPARE: &[&str] = &[ 383 "CRYPTO_memcmp", 384 "timingsafe_bcmp", 385 "timingsafe_memcmp", 386 "sodium_memcmp", 387 "mbedtls_ct_memcmp", 388 ]; 389 pub const CSPRNG: &[&str] = &[ 390 "getrandom", 391 "arc4random", 392 "arc4random_buf", 393 "arc4random_uniform", 394 "RAND_bytes", 395 "mbedtls_ctr_drbg_random", 396 ]; 397 pub const HOSTNAME_CHECK: &[&str] = &[ 398 "X509_check_host", 399 "X509_check_ip", 400 "X509_check_ip_asc", 401 "SSL_set1_host", 402 "SSL_add1_host", 403 "X509_VERIFY_PARAM_set1_host", 404 ]; 405 pub const SIGVERIFY: &[&str] = &[ 406 "RSA_verify", 407 "EVP_VerifyFinal", 408 "EVP_DigestVerifyFinal", 409 "ECDSA_verify", 410 "mbedtls_pk_verify", 411 ]; 412 413 const CURL_VERIFY_OPTS: &[(u64, &str)] = &[ 414 (64, "CURLOPT_SSL_VERIFYPEER"), 415 (81, "CURLOPT_SSL_VERIFYHOST"), 416 (248, "CURLOPT_PROXY_SSL_VERIFYPEER"), 417 (249, "CURLOPT_PROXY_SSL_VERIFYHOST"), 418 ]; 419 const WRDE_NOCMD: u64 = 4; 420 const WDIOC_SETOPTIONS: u64 = 0x8004_5704; 421 const WDIOC_SETOPTIONS_MIPS: u64 = 0x4004_5704; 422 const WDIOC_SETTIMEOUT: u64 = 0xc004_5706; 423 const LENGTH_NOT_WRITTEN: &[&str] = &["snprintf", "vsnprintf", "strlcpy", "strlcat"]; 424 const BOUNDS_LENGTH: &[&str] = &["strnlen", "wcsnlen"]; 425 const BOUND_NAMES: &[&str] = &["clamp", "bound", "limit", "min"]; 426 const MBEDTLS_VERIFY_NONE: u64 = 0; 427 const MBEDTLS_VERIFY_OPTIONAL: u64 = 1; 428 const PROT_WRITE_EXEC: u64 = 0o6; 429 const VERIFY_OFF_BONUS: i32 = 30; 430 const FORTIFY_OFF_BONUS: i32 = 40; 431 const FORTIFY_OFF_NOTE: &str = "FORTIFY bound is -1: the size check is disabled"; 432 const SHELL_TEMPLATE_BONUS: i32 = 25; 433 const SHELL_INJECTION_BONUS: i32 = 20; 434 const SHELL_META: &[&str] = &[">", "|", ";", "`", "$(", "&"]; 435 const DIGEST_LENGTHS: &[u64] = &[16, 20, 32, 48, 64]; 436 const MAX_TEMPLATES: usize = 3; 437 const MAX_SOCKET_PATHS: usize = 2; 438 const MAX_EXEC_NOTES: usize = 3; 439 const MAX_CONTEXT_STRINGS: usize = 2; 440 const MIN_CONTEXT_STRING: usize = 8; 441 const CGI_VARS: &[&str] = &[ 442 "QUERY_STRING", 443 "REQUEST_URI", 444 "CONTENT_LENGTH", 445 "HTTP_COOKIE", 446 ]; 447 const SEARCH_PATH_VARS: &[&str] = &[ 448 "LD_PRELOAD", 449 "LD_LIBRARY_PATH", 450 "PATH", 451 "IFS", 452 "SHELL", 453 "PHPRC", 454 "PERL5LIB", 455 "PYTHONSTARTUP", 456 ]; 457 const PRIV_DROP: &[&str] = &[ 458 "setuid", 459 "setgid", 460 "seteuid", 461 "setegid", 462 "setresuid", 463 "setresgid", 464 "setreuid", 465 "setregid", 466 "setfsuid", 467 "setfsgid", 468 ]; 469 470 const CMD_HEADS: &[&str] = &[ 471 "cp ", 472 "mv ", 473 "rm ", 474 "cat ", 475 "tar ", 476 "chmod ", 477 "chown ", 478 "wget ", 479 "curl ", 480 "tftp ", 481 "ping ", 482 "traceroute ", 483 "iwpriv ", 484 "ifconfig ", 485 "route ", 486 "killall ", 487 "iptables ", 488 "nvram ", 489 "sed ", 490 "mount ", 491 "umount ", 492 "dd ", 493 "mtd ", 494 "echo ", 495 "touch ", 496 "mkdir ", 497 "insmod ", 498 "modprobe ", 499 "reboot", 500 "sh ", 501 ]; 502 503 #[derive(Serialize)] 504 pub struct Finding { 505 pub bin: String, 506 pub class: Class, 507 pub risky_call: String, 508 #[serde(serialize_with = "hex")] 509 pub site: u64, 510 pub func: String, 511 pub reach: Option<u32>, 512 pub evidence: Vec<Evidence>, 513 pub score: i32, 514 #[serde(skip_serializing_if = "std::ops::Not::not")] 515 pub shell_injection: bool, 516 } 517 518 #[derive(Serialize)] 519 pub struct Evidence { 520 pub points: i32, 521 pub text: String, 522 } 523 524 impl Evidence { 525 fn new(points: i32, text: impl Into<String>) -> Evidence { 526 Evidence { 527 points, 528 text: text.into(), 529 } 530 } 531 } 532 533 fn hex<S: serde::Serializer>(v: &u64, s: S) -> Result<S::Ok, S::Error> { 534 s.serialize_str(&format!("{v:#x}")) 535 } 536 537 fn stack_off(k: i64) -> String { 538 if k < 0 { 539 format!("sp-{:#x}", -k) 540 } else { 541 format!("sp+{k:#x}") 542 } 543 } 544 545 fn looks_shell(s: &str) -> bool { 546 if !(s.contains("%s") || s.contains("%d")) { 547 return false; 548 } 549 let meta = [ 550 " -", 551 ";", 552 "|", 553 "&&", 554 "`", 555 "$(", 556 ">", 557 "${IFS}", 558 "2>&1", 559 "/bin/", 560 "/sbin/", 561 "/usr/bin/", 562 ]; 563 if meta.iter().any(|m| s.contains(m)) { 564 return true; 565 } 566 let trimmed = s.trim_start(); 567 CMD_HEADS.iter().any(|head| trimmed.starts_with(head)) 568 } 569 570 fn is_neutered(v: u64) -> bool { 571 v == u64::MAX || v == 0xffff_ffff 572 } 573 574 fn unbounded_scan(fmt: &str) -> bool { 575 let chars: Vec<char> = fmt.chars().collect(); 576 let mut i = 0; 577 while i < chars.len() { 578 if chars[i] != '%' { 579 i += 1; 580 continue; 581 } 582 let mut j = i + 1; 583 if j < chars.len() && chars[j] == '%' { 584 i = j + 1; 585 continue; 586 } 587 let suppressed = j < chars.len() && chars[j] == '*'; 588 if suppressed { 589 j += 1; 590 } 591 let had_width = j < chars.len() && chars[j].is_ascii_digit(); 592 while j < chars.len() && chars[j].is_ascii_digit() { 593 j += 1; 594 } 595 if j < chars.len() && (chars[j] == 's' || chars[j] == '[') && !had_width && !suppressed { 596 return true; 597 } 598 i = j + 1; 599 } 600 false 601 } 602 603 // unquoted %s plus a metacharacter only a shell interprets => injection, not an inert arg 604 fn shell_injection(t: &str) -> bool { 605 unbounded_scan(t) && SHELL_META.iter().any(|m| t.contains(m)) 606 } 607 608 fn mode_note(m: u64) -> Option<String> { 609 if m & 0o4000 != 0 { 610 Some(format!("setuid bit in mode {m:#o}")) 611 } else if m & 0o2000 != 0 { 612 Some(format!("setgid bit in mode {m:#o}")) 613 } else if m & 0o2 != 0 { 614 Some(format!("world-writable mode {m:#o}")) 615 } else { 616 None 617 } 618 } 619 620 struct Hit { 621 class: Class, 622 score: i32, 623 evidence: Vec<Evidence>, 624 shell_injection: bool, 625 } 626 627 impl Hit { 628 fn new(class: Class, adjust: i32) -> Hit { 629 let score = class.base() + adjust; 630 let why = format!("{} base {}, rule {adjust:+}", class.tag(), class.base()); 631 Hit { 632 class, 633 score, 634 evidence: vec![Evidence::new(score, why)], 635 shell_injection: false, 636 } 637 } 638 fn note(&mut self, ev: impl Into<String>) { 639 self.evidence.push(Evidence::new(0, ev)); 640 } 641 fn bump(&mut self, delta: i32, ev: impl Into<String>) { 642 self.score += delta; 643 self.evidence.push(Evidence::new(delta, ev)); 644 } 645 } 646 647 struct Scan<'a> { 648 bin: &'a Binary, 649 graph: &'a Graph, 650 name: String, 651 reach: HashMap<u64, u32>, 652 wrappers: HashSet<u64>, 653 calls: HashMap<u64, Vec<&'a str>>, 654 unix_paths: Vec<String>, 655 exec_imports: Vec<&'a str>, 656 tokenish: bool, 657 no_peercred: bool, 658 drops_privilege: bool, 659 } 660 661 fn call_index(g: &Graph) -> HashMap<u64, Vec<&str>> { 662 let mut m: HashMap<u64, Vec<&str>> = HashMap::new(); 663 for s in &g.sites { 664 if let Some(n) = s.import.as_deref() { 665 m.entry(s.func).or_default().push(n); 666 } 667 } 668 for v in m.values_mut() { 669 v.sort_unstable(); 670 v.dedup(); 671 } 672 m 673 } 674 675 fn is_unix_socket_path(text: &str) -> bool { 676 text.contains(".sock") && text.starts_with('/') 677 } 678 679 fn socket_paths(g: &Graph) -> Vec<String> { 680 let mut paths: Vec<String> = g 681 .strings 682 .values() 683 .flatten() 684 .filter(|text| is_unix_socket_path(text)) 685 .cloned() 686 .collect(); 687 paths.sort_unstable(); 688 paths.dedup(); 689 paths 690 } 691 692 fn is_exec_primitive(import: &str) -> bool { 693 SHELL.contains(&import) || PRINTF_EXEC.contains(&import) || ARGV_EXEC.contains(&import) 694 } 695 696 fn exec_imports(bin: &Binary) -> Vec<&str> { 697 let mut exec_like: Vec<&str> = bin 698 .imports 699 .iter() 700 .map(String::as_str) 701 .filter(|import| is_exec_primitive(import)) 702 .collect(); 703 exec_like.sort_unstable(); 704 exec_like 705 } 706 707 fn names_credential(text: &str) -> bool { 708 let lower = text.to_ascii_lowercase(); 709 lower.contains("token") || lower.contains("session") || lower.contains("cookie") 710 } 711 712 fn mentions_session_token(g: &Graph) -> bool { 713 g.strings 714 .values() 715 .flatten() 716 .any(|text| names_credential(text)) 717 } 718 719 impl<'a> Scan<'a> { 720 fn new(bin: &'a Binary, graph: &'a Graph) -> Scan<'a> { 721 let mut seeds: Vec<&str> = SHELL.to_vec(); 722 seeds.extend_from_slice(PRINTF_EXEC); 723 Scan { 724 bin, 725 graph, 726 name: bin.path.to_string_lossy().into_owned(), 727 reach: graph.reach_from(UNTRUSTED_INPUTS), 728 wrappers: graph.shell_equivalent(&seeds), 729 calls: call_index(graph), 730 unix_paths: socket_paths(graph), 731 exec_imports: exec_imports(bin), 732 tokenish: mentions_session_token(graph), 733 no_peercred: !PEERCRED.iter().any(|n| bin.imports.contains(*n)), 734 drops_privilege: PRIV_DROP.iter().any(|n| bin.imports.contains(*n)), 735 } 736 } 737 fn has(&self, n: &str) -> bool { 738 self.bin.imports.contains(n) 739 } 740 fn any(&self, v: &[&str]) -> bool { 741 v.iter().any(|n| self.has(n)) 742 } 743 } 744 745 struct Site<'a> { 746 scan: &'a Scan<'a>, 747 call: &'a CallSite, 748 imp: &'a str, 749 reach: Option<u32>, 750 } 751 752 impl Site<'_> { 753 fn text(&self, n: usize) -> Option<String> { 754 match self.call.args.get(n) { 755 Some(Some(Val::Num(a))) => self.scan.bin.cstr_at(*a), 756 _ => None, 757 } 758 } 759 fn num(&self, n: usize) -> Option<u64> { 760 match self.call.args.get(n) { 761 Some(Some(Val::Num(v))) => Some(*v), 762 _ => None, 763 } 764 } 765 fn stack(&self, n: usize) -> Option<i64> { 766 match self.call.args.get(n) { 767 Some(Some(Val::Stack(k))) => Some(*k), 768 _ => None, 769 } 770 } 771 fn unknown(&self, n: usize) -> bool { 772 matches!(self.call.args.get(n), Some(None | Some(Val::Ret(_)))) 773 } 774 fn source(&self, n: usize) -> Option<&str> { 775 let Some(Some(Val::Ret(i))) = self.call.args.get(n) else { 776 return None; 777 }; 778 let producer = self.scan.graph.sites.get(*i)?; 779 producer.import.as_deref().or_else(|| { 780 self.scan 781 .graph 782 .names 783 .get(&producer.target) 784 .map(String::as_str) 785 }) 786 } 787 fn tainted(&self, n: usize) -> bool { 788 self.source(n) 789 .is_some_and(|f| UNTRUSTED_INPUTS.contains(&f)) 790 } 791 fn visible(&self, n: usize) -> bool { 792 n < self.call.args.len() 793 } 794 fn calls(&self) -> &[&str] { 795 self.scan 796 .calls 797 .get(&self.call.func) 798 .map_or(&[], Vec::as_slice) 799 } 800 fn strings(&self) -> &[String] { 801 self.scan 802 .graph 803 .strings 804 .get(&self.call.func) 805 .map_or(&[], Vec::as_slice) 806 } 807 fn has(&self, n: &str) -> bool { 808 self.scan.has(n) 809 } 810 fn any(&self, v: &[&str]) -> bool { 811 self.scan.any(v) 812 } 813 } 814 815 fn shell(s: &Site) -> Option<Hit> { 816 let mut h = Hit::new(Class::Exec, 0); 817 let cmd_arg = if SHELL_ARG1.contains(&s.imp) { 1 } else { 0 }; 818 if PRINTF_EXEC.contains(&s.imp) { 819 h.note(format!( 820 "{} takes a printf format, not a finished command", 821 s.imp 822 )); 823 } 824 match s.text(cmd_arg) { 825 Some(t) if t.contains('%') => { 826 h.bump(25, format!("command template {t:?}")); 827 let shell_call = ["system", "popen", "wordexp"].contains(&s.imp); 828 if shell_injection(&t) || (shell_call && unbounded_scan(&t)) { 829 h.shell_injection = true; 830 h.bump( 831 SHELL_INJECTION_BONUS, 832 "shell injection: unquoted %s with a shell metacharacter", 833 ); 834 } 835 } 836 Some(t) => h.bump(-30, format!("constant command {t:?}")), 837 None if s.num(cmd_arg).is_some() => { 838 h.bump(-10, "argument is a constant that is not readable text") 839 } 840 None => h.bump(15, "argument not a compile-time constant"), 841 } 842 if s.imp == "wordexp" { 843 match s.num(2) { 844 Some(f) if f & WRDE_NOCMD != 0 => { 845 h.bump(-25, "WRDE_NOCMD set, command substitution refused") 846 } 847 _ => h.bump(25, "no WRDE_NOCMD: `$(...)` in the input is executed"), 848 } 849 } 850 let templates: Vec<&String> = s.strings().iter().filter(|t| looks_shell(t)).collect(); 851 for t in templates.iter().take(MAX_TEMPLATES) { 852 h.note(format!("command template {t:?}")); 853 } 854 if !templates.is_empty() { 855 h.bump( 856 SHELL_TEMPLATE_BONUS, 857 "shell-looking strings in the same function", 858 ); 859 } 860 Some(h) 861 } 862 863 fn script_eval(s: &Site) -> Option<Hit> { 864 let mut h = Hit::new(Class::Exec, -5); 865 h.note(format!("{} evaluates a script at runtime", s.imp)); 866 if s.text(0).is_none() { 867 h.bump(20, "the evaluated string is not a compile-time constant"); 868 } 869 Some(h) 870 } 871 872 fn argv_exec(s: &Site) -> Option<Hit> { 873 let mut h = Hit::new(Class::Exec, -25); 874 h.note("argv exec, metacharacters are inert"); 875 let path_relative = !matches!(s.text(0), Some(t) if t.starts_with('/')); 876 if (s.imp == "execvp" || s.imp == "execlp") && path_relative { 877 h.bump( 878 25, 879 "execvp/execlp resolves through $PATH, not an absolute path", 880 ); 881 } 882 Some(h) 883 } 884 885 fn dynamic_load(s: &Site) -> Option<Hit> { 886 let mut h = Hit::new(Class::Exec, -20); 887 match s.text(0) { 888 Some(t) if t.starts_with("/lib") || t.starts_with("/usr/lib") => return None, 889 Some(t) => h.note(format!("loads library from {t:?}")), 890 None => { 891 h.note("library path is not a compile-time constant"); 892 if !s.calls().contains(&"strchr") { 893 h.bump(20, "no strchr guard on the name: no '/' rejection"); 894 } 895 } 896 } 897 Some(h) 898 } 899 900 fn env_hijack(s: &Site) -> Option<Hit> { 901 let name = s.text(0)?; 902 if !SEARCH_PATH_VARS.iter().any(|v| name.starts_with(v)) { 903 return None; 904 } 905 let mut h = Hit::new(Class::Exec, -15); 906 h.note(format!( 907 "sets {name:?}, a search-path primitive for any child" 908 )); 909 Some(h) 910 } 911 912 fn curl_verify(s: &Site) -> Option<Hit> { 913 let (opt, val) = (s.num(1)?, s.num(2)?); 914 let (_, name) = CURL_VERIFY_OPTS.iter().find(|(o, _)| *o == opt)?; 915 if val != 0 { 916 return None; 917 } 918 let mut h = Hit::new(Class::Tls, VERIFY_OFF_BONUS); 919 h.note(format!("{name} set to 0: certificate check disabled")); 920 h.note("DNS-hijack MITM works without a valid certificate"); 921 Some(h) 922 } 923 924 fn verify_mode(s: &Site) -> Option<Hit> { 925 if s.num(1) != Some(0) { 926 return None; 927 } 928 let mut h = Hit::new(Class::Tls, VERIFY_OFF_BONUS); 929 h.note("verify mode 0 (VERIFY_NONE): peer certificate not checked"); 930 if s.has("SSL_get_verify_result") { 931 h.bump( 932 -20, 933 "SSL_get_verify_result present, the result may still be inspected", 934 ); 935 } 936 Some(h) 937 } 938 939 fn mbedtls_authmode(s: &Site) -> Option<Hit> { 940 let (adjust, note) = match s.num(1)? { 941 MBEDTLS_VERIFY_NONE => ( 942 VERIFY_OFF_BONUS, 943 "MBEDTLS_SSL_VERIFY_NONE: peer certificate not checked", 944 ), 945 MBEDTLS_VERIFY_OPTIONAL => ( 946 0, 947 "MBEDTLS_SSL_VERIFY_OPTIONAL: handshake continues on failure", 948 ), 949 _ => return None, 950 }; 951 let mut h = Hit::new(Class::Tls, adjust); 952 h.note(note); 953 Some(h) 954 } 955 956 fn unbounded_write(s: &Site, dest: usize, fmt: Option<usize>) -> Option<Hit> { 957 let mut h = Hit::new(Class::Mem, 0); 958 let stack_dest = s.stack(dest); 959 if let Some(k) = stack_dest { 960 h.bump( 961 20, 962 format!("destination is a stack buffer at {}", stack_off(k)), 963 ); 964 } 965 let mut conversions = 0; 966 if let Some(fmt) = fmt { 967 match s.text(fmt) { 968 Some(t) => { 969 conversions = t.matches("%s").count(); 970 h.bump(10 * conversions as i32, format!("format {t:?}")); 971 } 972 None if s.num(fmt).is_some() => h.note("format not a readable literal"), 973 None => h.bump(25, "format argument is not a literal (format string bug)"), 974 } 975 } 976 if stack_dest.is_some() && (conversions > 0 || fmt.is_none()) { 977 h.bump( 978 35, 979 "unbounded write of a variable-length value into a fixed stack buffer", 980 ); 981 } 982 fortify_note(s, &mut h); 983 Some(h) 984 } 985 986 fn fortify_bound(s: &Site) -> Option<u64> { 987 let (_, bound) = FORTIFY_BOUND.iter().find(|(n, _)| *n == s.imp)?; 988 s.num(*bound) 989 } 990 991 fn fortify_note(s: &Site, h: &mut Hit) { 992 match fortify_bound(s) { 993 Some(v) if is_neutered(v) => h.bump(FORTIFY_OFF_BONUS, FORTIFY_OFF_NOTE), 994 Some(_) => h.bump(-30, "FORTIFY bound is a real constant, overflow aborts"), 995 None => {} 996 } 997 } 998 999 fn measures_input(s: &Site) -> bool { 1000 s.calls().contains(&"strlen") || s.calls().contains(&"strspn") 1001 } 1002 1003 fn sized_write(s: &Site, len: usize) -> Option<Hit> { 1004 if s.num(len) == Some(0) { 1005 let mut h = Hit::new(Class::Mem, -10); 1006 h.note("length 0 turns this into a no-op, usually an underflow artefact"); 1007 return Some(h); 1008 } 1009 let fortify_disabled = fortify_bound(s).is_some_and(is_neutered); 1010 let dest = if s.imp == "bcopy" { 1 } else { 0 }; 1011 let stack_dest = s.stack(dest); 1012 let measures_reachable_input = measures_input(s) && s.reach == Some(0); 1013 let suspicious = 1014 stack_dest.is_some() || fortify_disabled || measures_reachable_input || s.tainted(len); 1015 if !s.unknown(len) || !suspicious { 1016 return None; 1017 } 1018 let mut h = Hit::new(Class::Mem, 0); 1019 if let Some(k) = stack_dest { 1020 h.note(format!( 1021 "non-constant length into a stack buffer at {}", 1022 stack_off(k) 1023 )); 1024 } 1025 if fortify_disabled { 1026 h.bump(FORTIFY_OFF_BONUS, FORTIFY_OFF_NOTE); 1027 } 1028 if measures_input(s) { 1029 h.bump( 1030 20, 1031 "strlen/strspn in the same function: size may be derived from the \ 1032 input length, not the destination size", 1033 ); 1034 } 1035 Some(h) 1036 } 1037 1038 fn stack_alloc(s: &Site) -> Option<Hit> { 1039 let mut h = Hit::new(Class::Mem, -5); 1040 match s.num(0) { 1041 Some(v) => h.bump(-20, format!("alloca of a constant {v:#x}")), 1042 None => h.note("alloca with a non-constant size: stack clash"), 1043 } 1044 Some(h) 1045 } 1046 1047 fn unbounded_read(s: &Site, fmt: usize) -> Option<Hit> { 1048 if !s.visible(fmt) { 1049 return None; 1050 } 1051 let f = s.text(fmt)?; 1052 if !unbounded_scan(&f) { 1053 return None; 1054 } 1055 let mut h = Hit::new(Class::Mem, 10); 1056 h.note(format!("format {f:?} has a %s or %[ with no field width")); 1057 Some(h) 1058 } 1059 1060 fn format_string(s: &Site, fmt: usize) -> Option<Hit> { 1061 if !s.visible(fmt) || s.text(fmt).is_some() { 1062 return None; 1063 } 1064 let mut h = Hit::new(Class::Fmt, 0); 1065 h.note("format argument is not a readable literal"); 1066 Some(h) 1067 } 1068 1069 fn writable_executable(s: &Site) -> Option<Hit> { 1070 let prot = s.num(2)?; 1071 if prot & PROT_WRITE_EXEC != PROT_WRITE_EXEC { 1072 return None; 1073 } 1074 let mut h = Hit::new(Class::Mem, 5); 1075 h.note(format!( 1076 "prot {prot:#x} is PROT_WRITE|PROT_EXEC: writable and executable at once" 1077 )); 1078 Some(h) 1079 } 1080 1081 fn des_crypt(s: &Site) -> Option<Hit> { 1082 let salt = s.text(1)?; 1083 if salt.starts_with('$') { 1084 return None; 1085 } 1086 let mut h = Hit::new(Class::Auth, 15); 1087 h.note(format!( 1088 "salt {salt:?} selects traditional DES crypt, key truncated to 8 characters" 1089 )); 1090 Some(h) 1091 } 1092 1093 fn weak_random(s: &Site) -> Option<Hit> { 1094 let mut h = Hit::new(Class::Auth, -15); 1095 h.note(format!("{} is not a CSPRNG", s.imp)); 1096 if !s.any(CSPRNG) { 1097 h.bump( 1098 15, 1099 "no getrandom/arc4random/RAND_bytes anywhere in this binary", 1100 ); 1101 } 1102 if s.scan.tokenish { 1103 h.bump(20, "binary references token/session/cookie strings"); 1104 } 1105 Some(h) 1106 } 1107 1108 fn predictable_seed(s: &Site) -> Option<Hit> { 1109 let mut h = Hit::new(Class::Auth, -10); 1110 match s.num(0) { 1111 Some(v) => h.note(format!("seeded with the constant {v:#x}")), 1112 None if s.calls().iter().any(|c| *c == "time" || *c == "getpid") => { 1113 h.note("seeded from time()/getpid() in the same function") 1114 } 1115 None => return None, 1116 } 1117 Some(h) 1118 } 1119 1120 fn mac_compare(s: &Site) -> Option<Hit> { 1121 let len = s.num(2)?; 1122 if !DIGEST_LENGTHS.contains(&len) { 1123 return None; 1124 } 1125 let beside_mac = s.calls().iter().any(|c| { 1126 c.contains("HMAC") || c.contains("MD5") || c.contains("SHA") || c.contains("CMAC") 1127 }); 1128 if !beside_mac { 1129 return None; 1130 } 1131 let mut h = Hit::new(Class::Auth, 0); 1132 h.note(format!( 1133 "memcmp of {len} bytes beside a MAC/hash call: not constant time" 1134 )); 1135 if s.any(CT_COMPARE) { 1136 h.bump(-20, "a constant-time compare exists in this binary"); 1137 } 1138 Some(h) 1139 } 1140 1141 fn privilege_op(s: &Site) -> Option<Hit> { 1142 let mut h = Hit::new(Class::Priv, -10); 1143 match (s.imp, s.num(0)) { 1144 ("umask", Some(mode)) => { 1145 let masks_world_write = mode != 0 && mode & 0o2 != 0; 1146 if masks_world_write { 1147 return None; 1148 } 1149 h.bump( 1150 25, 1151 format!("umask({mode:#o}) leaves later creations group- or world-writable"), 1152 ); 1153 } 1154 (_, Some(v)) => h.note(format!("argument {v:#x}")), 1155 _ => {} 1156 } 1157 if s.imp == "setuid" && !s.has("setgroups") && !s.has("initgroups") { 1158 h.bump( 1159 20, 1160 "no setgroups/initgroups anywhere: setuid keeps the supplementary groups", 1161 ); 1162 } 1163 Some(h) 1164 } 1165 1166 fn chroot_escape(s: &Site) -> Option<Hit> { 1167 if s.calls().contains(&"chdir") { 1168 return None; 1169 } 1170 let mut h = Hit::new(Class::Priv, 20); 1171 h.note("no chdir in the same function: `../` walks out of the jail"); 1172 Some(h) 1173 } 1174 1175 fn permissive_mode(s: &Site) -> Option<Hit> { 1176 let note = mode_note(s.num(1)?)?; 1177 let mut h = Hit::new(Class::Path, 20); 1178 h.note(note); 1179 if let Some(p) = s.text(0) { 1180 h.note(format!("path {p:?}")); 1181 } 1182 Some(h) 1183 } 1184 1185 fn temp_file(s: &Site) -> Option<Hit> { 1186 let mut h = Hit::new(Class::Path, 10); 1187 h.note(format!( 1188 "{} names a temp file without creating it atomically", 1189 s.imp 1190 )); 1191 if let Some(p) = s.text(0) { 1192 h.note(format!("template {p:?}")); 1193 } 1194 Some(h) 1195 } 1196 1197 fn unix_listener(s: &Site) -> Option<Hit> { 1198 let mut h = Hit::new(Class::Ipc, 0); 1199 for p in s.scan.unix_paths.iter().take(MAX_SOCKET_PATHS) { 1200 h.note(format!("socket path {p:?}")); 1201 } 1202 if s.scan.no_peercred && !s.scan.unix_paths.is_empty() { 1203 h.bump(30, "no SO_PEERCRED / getpeereid anywhere in this binary"); 1204 } 1205 let execs = &s.scan.exec_imports; 1206 for e in execs.iter().take(MAX_EXEC_NOTES) { 1207 h.note(format!("exec reachable via {e}")); 1208 } 1209 if !execs.is_empty() { 1210 h.bump(20, "this binary can exec"); 1211 } 1212 if !s.scan.drops_privilege && !execs.is_empty() { 1213 h.bump( 1214 15, 1215 "no setuid/setgid anywhere: this listener never drops privilege", 1216 ); 1217 } 1218 Some(h) 1219 } 1220 1221 fn classify(s: &Site) -> Option<Hit> { 1222 let imp = s.imp; 1223 if SHELL.contains(&imp) || PRINTF_EXEC.contains(&imp) || SHELL_ARG1.contains(&imp) { 1224 shell(s) 1225 } else if EVAL.contains(&imp) { 1226 script_eval(s) 1227 } else if ARGV_EXEC.contains(&imp) { 1228 argv_exec(s) 1229 } else if imp == "dlopen" { 1230 dynamic_load(s) 1231 } else if imp == "setenv" || imp == "putenv" { 1232 env_hijack(s) 1233 } else if imp == "curl_easy_setopt" { 1234 curl_verify(s) 1235 } else if VERIFY_MODE.contains(&imp) { 1236 verify_mode(s) 1237 } else if imp == "mbedtls_ssl_conf_authmode" { 1238 mbedtls_authmode(s) 1239 } else if OLD_TLS.contains(&imp) { 1240 obsolete_tls(s) 1241 } else if let Some((_, dest, fmt)) = UNBOUNDED.iter().find(|(n, _, _)| *n == imp) { 1242 unbounded_write(s, *dest, *fmt) 1243 } else if let Some((_, len)) = SIZED.iter().find(|(n, _)| *n == imp) { 1244 sized_write(s, *len) 1245 } else if imp == "alloca" { 1246 stack_alloc(s) 1247 } else if let Some((_, fmt)) = SCANF.iter().find(|(n, _)| *n == imp) { 1248 unbounded_read(s, *fmt) 1249 } else if let Some((_, fmt)) = FORMAT.iter().find(|(n, _)| *n == imp) { 1250 format_string(s, *fmt) 1251 } else if imp == "mmap" || imp == "mprotect" { 1252 writable_executable(s) 1253 } else if imp == "crypt" || imp == "crypt_r" { 1254 des_crypt(s) 1255 } else if WEAK_CRYPTO.contains(&imp) { 1256 weak_crypto(s) 1257 } else if WEAK_RANDOM.contains(&imp) { 1258 weak_random(s) 1259 } else if SEED.contains(&imp) { 1260 predictable_seed(s) 1261 } else if imp == "memcmp" { 1262 mac_compare(s) 1263 } else if DESER.contains(&imp) { 1264 parses_document(s) 1265 } else if PRIVOPS.contains(&imp) { 1266 privilege_op(s) 1267 } else if imp == "chroot" { 1268 chroot_escape(s) 1269 } else if imp == "chmod" || imp == "fchmod" || imp == "mkdir" { 1270 permissive_mode(s) 1271 } else if TEMPFILE.contains(&imp) { 1272 temp_file(s) 1273 } else if imp == "bind" { 1274 unix_listener(s) 1275 } else if imp == "ioctl" { 1276 watchdog_ioctl(s) 1277 } else if imp == "write" { 1278 watchdog_magic_close(s) 1279 } else { 1280 None 1281 } 1282 } 1283 1284 fn watchdog_ioctl(s: &Site) -> Option<Hit> { 1285 let setoptions = match s.scan.bin.arch { 1286 crate::arch::Arch::Mips => WDIOC_SETOPTIONS_MIPS, 1287 _ => WDIOC_SETOPTIONS, 1288 }; 1289 let (adjust, why) = match s.num(1)? { 1290 n if n == setoptions => ( 1291 15, 1292 "WDIOC_SETOPTIONS: WDIOS_DISABLECARD disarms the watchdog", 1293 ), 1294 WDIOC_SETTIMEOUT => (5, "WDIOC_SETTIMEOUT: a huge timeout is a disarmed watchdog"), 1295 _ => return None, 1296 }; 1297 let mut h = Hit::new(Class::Wdt, adjust); 1298 h.note(why); 1299 Some(h) 1300 } 1301 1302 fn watchdog_magic_close(s: &Site) -> Option<Hit> { 1303 if s.text(1).as_deref() != Some("V") { 1304 return None; 1305 } 1306 let mut h = Hit::new(Class::Wdt, 10); 1307 h.note("magic close: writing 'V' disarms the watchdog when this fd closes (unless nowayout)"); 1308 Some(h) 1309 } 1310 1311 fn is_bound_name(name: &str) -> bool { 1312 let name = name.to_ascii_lowercase(); 1313 BOUND_NAMES.iter().any(|k| name.contains(k)) 1314 } 1315 1316 fn note_provenance(s: &Site, h: &mut Hit) { 1317 for n in 0..s.call.args.len() { 1318 let Some(src) = s.source(n) else { continue }; 1319 if UNTRUSTED_INPUTS.contains(&src) { 1320 h.bump(15, format!("arg {n} is the raw return of {src}()")); 1321 } else if LENGTH_NOT_WRITTEN.contains(&src) { 1322 h.bump( 1323 15, 1324 format!( 1325 "arg {n} is the return of {src}(): the untruncated length, not bytes written" 1326 ), 1327 ); 1328 } else if BOUNDS_LENGTH.contains(&src) || is_bound_name(src) { 1329 h.bump(-20, format!("arg {n} is bounded by {src}()")); 1330 } 1331 } 1332 } 1333 1334 fn note_sanitizers(s: &Site, h: &mut Hit) { 1335 if matches!(h.class, Class::Ipc | Class::Tls) { 1336 return; 1337 } 1338 let sanitizers_in_function: Vec<&str> = s 1339 .calls() 1340 .iter() 1341 .copied() 1342 .filter(|name| SANITIZERS.contains(name)) 1343 .collect(); 1344 if sanitizers_in_function.is_empty() { 1345 return; 1346 } 1347 h.bump( 1348 -20, 1349 format!( 1350 "value may be normalized first: {} in the same function", 1351 sanitizers_in_function.join(", ") 1352 ), 1353 ); 1354 } 1355 1356 fn note_function_strings(s: &Site, h: &mut Hit) { 1357 if !matches!(h.class, Class::Mem | Class::Fmt) { 1358 return; 1359 } 1360 let context_strings = s 1361 .strings() 1362 .iter() 1363 .filter(|text| text.len() >= MIN_CONTEXT_STRING) 1364 .take(MAX_CONTEXT_STRINGS); 1365 for text in context_strings { 1366 h.note(format!("function references {text:?}")); 1367 } 1368 } 1369 1370 fn obsolete_tls(s: &Site) -> Option<Hit> { 1371 let mut h = Hit::new(Class::Tls, -15); 1372 h.note(format!("{} pins an obsolete protocol version", s.imp)); 1373 Some(h) 1374 } 1375 1376 fn weak_crypto(s: &Site) -> Option<Hit> { 1377 let mut h = Hit::new(Class::Auth, -10); 1378 h.note(format!("{}: broken or ECB-mode primitive", s.imp)); 1379 Some(h) 1380 } 1381 1382 fn parses_document(s: &Site) -> Option<Hit> { 1383 let mut h = Hit::new(Class::Mem, -10); 1384 h.note(format!("{} parses an attacker-supplied document", s.imp)); 1385 Some(h) 1386 } 1387 1388 fn is_cgi_variable(text: &str) -> bool { 1389 text.starts_with("HTTP_") || CGI_VARS.contains(&text) 1390 } 1391 1392 fn note_cgi_variable(s: &Site, h: &mut Hit) { 1393 let Some(var) = s.strings().iter().find(|text| is_cgi_variable(text)) else { 1394 return; 1395 }; 1396 h.bump( 1397 20, 1398 format!("reads the CGI variable {var:?}, a raw client header"), 1399 ); 1400 } 1401 1402 fn note_reachability(s: &Site, h: &mut Hit) { 1403 match s.reach { 1404 Some(0) => h.bump(40, "same function as a network/env input"), 1405 Some(d) if d <= 2 => h.bump(25, format!("{d} hop(s) from a network/env input")), 1406 Some(d) if d <= 5 => h.bump(10, format!("{d} hops from a network/env input")), 1407 Some(_) => {} 1408 None if s.scan.graph.addr_taken.contains(&s.call.func) => { 1409 h.note("address-taken: reached by indirect dispatch, not a direct call") 1410 } 1411 None => h.bump(-20, "no path from any network or environment input"), 1412 } 1413 } 1414 1415 fn adjust(s: &Site, h: &mut Hit) { 1416 note_sanitizers(s, h); 1417 note_function_strings(s, h); 1418 note_cgi_variable(s, h); 1419 note_provenance(s, h); 1420 if s.scan.wrappers.contains(&s.call.func) && h.class != Class::Exec { 1421 h.bump(10, "inside a shell-equivalent wrapper"); 1422 } 1423 note_reachability(s, h); 1424 } 1425 1426 pub fn analyze(bin: &Binary, graph: &Graph) -> Vec<Finding> { 1427 let scan = Scan::new(bin, graph); 1428 let mut out = Vec::new(); 1429 for call in &graph.sites { 1430 let Some(imp) = call.import.as_deref() else { 1431 continue; 1432 }; 1433 let s = Site { 1434 scan: &scan, 1435 call, 1436 imp, 1437 reach: scan.reach.get(&call.func).copied(), 1438 }; 1439 let Some(mut h) = classify(&s) else { continue }; 1440 adjust(&s, &mut h); 1441 out.push(Finding { 1442 bin: scan.name.clone(), 1443 class: h.class, 1444 risky_call: imp.to_string(), 1445 site: call.site, 1446 func: graph.func_name(call.func), 1447 reach: s.reach, 1448 evidence: h.evidence, 1449 score: h.score, 1450 shell_injection: h.shell_injection, 1451 }); 1452 } 1453 out.extend(absences(&scan)); 1454 out.sort_by(|a, b| b.score.cmp(&a.score).then(a.site.cmp(&b.site))); 1455 out 1456 } 1457 1458 struct Absence { 1459 present: &'static [&'static str], 1460 absent: &'static [&'static str], 1461 class: Class, 1462 risky_call: &'static str, 1463 score: i32, 1464 evidence: &'static [&'static str], 1465 } 1466 1467 const SSL_CLIENT: &[&str] = &["SSL_connect", "SSL_CTX_new"]; 1468 1469 const ABSENT: &[Absence] = &[ 1470 Absence { 1471 present: SSL_CLIENT, 1472 absent: &["SSL_CTX_set_verify", "SSL_set_verify"], 1473 class: Class::Tls, 1474 risky_call: "(no verify mode set)", 1475 score: 75, 1476 evidence: &[ 1477 "SSL_CTX_new/SSL_connect present but no verify mode is ever configured", 1478 "OpenSSL's documented default is SSL_VERIFY_NONE, so the handshake completes regardless of the certificate", 1479 ], 1480 }, 1481 Absence { 1482 present: SSL_CLIENT, 1483 absent: HOSTNAME_CHECK, 1484 class: Class::Tls, 1485 risky_call: "(no hostname check)", 1486 score: 65, 1487 evidence: &[ 1488 "no X509_check_host / SSL_set1_host / X509_VERIFY_PARAM_set1_host", 1489 "OpenSSL does not bind a chain to a hostname on its own, so any CA-signed certificate for any name is accepted", 1490 ], 1491 }, 1492 Absence { 1493 present: SSL_CLIENT, 1494 absent: &["SSL_CTX_load_verify_locations", "SSL_CTX_set_default_verify_paths"], 1495 class: Class::Tls, 1496 risky_call: "(no trust store)", 1497 score: 55, 1498 evidence: &["no CA store is ever loaded, so chain verification cannot succeed"], 1499 }, 1500 Absence { 1501 present: &["mbedtls_ssl_handshake"], 1502 absent: &["mbedtls_ssl_set_hostname"], 1503 class: Class::Tls, 1504 risky_call: "(no mbedtls hostname)", 1505 score: 65, 1506 evidence: &["mbedtls_ssl_set_hostname is never called, so CN/SAN matching is skipped"], 1507 }, 1508 Absence { 1509 present: &["chroot"], 1510 absent: &["chdir"], 1511 class: Class::Priv, 1512 risky_call: "(chroot without chdir)", 1513 score: 55, 1514 evidence: &["chroot imported but chdir is not, so the jail is trivially escaped"], 1515 }, 1516 Absence { 1517 present: TEMPFILE, 1518 absent: &["mkstemp", "mkostemp", "mkdtemp"], 1519 class: Class::Path, 1520 risky_call: "(no atomic temp file)", 1521 score: 45, 1522 evidence: &["mktemp/tmpnam used and no mkstemp/mkdtemp is linked at all"], 1523 }, 1524 ]; 1525 1526 fn is_unbounded_write(import: &str) -> bool { 1527 UNBOUNDED.iter().any(|(name, _, _)| *name == import) 1528 } 1529 1530 fn uses_unbounded_write(g: &Graph) -> bool { 1531 let mut imports = g.sites.iter().filter_map(|site| site.import.as_deref()); 1532 imports.any(is_unbounded_write) 1533 } 1534 1535 fn names_flash_target(text: &str) -> bool { 1536 text.contains("sysupgrade") || text.starts_with("mtd ") || text.contains("/dev/mtd") 1537 } 1538 1539 fn flashes_firmware(g: &Graph) -> bool { 1540 g.strings 1541 .values() 1542 .flatten() 1543 .any(|text| names_flash_target(text)) 1544 } 1545 1546 fn absences(sc: &Scan) -> Vec<Finding> { 1547 let mut out = Vec::new(); 1548 let mut push = |class: Class, risky_call: &str, score: i32, ev: &[&str]| { 1549 out.push(Finding { 1550 bin: sc.name.clone(), 1551 class, 1552 risky_call: risky_call.to_string(), 1553 site: 0, 1554 func: "(whole binary)".into(), 1555 reach: None, 1556 evidence: ev 1557 .iter() 1558 .enumerate() 1559 .map(|(i, e)| Evidence::new(if i == 0 { score } else { 0 }, *e)) 1560 .collect(), 1561 score, 1562 shell_injection: false, 1563 }) 1564 }; 1565 1566 let unbounded = uses_unbounded_write(sc.graph); 1567 if unbounded && !sc.has("__stack_chk_fail") { 1568 push( 1569 Class::Mem, 1570 "(no stack canary)", 1571 60, 1572 &[ 1573 "no __stack_chk_fail import: built without -fstack-protector", 1574 "every stack overflow here reaches the saved return address directly", 1575 ], 1576 ); 1577 } 1578 if unbounded && !sc.any(BOUNDED) { 1579 push( 1580 Class::Mem, 1581 "(no bounded copy)", 1582 55, 1583 &[ 1584 "no snprintf/strlcpy/strncpy/strncat anywhere in this binary", 1585 "every string operation it performs is unbounded", 1586 ], 1587 ); 1588 } 1589 for a in ABSENT { 1590 if sc.any(a.present) && !sc.any(a.absent) { 1591 push(a.class, a.risky_call, a.score, a.evidence); 1592 } 1593 } 1594 if flashes_firmware(sc.graph) && (sc.has("system") || sc.has("popen")) && !sc.any(SIGVERIFY) { 1595 push( 1596 Class::Exec, 1597 "(unsigned update path)", 1598 60, 1599 &[ 1600 "references mtd/sysupgrade and shells out, but links no RSA/ECDSA verify", 1601 "check whether the update image is authenticated at all", 1602 ], 1603 ); 1604 } 1605 out 1606 } 1607 1608 #[cfg(test)] 1609 mod tests { 1610 use super::*; 1611 1612 #[test] 1613 fn unbounded_scan_flags_widthless_conversions() { 1614 assert!(unbounded_scan("%s")); 1615 assert!(unbounded_scan("%[abc]")); 1616 assert!(unbounded_scan("%d %s")); 1617 } 1618 1619 #[test] 1620 fn unbounded_scan_respects_field_width() { 1621 assert!(!unbounded_scan("%10s")); 1622 assert!(!unbounded_scan("%31[^\n]")); 1623 } 1624 1625 #[test] 1626 fn unbounded_scan_ignores_literal_percent() { 1627 assert!(!unbounded_scan("%%s")); 1628 assert!(!unbounded_scan("hello world")); 1629 } 1630 1631 #[test] 1632 fn unbounded_scan_ignores_suppressed_star() { 1633 assert!(!unbounded_scan("%*s")); 1634 assert!(!unbounded_scan("%*[^\n]")); 1635 } 1636 1637 #[test] 1638 fn looks_shell_detects_command_templates() { 1639 assert!(looks_shell("cp %s /tmp")); 1640 assert!(looks_shell("ping %s")); 1641 } 1642 1643 #[test] 1644 fn looks_shell_ignores_benign_formats() { 1645 assert!(!looks_shell("value=%d")); 1646 assert!(!looks_shell("hello")); 1647 } 1648 1649 #[test] 1650 fn shell_injection_flags_redirect_and_pipe() { 1651 assert!(shell_injection("ping %s -s 56 -c 3 >%s")); 1652 assert!(shell_injection("echo %s | sh")); 1653 assert!(!shell_injection("value=%d")); // no %s 1654 assert!(!shell_injection("cp %s /tmp")); // %s but no proving metachar 1655 } 1656 1657 #[test] 1658 fn system_with_unquoted_s_flags_injection_without_metachar() { 1659 let mut b = bin(crate::arch::Arch::Aarch64, &[]); 1660 b.data = b"ping %s\0".to_vec(); 1661 b.segs = vec![crate::load::Seg { 1662 vaddr: 0x2000, 1663 off: 0, 1664 filesz: b.data.len() as u64, 1665 exec: false, 1666 }]; 1667 let g = graph(vec![site("system", vec![Some(Val::Num(0x2000))])], HashMap::new()); 1668 let f = analyze(&b, &g); 1669 assert!(f.iter().any(|f| f.risky_call == "system" && f.shell_injection)); 1670 } 1671 1672 #[test] 1673 fn is_neutered_matches_all_ones() { 1674 assert!(is_neutered(u64::MAX)); 1675 assert!(is_neutered(0xffff_ffff)); 1676 assert!(!is_neutered(0)); 1677 assert!(!is_neutered(0x10)); 1678 } 1679 1680 #[test] 1681 fn stack_off_formats_sign() { 1682 assert_eq!(stack_off(-16), "sp-0x10"); 1683 assert_eq!(stack_off(32), "sp+0x20"); 1684 } 1685 1686 #[test] 1687 fn mode_note_precedence() { 1688 assert_eq!( 1689 mode_note(0o4755), 1690 Some("setuid bit in mode 0o4755".to_string()) 1691 ); 1692 assert_eq!( 1693 mode_note(0o2755), 1694 Some("setgid bit in mode 0o2755".to_string()) 1695 ); 1696 assert_eq!( 1697 mode_note(0o0666), 1698 Some("world-writable mode 0o666".to_string()) 1699 ); 1700 assert_eq!(mode_note(0o0755), None); 1701 } 1702 1703 fn bin(arch: crate::arch::Arch, imports: &[&str]) -> Binary { 1704 Binary { 1705 path: "/rootfs/bin/foo".into(), 1706 data: vec![], 1707 arch, 1708 little: true, 1709 entry: 0, 1710 segs: vec![], 1711 got2sym: HashMap::new(), 1712 undef_stub: vec![], 1713 imports: imports.iter().map(|s| s.to_string()).collect(), 1714 exports: vec![], 1715 locals: vec![], 1716 gp: None, 1717 } 1718 } 1719 1720 fn graph(sites: Vec<CallSite>, strings: HashMap<u64, Vec<String>>) -> Graph { 1721 Graph { 1722 names: HashMap::new(), 1723 sites, 1724 edges: HashMap::new(), 1725 strings, 1726 addr_taken: HashSet::new(), 1727 } 1728 } 1729 1730 fn site(import: &str, args: Vec<Option<Val>>) -> CallSite { 1731 CallSite { 1732 site: 0x1000, 1733 func: 0, 1734 import: Some(import.into()), 1735 target: 0, 1736 args, 1737 } 1738 } 1739 1740 #[test] 1741 fn is_exec_primitive_rejects_substrings() { 1742 assert!(!is_exec_primitive("regexec")); 1743 assert!(!is_exec_primitive("sqlite3_exec")); 1744 assert!(!is_exec_primitive("pcre_exec")); 1745 assert!(is_exec_primitive("system")); 1746 assert!(is_exec_primitive("qid_sys_execute_update_script")); 1747 } 1748 1749 #[test] 1750 fn finding_bin_carries_full_path_not_basename() { 1751 let b = bin(crate::arch::Arch::Aarch64, &[]); 1752 let g = graph(vec![site("system", vec![None])], HashMap::new()); 1753 let findings = analyze(&b, &g); 1754 assert!(findings.iter().any(|f| f.bin == "/rootfs/bin/foo")); 1755 assert!(!findings.iter().any(|f| f.bin == "foo")); 1756 } 1757 1758 #[test] 1759 fn bind_tcp_without_socket_evidence_omits_peercred_bonus() { 1760 let b = bin(crate::arch::Arch::Aarch64, &[]); 1761 let g = graph(vec![site("bind", vec![])], HashMap::new()); 1762 let findings = analyze(&b, &g); 1763 assert!(!findings 1764 .iter() 1765 .any(|f| f.evidence.iter().any(|e| e.text.contains("no SO_PEERCRED")))); 1766 } 1767 1768 #[test] 1769 fn bind_unix_socket_fires_peercred_bonus() { 1770 let b = bin(crate::arch::Arch::Aarch64, &[]); 1771 let mut strings = HashMap::new(); 1772 strings.insert(0x1000u64, vec!["/tmp/foo.sock".to_string()]); 1773 let g = graph(vec![site("bind", vec![])], strings); 1774 let findings = analyze(&b, &g); 1775 assert!(findings 1776 .iter() 1777 .any(|f| f.evidence.iter().any(|e| e.text.contains("no SO_PEERCRED")))); 1778 } 1779 1780 #[test] 1781 fn bcopy_destination_is_arg1() { 1782 let b = bin(crate::arch::Arch::Aarch64, &[]); 1783 let args = vec![None, Some(Val::Stack(-0x10)), None]; 1784 let g = graph(vec![site("bcopy", args)], HashMap::new()); 1785 let findings = analyze(&b, &g); 1786 assert!(findings 1787 .iter() 1788 .any(|f| f.evidence.iter().any(|e| e.text.contains("stack buffer")))); 1789 } 1790 1791 fn at(import: &str, site: u64, args: Vec<Option<Val>>) -> CallSite { 1792 CallSite { 1793 site, 1794 func: 0, 1795 import: Some(import.into()), 1796 target: 0, 1797 args, 1798 } 1799 } 1800 1801 fn scan(b: &Binary, sites: Vec<CallSite>, sink: &str) -> Vec<Finding> { 1802 let g = graph(sites, HashMap::new()); 1803 analyze(b, &g) 1804 .into_iter() 1805 .filter(|f| f.risky_call == sink) 1806 .collect() 1807 } 1808 1809 fn says(f: &Finding, text: &str) -> bool { 1810 f.evidence.iter().any(|e| e.text.contains(text)) 1811 } 1812 1813 fn memcpy_len_from(producer: &str) -> Vec<Finding> { 1814 let b = bin(crate::arch::Arch::Arm, &[]); 1815 let sites = vec![ 1816 at(producer, 0x1000, vec![]), 1817 at("memcpy", 0x1010, vec![None, None, Some(Val::Ret(0))]), 1818 ]; 1819 scan(&b, sites, "memcpy") 1820 } 1821 1822 #[test] 1823 fn breakdown_adds_up_to_score() { 1824 let b = bin(crate::arch::Arch::Aarch64, &["system", "recv"]); 1825 let mut strings = HashMap::new(); 1826 strings.insert( 1827 0u64, 1828 vec!["ping -c 1 %s".to_string(), "/tmp/x.sock".to_string()], 1829 ); 1830 let sites = vec![ 1831 at("recv", 0x1000, vec![]), 1832 at("system", 0x1010, vec![None]), 1833 at("bind", 0x1020, vec![]), 1834 at( 1835 "memcpy", 1836 0x1030, 1837 vec![Some(Val::Stack(-0x40)), None, Some(Val::Ret(0))], 1838 ), 1839 ]; 1840 let findings = analyze(&b, &graph(sites, strings)); 1841 let calls: HashSet<&str> = findings.iter().map(|f| f.risky_call.as_str()).collect(); 1842 assert_eq!(calls, HashSet::from(["system", "bind", "memcpy"])); 1843 for f in &findings { 1844 let sum: i32 = f.evidence.iter().map(|e| e.points).sum(); 1845 assert_eq!( 1846 sum, 1847 f.score, 1848 "{} {:?}", 1849 f.risky_call, 1850 f.evidence.iter().map(|e| &e.text).collect::<Vec<_>>() 1851 ); 1852 } 1853 } 1854 1855 #[test] 1856 fn heap_memcpy_sized_by_recv_is_reported() { 1857 let f = memcpy_len_from("recv"); 1858 assert!(says(&f[0], "raw return of recv()")); 1859 } 1860 1861 #[test] 1862 fn heap_memcpy_with_opaque_length_stays_silent() { 1863 let b = bin(crate::arch::Arch::Arm, &[]); 1864 assert!(scan( 1865 &b, 1866 vec![at("memcpy", 0x1010, vec![None, None, None])], 1867 "memcpy" 1868 ) 1869 .is_empty()); 1870 } 1871 1872 #[test] 1873 fn provenance_splits_sibling_sinks() { 1874 let b = bin(crate::arch::Arch::Arm, &[]); 1875 let sites = vec![ 1876 at("recv", 0x1000, vec![]), 1877 at("strnlen", 0x1004, vec![]), 1878 at( 1879 "memcpy", 1880 0x1008, 1881 vec![Some(Val::Stack(-0x40)), None, Some(Val::Ret(0))], 1882 ), 1883 at( 1884 "memcpy", 1885 0x100c, 1886 vec![Some(Val::Stack(-0x40)), None, Some(Val::Ret(1))], 1887 ), 1888 ]; 1889 let f = scan(&b, sites, "memcpy"); 1890 let score = |site| f.iter().find(|f| f.site == site).unwrap().score; 1891 assert_eq!(score(0x1008) - score(0x100c), 35); 1892 } 1893 1894 #[test] 1895 fn snprintf_return_as_length_is_up_ranked() { 1896 let b = bin(crate::arch::Arch::Arm, &[]); 1897 let sites = vec![ 1898 at("snprintf", 0x1000, vec![]), 1899 at( 1900 "memcpy", 1901 0x1010, 1902 vec![Some(Val::Stack(-0x40)), None, Some(Val::Ret(0))], 1903 ), 1904 ]; 1905 assert!(says(&scan(&b, sites, "memcpy")[0], "untruncated length")); 1906 } 1907 1908 #[test] 1909 fn local_clamp_bounds_the_length() { 1910 let b = bin(crate::arch::Arch::Arm, &[]); 1911 let mut clamp = at("x", 0x1000, vec![]); 1912 clamp.import = None; 1913 clamp.target = 0x4000; 1914 let sites = vec![ 1915 clamp, 1916 at( 1917 "memcpy", 1918 0x1010, 1919 vec![Some(Val::Stack(-0x40)), None, Some(Val::Ret(0))], 1920 ), 1921 ]; 1922 let mut g = graph(sites, HashMap::new()); 1923 g.names.insert(0x4000, "len_clamp".into()); 1924 let f: Vec<Finding> = analyze(&b, &g) 1925 .into_iter() 1926 .filter(|f| f.risky_call == "memcpy") 1927 .collect(); 1928 assert!(says(&f[0], "bounded by len_clamp()")); 1929 assert!(f[0] 1930 .evidence 1931 .iter() 1932 .any(|e| e.text.contains("bounded by len_clamp") && e.points == -20)); 1933 } 1934 1935 #[test] 1936 fn watchdog_setoptions_uses_arch_encoding() { 1937 let arm = bin(crate::arch::Arch::Arm, &[]); 1938 let mips = bin(crate::arch::Arch::Mips, &[]); 1939 let ioctl = |req| vec![at("ioctl", 0x1000, vec![None, Some(Val::Num(req)), None])]; 1940 assert_eq!(scan(&arm, ioctl(0x8004_5704), "ioctl")[0].class, Class::Wdt); 1941 assert_eq!( 1942 scan(&mips, ioctl(0x4004_5704), "ioctl")[0].class, 1943 Class::Wdt 1944 ); 1945 assert!(scan(&arm, ioctl(0x4004_5704), "ioctl").is_empty()); 1946 assert!(scan(&arm, ioctl(0x5401), "ioctl").is_empty()); 1947 } 1948 1949 #[test] 1950 fn watchdog_magic_close() { 1951 let mut b = bin(crate::arch::Arch::Arm, &[]); 1952 b.data = b"V\0V?\0".to_vec(); 1953 b.segs = vec![crate::load::Seg { 1954 vaddr: 0x2000, 1955 off: 0, 1956 filesz: 5, 1957 exec: false, 1958 }]; 1959 let write = |buf| { 1960 vec![at( 1961 "write", 1962 0x1000, 1963 vec![None, Some(Val::Num(buf)), Some(Val::Num(1))], 1964 )] 1965 }; 1966 assert_eq!(scan(&b, write(0x2000), "write")[0].class, Class::Wdt); 1967 assert!(scan(&b, write(0x2002), "write").is_empty()); 1968 } 1969 1970 #[test] 1971 fn watchdog_settimeout_flagged_on_all_arches_and_note_only_sums() { 1972 let ioctl = |req| vec![at("ioctl", 0x1000, vec![None, Some(Val::Num(req)), None])]; 1973 for arch in [crate::arch::Arch::Arm, crate::arch::Arch::Mips] { 1974 let b = bin(arch, &[]); 1975 let f = &scan(&b, ioctl(0xc004_5706), "ioctl")[0]; 1976 assert_eq!(f.class, Class::Wdt); 1977 assert!(says(f, "SETTIMEOUT")); 1978 let sum: i32 = f.evidence.iter().map(|e| e.points).sum(); 1979 assert_eq!(sum, f.score); 1980 } 1981 } 1982 }