feat(ios): secrets in UserDefaults, URL schemes and permissions of iOS apps (#479)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy Dashboard (push) Successful in 5m51s
CI / Deploy Agent (push) Successful in 7m29s

This commit was merged in pull request #479.
This commit is contained in:
sharang committed 2026-10-05 23:35:23 +00:00
1 parent 5fdf80a1e0
commit 5b2deec9e8
19 files changed
+906 -5

No files matched your search

+617
View File
@@ -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<ScanOutput, CoreError> {
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<String, u32>,
url_schemes: Option<(Vec<String>, 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<Hit> {
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<Declared> {
// 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<String> = 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_<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<Hit> {
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<Hit> {
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<String> {
check_tree(&t.0)
.into_iter()
.map(|h| format!("{} {}:{}", h.rule_id, h.path, h.line.unwrap_or(0)))
.collect()
}
const PLIST: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>com.example.pumpremote</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>pairing</string>
<key>CFBundleURLSchemes</key>
<array>
<string>pumpremote</string>
<string>com.googleusercontent.apps.123</string>
</array>
</dict>
</array>
<key>NSBluetoothAlwaysUsageDescription</key>
<string>Connects to your pump.</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Connects to your pump.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Finds pumps nearby.</string>
<key>UIRequiredDeviceCapabilities</key>
<array><string>armv7</string></array>
</dict>
</plist>
"#;
#[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 <Contacts/Contacts.h>\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("<plist><dict><key>A</key>").is_none());
}
}
+1
View File
@@ -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;
@@ -495,6 +495,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"))
+15
View File
@@ -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"),