SPB Git

Repository Public License

security-engine.md 15.1 KB 232 lines markdown

1<!--2ORIX Secure3File: docs/architecture/security-engine.md4Description: Security assessment pipeline, automatic findings, checklist semantics, the no-score methodology,5             the integrity heuristic and the investigation engine.6Author: Simon-Pierre Boucher7Contact: contact@spboucher.ai8-->910# ORIX Secure — Security engine1112Sources: `Packages/ORIXSecureEngines/Sources/ORIXSecureEngines/` — `SecuritySignals.swift`13(`SystemSecurityProbe`), `SecurityAssessmentEngine.swift`, `Checklist.swift`, `InvestigationEngine.swift`,14`DeviceSnapshot.swift` (`PlatformLimits`); wiring in `App/Sources/Core/AppModel.swift`.1516## 1. Pipeline1718```mermaid19flowchart TD20    DP["SystemDeviceProbe.snapshot()<br/>@MainActor"] --> DS["DeviceSnapshot"]21    SC["AppModel.screenCaptured()<br/>UITraitCollection.sceneCaptureState"] --> SP22    SP["SystemSecurityProbe.signals(isSimulator:screenCaptured:)"] --> SS["SecuritySignals"]23    ST[("LocalStore.responses()<br/>StoredAnswer rows")] --> CR["[ChecklistResponse]"]24    NC["NetworkController.assess()<br/>NetworkAssessment.findings"] --> CF["contributed: [Finding]<br/>AppModel.networkFindings"]2526    DS --> ENG["SecurityAssessmentEngine.assess(device:signals:responses:contributed:now:)"]27    SS --> ENG28    CR --> ENG29    CF --> ENG3031    ENG --> AUTO["automatic<br/>9 findings + 1 conditional"]32    ENG --> CHK["checklist<br/>one finding per ChecklistCatalog.security item"]33    ENG --> CON["contributed<br/>carried unchanged"]34    ENG --> NA["notAssessable<br/>PlatformLimits.securityAssessments"]3536    AUTO --> SA["SecurityAssessment"]37    CHK --> SA38    CON --> SA39    NA --> SA40    SA --> SUM["AssessmentSummary<br/>counts by state, coverage, highest severity"]41    SA --> ACT["actions: attention findings, prioritized()"]42    SA --> PEND["pendingConfirmations"]43```4445`AppModel` runs the pipeline in `init`, in `refresh()` (scene becomes active, explicit refresh) and in46`recompute()` (a checklist answer changes, network findings arrive). The engine is a pure function of its47inputs; tests inject `FixedDeviceProbe` and `FixedSecurityProbe`.4849Contributed findings are those of `NetworkAssessment.findings(for:)` — connection, addresses, proxy, VPN50indicator, Wi-Fi security (see [network.md](network.md)). Results of the user-started probes (DNS, latency,51TLS, HTTPS) are not contributed to the security assessment.5253## 2. Signals read by `SystemSecurityProbe`5455| Signal | API | Notes |56|---|---|---|57| `passcodeSet: Reading<Bool>` | `LAContext.canEvaluatePolicy(.deviceOwnerAuthentication)`; `LAError.passcodeNotSet` gives `measured(false)` | Any other error gives `.unavailable(.failed)`. |58| `biometryKind`, `biometryEnrolled`, `biometryLockedOut` | `LAContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics)`, `biometryType` | `biometryNotAvailable` gives `.unsupportedOnDevice` when there is no sensor, else `.permissionRequired`. |59| `secureEnclaveAvailable` | `CryptoKit.SecureEnclave.isAvailable` | |60| `appAttestSupported` | `DCAppAttestService.shared.isSupported` | `.unavailable(.simulator)` in the Simulator. No attestation is performed. |61| `debuggerAttached` | `sysctl(CTL_KERN, KERN_PROC, KERN_PROC_PID)`, flag `P_TRACED` | This process only. |62| `integrityIndicators`, `integrityChecksPerformed` | `FileManager.fileExists`, `Data.write`, `_dyld_image_count` / `_dyld_get_image_name`, `ProcessInfo.environment` | Section 5. Skipped in the Simulator (`performed == 0`). |63| `fileProtection: Reading<String>` | Writes a probe file with `.completeFileProtection`, reads `FileAttributeKey.protectionKey`, deletes it | `.unavailable(.simulator)` in the Simulator. |64| `screenCaptured` | Supplied by the app: `UIWindowScene.traitCollection.sceneCaptureState == .active` | `.unavailable(.notRequested)` when no window scene exists. |6566## 3. Automatic findings6768Each reading that is `.unavailable` produces the same finding id with state `notAvailable`, confidence69`none`, verification `notVerifiable` and the unavailability detail as explanation.7071| Finding id | Input | Possible states | Severity when `attention` |72|---|---|---|---|73| `device.os.outdated` | `DeviceSnapshot.systemMajorVersion` vs. the major version of `builtAgainstSDKVersion` (`Info.plist` `DTPlatformVersion`) | Emitted only when the installed major is lower than the SDK major: `attention`. Otherwise no finding. | `low`; `moderate` when two or more majors behind |74| `auth.passcode` | `passcodeSet` | `verified` / `attention` / `notAvailable` | `high` |75| `auth.biometry` | `biometryLockedOut`, `biometryEnrolled` | `verified` / `attention` (locked out, or not enrolled) / `notAvailable` | `low` |76| `device.secureEnclave` | `secureEnclaveAvailable` | `verified` / `notAvailable` | — |77| `app.integrity` | `integrityIndicators`, `integrityChecksPerformed` | `verified` (heuristic) / `attention` (heuristic) / `notAvailable` (0 checks) | `high` |78| `app.debugger` | `debuggerAttached` | `verified` / `attention` / `notAvailable` | `low` |79| `app.dataProtection` | `fileProtection` compared with `FileProtectionType.complete.rawValue` | `verified` / `attention` / `notAvailable` | `low` |80| `app.attest` | `appAttestSupported` | `verified` / `notAvailable` (unsupported or unreadable) | — |81| `device.screenCapture` | `screenCaptured` | `verified` / `attention` / `notAvailable` | `low` |82| `device.restart` | `DeviceSnapshot.lastBoot` (`sysctl kern.boottime`) | `verified` / `attention` when days since boot ≥ `SecurityAssessmentEngine.restartSuggestionDays` (30) / `notAvailable` | `low` |8384Notes:8586- `device.os.outdated` uses the SDK the build was compiled against as a dated reference; the engine works87  offline and its `notInspected` text says it does not know the latest release.88- `app.integrity` is the only automatic finding with `confidence: .heuristic` in both its `verified` and89  `attention` forms; all others are `measured` / `publicAPI`.90- Categories: `device` (os, Secure Enclave, App Attest, restart), `authentication` (passcode, biometry),91  `appIntegrity` (integrity, debugger, data protection), `privacy` (screen capture).9293## 4. Checklist9495`ChecklistCatalog.security` holds 19 items (`sec.*`), `ChecklistCatalog.privacyItems` 16 items (`priv.*`,96consumed by `PrivacyAuditEngine`). Each `ChecklistItem` carries a question, the Settings path, `expected`97(default `.yes`; no catalog item overrides it), `importance`, `isOptional` (default `false`) and98`validityDays` (default 90).99100`SecurityChecklistEngine.finding(for:response:now:extraEvidence:)` — rules in evaluation order:101102| Condition | State | Confidence / verification | Severity |103|---|---|---|---|104| No response, item not optional | `userConfirmationRequired` | `none` / `notVerifiable` | `none` |105| No response, item optional | `notAssessed` | `none` / `notVerifiable` | `none` |106| Response older than `validityDays` (`isStale`: `now − answeredAt > validityDays × 86 400 s`) | `userConfirmationRequired` (whatever the answer was) | `none` / `notVerifiable` | `none` |107| Answer `notApplicable` | `notAvailable` | `userReported` / `userConfirmed` | `none` |108| Answer `notSure` | `userConfirmationRequired` | `none` / `notVerifiable` | `none` |109| Answer equals `expected` | `userConfirmed` | `userReported` / `userConfirmed` | `none` |110| Answer differs, item optional | `userConfirmed` (explanation says the protection is optional and off; `recommendation` = item action) | `userReported` / `userConfirmed` | `none` |111| Answer differs, item not optional | `attention` | `userReported` / `userConfirmed` | `item.importance` |112113Further rules:114115- When several responses exist for one item, the latest `answeredAt` wins (`Dictionary(uniquingKeysWith:)`).116  `LocalStore` keeps at most one row per item anyway.117- A checklist finding never has state `verified`. Its evidence is the answer, the answer date and the118  Settings path; `notInspected` states that the app cannot read the setting.119- `sec.updates.current` receives one extra measured evidence line, the installed system version.120- Optional items: `sec.lockdown`, `sec.adp`, `sec.erase`, `priv.significant` (all with `importance: .none`).121- Non-default validity: 30 days `sec.updates.current`; 60 days `sec.passwords.review`; 180 days122  `sec.lockdown`, `sec.adp`, `priv.safetycheck`, `priv.significant`; 365 days `sec.passcode.strength`,123  `sec.account.recovery`, `sec.erase`.124- Items with `importance: .high`: `sec.updates.current`, `sec.account.2fa`, `sec.account.devices`,125  `sec.profiles.unknown`, `sec.profiles.mdm`, `sec.certs.trust`.126127## 5. Integrity-indicator heuristic128129`SystemSecurityProbe.integrityIndicators()` runs on a physical device only and counts each check in130`integrityChecksPerformed`:131132| Check | Count | Indicator id | Source recorded |133|---|---|---|---|134| Existence of each path in `jailbreakPaths` (package-manager apps, Substrate/substitute/libhooker libraries, `sshd`, `/bin/bash`, apt/cydia folders, `/var/jb`, bootstrap markers) | 22 | `path:<path>` | `FileManager.fileExists` |135| Write of a probe file under `/private/` (removed if it succeeds) | 1 | `sandbox.write` | `Data.write` |136| Name of every loaded image against `injectedLibraryMarkers` (`mobilesubstrate`, `substrate`, `substitute`, `libhooker`, `frida`, `cycript`, `sslkillswitch`, `ellekit`, `systemhook`) | 1 | `dyld:<marker>` | `_dyld_get_image_name` |137| `DYLD_INSERT_LIBRARIES` non-empty | 1 | `dyld.insert` | `ProcessInfo.environment` |138139That is 25 checks. Zero indicators gives `app.integrity` = `verified` with the title "No known sign of system140modification observed"; one or more gives `attention` / `high` with every observation listed as evidence.141142Stated limits (they are in the finding's `notInspected` and explanation):143144- The checks run inside the app sandbox and look for known signs only; tools built to hide from apps avoid them.145- System files, the kernel and other apps cannot be inspected.146- "None observed" is an absence of known signs, not proof that the system is unmodified.147- Each indicator can have a harmless cause; a user who jailbroke the device on purpose will see them.148- In the Simulator the finding is `notAvailable`: the checks are not meaningful on a Mac's file system.149150## 6. No score151152`AssessmentSummary(findings:)` contains counts only: `verified`, `attention`, `userConfirmed`,153`awaitingConfirmation`, `notAvailable`, `notAssessed`, and `highestSeverity`.154155- `assessable = verified + attention + userConfirmed + awaitingConfirmation` (excludes `notAvailable` and156  optional items never answered).157- `coverage = (verified + attention + userConfirmed) / assessable`, or `nil` when `assessable == 0`.158159Coverage measures how much was looked at. An `attention` finding raises coverage exactly as a `verified`160one does, so coverage cannot be read as a security level. `AssessmentSummary.methodology` (seven sentences,161shown in the UI and written into the "Summary" section of the security report by `ReportBuilder.security`)162states that no score is computed because a single number would hide what was and was not checked, and that163full coverage does not mean absence of risk.164165`SecurityAssessment.notAssessable` always carries `PlatformLimits.securityAssessments` (8 entries:166`malware.scan`, `apps.installed`, `apps.permissions`, `safari.history`, `profiles.list`, `traffic.others`,167`wifi.router`, `settings.system`); the report lists them under `unavailable`.168169## 7. Investigation engine170171`InvestigationEngine` supports eight `Symptom` cases: `batteryDrain`, `dataUsage`, `suspiciousLink`,172`unknownProfile`, `accountActivity`, `storageAnomaly`, `crashes`, `networkBehavior`.173174- `plan(for:)` returns an `InvestigationPlan`: five yes/no questions (`InvestigationQuestion`, answered with175  `ChecklistAnswer`), two or three `SettingsCheck` entries, and the `InvestigationTool`s relevant to the symptom.176- `evaluate(_ input: InvestigationInput)` returns an `InvestigationResult` that keeps four things apart:177  `observations` (measured `Evidence`: system version; thermal state, Low Power Mode, battery, last restart178  and storage for `batteryDrain`/`crashes`; capacity and free space for `storageAnomaly`; the integrity179  indicator count when checks ran; the title of each `attention` tool finding), `reported` (the user's180  answers, source `"user"`), `hypotheses`, and `actions` + `escalation`. `notInspected` always includes181  "Whether the device is compromised: no App Store app can determine that."182183### Hypothesis support184185`Hypothesis.Support` is `lessLikely` (0) < `possible` (1) < `supported` (2).186187- An ordinary hypothesis is built by the local helper `h(id, title, explanation, when:)`: it is `supported`188  when at least one of its conditions holds (the matching phrases become its `basis`), otherwise `possible`.189- Hypotheses are sorted by support descending, then by `id`. Ordinary ids start with `a.`–`e.`; the compromise190  hypothesis is `z.compromise`, so with equal support it is listed last.191192### The compromise hypothesis193194`compromiseHypothesis(_:extraBasis:)` produces "The device or account has been tampered with". Its support is195`basis.isEmpty ? .lessLikely : .supported`; it is never `possible`. The basis can only contain:196197| Basis entry | Origin | Symptoms |198|---|---|---|199| "N known sign(s) of system modification observed" | Measured: `signals.integrityIndicators` non-empty | all |200| "a VPN or profile you do not recognise is installed" | Reported: `unknownVPN` = yes | `dataUsage` |201| "iOS is not up to date" | Reported: `upToDate` = no | `suspiciousLink` |202| "nobody you know installed a profile that changes trust or routing" | Reported: `workDevice` = no and `installedByApp` = no and (`hasCertificate` or `hasVPNProxy` = yes) | `unknownProfile` |203204For `batteryDrain`, `accountActivity`, `storageAnomaly`, `crashes` and `networkBehavior` only an observed205integrity indicator can move it to `supported`. The symptom alone never does; the explanation text says it206"cannot be confirmed or excluded by an app". Tests `withNoEvidenceCompromiseIsAlwaysLastAndLessLikely` and207`compromiseNeedsAConcreteSign` cover the rule.208209### Tool findings210211`InvestigationFlowView.evaluate()` refreshes the model and passes212`model.networkFindings + (model.network.tls?.findings ?? [])` as `toolFindings` for `networkBehavior`,213`dataUsage` and `unknownProfile` — the connection assessment plus the last certificate check run in this214session; other symptoms receive none. In `networkBehavior`:215216- `b.config` gains a basis when a tool finding whose id contains `proxy` is in `attention` (`network.proxy`);217- `c.interception` gains a basis when a `network` finding whose id contains `tls` is in `attention`218  (`tls.trust`, `tls.hostname`, `tls.validity`…). It is reachable once the user has run a certificate check219  in the Network Lab during the session; DNS, latency and HTTPS probe results are not passed.220221`InvestigationResult.report()` builds a `ReportDocument` of kind `.investigation` whose hypotheses section222opens with "None is a confirmed diagnosis."223224## 8. Verification status225226- Covered by package tests on macOS (`SecurityAssessmentTests`, `InvestigationTests`): state mapping for every227  answer, expiry, optional items, summary counts, the compromise rule, JSON round-trip.228- Not exercised on a physical device: `fileProtection`, `appAttest`, the 25 integrity checks (all skipped or229  unavailable in the Simulator), biometric lockout, and the `sceneCaptureState` reading during a real230  recording or AirPlay session.231- The tests were not re-run while writing this document.232
Files main
Menu

Theme