SPB Git

Repository Public License

network.md 16.6 KB 263 lines markdown

1<!--2ORIX Secure3File: docs/architecture/network.md4Description: Network probes and their requirements, what is never done, URL analysis, QR payload classifier.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->89# ORIX Secure — Network Lab and link analysis1011Sources: package `ORIXNetworkLab`, package `ORIXURLRisk`, `App/Sources/Features/Network/NetworkController.swift`,12`App/Sources/Features/URLAnalysis/LinkAnalyzerView.swift`, `App/Sources/Platform/QRReading.swift`,13`ShareExtension/Sources/ShareViewController.swift`.1415## 1. Network diagnostics1617```mermaid18flowchart TD19    subgraph Passive["Local state — contacts no remote endpoint"]20        M["ConnectivityMonitor<br/>NWPathMonitor"] --> SNAP["ConnectivitySnapshot"]21        IF["InterfaceInspector.addresses()<br/>getifaddrs"] --> ADDR["[InterfaceAddress]"]22        PX["InterfaceInspector.proxyConfiguration()<br/>CFNetworkCopySystemProxySettings"] --> PROXY["ProxyConfiguration"]23        ADDR --> VPN["vpnIndicator — heuristic"]24        PROXY --> VPN25        WF["WiFiInspector.currentNetwork<br/>NEHotspotNetwork.fetchCurrent()"] --> WIFI["Reading of WiFiNetworkInfo"]26    end27    SNAP --> IN["NetworkAssessmentInput<br/>NetworkAssessment.collect"]28    ADDR --> IN29    PROXY --> IN30    WIFI --> IN31    IN --> NF["NetworkAssessment.findings — pure"]32    NF --> SEC["AppModel.networkFindings<br/>contributed to the security assessment"]3334    subgraph Active["User-started probes — host typed by the user"]35        H["host"] --> DNS["DNSProbe.resolve<br/>getaddrinfo, 5 s"]36        H --> LAT["LatencyProbe.measure<br/>TCP 443, 5 samples"]37        H --> TLS["TLSInspector.inspect<br/>one handshake, no data sent"]38        TLS --> X509["X509Certificate + HostnameMatcher"]39        X509 --> TF["TLSAssessment.findings"]40        H -->|"separate button"| HTTPS["HTTPSProbe.head<br/>HEAD, at most 5 redirects"]41    end42    BON["LocalNetworkBrowser.browse<br/>NWBrowser, 6 s"] --> SUM["BonjourBrowseSummary"]43    NF --> REP["NetworkAssessment.report<br/>ReportDocument kind .network"]44    DNS --> REP45    LAT --> REP46    TF --> REP47    SUM --> REP48```4950`NetworkController.runProbes(on:)` starts DNS, latency and TLS concurrently for the host shown on screen;51the HTTPS probe and the Bonjour scan each have their own button.5253### 1.1 Connectivity monitor5455`ConnectivityMonitor` wraps `NWPathMonitor`: `snapshots()` (an `AsyncStream`), `current(timeout:)` (2 s56default) and a bounded in-memory change log (`logCapacity` 200, oldest dropped). A `ConnectivitySnapshot`57holds `status`, `interfaceKinds`, `isExpensive`, `isConstrained`, `supportsIPv4/IPv6/DNS`,58`unsatisfiedReason`, `availableInterfaces`. Monitoring runs while the app is active: `AppModel.init` calls59`network.startMonitoring()` at launch (the dashboard shows the connection) and `stopMonitoring()` has no60caller. The change log is not persisted.6162### 1.2 Interfaces, proxy, VPN indicator6364- `InterfaceInspector.addresses()` lists this device's own IPv4/IPv6 addresses with `getifaddrs`, each65  classified by `AddressScope` (loopback, private, CGNAT, link-local, unique local, global, multicast…).66- `proxyConfiguration()` interprets `CFNetworkCopySystemProxySettings`: HTTP/HTTPS/SOCKS endpoints, PAC URL,67  auto-discovery, exceptions and the interface names under `__SCOPED__`. `isProxyConfigured` is true for an68  explicit proxy or a PAC script; auto-discovery alone does not count.69- `vpnIndicator(addresses:proxy:)` is a heuristic over names with the prefixes `utun`, `ipsec`, `ppp`,70  `tap`, `tun`: (a) such an interface that is up and holds a routable address, and/or (b) such a name in the71  scoped proxy settings. Up tunnel interfaces holding only link-local addresses are reported separately as72  `systemOnlyTunnelInterfaces` and do not trigger the indicator. `VPNIndicator.confidence` is always73  `.heuristic`; the source states it can be wrong in both directions (iOS system `utun` interfaces, iCloud74  Private Relay, device management, content filters).7576Findings of `NetworkAssessment.findings`: `network.connectivity`, `network.lowDataMode`, `network.expensive`,77`network.ipv6`, `network.addresses`, `network.proxy` (`attention`/`moderate` when a proxy is78configured), `network.vpn` (`attention` with severity `low`, heuristic, when indicated; `verified` heuristic79otherwise), plus `wifi.security` when the path may be on Wi-Fi. The public address is not determined.80`NWPath.supportsDNS` is shown as reported but is not turned into a finding: it was observed to be false in the81iOS Simulator while names resolved, so the DNS probe is the only source of a DNS conclusion.8283### 1.3 DNS8485`DNSProbe.resolve(_:timeout:)` calls `getaddrinfo` on a dedicated thread with a 5 s default timeout; a lookup86that times out is abandoned, not interrupted. Failures are classified (`DNSFailure.Kind`, including not found,87timeout, no network). `resolve(hosts:maxConcurrent:)` runs at most 4 lookups at a time. Not visible to an app88and stated as such: which resolver answered, whether the answer was cached, DNSSEC.8990### 1.4 TCP latency9192`LatencyProbe.measure(host:port:samples:timeout:interval:)` — defaults port 443, 5 samples (clamped 1…50),933 s per attempt, 200 ms pause — opens sequential `NWConnection`s with `NWParameters.tcp`, sends nothing and94cancels each once ready. A sample's duration is the TCP handshake time from the connection's establishment95report when available, else wall-clock time. `LatencyStatistics`: minimum, average, median, maximum, jitter96(population standard deviation), loss count. This is not ICMP echo.9798### 1.5 TLS inspector99100`TLSInspector.inspect(_:mode:alpn:allowLegacyProtocols:timeout:now:)` performs one handshake over101`NWConnection` (defaults: `mode: .reportOnly`, ALPN `h2` and `http/1.1`, legacy protocols offered so that an102obsolete server can be reported, 10 s). In the `sec_protocol_options_set_verify_block` it evaluates the chain103with `SecTrustEvaluateWithError`, copies at most 16 certificates as DER, and — in `reportOnly` mode — lets the104handshake finish so the negotiated version, cipher suite and ALPN can be read from105`sec_protocol_metadata`. No application data is sent in either mode; the connection is closed when the106handshake ends.107108In-house parsing (no OS certificate-field API):109110- `DER.swift` — definite lengths only, at most 4 length bytes, `maxDepth` 24, `maxElements` 50 000,111  `maxInputSize` 1 MiB, every access bounds-checked.112- `X509Certificate(der:)` — subject, issuer, validity, public key (algorithm, bits, curve), signature113  algorithm, subject alternative names, basic constraints, key usages, SHA-256 fingerprint;114  `verifySelfSignature()` for self-signed leaves.115- `HostnameMatcher` — RFC 6125 / 9525: exact DNS SAN match; a wildcard only as the whole left-most label,116  standing for exactly one label; no wildcard under a TLD or a public-suffix-like two-label name (short117  built-in list, a heuristic); IP addresses against IP SANs only; no common-name fallback.118119`TLSAssessment.findings` (constants `expiryWarningDays` 14, `publicLeafMaximumValidityDays` 398):120121| Finding id | `attention` condition | Severity |122|---|---|---|123| `tls.handshake` | Handshake did not complete | `low` without chain or verdict, else `moderate` |124| `tls.trust` | `SecTrustEvaluateWithError` false | `high` |125| `tls.validity` | Expired / not yet valid; expires within 14 days | `high`; `low` |126| `tls.hostname` | SANs do not cover the host | `high` |127| `tls.selfSigned` / `tls.issuer` | Self-signed leaf / issuer not trusted by the device | `moderate` |128| `tls.protocol` | TLS 1.0, TLS 1.1 or DTLS 1.0 negotiated | `moderate` |129| `tls.signature` | MD2, MD5 or SHA-1 signature | `high` |130| `tls.key` | RSA under 2048 bits, EC under 224 bits | `high` |131| `tls.validityPeriod` | Leaf valid for more than 398 days | `low` |132133Not checked: revocation (independently of iOS), Certificate Transparency, the origin of the trusted root.134135### 1.6 HTTPS probe136137`HTTPSProbe.head(_:timeout:)` sends `HEAD` with an ephemeral `URLSession` (no cookie storage, no cache, no138credential storage, 10 s), refuses automatic redirects through its delegate and requests each hop explicitly,139at most `maximumRedirects` (5). Findings: `https.request`, `https.upgrade` (`attention`/`moderate` when the140site stays on http), `https.hsts` (`attention`/`low` without an effective `Strict-Transport-Security`),141`https.redirects`. The app calls it only from "Check HTTPS Policy", with `https://HOST/`.142143### 1.7 Bonjour browser144145`LocalNetworkBrowser.browse(serviceTypes:duration:)` runs one `NWBrowser` per service type for a bounded146duration (clamped 1–30 s; the app uses 6 s) and streams `.found` / `.lost` / `.finished`. The 14147`defaultServiceTypes` are exactly the entries of `NSBonjourServices` in `Info.plist`. Error148`kDNSServiceErr_PolicyDenied` (−65570) maps to `.permissionRequired`. Discovered devices are not contacted;149the result is a list of advertised services, not a device inventory.150151### 1.8 Wi-Fi inspector152153`WiFiInspector.currentNetwork(locationAuthorization:isOnWiFi:)` calls `NEHotspotNetwork.fetchCurrent()` and154returns SSID (first 64 characters), BSSID, `WiFiSecurity` (`open`, `wep`, `personal`, `enterprise`,155`unknown`) and a signal strength only when in (0, 1]. `WiFiInspector.requirements` restates Apple's156conditions: the Access Wi-Fi Information entitlement, plus precise Location authorization, or a network the157app configured with `NEHotspotConfiguration`, or an active VPN or `NEDNSSettingsManager` configuration of the158app. ORIX Secure uses only the Location route. When iOS returns nothing, the unavailability kind tells why:159`permissionRequired` (not authorized, or approximate accuracy only), `entitlementRequired` (precise location160authorized but no network), `simulator`. `wifi.security` is `attention`/`moderate` for open networks,161`attention`/`high` for WEP, `verified` for personal/enterprise, `userConfirmationRequired` when the type is162not reported. iOS does not distinguish WPA2 from WPA3.163164### 1.9 Requirements per probe165166| Probe | Info.plist key | Entitlement | Runtime prompt |167|---|---|---|---|168| Connectivity, interfaces, proxy, VPN indicator | none | none | none |169| DNS, TCP latency, TLS, HTTPS | none | none | none |170| Bonjour browser | `NSLocalNetworkUsageDescription`, `NSBonjourServices` | none | Local network, at the first browse |171| Wi-Fi inspector | `NSLocationWhenInUseUsageDescription` | `com.apple.developer.networking.wifi-info` | Location, from the "Allow to Read Wi-Fi Security" button |172173### 1.10 Never done174175- No ICMP echo, no raw sockets, no port scan: the latency probe contacts one port of one host.176- No interception or proxying of traffic; no certificate is installed; no trust setting is modified.177- No VPN, no DNS configuration, no content filter. `NetworkExtension` is imported only for178  `NEHotspotNetwork.fetchCurrent()`; the project contains no NetworkExtension provider target and no179  `NEVPNManager`, `NEHotspotConfiguration` or `NEDNSSettingsManager` use.180- No throughput test, no "what is my IP" service, no reputation lookup, no probe of a host the user did not enter.181182## 2. URL analysis183184```mermaid185flowchart TD186    I["Input: typed, pasted, orixsecure:// URL,<br/>share extension, QR payload"] --> EX["extractURLs(from:) when the text has whitespace<br/>NSDataDetector + token pass"]187    EX --> A["URLRiskAnalyzer.analyze(_:)"]188    A --> L{"≤ 100 000 scalars<br/>and not empty?"}189    L -->|no| INV["url.invalid, weight 10"]190    L -->|yes| CH["checkCharacters<br/>invisible / bidi, full-width"]191    CH --> P["URLParser.parse<br/>after removing invisible characters"]192    P -->|failure| INV193    P -->|"hierarchical with host"| H["checkScheme → checkHost (IP, IDN, brands, keywords)<br/>→ checkUserinfo → checkPort → checkEncoding<br/>→ checkRedirects → checkPath"]194    P -->|"opaque scheme"| O["checkOpaqueScheme"]195    H --> S["signals: [URLSignal], one per kind"]196    O --> S197    INV --> S198    S --> SC["URLRiskScoring.score = min(100, Σ weights)"]199    SC --> LV["URLRiskScoring.level(forScore:)"]200    LV --> R["URLAnalysis<br/>decomposition, signals, score, level,<br/>methodology, notInspected"]201    R --> RD["reportDocument() — kind .urlAnalysis"]202```203204The analysis is offline and textual: the link is never opened, fetched or resolved, and no redirect is205followed. The same `URLRiskAnalyzer` runs in the app and in the share extension, which makes no network206request and stores nothing.207208### 2.1 Scoring209210| Score | `URLRiskLevel` |211|---|---|212| 0 | `noSignals` ("No signals found") |213| 1 … 29 | `low` |214| 30 … 59 (`elevatedThreshold` = 30) | `elevated` |215| ≥ 60 (`highThreshold` = 60), capped at `maximumScore` = 100 | `high` |216217Each signal kind appears at most once; if a check fires twice the higher weight is kept and the evidence218merged. A weight of 0 is an informational signal (`state: .verified`, severity `none`); otherwise the finding219is `attention` with severity `low` (weight < 20), `moderate` (< 45) or `high` (≥ 45). Parsed facts are220`measured` / `parsedData`; pattern judgments are `heuristic`. `URLRiskScoring.methodology` states that the221weights are editorial judgments, not measured probabilities. There is no level meaning "safe".222223### 2.2 Signal kinds (`URLSignalKind`) and weights224225| Group | Kinds (raw value → weight) |226|---|---|227| Input and scheme | `url.invalid` 10 · `url.scheme.missing` 0 · `url.scheme.unencrypted` 10 · `url.scheme.non-web` 45 (`javascript`, `vbscript`), 40 (`data`, `blob`), 20 (`file`), 5 (call/message schemes), 10 (other app schemes), 5 (other hierarchical non-web) |228| Characters and scripts | `url.characters.invisible` 45 · `url.characters.full-width` 30 · `url.idn` 5 · `url.idn.invalid-punycode` 30 · `url.script.mixed` 45 · `url.script.confusable` 30, or 10 under a native-script suffix |229| Brand resemblance | `url.brand.confusable` 70 · `url.brand.typosquat` 40 (distance 1) or 30 · `url.brand.embedded` 30, 35 or 50 · `url.brand.other-suffix` 15 · `url.brand.path` 10 |230| Host shape | `url.host.ip` 30 (5 for local addresses) · `url.host.ip-obfuscated` 40 · `url.host.single-label` 0 · `url.host.subdomain-depth` 15 (depth ≥ 4) · `url.host.long` 10 (> 60 bytes) · `url.host.hyphens-digits` 10 · `url.host.keywords` 5 or 10 · `url.shortener` 10 · `url.tld` 0 |231| Authority and encoding | `url.userinfo` 25, or 45 when the user part looks like a host · `url.port` 10 (0 for local hosts) · `url.encoding.host` 35 · `url.encoding.double` 10 or 15 · `url.encoding.path` 10 · `url.encoding.script` 35 · `url.encoding.null` 35 |232| Redirection and path | `url.redirect.parameter` 20 · `url.redirect.path` 15 · `url.path.download-extension` 5 to 30 (25 for `mobileconfig`, at least 30 with a double extension) · `url.length` 0 (> 200 scalars) |233234Supporting data is embedded, with its limits listed in `URLAnalysis.standardNotInspected`: a Public Suffix235List subset, `BrandList.brands`, a confusables table (mainly Cyrillic and Greek) and word lists.236237### 2.3 QR payload classifier238239`QRPayloadClassifier.classify(_:)` (also `QRPayload(decoding:analyzer:)`) sorts a decoded payload into240`QRPayload.Kind`: `url`, `wifi`, `contact`, `email`, `phone`, `sms`, `location`, `calendarEvent`, `text`,241`empty`. A `url` payload gets a full `URLAnalysis`; links found inside contact cards, calendar events and242free text are analysed as `embeddedURLAnalyses`. A `WIFI:` payload is parsed into `WiFiConfiguration`243(`open`, `wep`, `wpa`, `enterprise`, `unknown`) with findings `qr.wifi.open` and `qr.wifi.wep`244(`attention`/`moderate`) and `qr.wifi.unknown` (`attention`/`low`). The payload is analysed and displayed;245it is never opened and no network is joined.246247Decoding happens in the app: `QRImageReader` (Vision `VNDetectBarcodesRequest`, QR / Aztec / Data Matrix, on248a `PhotosPicker` image, no photo permission) and `QRScannerView` (VisionKit `DataScannerViewController`).249`LinkAnalyzerView.openScanner()` calls `AVCaptureDevice.requestAccess(for: .video)` when the status is250`.notDetermined`, then presents the scanner sheet.251252## 3. Verification status253254- `ORIXNetworkLabTests` has logic, findings and X.509 suites that run offline, and `LiveTests` that contact255  real hosts; `ORIXURLRiskTests` runs corpora of links, Punycode vectors and QR payloads. They were not256  re-run while writing this document.257- Wi-Fi: `WiFiInspector` returns `.unavailable(.simulator)` in the Simulator, so `NEHotspotNetwork.fetchCurrent()`,258  the entitlement and the precise-location requirement have never been exercised on a device.259- Bonjour and the local-network prompt, cellular / expensive / constrained paths, real VPN and proxy260  configurations, and the camera QR scanner were run in the Simulator or compiled only.261- The camera request (`openScanner()`), the scanner sheet and its "Camera not available" fallback when262  `DataScannerViewController.isAvailable` is false have not been exercised on a physical device.263
Files main
Menu

Theme