From 19d38a31027af86a835d4d0896d6a8ea230bd078 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:16:46 +0200 Subject: [PATCH] feat(ios): secrets in UserDefaults, URL schemes and permissions of iOS apps iOS readiness, story 2 (static checks). mobsfscan already covers ATS, Keychain accessibility, weak hashes/ciphers, TLS and web views; this adds what it does not. - Own semgrep rules in new packs (rules/cra_semgrep_swift.yaml, rules/cra_semgrep_objc.yaml, both in RULE_PACKS): cra-ai-14-swift-secret-in-userdefaults (UserDefaults.standard or a suite, directly or through a local), cra-ai-14-swift-secret-in-appstorage (@AppStorage) and cra-ai-14-objc-secret-in-userdefaults (a regex rule: semgrep has no Objective-C parser). A key or value naming a password, token, key, credential or session id, never a literal flag or number. Test cases beside them (semgrep --test: 20/20). Mapped to cra-ai-14; ids come out bare through #463's bare_rule_id, which a test pins. - pipeline/ios_config.rs (scanner ios-config, stage 4): every Info.plist (Apple's DOCTYPE allowed) and the pbxproj INFOPLIST_KEY_* settings, outside Pods/Carthage/build: - ios-custom-url-scheme (Low, CWE-939): CFBundleURLTypes schemes; - ios-sensitive-permission (Info, CWE-250): one per access granted (location, camera, microphone, contacts, photos, calendars, Bluetooth, local network, health, motion, speech, tracking); - ios-permission-without-usage-string (Low): a request in Swift or Objective-C no usage string covers, at the call; judged only when the tree holds a plist or Xcode project (not an Expo app.json). The first two are an inventory, bound to no control: cra-ai-2 and cra-ai-17 stay not code-checkable. - Dashboard label "iOS-App-Einstellungen"; docs (scanning, tools). - Nightly fixture mobile/ios-app-settings (all six findings); the ios-insecure baseline gains the password Store.swift keeps in UserDefaults, a true positive mobsfscan missed. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/rules/cra_semgrep_objc.m | 15 + compliance-agent/rules/cra_semgrep_objc.yaml | 16 + .../rules/cra_semgrep_swift.swift | 31 + compliance-agent/rules/cra_semgrep_swift.yaml | 72 ++ compliance-agent/src/pipeline/ios_config.rs | 617 ++++++++++++++++++ compliance-agent/src/pipeline/mod.rs | 1 + compliance-agent/src/pipeline/orchestrator.rs | 10 + compliance-agent/src/pipeline/semgrep.rs | 15 + compliance-dashboard/src/i18n/texts.rs | 4 + control-map/data/cra_control_map.json | 16 + docs/guide/scanning.md | 7 +- docs/reference/tools.md | 23 + .../baselines/mobile-ios-app-settings.json | 14 + .../baselines/mobile-ios-insecure.json | 3 +- fixtures/nightly/mobile/README.md | 3 +- .../ios-app-settings/PumpLink/Info.plist | 23 + .../ios-app-settings/PumpLink/LegacyLogin.m | 5 + .../ios-app-settings/PumpLink/Session.swift | 15 + fixtures/nightly/targets.json | 21 + 19 files changed, 906 insertions(+), 5 deletions(-) create mode 100644 compliance-agent/rules/cra_semgrep_objc.m create mode 100644 compliance-agent/rules/cra_semgrep_objc.yaml create mode 100644 compliance-agent/rules/cra_semgrep_swift.swift create mode 100644 compliance-agent/rules/cra_semgrep_swift.yaml create mode 100644 compliance-agent/src/pipeline/ios_config.rs create mode 100644 fixtures/nightly/baselines/mobile-ios-app-settings.json create mode 100644 fixtures/nightly/mobile/ios-app-settings/PumpLink/Info.plist create mode 100644 fixtures/nightly/mobile/ios-app-settings/PumpLink/LegacyLogin.m create mode 100644 fixtures/nightly/mobile/ios-app-settings/PumpLink/Session.swift diff --git a/compliance-agent/rules/cra_semgrep_objc.m b/compliance-agent/rules/cra_semgrep_objc.m new file mode 100644 index 0000000..d0c3eae --- /dev/null +++ b/compliance-agent/rules/cra_semgrep_objc.m @@ -0,0 +1,15 @@ +// Test cases for cra_semgrep_objc.yaml: `semgrep --test compliance-agent/rules`. +// Each `ruleid:` line must be found by that rule; each `ok:` line must not. +#import + +void storeLogin(NSString *password, NSString *name) { + NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; + // ruleid: cra-ai-14-objc-secret-in-userdefaults + [[NSUserDefaults standardUserDefaults] setObject:password forKey:@"pumpPassword"]; + // ruleid: cra-ai-14-objc-secret-in-userdefaults + [userDefaults setValue:name forKey:@"auth_token"]; + // ok: cra-ai-14-objc-secret-in-userdefaults + [userDefaults setObject:name forKey:@"lastUser"]; + // ok: cra-ai-14-objc-secret-in-userdefaults + [cache setObject:password forKey:@"pumpPassword"]; +} diff --git a/compliance-agent/rules/cra_semgrep_objc.yaml b/compliance-agent/rules/cra_semgrep_objc.yaml new file mode 100644 index 0000000..0d91cbc --- /dev/null +++ b/compliance-agent/rules/cra_semgrep_objc.yaml @@ -0,0 +1,16 @@ +# Prüfwerk's own semgrep rules for Objective-C (iOS apps), as regex patterns: +# semgrep has no Objective-C parser. Same conventions and provenance as +# cra_semgrep_swift.yaml, whose Swift rules these mirror. +# Test cases: cra_semgrep_objc.m (`semgrep --test compliance-agent/rules`). +rules: + # --- cra-ai-14: data at rest ------------------------------------------------- + - id: cra-ai-14-objc-secret-in-userdefaults + languages: [regex] + severity: WARNING + message: A password, token or key is stored in NSUserDefaults, an unencrypted plist in the app container that backups and device extraction read (CWE-312). Store it in the Keychain (kSecClassGenericPassword, with a ThisDeviceOnly accessibility). + metadata: + cwe: ["CWE-312: Cleartext Storage of Sensitive Information"] + control: cra-ai-14 + paths: + include: ["*.m", "*.mm"] + pattern-regex: (?i)\[\s*(?:\[\s*NSUserDefaults\s+standardUserDefaults\s*\]|\[\s*\[\s*NSUserDefaults\s+alloc\s*\]\s*initWithSuiteName:[^\]]*\]|\w*defaults)\s+set(?:Object|Value):[^\]\n]*(?:passw|passcode|token|secret|api_?key|credential|private_?key|session_?id)[^\]\n]*\] diff --git a/compliance-agent/rules/cra_semgrep_swift.swift b/compliance-agent/rules/cra_semgrep_swift.swift new file mode 100644 index 0000000..830d874 --- /dev/null +++ b/compliance-agent/rules/cra_semgrep_swift.swift @@ -0,0 +1,31 @@ +// Test cases for cra_semgrep_swift.yaml: `semgrep --test compliance-agent/rules`. +// Each `ruleid:` line must be found by that rule; each `ok:` line must not. +import SwiftUI + +func storeLogin(password: String, authToken: String, name: String) { + // ruleid: cra-ai-14-swift-secret-in-userdefaults + UserDefaults.standard.set(password, forKey: "pump_password") + // ruleid: cra-ai-14-swift-secret-in-userdefaults + UserDefaults.standard.set(authToken, forKey: Keys.session) + // ruleid: cra-ai-14-swift-secret-in-userdefaults + UserDefaults(suiteName: "group.pump")?.set(authToken, forKey: "auth") + let defaults = UserDefaults.standard + // ruleid: cra-ai-14-swift-secret-in-userdefaults + defaults.set(name, forKey: "apiKey") + // ok: cra-ai-14-swift-secret-in-userdefaults + UserDefaults.standard.set(name, forKey: "lastUser") + // ok: cra-ai-14-swift-secret-in-userdefaults + UserDefaults.standard.set(true, forKey: "didShowPasswordHint") + // ok: cra-ai-14-swift-secret-in-userdefaults + cache.set(password, forKey: "pump_password") +} + +struct SettingsView: View { + // ruleid: cra-ai-14-swift-secret-in-appstorage + @AppStorage("refreshToken") var refreshToken: String = "" + // ruleid: cra-ai-14-swift-secret-in-appstorage + @AppStorage("pump.cfg") var apiKey = "" + // ok: cra-ai-14-swift-secret-in-appstorage + @AppStorage("units") var units: String = "metric" + var body: some View { Text(units) } +} diff --git a/compliance-agent/rules/cra_semgrep_swift.yaml b/compliance-agent/rules/cra_semgrep_swift.yaml new file mode 100644 index 0000000..2e31448 --- /dev/null +++ b/compliance-agent/rules/cra_semgrep_swift.yaml @@ -0,0 +1,72 @@ +# Prüfwerk's own semgrep rules for Swift (iOS apps; Objective-C is in +# cra_semgrep_objc.yaml). Written for Prüfwerk, not +# adapted from any third-party rule set (the Semgrep registry rules may not be +# used for a service offered to others). mobsfscan already covers ATS, the +# Keychain accessibility, weak hashes and ciphers, TLS and web views; these +# rules cover what it does not. +# Same conventions as cra_semgrep.yaml: each rule id is `cra-ai--`, +# keyed back to its control via the `control-map` LUT, with its CWE and +# control in the metadata. Keep patterns tight: a false positive that the +# judge refutes marks the whole finding a false positive. +# Test cases: cra_semgrep_swift.swift (`semgrep --test compliance-agent/rules`). +rules: + # --- cra-ai-14: data at rest ------------------------------------------------- + - id: cra-ai-14-swift-secret-in-userdefaults + languages: [swift] + severity: WARNING + message: A password, token or key is stored in UserDefaults, an unencrypted plist in the app container that backups and device extraction read (CWE-312). Store it in the Keychain (kSecClassGenericPassword, with a ThisDeviceOnly accessibility). + metadata: + cwe: ["CWE-312: Cleartext Storage of Sensitive Information"] + control: cra-ai-14 + patterns: + - pattern-either: + # The key names the secret ... + - patterns: + - pattern-either: &userdefaults-set + - pattern: 'UserDefaults.standard.set($V, forKey: $K)' + - pattern: 'UserDefaults(suiteName: $S)?.set($V, forKey: $K)' + - pattern: 'UserDefaults(suiteName: $S)!.set($V, forKey: $K)' + - patterns: + - pattern-either: + - pattern-inside: | + let $D = UserDefaults.standard + ... + - pattern-inside: | + let $D = UserDefaults(suiteName: $S) + ... + - pattern: '$D.set($V, forKey: $K)' + - metavariable-regex: + metavariable: $K + regex: &secret (?i).*(passw|passcode|token|secret|api_?key|credential|private_?key|session_?id) + # ... or the stored value does. + - patterns: + - pattern-either: *userdefaults-set + - metavariable-regex: + metavariable: $V + regex: *secret + # A flag or a count is not the secret, even if its key names one. + - metavariable-regex: + metavariable: $V + regex: ^(?!(true|false|nil|-?\d+(\.\d+)?|Date\(\))$) + - id: cra-ai-14-swift-secret-in-appstorage + languages: [swift] + severity: WARNING + message: A password, token or key is kept in @AppStorage, which stores it in UserDefaults, an unencrypted plist in the app container that backups and device extraction read (CWE-312). Store it in the Keychain instead. + metadata: + cwe: ["CWE-312: Cleartext Storage of Sensitive Information"] + control: cra-ai-14 + pattern-either: + - patterns: + - pattern-either: &appstorage + - pattern: | + @AppStorage($K) var $X: $T = $E + - pattern: | + @AppStorage($K) var $X = $E + - metavariable-regex: + metavariable: $K + regex: *secret + - patterns: + - pattern-either: *appstorage + - metavariable-regex: + metavariable: $X + regex: *secret diff --git a/compliance-agent/src/pipeline/ios_config.rs b/compliance-agent/src/pipeline/ios_config.rs new file mode 100644 index 0000000..ec23fa1 --- /dev/null +++ b/compliance-agent/src/pipeline/ios_config.rs @@ -0,0 +1,617 @@ +//! What an iOS app declares about itself, from its `Info.plist` files and the +//! `INFOPLIST_KEY_*` build settings Xcode generates them from: +//! +//! - **custom URL schemes** (`CFBundleURLTypes`): any app can register the same +//! scheme and receive the URLs meant for this one, and every URL opened +//! through it is untrusted input to the app; +//! - **sensitive permissions** (`NS…UsageDescription`): the personal data and +//! device access the app asks for, an inventory for the risk assessment; +//! - **permissions used without a usage string**: code that asks for camera, +//! location, contacts and the like while no plist explains why; iOS +//! terminates the app at that call. +//! +//! mobsfscan already reads App Transport Security from the same plists; it is +//! not repeated here. The first two are an inventory (Info, Low), not a CRA +//! violation in themselves, so the control map binds none of them: minimal +//! attack surface and data minimisation are judged in the design review. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use compliance_core::models::{ScanType, Severity}; +use compliance_core::traits::{ScanOutput, Scanner}; +use compliance_core::CoreError; + +use crate::pipeline::dotnet::config::{into_finding, Hit}; + +/// The scanner name of these findings. +pub const SCANNER: &str = "ios-config"; + +/// How deep plists and sources are looked for. +const MAX_DEPTH: usize = 10; + +/// Directories never searched: dependencies, build output, tool caches. +const SKIPPED_DIRS: &[&str] = &[ + ".git", + "build", + "DerivedData", + "node_modules", + "Pods", + "Carthage", + ".symlinks", +]; + +/// Source files larger than this are not searched for permission requests. +const MAX_SOURCE_BYTES: u64 = 2 * 1024 * 1024; + +/// A permission an app declares with a usage string. +struct Permission { + /// The `Info.plist` key. + key: &'static str, + /// What it grants, for the finding text. + grants: &'static str, +} + +/// The usage strings that name personal data or device access. +const SENSITIVE_PERMISSIONS: &[Permission] = &[ + Permission { + key: "NSLocationAlwaysAndWhenInUseUsageDescription", + grants: "the device location, also in the background", + }, + Permission { + key: "NSLocationAlwaysUsageDescription", + grants: "the device location, also in the background", + }, + Permission { + key: "NSLocationWhenInUseUsageDescription", + grants: "the device location while the app is in use", + }, + Permission { + key: "NSCameraUsageDescription", + grants: "the camera", + }, + Permission { + key: "NSMicrophoneUsageDescription", + grants: "the microphone", + }, + Permission { + key: "NSContactsUsageDescription", + grants: "the user's contacts", + }, + Permission { + key: "NSPhotoLibraryUsageDescription", + grants: "the user's photo library", + }, + Permission { + key: "NSCalendarsUsageDescription", + grants: "the user's calendars", + }, + Permission { + key: "NSCalendarsFullAccessUsageDescription", + grants: "the user's calendars", + }, + Permission { + key: "NSBluetoothAlwaysUsageDescription", + grants: "Bluetooth devices nearby", + }, + Permission { + key: "NSBluetoothPeripheralUsageDescription", + grants: "Bluetooth devices nearby", + }, + Permission { + key: "NSLocalNetworkUsageDescription", + grants: "devices on the local network", + }, + Permission { + key: "NSHealthShareUsageDescription", + grants: "the user's health data", + }, + Permission { + key: "NSHealthUpdateUsageDescription", + grants: "writing the user's health data", + }, + Permission { + key: "NSMotionUsageDescription", + grants: "motion and fitness data", + }, + Permission { + key: "NSSpeechRecognitionUsageDescription", + grants: "speech recognition of the user's voice", + }, + Permission { + key: "NSUserTrackingUsageDescription", + grants: "tracking the user across other companies' apps and websites", + }, +]; + +/// Code that asks iOS for a permission, and the usage strings any one of which +/// lets it. +struct Request { + /// Text in a Swift or Objective-C source that makes the request. + needles: &'static [&'static str], + /// The usage strings that cover it (any one). + keys: &'static [&'static str], + /// What it asks for, for the finding text. + what: &'static str, +} + +/// The permission requests looked for. Kept to calls that only exist to ask +/// for the permission, so a match is the request itself. +const REQUESTS: &[Request] = &[ + Request { + needles: &["requestAlwaysAuthorization"], + keys: &[ + "NSLocationAlwaysAndWhenInUseUsageDescription", + "NSLocationAlwaysUsageDescription", + ], + what: "the location in the background", + }, + Request { + needles: &["requestWhenInUseAuthorization"], + keys: &[ + "NSLocationWhenInUseUsageDescription", + "NSLocationAlwaysAndWhenInUseUsageDescription", + ], + what: "the location", + }, + Request { + needles: &[ + "requestAccess(for: .video", + "AVMediaTypeVideo completionHandler", + ], + keys: &["NSCameraUsageDescription"], + what: "the camera", + }, + Request { + needles: &[ + "requestAccess(for: .audio", + "requestRecordPermission", + "AVMediaTypeAudio completionHandler", + ], + keys: &["NSMicrophoneUsageDescription"], + what: "the microphone", + }, + Request { + needles: &["CNContactStore(", "[CNContactStore alloc]"], + keys: &["NSContactsUsageDescription"], + what: "the contacts", + }, + Request { + needles: &[ + "PHPhotoLibrary.requestAuthorization", + "PHPhotoLibrary requestAuthorization", + ], + keys: &["NSPhotoLibraryUsageDescription"], + what: "the photo library", + }, + Request { + needles: &[ + "CBCentralManager(", + "CBPeripheralManager(", + "[CBCentralManager alloc]", + "[CBPeripheralManager alloc]", + ], + keys: &[ + "NSBluetoothAlwaysUsageDescription", + "NSBluetoothPeripheralUsageDescription", + ], + what: "Bluetooth", + }, + Request { + needles: &["requestTrackingAuthorization"], + keys: &["NSUserTrackingUsageDescription"], + what: "tracking across apps", + }, +]; + +/// The checks over an iOS app's tree. +#[derive(Debug, Default)] +pub struct IosConfigScanner; + +impl Scanner for IosConfigScanner { + fn name(&self) -> &str { + SCANNER + } + + fn scan_type(&self) -> ScanType { + ScanType::Sast + } + + #[tracing::instrument(skip_all)] + async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result { + let root = repo_path.to_path_buf(); + let hits = tokio::task::spawn_blocking(move || check_tree(&root)) + .await + .map_err(|e| CoreError::Scanner { + scanner: SCANNER.to_string(), + source: Box::new(e), + })?; + Ok(ScanOutput { + findings: hits + .into_iter() + .map(|hit| into_finding(repo_path, repo_id, hit)) + .collect(), + sbom_entries: Vec::new(), + }) + } +} + +/// What one plist or project file declares: each key at its first line, and +/// the URL schemes with the line of `CFBundleURLTypes`. +#[derive(Debug, Default)] +struct Declared { + keys: BTreeMap, + url_schemes: Option<(Vec, u32)>, +} + +/// `path` relative to `root`, `/`-separated. +fn relative(root: &Path, path: &Path) -> String { + path.strip_prefix(root) + .unwrap_or(path) + .to_string_lossy() + .replace('\\', "/") +} + +/// Every check over the tree under `root`. +pub(crate) fn check_tree(root: &Path) -> Vec { + let mut declared: Vec<(String, Declared)> = Vec::new(); + let mut sources = Vec::new(); + let files = walkdir::WalkDir::new(root) + .min_depth(1) + .max_depth(MAX_DEPTH) + .sort_by_file_name() + .into_iter() + .filter_entry(|e| { + !(e.file_type().is_dir() + && SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref())) + }) + .filter_map(Result::ok) + .filter(|e| e.file_type().is_file()); + for entry in files { + let name = entry.file_name().to_string_lossy(); + let path = entry.path(); + if name.ends_with("Info.plist") { + if let Some(found) = std::fs::read_to_string(path) + .ok() + .and_then(|text| read_plist(&text)) + { + declared.push((relative(root, path), found)); + } + } else if name == "project.pbxproj" { + if let Ok(text) = std::fs::read_to_string(path) { + declared.push((relative(root, path), read_build_settings(&text))); + } + } else if [".swift", ".m", ".mm"] + .iter() + .any(|ext| name.ends_with(ext)) + && entry.metadata().is_ok_and(|m| m.len() <= MAX_SOURCE_BYTES) + { + sources.push(path.to_path_buf()); + } + } + let mut hits = Vec::new(); + for (path, found) in &declared { + hits.extend(declaration_hits(path, found)); + } + // Without any plist or project file the app's settings live elsewhere + // (an Expo app.json, a generated project): no request can be judged. + if !declared.is_empty() { + let keys: BTreeSet<&str> = declared + .iter() + .flat_map(|(_, found)| found.keys.keys().map(String::as_str)) + .collect(); + hits.extend(undeclared_requests(root, &sources, &keys)); + } + hits +} + +/// The 1-based line of byte `offset` in `text`. +fn line_at(text: &str, offset: usize) -> u32 { + let before = text.get(..offset).unwrap_or(text); + u32::try_from(before.matches('\n').count() + 1).unwrap_or(u32::MAX) +} + +/// The keys of an XML plist's top-level dictionary and its URL schemes. +/// `None` for a binary or malformed plist. +fn read_plist(text: &str) -> Option { + // Every plist Xcode writes starts with Apple's DOCTYPE. + let options = roxmltree::ParsingOptions { + allow_dtd: true, + ..roxmltree::ParsingOptions::default() + }; + let doc = roxmltree::Document::parse_with_options(text, options).ok()?; + let dict = doc + .root_element() + .children() + .find(|n| n.has_tag_name("dict"))?; + let mut found = Declared::default(); + let mut children = dict.children().filter(roxmltree::Node::is_element); + while let Some(key) = children.next() { + let value = children.next(); + if !key.has_tag_name("key") { + continue; + } + let name = key.text().unwrap_or_default().trim().to_string(); + let line = line_at(text, key.range().start); + if name == "CFBundleURLTypes" { + let schemes: Vec = value + .into_iter() + .flat_map(|v| v.descendants()) + .filter(|n| n.has_tag_name("key")) + .filter(|n| n.text().is_some_and(|t| t.trim() == "CFBundleURLSchemes")) + .filter_map(|n| n.next_sibling_element()) + .flat_map(|array| array.children()) + .filter(|n| n.has_tag_name("string")) + .filter_map(|n| n.text().map(|t| t.trim().to_string())) + .filter(|s| !s.is_empty()) + .collect(); + if !schemes.is_empty() { + found.url_schemes = Some((schemes, line)); + } + } + found.keys.entry(name).or_insert(line); + } + Some(found) +} + +/// The `INFOPLIST_KEY_ = …;` build settings of an Xcode project file, +/// from which Xcode generates the plist. +fn read_build_settings(text: &str) -> Declared { + let mut found = Declared::default(); + for (i, line) in text.lines().enumerate() { + let Some(rest) = line.trim().strip_prefix("INFOPLIST_KEY_") else { + continue; + }; + let key: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + let line_number = u32::try_from(i + 1).unwrap_or(u32::MAX); + found.keys.entry(key).or_insert(line_number); + } + found +} + +/// The URL-scheme and permission findings of one declaring file. +fn declaration_hits(path: &str, found: &Declared) -> Vec { + let mut hits = Vec::new(); + if let Some((schemes, line)) = &found.url_schemes { + hits.push(Hit { + scanner: SCANNER, + scan_type: ScanType::Sast, + rule_id: "ios-custom-url-scheme", + title: format!("Custom URL scheme: {}", schemes.join(", ")), + description: format!( + "{path} registers the URL scheme(s) {}. Any app can register the same scheme \ + and receive the URLs meant for this one (an OAuth redirect, a pairing link), \ + and every URL opened through it is untrusted input to the app.", + schemes.join(", ") + ), + remediation: "Prefer Universal Links (associated domains) for links into the app. \ + Validate every parameter of a URL opened through the scheme, never \ + act on it without the user's confirmation, and protect OAuth \ + redirects with PKCE.", + severity: Severity::Low, + cwe: "CWE-939", + path: path.to_string(), + line: Some(*line), + }); + } + // The location keys differ in what they grant; Bluetooth and calendars + // have an old and a new key for the same thing: one finding each. + let mut reported = BTreeSet::new(); + for permission in SENSITIVE_PERMISSIONS { + let Some(line) = found.keys.get(permission.key) else { + continue; + }; + if !reported.insert(permission.grants) { + continue; + } + hits.push(Hit { + scanner: SCANNER, + scan_type: ScanType::Sast, + rule_id: "ios-sensitive-permission", + title: format!("The app asks for access to {}", permission.grants), + description: format!( + "{path} declares {} for access to {}. Each access is personal data or device \ + access the app processes; the risk assessment and the privacy notice must \ + account for it, and an app that does not need it should not ask.", + permission.key, permission.grants + ), + remediation: "Confirm the app needs this access for its purpose, and remove the \ + usage string and the code requesting it otherwise.", + severity: Severity::Info, + cwe: "CWE-250", + path: path.to_string(), + line: Some(*line), + }); + } + hits +} + +/// The permission requests in `sources` that no usage string in `keys` +/// covers: one finding per kind, at its first request. +fn undeclared_requests( + root: &Path, + sources: &[std::path::PathBuf], + keys: &BTreeSet<&str>, +) -> Vec { + let open: Vec<&Request> = REQUESTS + .iter() + .filter(|r| !r.keys.iter().any(|k| keys.contains(k))) + .collect(); + let mut hits = Vec::new(); + let mut found = BTreeSet::new(); + for source in sources { + if found.len() == open.len() { + break; + } + let Ok(text) = std::fs::read_to_string(source) else { + continue; + }; + for (i, request) in open.iter().enumerate() { + if found.contains(&i) { + continue; + } + let Some(offset) = request.needles.iter().filter_map(|n| text.find(n)).min() else { + continue; + }; + found.insert(i); + hits.push(Hit { + scanner: SCANNER, + scan_type: ScanType::Sast, + rule_id: "ios-permission-without-usage-string", + title: format!( + "Access to {} is requested without a usage string", + request.what + ), + description: format!( + "The app asks for access to {} here, but no Info.plist or build setting \ + declares {}. iOS terminates the app at this request, and the user is never \ + told why the access is needed.", + request.what, + request.keys.join(" or ") + ), + remediation: "Declare the usage string with a purpose the user understands, or \ + remove the request if the app does not need the access.", + severity: Severity::Low, + cwe: "CWE-1188", + path: relative(root, source), + line: Some(line_at(&text, offset)), + }); + } + } + hits +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + /// A scratch tree holding `files`, removed on drop. + struct Tree(std::path::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-iosconfig-{}", 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) + } + + fn hits(t: &Tree) -> Vec { + check_tree(&t.0) + .into_iter() + .map(|h| format!("{} {}:{}", h.rule_id, h.path, h.line.unwrap_or(0))) + .collect() + } + + const PLIST: &str = r#" + + + + CFBundleIdentifier + com.example.pumpremote + CFBundleURLTypes + + + CFBundleURLName + pairing + CFBundleURLSchemes + + pumpremote + com.googleusercontent.apps.123 + + + + NSBluetoothAlwaysUsageDescription + Connects to your pump. + NSBluetoothPeripheralUsageDescription + Connects to your pump. + NSLocationWhenInUseUsageDescription + Finds pumps nearby. + UIRequiredDeviceCapabilities + armv7 + + +"#; + + #[test] + fn a_plist_gives_its_url_schemes_and_permissions() { + let t = tree(&[ + ("PumpRemote/Info.plist", PLIST), + ( + "PumpRemote/Scanner.swift", + "import CoreBluetooth\nlet central = CBCentralManager(delegate: nil, queue: nil)\n\ + manager.requestWhenInUseAuthorization()\n", + ), + // Dependencies' plists are theirs. + ("Pods/Lib/Info.plist", PLIST), + ]); + assert_eq!( + hits(&t), + [ + "ios-custom-url-scheme PumpRemote/Info.plist:7", + "ios-sensitive-permission PumpRemote/Info.plist:23", + "ios-sensitive-permission PumpRemote/Info.plist:19", + ] + ); + let all = check_tree(&t.0); + assert_eq!( + all[0].title, + "Custom URL scheme: pumpremote, com.googleusercontent.apps.123" + ); + } + + #[test] + fn requests_without_a_usage_string_are_found_at_the_call() { + let t = tree(&[ + ( + "App.xcodeproj/project.pbxproj", + "\t\t\t\tINFOPLIST_KEY_NSCameraUsageDescription = \"Scans the pump label\";\n", + ), + ( + "App/Capture.swift", + "import AVFoundation\n\nfunc ask() {\n AVCaptureDevice.requestAccess(for: .video) { _ in }\n \ + AVCaptureDevice.requestAccess(for: .audio) { _ in }\n}\n", + ), + ( + "App/Legacy.m", + "#import \nvoid f(void) {\n CNContactStore *s = [[CNContactStore alloc] init];\n \ + [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus st) {}];\n}\n", + ), + ]); + assert_eq!( + hits(&t), + [ + "ios-sensitive-permission App.xcodeproj/project.pbxproj:1", + "ios-permission-without-usage-string App/Capture.swift:5", + "ios-permission-without-usage-string App/Legacy.m:3", + "ios-permission-without-usage-string App/Legacy.m:4", + ] + ); + } + + #[test] + fn without_any_plist_requests_are_not_judged() { + let t = tree(&[( + "App/Capture.swift", + "AVCaptureDevice.requestAccess(for: .video) { _ in }\n", + )]); + assert!(hits(&t).is_empty()); + } + + #[test] + fn binary_and_broken_plists_are_skipped() { + assert!(read_plist("bplist00\u{1}\u{2}").is_none()); + assert!(read_plist("A").is_none()); + } +} diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index dbfdc11..03ea343 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -12,6 +12,7 @@ pub mod git; pub mod git_submodules; pub mod gitleaks; mod graph_build; +pub mod ios_config; mod issue_creation; pub(crate) mod issue_sync; pub mod languages; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 8c6bef7..de9e06e 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -504,6 +504,16 @@ impl PipelineOrchestrator { } Err(e) => tracing::warn!("[{repo_id}] build lifecycle check failed: {e}"), } + // What an iOS app declares: URL schemes, permissions, and + // permission requests without a usage string. + let ios = crate::pipeline::ios_config::IosConfigScanner; + match ios.scan(&repo_path, &repo_id).await { + Ok(output) => { + completed.push(crate::pipeline::ios_config::SCANNER.to_string()); + findings.extend(output.findings); + } + Err(e) => tracing::warn!("[{repo_id}] iOS configuration check failed: {e}"), + } (findings, completed) } .instrument(tracing::info_span!("stage_pattern_scanning")) diff --git a/compliance-agent/src/pipeline/semgrep.rs b/compliance-agent/src/pipeline/semgrep.rs index d27dde4..644eff6 100644 --- a/compliance-agent/src/pipeline/semgrep.rs +++ b/compliance-agent/src/pipeline/semgrep.rs @@ -31,6 +31,14 @@ const RULE_PACKS: &[(&str, &str)] = &[ "compliance-cra-semgrep-csharp.yaml", include_str!("../../rules/cra_semgrep_csharp.yaml"), ), + ( + "compliance-cra-semgrep-swift.yaml", + include_str!("../../rules/cra_semgrep_swift.yaml"), + ), + ( + "compliance-cra-semgrep-objc.yaml", + include_str!("../../rules/cra_semgrep_objc.yaml"), + ), ]; /// What a finding's fingerprint hashes in front of our rule id. @@ -387,6 +395,13 @@ mod tests { bare_rule_id("tmp.cra-ai-20-c-unbounded-string-function"), "cra-ai-20-c-unbounded-string-function" ); + // Every pack, the iOS ones included. + for id in [ + "cra-ai-14-swift-secret-in-userdefaults", + "cra-ai-14-objc-secret-in-userdefaults", + ] { + assert_eq!(bare_rule_id(&format!("tmp.{id}")), id); + } // Not ours: left as semgrep reported it. assert_eq!( bare_rule_id("python.lang.security.audit.exec-detected"), diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 5093d14..b931189 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -1734,6 +1734,10 @@ pub mod findings { de: "Build-System und Plattform", en: "Build system and platform", }, + "ios-config" => Text { + de: "iOS-App-Einstellungen", + en: "iOS app settings", + }, "gdpr-patterns" => Text { de: "Datenschutz-Muster", en: "Privacy patterns", diff --git a/control-map/data/cra_control_map.json b/control-map/data/cra_control_map.json index 7d484a2..1094774 100644 --- a/control-map/data/cra_control_map.json +++ b/control-map/data/cra_control_map.json @@ -442,6 +442,22 @@ ], "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." + }, + { + "tool": "semgrep", + "scan_type": "sast", + "languages": [ + "swift", + "objc", + "regex" + ], + "cwe": [], + "rules": [ + "cra-ai-14-swift-secret-in-userdefaults", + "cra-ai-14-swift-secret-in-appstorage", + "cra-ai-14-objc-secret-in-userdefaults" + ], + "check": "An iOS app must keep passwords, tokens and keys in the Keychain; storing them in UserDefaults (also through @AppStorage), an unencrypted plist in the app container, violates it. The Objective-C rule is a regex pattern (semgrep has no Objective-C parser), hence the regex language." } ], "note": null, diff --git a/docs/guide/scanning.md b/docs/guide/scanning.md index a87ff8d..38618b9 100644 --- a/docs/guide/scanning.md +++ b/docs/guide/scanning.md @@ -17,9 +17,10 @@ names while the scan runs. - *Projekttyp bestimmen* -- firmware, PLC project, backend service, and so on. - *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 Android and iOS apps mobsfscan (code, - AndroidManifest and Info.plist); for C and C++ also cppcheck, which follows values through the code + Prüfwerk's own rules (Python, JavaScript/TypeScript, C and C++, Swift and + Objective-C; see [Tools](/reference/tools)); for Android and iOS apps + mobsfscan (code, AndroidManifest and Info.plist), and for iOS apps the URL + schemes and permissions the app declares; 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 d9817ea..465b243 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -14,6 +14,10 @@ Prüfwerk runs the engine with **its own CRA rules only**: plain `http://` requests, and (Python) hard-coded credentials. - C and C++: unbounded string functions, non-literal format strings, hard-coded credentials, broken hashes and ciphers, `rand()` for security. +- Swift and Objective-C (iOS apps): passwords, tokens and keys kept in + `UserDefaults` / `NSUserDefaults` (also through `@AppStorage`) instead of the + Keychain. The Objective-C rule is a text pattern, as Semgrep cannot parse + Objective-C. The rules of the Semgrep registry (`--config=auto`, `p/...`) are not used: their licence (Semgrep Rules License v1.0) allows internal use only, not a @@ -55,6 +59,25 @@ 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`. +### iOS app settings + +Prüfwerk reads every `Info.plist` and the `INFOPLIST_KEY_*` build settings of +the Xcode project (outside `Pods/` and `Carthage/`) itself, as findings with the +tool name `ios-config`: + +- **Custom URL schemes** (`CFBundleURLTypes`, Low): any app can register the + same scheme and receive the URLs meant for this one; Universal Links avoid it. +- **Sensitive permissions** (`NS…UsageDescription`, Info): location, camera, + microphone, contacts, photos, calendars, Bluetooth, local network, health, + motion, speech, tracking. An inventory for the risk assessment and the privacy + notice, not a violation. +- **Permission requests without a usage string** (Low): code that asks for one + of these while no plist explains why; iOS terminates the app at that call. + Judged only when the repository holds a plist or an Xcode project. + +The first two map to no CRA requirement: a minimal attack surface and data +minimisation are judged in the design review. + 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. diff --git a/fixtures/nightly/baselines/mobile-ios-app-settings.json b/fixtures/nightly/baselines/mobile-ios-app-settings.json new file mode 100644 index 0000000..5016671 --- /dev/null +++ b/fixtures/nightly/baselines/mobile-ios-app-settings.json @@ -0,0 +1,14 @@ +{ + "scan_status": "completed", + "skipped_stages": [], + "sbom": [], + "findings": [ + "ios-config:ios-custom-url-scheme Info.plist:7", + "ios-config:ios-permission-without-usage-string Session.swift:12", + "ios-config:ios-sensitive-permission Info.plist:18", + "ios-config:ios-sensitive-permission Info.plist:20", + "semgrep:cra-ai-14-objc-secret-in-userdefaults LegacyLogin.m:4", + "semgrep:cra-ai-14-swift-secret-in-userdefaults Session.swift:7" + ], + "cves": [] +} diff --git a/fixtures/nightly/baselines/mobile-ios-insecure.json b/fixtures/nightly/baselines/mobile-ios-insecure.json index 94657e9..3220b27 100644 --- a/fixtures/nightly/baselines/mobile-ios-insecure.json +++ b/fixtures/nightly/baselines/mobile-ios-insecure.json @@ -5,7 +5,8 @@ "findings": [ "mobsfscan:ios_app_logging PumpLink.m:8", "mobsfscan:ios_ats_arbitrary_loads Info.plist:6", - "mobsfscan:ios_weak_hash Store.swift:10" + "mobsfscan:ios_weak_hash Store.swift:10", + "semgrep:cra-ai-14-swift-secret-in-userdefaults Store.swift:6" ], "cves": [] } diff --git a/fixtures/nightly/mobile/README.md b/fixtures/nightly/mobile/README.md index 70de597..43f8cf5 100644 --- a/fixtures/nightly/mobile/README.md +++ b/fixtures/nightly/mobile/README.md @@ -17,7 +17,8 @@ as a source archive. They prove that no mobile app ends with "0 packages, | `react-native` | `package-lock.json`; neither `ios/Podfile` nor the Gradle app is locked | the npm packages; a recorded `sbom_dependencies` skip | | `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 | +| `ios-insecure` | nothing | mobsfscan: ATS off in `Info.plist`, `CC_MD5` in Swift, `NSLog` in Objective-C; semgrep: the password `Store.swift` keeps in `UserDefaults` | +| `ios-app-settings` | nothing | ios-config: the `pumplink` URL scheme, Bluetooth and local-network permissions, a contacts request without a usage string; semgrep: an access token in `UserDefaults` (Swift) and a password in `NSUserDefaults` (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 diff --git a/fixtures/nightly/mobile/ios-app-settings/PumpLink/Info.plist b/fixtures/nightly/mobile/ios-app-settings/PumpLink/Info.plist new file mode 100644 index 0000000..94334b4 --- /dev/null +++ b/fixtures/nightly/mobile/ios-app-settings/PumpLink/Info.plist @@ -0,0 +1,23 @@ + + + + + CFBundleIdentifier + com.example.pumplink + CFBundleURLTypes + + + CFBundleURLName + com.example.pumplink.pairing + CFBundleURLSchemes + + pumplink + + + + NSBluetoothAlwaysUsageDescription + PumpLink connects to your pump over Bluetooth. + NSLocalNetworkUsageDescription + PumpLink finds pump gateways on your network. + + diff --git a/fixtures/nightly/mobile/ios-app-settings/PumpLink/LegacyLogin.m b/fixtures/nightly/mobile/ios-app-settings/PumpLink/LegacyLogin.m new file mode 100644 index 0000000..f4a9a8a --- /dev/null +++ b/fixtures/nightly/mobile/ios-app-settings/PumpLink/LegacyLogin.m @@ -0,0 +1,5 @@ +#import + +void PLRememberLogin(NSString *password) { + [[NSUserDefaults standardUserDefaults] setObject:password forKey:@"PLPumpPassword"]; +} diff --git a/fixtures/nightly/mobile/ios-app-settings/PumpLink/Session.swift b/fixtures/nightly/mobile/ios-app-settings/PumpLink/Session.swift new file mode 100644 index 0000000..fdff751 --- /dev/null +++ b/fixtures/nightly/mobile/ios-app-settings/PumpLink/Session.swift @@ -0,0 +1,15 @@ +import Contacts +import Foundation + +/// Keeps the pump cloud session of the signed-in user. +final class Session { + func signedIn(accessToken: String, user: String) { + UserDefaults.standard.set(accessToken, forKey: "pumpCloudAccessToken") + UserDefaults.standard.set(user, forKey: "lastUser") + } + + func shareWithCaregiver() { + let store = CNContactStore() + store.requestAccess(for: .contacts) { _, _ in } + } +} diff --git a/fixtures/nightly/targets.json b/fixtures/nightly/targets.json index 5f444de..a126cce 100644 --- a/fixtures/nightly/targets.json +++ b/fixtures/nightly/targets.json @@ -729,6 +729,27 @@ ] } }, + { + "key": "mobile-ios-app-settings", + "name": "iOS · URL scheme, permissions and secrets in UserDefaults", + "target_type": "ios_app", + "description": "Uploaded as a source archive. A Swift and Objective-C app whose Info.plist registers a custom URL scheme and asks for Bluetooth and the local network, which requests the contacts without a usage string, and which keeps an access token and a password in UserDefaults. Prüfwerk's own Swift and Objective-C semgrep rules and the ios-config checks must find each one.", + "artifacts": [ + { + "kind": "source_archive", + "upload": "fixtures/nightly/mobile/ios-app-settings" + } + ], + "expect": { + "sast_rule_ids": [ + "ios-custom-url-scheme", + "ios-sensitive-permission", + "ios-permission-without-usage-string", + "cra-ai-14-swift-secret-in-userdefaults", + "cra-ai-14-objc-secret-in-userdefaults" + ] + } + }, { "key": "mobile-android-legacy-groovy", "name": "Android · Groovy build without a lockfile", -- 2.54.1