diff --git a/Dockerfile.agent b/Dockerfile.agent index bced8aa..57bad0e 100644 --- a/Dockerfile.agent +++ b/Dockerfile.agent @@ -9,6 +9,9 @@ ARG GITLEAKS_VERSION=8.21.2 ARG GITLEAKS_SHA256=5bc41815076e6ed6ef8fbecc9d9b75bcae31f39029ceb55da08086315316e3ba ARG SEMGREP_VERSION=1.177.0 ARG RUFF_VERSION=0.16.8 +# mobsfscan pins an older semgrep; it is installed without its dependencies so +# it runs on the semgrep above, and its other dependencies are pinned here. +ARG MOBSFSCAN_VERSION=1.0.1 FROM rust:1.94-bookworm AS builder @@ -42,6 +45,7 @@ ARG GITLEAKS_VERSION ARG GITLEAKS_SHA256 ARG SEMGREP_VERSION ARG RUFF_VERSION +ARG MOBSFSCAN_VERSION # No recommended packages: python3-pip would otherwise pull in a full C # toolchain, which nothing at runtime needs. @@ -74,10 +78,21 @@ RUN curl -sSfL -o /tmp/gitleaks.tar.gz \ RUN pip3 install --break-system-packages --no-cache-dir \ "semgrep==${SEMGREP_VERSION}" "ruff==${RUFF_VERSION}" +# Mobile app SAST (LGPL-3.0). The wrapper clears its substring path ignores; +# see compliance-agent/src/pipeline/mobsfscan.rs. +RUN pip3 install --break-system-packages --no-cache-dir --no-deps \ + "mobsfscan==${MOBSFSCAN_VERSION}" \ + && pip3 install --break-system-packages --no-cache-dir \ + "libsast==3.1.8" "billiard==4.3.0" "pyyaml==6.0.3" "colorama==0.4.6" \ + "sarif-om==1.0.4" "jschema-to-python==1.2.3" "jsonpickle==4.1.2" "pbr==7.0.3" \ + "tabulate==0.10.0" "xmltodict==1.0.4" +COPY docker/pruefwerk_mobsfscan.py /opt/pruefwerk/pruefwerk_mobsfscan.py + RUN mkdir -p /opt/pruefwerk \ - && printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s"}\n' \ + && printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s"}\n' \ "${RUST_VERSION}" "${CARGO_AUDIT_VERSION}" "${SYFT_VERSION}" "${GITLEAKS_VERSION}" \ "${SEMGREP_VERSION}" "${RUFF_VERSION}" "$(cppcheck --version | cut -d' ' -f2)" \ + "${MOBSFSCAN_VERSION}" \ > /opt/pruefwerk/tool-versions.json # The agent runs unprivileged. It writes only to its home (tool caches), the diff --git a/README.md b/README.md index 2749030..4c918e4 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Compliance Scanner is an autonomous agent that continuously monitors git reposit | Area | Capabilities | |------|-------------| -| **SAST Scanning** | Semgrep engine with our own CRA rules (no registry rules), cppcheck for C/C++ | +| **SAST Scanning** | Semgrep engine with our own CRA rules (no registry rules), cppcheck for C/C++, mobsfscan for Android and iOS apps | | **SBOM Generation** | Syft + cargo-audit for complete dependency inventory | | **CVE Monitoring** | OSV.dev batch queries, NVD CVSS enrichment, SearXNG context | | **GDPR Patterns** | Detect PII logging, missing consent, hardcoded retention, missing deletion | diff --git a/compliance-agent/src/evidence/compliance.rs b/compliance-agent/src/evidence/compliance.rs index 68b3a1d..8029bc6 100644 --- a/compliance-agent/src/evidence/compliance.rs +++ b/compliance-agent/src/evidence/compliance.rs @@ -70,6 +70,7 @@ pub fn tool_of_stage(stage: &str) -> Option<&'static str> { match stage { "sast" => Some("semgrep"), "sast_c_cpp" => Some("cppcheck"), + "sast_mobile" => Some("mobsfscan"), "cve_lookup" => Some("osv"), _ => None, } @@ -443,6 +444,7 @@ mod tests { ControlState::NoViolationFound ); assert_eq!(tool_of_stage("cve_lookup"), Some("osv")); + assert_eq!(tool_of_stage("sast_mobile"), Some("mobsfscan")); assert_eq!(tool_of_stage("sast_vendor_code"), None); } diff --git a/compliance-agent/src/pipeline/languages.rs b/compliance-agent/src/pipeline/languages.rs index 31f88e3..f7b0bb9 100644 --- a/compliance-agent/src/pipeline/languages.rs +++ b/compliance-agent/src/pipeline/languages.rs @@ -26,6 +26,9 @@ fn language_of(extension: &str) -> Option<&'static str> { "rs" => "rust", "cs" => "csharp", "swift" => "swift", + // Objective-C; `.m` is also MATLAB's extension, which only means + // mobsfscan looks at a tree it finds nothing in. + "m" | "mm" => "objc", _ => return None, }) } diff --git a/compliance-agent/src/pipeline/mobsfscan.rs b/compliance-agent/src/pipeline/mobsfscan.rs new file mode 100644 index 0000000..aa38d4f --- /dev/null +++ b/compliance-agent/src/pipeline/mobsfscan.rs @@ -0,0 +1,507 @@ +//! Mobile app SAST with mobsfscan (LGPL-3.0, rules used unchanged). +//! +//! mobsfscan checks Android and iOS source: Java and Kotlin, Swift and +//! Objective-C code (WebView bridges, weak crypto, insecure storage, TLS +//! handling), and the AndroidManifest and Info.plist settings (debuggable, +//! backups, cleartext traffic, App Transport Security exceptions). It runs its +//! rules on the semgrep engine with metrics off. +//! +//! Two of its defaults are not safe for a customer's tree, so the image runs it +//! through a wrapper (`docker/pruefwerk_mobsfscan.py`) and always passes our own config: +//! - libsast skips every file whose path merely *contains* an ignored name, and +//! the defaults include `spec` and `fixtures`, so code under `inspection/` +//! would vanish. The wrapper clears them; ours are anchored as `/name/`. +//! - Without `-c`, mobsfscan reads a `.mobsf` file from the scanned tree, which +//! would let the repository switch rules off. +//! +//! And with `--type auto` it configures the iOS rules only when the tree has no +//! Android code, so a React Native, Flutter or monorepo app would be checked as +//! Android only. It runs once per platform present instead. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use compliance_core::models::{Finding, ScanType, Severity}; +use compliance_core::traits::{ScanOutput, Scanner}; +use compliance_core::CoreError; + +use crate::pipeline::dedup; +use crate::pipeline::source_text::{read_lines, read_text, relative_path}; + +/// The wrapper the agent image installs (see `Dockerfile.agent`). +const WRAPPER: &str = "/opt/pruefwerk/pruefwerk_mobsfscan.py"; + +/// Source languages of Android apps, by the names +/// [`crate::pipeline::languages`] records. +const ANDROID_LANGUAGES: [&str; 2] = ["java", "kotlin"]; + +/// Source languages of iOS apps. +const IOS_LANGUAGES: [&str; 2] = ["swift", "objc"]; + +/// Directories never analysed: build output, installed dependencies and tool +/// caches. Vendor directories are added per tree. +const SKIPPED_DIRS: &[&str] = &[ + ".git", + ".gradle", + "build", + "DerivedData", + "node_modules", + "Pods", + "Carthage", +]; + +/// How long a scan may take before it is stopped and recorded as failed. +const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600); + +/// mobsfscan over a tree, skipping vendor and build directories. +#[derive(Debug, Default)] +pub struct MobsfscanScanner { + /// Directories (relative to the tree) left out of the analysis. + excluded: Vec, + /// The `--type` of each run: `android`, `ios`, or both. + platforms: Vec<&'static str>, +} + +impl MobsfscanScanner { + /// A scanner for a tree whose source `languages` include one mobsfscan + /// checks, skipping the `excluded` vendor directories; `None` otherwise. + /// + /// # Arguments + /// + /// * `languages` - the source languages found outside vendor code + /// * `excluded` - vendor directories relative to the tree + pub fn for_languages(languages: &[String], excluded: &[String]) -> Option { + let has = |set: &[&str]| languages.iter().any(|l| set.contains(&l.as_str())); + let platforms: Vec<&'static str> = [ + ("android", has(&ANDROID_LANGUAGES)), + ("ios", has(&IOS_LANGUAGES)), + ] + .into_iter() + .filter_map(|(platform, present)| present.then_some(platform)) + .collect(); + (!platforms.is_empty()).then(|| Self { + excluded: excluded.to_vec(), + platforms, + }) + } + + /// The `.mobsf` config passed with `-c`: the skipped and vendor + /// directories, anchored so a name only matches a whole path component. + fn config(&self) -> String { + let mut config = String::from("---\n- ignore-paths:\n"); + for dir in SKIPPED_DIRS + .iter() + .copied() + .chain(self.excluded.iter().map(String::as_str)) + { + // Quoted for YAML; a vendor path has no quote or backslash. + config.push_str(&format!(" - \"/{dir}/\"\n")); + } + config + } +} + +impl Scanner for MobsfscanScanner { + fn name(&self) -> &str { + "mobsfscan" + } + + fn scan_type(&self) -> ScanType { + ScanType::Sast + } + + #[tracing::instrument(skip_all)] + async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result { + let work = WorkFiles::new(&self.config()).map_err(|e| failed(Box::new(e)))?; + let mut findings = Vec::new(); + for platform in &self.platforms { + findings.extend(run(repo_path, repo_id, platform, &work).await?); + } + Ok(ScanOutput { + findings, + sbom_entries: Vec::new(), + }) + } +} + +/// A scanner error with `source` as its cause. +fn failed(source: Box) -> CoreError { + CoreError::Scanner { + scanner: "mobsfscan".to_string(), + source, + } +} + +/// One mobsfscan run over `repo_path` with the rules of `platform`. +/// +/// # Errors +/// +/// Returns `CoreError::Scanner` when mobsfscan cannot start, times out, exits +/// with an error, or reports errors and nothing else. +async fn run( + repo_path: &Path, + repo_id: &str, + platform: &str, + work: &WorkFiles, +) -> Result, CoreError> { + let report_path = work.report(platform); + let mut cmd = crate::pipeline::tool_cmd::tool("python3", &[]); + cmd.arg(WRAPPER) + // Threads, not processes: mobsfscan's default process pool breaks + // under Python 3.14's start method, and semgrep runs as its own + // process anyway. + .args(["--json", "--no-fail", "--multiprocessing", "thread"]) + .args(["--type", platform, "-c"]) + .arg(work.config()) + .arg("-o") + .arg(&report_path) + // Code matches come back absolute, manifest and plist matches + // relative to the working directory: from the tree, both resolve. + .arg(repo_path) + .current_dir(repo_path); + + let output = tokio::time::timeout(TIMEOUT, cmd.output()) + .await + .map_err(|_| failed("timed out after 10 minutes".into()))? + .map_err(|e| failed(Box::new(e)))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let tail: String = stderr.lines().rev().take(3).collect::>().join(" / "); + return Err(failed( + format!("{platform} run exited with {}: {tail}", output.status).into(), + )); + } + let report = std::fs::read(&report_path).map_err(|e| failed(Box::new(e)))?; + let report: Report = serde_json::from_slice(&report)?; + // A tool error with nothing found means nothing was checked. + if report.results.is_empty() && !report.errors.is_empty() { + return Err(failed( + format!( + "{platform} run reported errors: {}", + report.errors.join(" / ") + ) + .into(), + )); + } + for error in &report.errors { + tracing::warn!(%error, platform, "mobsfscan reported an error"); + } + Ok(report.findings(repo_path, repo_id)) +} + +/// mobsfscan's JSON report. +#[derive(Debug, serde::Deserialize)] +struct Report { + #[serde(default)] + results: BTreeMap, + #[serde(default)] + errors: Vec, +} + +/// One rule's matches and what it says about them. +#[derive(Debug, serde::Deserialize)] +struct RuleResult { + /// Where the rule matched. Empty for the "best practice" rules, which + /// report that a protection is missing from the whole app (no pinning, no + /// root detection); those are heuristics with no location to show. + #[serde(default)] + files: Vec, + metadata: Metadata, +} + +#[derive(Debug, serde::Deserialize)] +struct Match { + file_path: String, + match_lines: (u32, u32), + #[serde(default)] + match_string: String, +} + +#[derive(Debug, serde::Deserialize)] +struct Metadata { + #[serde(default)] + cwe: String, + #[serde(default)] + description: String, + #[serde(default)] + masvs: String, + #[serde(default)] + reference: String, + #[serde(default)] + severity: String, +} + +impl Report { + /// One finding per rule and location. + fn findings(self, root: &Path, repo_id: &str) -> Vec { + self.results + .into_iter() + .flat_map(|(rule, result)| { + result + .files + .iter() + .map(|m| finding(root, repo_id, &rule, &result.metadata, m)) + .collect::>() + }) + .collect() + } +} + +/// The finding for rule `rule` matching at `m`. +fn finding(root: &Path, repo_id: &str, rule: &str, meta: &Metadata, m: &Match) -> Finding { + let file = relative_path(root, &m.file_path); + let (start, end) = located(root, &file, m); + let fingerprint = + dedup::compute_fingerprint(&[repo_id, "mobsfscan", rule, &file, &start.to_string()]); + let mut description = meta.description.clone(); + if !meta.masvs.is_empty() { + description.push_str(&format!("\n\nOWASP MASVS: {}", meta.masvs)); + } + if !meta.reference.is_empty() { + description.push_str(&format!("\nReference: {}", meta.reference)); + } + let mut finding = Finding::new( + repo_id.to_string(), + fingerprint, + "mobsfscan".to_string(), + ScanType::Sast, + title(&meta.description, rule), + description, + match meta.severity.as_str() { + "ERROR" => Severity::High, + "WARNING" => Severity::Medium, + "INFO" => Severity::Low, + _ => Severity::Info, + }, + ); + finding.code_snippet = read_lines(root, &file, start, end); + finding.rule_id = Some(rule.to_string()); + finding.cwe = normalise_cwe(&meta.cwe); + finding.line_number = Some(start); + finding.file_path = Some(file); + finding +} + +/// The lines a match covers. Manifest and plist rules report line 1 with the +/// setting as `key=value` or `key (u32, u32) { + let is_config = file.ends_with(".xml") || file.ends_with(".plist"); + let Some(key) = setting_key(&m.match_string) else { + return m.match_lines; + }; + if m.match_lines != (1, 1) || !is_config { + return m.match_lines; + } + let Some(text) = read_text(root, file) else { + return m.match_lines; + }; + text.lines() + .position(|line| line.contains(key)) + .and_then(|i| u32::try_from(i + 1).ok()) + .map_or(m.match_lines, |line| (line, line)) +} + +/// The setting a manifest or plist match names: `android:debuggable` in +/// `android:debuggable=true`, `android:minSdkVersion` in +/// `android:minSdkVersion<29`. `None` for prose. +fn setting_key(match_string: &str) -> Option<&str> { + let end = match_string + .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | ':' | '.')))?; + let follows = match_string[end..].chars().next()?; + (end > 0 && matches!(follows, '=' | '<' | '>' | '!')).then(|| &match_string[..end]) +} + +/// A short title: the description's first sentence, or the rule id. +fn title(description: &str, rule: &str) -> String { + let first = description + .split_once(". ") + .map_or(description, |(first, _)| first) + .trim() + .trim_end_matches('.'); + if first.is_empty() { + rule.to_string() + } else { + first.to_string() + } +} + +/// `CWE-NNN` from mobsfscan's `cwe-489` or `CWE-327: Use of a Broken …`. +fn normalise_cwe(cwe: &str) -> Option { + let rest = cwe + .get(..4)? + .eq_ignore_ascii_case("cwe-") + .then(|| &cwe[4..])?; + let digits: String = rest.chars().take_while(char::is_ascii_digit).collect(); + (!digits.is_empty()).then(|| format!("CWE-{digits}")) +} + +/// The config and report files of one run, in a temporary directory removed +/// on drop. +struct WorkFiles(PathBuf); + +impl WorkFiles { + fn new(config: &str) -> std::io::Result { + let dir = std::env::temp_dir().join(format!("cs-mobsfscan-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir)?; + let files = Self(dir); + std::fs::write(files.config(), config)?; + Ok(files) + } + + fn config(&self) -> PathBuf { + self.0.join(".mobsf") + } + + fn report(&self, platform: &str) -> PathBuf { + self.0.join(format!("{platform}.json")) + } +} + +impl Drop for WorkFiles { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + /// A scratch tree holding `files`, removed on drop. + struct Tree(PathBuf); + impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn tree(files: &[(&str, &str)]) -> Tree { + let dir = std::env::temp_dir().join(format!("cs-mobsf-{}", uuid::Uuid::new_v4())); + for (path, content) in files { + let full = dir.join(path); + std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir"); + std::fs::write(full, content).expect("write"); + } + Tree(dir) + } + + const MANIFEST: &str = "\n \n \n\n"; + + fn report(root: &Path) -> String { + format!( + r#"{{ + "errors": [], + "results": {{ + "android_manifest_debugging_enabled": {{ + "files": [{{ + "file_path": "{root}/app/src/main/AndroidManifest.xml", + "match_lines": [1, 1], + "match_string": "android:debuggable=true" + }}], + "metadata": {{ + "cwe": "cwe-489", + "description": "Debugging was enabled on the app which makes it easier for reverse engineers to hook a debugger to it. This allows dumping a stack trace.", + "masvs": "code-2", + "reference": "https://mas.owasp.org/", + "severity": "ERROR" + }} + }}, + "android_root_detection": {{ + "metadata": {{ + "cwe": "CWE-919: Weaknesses in Mobile Applications", + "description": "This app does not have root detection capabilities.", + "severity": "INFO" + }} + }} + }} +}}"#, + root = root.display() + ) + } + + #[test] + fn a_manifest_finding_points_at_the_line_that_sets_it() { + let dir = tree(&[("app/src/main/AndroidManifest.xml", MANIFEST)]); + let parsed: Report = serde_json::from_str(&report(&dir.0)).expect("report"); + let findings = parsed.findings(&dir.0, "t"); + + // The app-wide "missing protection" heuristic has no location. + assert_eq!(findings.len(), 1); + let f = &findings[0]; + assert_eq!( + f.file_path.as_deref(), + Some("app/src/main/AndroidManifest.xml") + ); + assert_eq!(f.line_number, Some(3)); + assert_eq!(f.cwe.as_deref(), Some("CWE-489")); + assert_eq!(f.severity, Severity::High); + assert_eq!( + f.title, + "Debugging was enabled on the app which makes it easier for reverse engineers to hook a debugger to it" + ); + assert!(f.description.contains("OWASP MASVS: code-2")); + assert_eq!( + f.rule_id.as_deref(), + Some("android_manifest_debugging_enabled") + ); + } + + #[test] + fn a_setting_key_is_read_only_from_a_comparison() { + assert_eq!( + setting_key("android:debuggable=true"), + Some("android:debuggable") + ); + assert_eq!( + setting_key("android:minSdkVersion<29"), + Some("android:minSdkVersion") + ); + assert_eq!( + setting_key("NSAllowsArbitraryLoads=true"), + Some("NSAllowsArbitraryLoads") + ); + assert_eq!(setting_key("Activity exported, targetSdk<29"), None); + assert_eq!(setting_key(""), None); + } + + #[test] + fn cwe_ids_are_normalised() { + assert_eq!(normalise_cwe("cwe-489").as_deref(), Some("CWE-489")); + assert_eq!( + normalise_cwe("CWE-327: Use of a Broken or Risky Cryptographic Algorithm").as_deref(), + Some("CWE-327") + ); + assert_eq!(normalise_cwe(""), None); + assert_eq!(normalise_cwe("n/a"), None); + } + + #[test] + fn each_platform_present_gets_its_own_run() { + let platforms = |l: &[&str]| { + let langs: Vec = l.iter().map(|s| s.to_string()).collect(); + MobsfscanScanner::for_languages(&langs, &[]).map(|s| s.platforms) + }; + assert_eq!(platforms(&["kotlin"]), Some(vec!["android"])); + assert_eq!(platforms(&["c", "objc"]), Some(vec!["ios"])); + // A React Native or Flutter app: both, or the iOS rules never run. + assert_eq!( + platforms(&["java", "javascript", "swift"]), + Some(vec!["android", "ios"]) + ); + assert_eq!(platforms(&["python", "c"]), None); + } + + #[test] + fn the_config_anchors_every_skipped_directory() { + let scanner = + MobsfscanScanner::for_languages(&["swift".to_string()], &["Vendor/SDK".to_string()]) + .expect("scanner"); + let config = scanner.config(); + assert!(config.starts_with("---\n- ignore-paths:\n")); + assert!(config.contains(" - \"/Pods/\"\n")); + assert!(config.contains(" - \"/Vendor/SDK/\"\n")); + assert!(!config.contains("spec")); + } +} diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index d15b675..e639577 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -12,6 +12,7 @@ mod graph_build; mod issue_creation; pub mod languages; pub mod lint; +pub mod mobsfscan; pub mod nvd_cpe; pub mod orchestrator; pub mod patterns; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 447599b..38a0cbb 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -15,6 +15,7 @@ use crate::pipeline::cve::CveScanner; use crate::pipeline::git::GitOps; use crate::pipeline::gitleaks::GitleaksScanner; use crate::pipeline::lint::LintScanner; +use crate::pipeline::mobsfscan::MobsfscanScanner; use crate::pipeline::patterns::{GdprPatternScanner, OAuthPatternScanner}; use crate::pipeline::plan::build_scan_plan; use crate::pipeline::repo_view::RepoView; @@ -235,6 +236,33 @@ impl PipelineOrchestrator { } } } + // Android and iOS code and settings: mobsfscan has the rules for Java, + // Kotlin, Swift and Objective-C that our own pack does not. + if let Some(mobsfscan) = MobsfscanScanner::for_languages(&languages, &vendor) { + match mobsfscan + .scan(&repo_path, &repo_id) + .instrument(tracing::info_span!("stage_sast_mobile")) + .await + { + Ok(output) => { + run_findings.completed("mobsfscan"); + all_findings.extend(output.findings); + } + Err(e) => { + tracing::warn!("[{repo_id}] mobsfscan failed: {e}"); + self.skip_stage( + scan_run_id, + SkippedStage::new( + "sast_mobile", + SkipCode::ToolFailed, + "mobsfscan did not complete", + ) + .about("mobsfscan"), + ) + .await; + } + } + } run_findings.save_new(&self.db, &mut all_findings).await?; // Stage 2: SBOM Generation diff --git a/compliance-agent/src/pipeline/source_text.rs b/compliance-agent/src/pipeline/source_text.rs index 3306b78..4d837ae 100644 --- a/compliance-agent/src/pipeline/source_text.rs +++ b/compliance-agent/src/pipeline/source_text.rs @@ -19,12 +19,11 @@ pub fn relative_path(root: &Path, path: &str) -> String { rel.to_string_lossy().replace('\\', "/") } -/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at -/// [`MAX_SNIPPET_LINES`]. `None` when the file is unreadable or the path would -/// leave `root`. -pub fn read_lines(root: &Path, rel: &str, start: u32, end: u32) -> Option { +/// The whole text of `root/rel`. `None` when the file is unreadable or the +/// path would leave `root`: scanner output is not trusted to stay inside the +/// tree. +pub fn read_text(root: &Path, rel: &str) -> Option { let rel_path = Path::new(rel); - // Scanner output is not trusted to stay inside the tree. if rel_path.is_absolute() || rel_path .components() @@ -32,9 +31,16 @@ pub fn read_lines(root: &Path, rel: &str, start: u32, end: u32) -> Option Option { let start = start.max(1); let end = end.max(start).min(start + MAX_SNIPPET_LINES - 1); - let text = std::fs::read_to_string(root.join(rel_path)).ok()?; + let text = read_text(root, rel)?; let lines: Vec<&str> = text .lines() .skip(start as usize - 1) diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index fa26968..70c33f6 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -423,6 +423,10 @@ pub mod scans { de: "C/C++-Analyse (cppcheck)", en: "C/C++ analysis (cppcheck)", }, + "sast_mobile" => Text { + de: "Mobile-App-Analyse (mobsfscan)", + en: "Mobile app analysis (mobsfscan)", + }, "sast_vendor_code" => Text { de: "Herstellercode (HAL, CMSIS, Drittanbieter)", en: "Vendor code (HAL, CMSIS, third party)", diff --git a/control-map/data/cra_control_map.json b/control-map/data/cra_control_map.json index cc0fc64..89de6f4 100644 --- a/control-map/data/cra_control_map.json +++ b/control-map/data/cra_control_map.json @@ -21,6 +21,22 @@ "cra-ai-1-tls-verify-disabled", "cra-ai-1-cors-wildcard" ] + }, + { + "tool": "mobsfscan", + "scan_type": "sast", + "languages": [ + "java", + "kotlin" + ], + "cwe": [ + "CWE-489", + "CWE-1104", + "CWE-276", + "CWE-1021", + "CWE-284" + ], + "rules": [] } ], "note": null, @@ -97,6 +113,23 @@ "cra-ai-7-weak-password-hash" ], "check": "Passwords must be stored with a slow, salted password hash (bcrypt, scrypt, Argon2id, PBKDF2); a fast or unsalted hash (MD5, SHA-1, SHA-256) of a password violates it." + }, + { + "tool": "mobsfscan", + "scan_type": "sast", + "languages": [ + "java", + "kotlin", + "swift", + "objc" + ], + "cwe": [ + "CWE-287", + "CWE-305", + "CWE-303" + ], + "rules": [], + "check": "Passwords must be stored with a slow, salted password hash (bcrypt, scrypt, Argon2id, PBKDF2); a fast or unsalted hash (MD5, SHA-1, SHA-256) of a password violates it." } ], "note": null, @@ -131,6 +164,19 @@ "cra-ai-8-c-hardcoded-credential" ], "check": "No credential (password, key, token) may be written into the product's source, as a variable or a #define: every device would ship the same secret. A placeholder or an empty value does not violate it." + }, + { + "tool": "mobsfscan", + "scan_type": "sast", + "languages": [ + "java", + "kotlin" + ], + "cwe": [ + "CWE-798" + ], + "rules": [], + "check": "No credential (password, key, token) may be written into the product's source or configuration: every installation would ship the same secret." } ], "note": null, @@ -147,6 +193,19 @@ "cwe": [], "rules": [], "check": "Credentials must not be kept in plain text in the source or configuration; a real secret committed to the repository violates it." + }, + { + "tool": "mobsfscan", + "scan_type": "sast", + "languages": [ + "swift", + "objc" + ], + "cwe": [ + "CWE-312" + ], + "rules": [], + "check": "Credentials must not be kept in plain text in the source or configuration; a real secret committed to the repository violates it." } ], "note": null, @@ -250,6 +309,26 @@ "cra-ai-13-c-broken-hash-or-cipher" ], "check": "Data must not be protected with a broken algorithm: MD5, SHA-1 or DES used for integrity or confidentiality violates it. A non-security use (a cache key, a checksum of public data) does not." + }, + { + "tool": "mobsfscan", + "scan_type": "sast", + "languages": [ + "java", + "kotlin", + "swift", + "objc" + ], + "cwe": [ + "CWE-327", + "CWE-326", + "CWE-780", + "CWE-649", + "CWE-329", + "CWE-1204" + ], + "rules": [], + "check": "Data must not be protected with a broken algorithm: MD5, SHA-1 or DES used for integrity or confidentiality violates it. A non-security use (a cache key, a checksum of public data) does not." } ], "note": null, @@ -273,6 +352,24 @@ "cra-ai-14-node-weak-cipher" ], "check": "Stored data must be encrypted with a current cipher and mode (AES-GCM, ChaCha20-Poly1305); DES, RC4, ECB mode or a hard-coded key violates it." + }, + { + "tool": "mobsfscan", + "scan_type": "sast", + "languages": [ + "java", + "kotlin", + "swift", + "objc" + ], + "cwe": [ + "CWE-921", + "CWE-311", + "CWE-312", + "CWE-532" + ], + "rules": [], + "check": "Stored data must be encrypted with a current cipher and mode (AES-GCM, ChaCha20-Poly1305); DES, RC4, ECB mode or a hard-coded key violates it." } ], "note": null, @@ -296,6 +393,23 @@ "cra-ai-15-node-cleartext-http" ], "check": "Network traffic must use TLS 1.2 or newer with certificate checking; plain HTTP for sensitive data, disabled verification or old protocol versions violate it." + }, + { + "tool": "mobsfscan", + "scan_type": "sast", + "languages": [ + "java", + "kotlin", + "swift", + "objc" + ], + "cwe": [ + "CWE-295", + "CWE-319", + "CWE-757" + ], + "rules": [], + "check": "Network traffic must use TLS 1.2 or newer with certificate checking; plain HTTP for sensitive data, disabled verification or old protocol versions violate it." } ], "note": null, @@ -328,6 +442,21 @@ "cra-ai-16-c-predictable-random" ], "check": "Keys, nonces, tokens and session ids must come from a cryptographically secure random source (the MCU's hardware RNG, a DRBG); rand() used for them violates it." + }, + { + "tool": "mobsfscan", + "scan_type": "sast", + "languages": [ + "java", + "kotlin", + "swift" + ], + "cwe": [ + "CWE-330", + "CWE-321" + ], + "rules": [], + "check": "Keys must not be committed to the source: a private key or secret key in the repository violates it." } ], "note": null, @@ -415,6 +544,27 @@ ], "rules": [], "check": "The code must be free of memory-safety defects: out-of-bounds access, use of uninitialised memory, leaks, null dereferences and similar defects violate it." + }, + { + "tool": "mobsfscan", + "scan_type": "sast", + "languages": [ + "java", + "kotlin", + "swift", + "objc" + ], + "cwe": [ + "CWE-78", + "CWE-611", + "CWE-502", + "CWE-749", + "CWE-95", + "CWE-73", + "CWE-676" + ], + "rules": [], + "check": "Untrusted input must not reach a shell, an SQL statement or an HTML response unencoded, and the code must not write past a buffer or let input control a format string: a command or query built from a variable, request input echoed into a response, strcpy, strcat, sprintf, gets, scanf(\"%s\") or a non-literal format argument violates it." } ], "note": null, diff --git a/docker/pruefwerk_mobsfscan.py b/docker/pruefwerk_mobsfscan.py new file mode 100644 index 0000000..02650df --- /dev/null +++ b/docker/pruefwerk_mobsfscan.py @@ -0,0 +1,18 @@ +"""Run mobsfscan without its default path ignores. + +libsast skips every file whose path merely contains an ignored name, and +mobsfscan's defaults include 'spec' and 'fixtures', so a customer's code under +`inspection/` or `specs/` would silently go unscanned. Prüfwerk passes its own +ignores with `-c`, anchored as `/name/`. mobsfscan itself is used unchanged +(LGPL-3.0); this file only adjusts its settings before starting it. +""" + +import sys + +import mobsfscan.settings as settings + +settings.IGNORE_PATHS.clear() + +from mobsfscan.__main__ import main # noqa: E402 + +sys.exit(main()) diff --git a/docs/features/control-mapping.md b/docs/features/control-mapping.md index 77ed8ac..a7a7830 100644 --- a/docs/features/control-mapping.md +++ b/docs/features/control-mapping.md @@ -27,6 +27,7 @@ For the **CRA** framework (40 controls) the split is **21 covered · 0 needs_too - **Custom semgrep detectors**, shipped in the binary and matched back to controls **by rule id** so a broad CWE can't over-attribute: - for Python and JavaScript/TypeScript: `cra-ai-1`, `7`, `10`, `14` (secure-by-default, weak password hashing, insecure session cookies, weak data-at-rest ciphers), `cra-ai-20` (shell commands and SQL built from variables, request input echoed into a response), `cra-ai-8` (hard-coded credentials, Python) and `cra-ai-15` (plain `http://` requests); - for C and C++ firmware: `cra-ai-8`, `13`, `16`, `20` (hard-coded credentials including `#define` macros, broken hash/cipher, `rand()`, unbounded string functions and non-literal format strings), next to cppcheck for memory safety. +- **mobsfscan** for Android and iOS apps, bound **by CWE** (a mobsfscan binding only ever attaches mobsfscan findings): `cra-ai-1` (debuggable, exported components, outdated `minSdkVersion`), `7`, `8`, `9`, `13`, `14`, `15` (cleartext, TLS, App Transport Security), `16` and `20`. Each binding lists only the languages mobsfscan has rules for under those CWEs, so `cra-ai-1` covers Java and Kotlin (its manifest checks) but not Swift. - **8 grounded surface checks** (`cra-ai-6`, `11`, `12`, `24`, `27`, `28`, `29`, `30`): the absence-based controls (no rate limiting, no security logging, no update-signature check…) that have no syntactic pattern. - **Marked not_code_checkable** (`cra-ai-2`, `3`, `4`, `5`, among the 19): minimal attack surface, secure architecture, least privilege, tamper protection. @@ -34,7 +35,7 @@ For the **CRA** framework (40 controls) the split is **21 covered · 0 needs_too Each binding in the control map names the **languages** its rules run on (`languages`, empty for language-independent tools such as gitleaks, syft and osv). A test keeps these in step with the rule pack. Each scan run records the source languages it saw outside vendor code (`ScanRun.languages`). -The CRA status calls a covered control **"no violation found"** only when one of its bindings applies to those languages *and* no tool it relies on failed in that scan (a skipped `sast`, `sast_c_cpp` or `cve_lookup` stage). Otherwise the control is **not assessed**, with the reason: not scanned yet, no rule for the languages found, a tool that did not complete, or languages unknown (a run from before they were recorded). A C-only firmware repo therefore never reads "no violation found" for controls only Python rules check (#368, #387). +The CRA status calls a covered control **"no violation found"** only when one of its bindings applies to those languages *and* no tool it relies on failed in that scan (a skipped `sast`, `sast_c_cpp`, `sast_mobile` or `cve_lookup` stage). Otherwise the control is **not assessed**, with the reason: not scanned yet, no rule for the languages found, a tool that did not complete, or languages unknown (a run from before they were recorded). A C-only firmware repo therefore never reads "no violation found" for controls only Python rules check (#368, #387). At scale, the **master-controls** corpus (breakpilot's deduped clusters, exported as OSCAL) currently provides **~2,882 code-checkable controls** (2,143 `network` + 739 `source_code`), matched semantically. diff --git a/docs/guide/scanning.md b/docs/guide/scanning.md index d1d899d..a87ff8d 100644 --- a/docs/guide/scanning.md +++ b/docs/guide/scanning.md @@ -18,7 +18,8 @@ names while the scan runs. - *Firmware analysieren* -- for firmware, lists the libraries and toolchain the build uses. 2. **Static code analysis** (*Statische Codeanalyse*) -- Semgrep with Prüfwerk's own rules (Python, JavaScript/TypeScript, C and C++; see - [Tools](/reference/tools)); for C and C++ also cppcheck, which follows values through the code + [Tools](/reference/tools)); for Android and iOS apps mobsfscan (code, + AndroidManifest and Info.plist); for C and C++ also cppcheck, which follows values through the code (out-of-bounds writes, uninitialised reads, null dereferences). Vendor and third-party code (HAL, CMSIS, vendored libraries) is left out of the code findings and listed under **Nicht ausgeführt**; it stays in the SBOM. diff --git a/docs/reference/tools.md b/docs/reference/tools.md index 61f086c..ca50e49 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -33,6 +33,32 @@ finds the defects that matter in firmware: out-of-bounds writes, uninitialised reads, null dereferences and leaks. It parses the code and never runs it. Its findings are **Codeanalyse (SAST)** findings with the tool name `cppcheck`. +## mobsfscan -- Android and iOS Apps + +[mobsfscan](https://github.com/MobSF/mobsfscan) (LGPL-3.0, used unchanged) runs +on trees with Java, Kotlin, Swift or Objective-C code. It checks the code and +the app settings: + +- **AndroidManifest.xml:** `debuggable`, `allowBackup`, cleartext traffic, an + outdated `minSdkVersion`, exported components, task hijacking. +- **Info.plist:** App Transport Security exceptions (`NSAllowsArbitraryLoads`). +- **Code:** WebViews with a JavaScript bridge or ignored TLS errors, weak hashes + and ciphers, ECB mode and static IVs, `java.util.Random` for security, + world-readable storage, trust-all certificate handling, command and SQL + injection, unsafe deserialisation, sensitive data in logs. + +Each finding carries its CWE and the OWASP MASVS requirement. mobsfscan runs +once with the Android and once with the iOS rules when a repository holds both +apps (React Native, Flutter); on its own it would check such a repository as +Android only. It runs on the same Semgrep engine with metrics off, never reads +a `.mobsf` file from your repository, and skips `Pods/`, `build/`, `.gradle/`, +`DerivedData/`, `Carthage/` and `node_modules/`. Its findings are +**Codeanalyse (SAST)** findings with the tool name `mobsfscan`. + +Not reported: the app-wide "missing protection" hints (no certificate pinning, +no root or jailbreak detection, no screenshot protection). They name no place in +the code and are heuristics. Dart code (Flutter) has no rules yet. + ## Vendor Code Exclusion Firmware projects carry their silicon vendor's SDK (HAL, CMSIS, board support) diff --git a/fixtures/nightly/baselines/mobile-android-insecure.json b/fixtures/nightly/baselines/mobile-android-insecure.json new file mode 100644 index 0000000..956bb1b --- /dev/null +++ b/fixtures/nightly/baselines/mobile-android-insecure.json @@ -0,0 +1,19 @@ +{ + "scan_status": "completed", + "skipped_stages": [ + "sbom_dependencies" + ], + "sbom": [], + "findings": [ + "mobsfscan:android_kotlin_md5 MainActivity.kt:12", + "mobsfscan:android_kotlin_webview MainActivity.kt:9", + "mobsfscan:android_manifest_allow_backup AndroidManifest.xml:4", + "mobsfscan:android_manifest_debugging_enabled AndroidManifest.xml:4", + "mobsfscan:android_manifest_insecure_minsdk_error AndroidManifest.xml:3", + "mobsfscan:android_manifest_usescleartext AndroidManifest.xml:4", + "mobsfscan:android_task_hijacking2 AndroidManifest.xml:1", + "mobsfscan:java_insecure_random Store.java:5", + "mobsfscan:world_readable Store.java:9" + ], + "cves": [] +} diff --git a/fixtures/nightly/baselines/mobile-ios-insecure.json b/fixtures/nightly/baselines/mobile-ios-insecure.json new file mode 100644 index 0000000..94657e9 --- /dev/null +++ b/fixtures/nightly/baselines/mobile-ios-insecure.json @@ -0,0 +1,11 @@ +{ + "scan_status": "completed", + "skipped_stages": [], + "sbom": [], + "findings": [ + "mobsfscan:ios_app_logging PumpLink.m:8", + "mobsfscan:ios_ats_arbitrary_loads Info.plist:6", + "mobsfscan:ios_weak_hash Store.swift:10" + ], + "cves": [] +} diff --git a/fixtures/nightly/baselines/mobile-react-native.json b/fixtures/nightly/baselines/mobile-react-native.json index 6bedbdd..a9e9280 100644 --- a/fixtures/nightly/baselines/mobile-react-native.json +++ b/fixtures/nightly/baselines/mobile-react-native.json @@ -9,7 +9,10 @@ "npm:express@4.17.1", "npm:lodash@4.17.20" ], - "findings": [], + "findings": [ + "mobsfscan:ios_sha1_collision Checksum.swift:8", + "mobsfscan:java_insecure_random MainActivity.java:3" + ], "cves": [ "GHSA-29mw-wpgm-hmr9", "GHSA-35jh-r3h4-6jhm", diff --git a/fixtures/nightly/mobile/README.md b/fixtures/nightly/mobile/README.md index ce27a4f..01dd0b0 100644 --- a/fixtures/nightly/mobile/README.md +++ b/fixtures/nightly/mobile/README.md @@ -14,5 +14,13 @@ as a source archive. They prove that no mobile app ends with "0 packages, | `flutter` | `pubspec.lock` (dio 3.0.10); the Android host app is unlocked | the Dart packages; a recorded `sbom_dependencies` skip | | `react-native` | `package-lock.json`; neither `ios/Podfile` nor the Gradle app is locked | the npm packages; a recorded `sbom_dependencies` skip | -The code files only make each tree look like the app it stands for; they plant -no SAST findings yet (mobile rules are #437). +| `android-insecure` | nothing (no Gradle lock) | mobsfscan: manifest (debuggable, backups, cleartext, minSdk), Kotlin (JavaScript bridge, MD5), Java under `inspection/` (world-readable, `Random`) | +| `ios-insecure` | nothing | mobsfscan: ATS off in `Info.plist`, `CC_MD5` in Swift, `NSLog` in Objective-C | + +The other fixtures' code only makes each tree look like the app it stands for +and must stay free of findings, except React Native, whose Java and Swift files +each plant one flaw: both must be found, which proves mobsfscan runs with the +Android and the iOS rules on a repository holding both apps. + +The Java file under `inspection/` guards a mobsfscan default: libsast skips any +path that merely contains `spec`, which Prüfwerk switches off. diff --git a/fixtures/nightly/mobile/android-insecure/app/build.gradle.kts b/fixtures/nightly/mobile/android-insecure/app/build.gradle.kts new file mode 100644 index 0000000..7cbafc8 --- /dev/null +++ b/fixtures/nightly/mobile/android-insecure/app/build.gradle.kts @@ -0,0 +1 @@ +plugins { id("com.android.application") } diff --git a/fixtures/nightly/mobile/android-insecure/app/src/main/AndroidManifest.xml b/fixtures/nightly/mobile/android-insecure/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..9e4b62f --- /dev/null +++ b/fixtures/nightly/mobile/android-insecure/app/src/main/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/fixtures/nightly/mobile/android-insecure/app/src/main/java/com/example/pump/MainActivity.kt b/fixtures/nightly/mobile/android-insecure/app/src/main/java/com/example/pump/MainActivity.kt new file mode 100644 index 0000000..d8ed44c --- /dev/null +++ b/fixtures/nightly/mobile/android-insecure/app/src/main/java/com/example/pump/MainActivity.kt @@ -0,0 +1,13 @@ +package com.example.pump + +import android.webkit.WebView +import java.security.MessageDigest + +class MainActivity { + fun show(web: WebView, bridge: Any) { + web.settings.javaScriptEnabled = true + web.addJavascriptInterface(bridge, "pump") + web.loadUrl("http://gateway.example.com/panel") + } + fun hash(pin: String): ByteArray = MessageDigest.getInstance("MD5").digest(pin.toByteArray()) +} diff --git a/fixtures/nightly/mobile/android-insecure/app/src/main/java/com/example/pump/inspection/Store.java b/fixtures/nightly/mobile/android-insecure/app/src/main/java/com/example/pump/inspection/Store.java new file mode 100644 index 0000000..30a2557 --- /dev/null +++ b/fixtures/nightly/mobile/android-insecure/app/src/main/java/com/example/pump/inspection/Store.java @@ -0,0 +1,13 @@ +package com.example.pump.inspection; + +import android.content.Context; +import android.content.SharedPreferences; +import java.util.Random; + +public class Store { + public void save(Context ctx, String password) { + SharedPreferences p = ctx.getSharedPreferences("pump", Context.MODE_WORLD_READABLE); + p.edit().putString("password", password).apply(); + int token = new Random().nextInt(); + } +} diff --git a/fixtures/nightly/mobile/android-insecure/settings.gradle.kts b/fixtures/nightly/mobile/android-insecure/settings.gradle.kts new file mode 100644 index 0000000..7c1a18b --- /dev/null +++ b/fixtures/nightly/mobile/android-insecure/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "pump-app" +include(":app") diff --git a/fixtures/nightly/mobile/ios-insecure/PumpApp/Info.plist b/fixtures/nightly/mobile/ios-insecure/PumpApp/Info.plist new file mode 100644 index 0000000..3b1a89b --- /dev/null +++ b/fixtures/nightly/mobile/ios-insecure/PumpApp/Info.plist @@ -0,0 +1,8 @@ + + + + + NSAppTransportSecurity + NSAllowsArbitraryLoads + + diff --git a/fixtures/nightly/mobile/ios-insecure/PumpApp/PumpLink.m b/fixtures/nightly/mobile/ios-insecure/PumpApp/PumpLink.m new file mode 100644 index 0000000..98d2a5a --- /dev/null +++ b/fixtures/nightly/mobile/ios-insecure/PumpApp/PumpLink.m @@ -0,0 +1,12 @@ +#import + +// Talks to the pump gateway. +@implementation PumpLink + +- (NSString *)gatewayLogin { + NSString *password = @"pump-admin-2024"; + NSLog(@"logging in to the gateway"); + return password; +} + +@end diff --git a/fixtures/nightly/mobile/ios-insecure/PumpApp/Store.swift b/fixtures/nightly/mobile/ios-insecure/PumpApp/Store.swift new file mode 100644 index 0000000..fa0b274 --- /dev/null +++ b/fixtures/nightly/mobile/ios-insecure/PumpApp/Store.swift @@ -0,0 +1,12 @@ +import Foundation +import CommonCrypto + +final class Store { + func save(password: String) { + UserDefaults.standard.set(password, forKey: "password") + } + func digest(_ data: Data) { + var out = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) + data.withUnsafeBytes { _ = CC_MD5($0.baseAddress, CC_LONG(data.count), &out) } + } +} diff --git a/fixtures/nightly/mobile/react-native/android/app/src/main/java/com/pumpapp/MainActivity.java b/fixtures/nightly/mobile/react-native/android/app/src/main/java/com/pumpapp/MainActivity.java new file mode 100644 index 0000000..dce9593 --- /dev/null +++ b/fixtures/nightly/mobile/react-native/android/app/src/main/java/com/pumpapp/MainActivity.java @@ -0,0 +1,10 @@ +package com.pumpapp; + +import java.util.Random; + +public class MainActivity { + // Session ids from a predictable generator. + public int sessionId() { + return new Random().nextInt(); + } +} diff --git a/fixtures/nightly/mobile/react-native/ios/PumpApp/Checksum.swift b/fixtures/nightly/mobile/react-native/ios/PumpApp/Checksum.swift new file mode 100644 index 0000000..9cb340b --- /dev/null +++ b/fixtures/nightly/mobile/react-native/ios/PumpApp/Checksum.swift @@ -0,0 +1,11 @@ +import CommonCrypto +import Foundation + +/// Checks a firmware image before it is sent to the pump. +enum Checksum { + static func digest(_ data: Data) -> [UInt8] { + var out = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) + data.withUnsafeBytes { _ = CC_SHA1($0.baseAddress, CC_LONG(data.count), &out) } + return out + } +} diff --git a/fixtures/nightly/targets.json b/fixtures/nightly/targets.json index 87d116e..0e8de72 100644 --- a/fixtures/nightly/targets.json +++ b/fixtures/nightly/targets.json @@ -643,7 +643,7 @@ "key": "mobile-react-native", "name": "React Native app", "target_type": "android_app", - "description": "Uploaded as a source archive. The JavaScript side is locked (package-lock.json), but neither ios/Podfile nor android/app/build.gradle is: the run lists the npm packages and records both gaps (#434).", + "description": "Uploaded as a source archive. The JavaScript side is locked (package-lock.json), but neither ios/Podfile nor android/app/build.gradle is: the run lists the npm packages and records both gaps (#434). Its Java and Swift sources each plant one flaw, so mobsfscan must run with the Android and the iOS rules (its auto mode picks Android only).", "artifacts": [ { "kind": "source_archive", @@ -651,7 +651,63 @@ } ], "expect": { - "min_sbom_components": 3 + "min_sbom_components": 3, + "sast_rule_ids": [ + "java_insecure_random", + "ios_sha1_collision" + ] + } + }, + { + "key": "mobile-android-insecure", + "name": "Android · planted flaws", + "target_type": "android_app", + "description": "Uploaded as a source archive. A debuggable manifest with backups, cleartext traffic and an old minSdk; Kotlin with a JavaScript bridge and MD5; Java with a world-readable store and java.util.Random, placed under inspection/ so a path containing 'spec' is still scanned. mobsfscan must report each.", + "artifacts": [ + { + "kind": "source_archive", + "upload": "fixtures/nightly/mobile/android-insecure" + } + ], + "expect": { + "sast_rule_ids": [ + "android_manifest_debugging_enabled", + "android_manifest_allow_backup", + "android_manifest_usescleartext", + "android_kotlin_webview", + "android_kotlin_md5", + "world_readable", + "java_insecure_random" + ], + "cwes": [ + "CWE-489", + "CWE-319", + "CWE-749", + "CWE-327" + ] + } + }, + { + "key": "mobile-ios-insecure", + "name": "iOS · planted flaws", + "target_type": "ios_app", + "description": "Uploaded as a source archive. Info.plist switches App Transport Security off (NSAllowsArbitraryLoads), Swift hashes with CC_MD5, Objective-C logs with NSLog. mobsfscan must report each.", + "artifacts": [ + { + "kind": "source_archive", + "upload": "fixtures/nightly/mobile/ios-insecure" + } + ], + "expect": { + "sast_rule_ids": [ + "ios_ats_arbitrary_loads", + "ios_weak_hash", + "ios_app_logging" + ], + "cwes": [ + "CWE-319", + "CWE-327" + ] } } ]