SPB Git

Repository Public License

network.md 16.6 KB

# ORIX Secure — Network Lab and link analysis

Sources: package ORIXNetworkLab, package ORIXURLRisk, App/Sources/Features/Network/NetworkController.swift, App/Sources/Features/URLAnalysis/LinkAnalyzerView.swift, App/Sources/Platform/QRReading.swift, ShareExtension/Sources/ShareViewController.swift.

# 1. Network diagnostics

flowchart TD
    subgraph Passive["Local state — contacts no remote endpoint"]
        M["ConnectivityMonitor<br/>NWPathMonitor"] --> SNAP["ConnectivitySnapshot"]
        IF["InterfaceInspector.addresses()<br/>getifaddrs"] --> ADDR["[InterfaceAddress]"]
        PX["InterfaceInspector.proxyConfiguration()<br/>CFNetworkCopySystemProxySettings"] --> PROXY["ProxyConfiguration"]
        ADDR --> VPN["vpnIndicator — heuristic"]
        PROXY --> VPN
        WF["WiFiInspector.currentNetwork<br/>NEHotspotNetwork.fetchCurrent()"] --> WIFI["Reading of WiFiNetworkInfo"]
    end
    SNAP --> IN["NetworkAssessmentInput<br/>NetworkAssessment.collect"]
    ADDR --> IN
    PROXY --> IN
    WIFI --> IN
    IN --> NF["NetworkAssessment.findings — pure"]
    NF --> SEC["AppModel.networkFindings<br/>contributed to the security assessment"]

    subgraph Active["User-started probes — host typed by the user"]
        H["host"] --> DNS["DNSProbe.resolve<br/>getaddrinfo, 5 s"]
        H --> LAT["LatencyProbe.measure<br/>TCP 443, 5 samples"]
        H --> TLS["TLSInspector.inspect<br/>one handshake, no data sent"]
        TLS --> X509["X509Certificate + HostnameMatcher"]
        X509 --> TF["TLSAssessment.findings"]
        H -->|"separate button"| HTTPS["HTTPSProbe.head<br/>HEAD, at most 5 redirects"]
    end
    BON["LocalNetworkBrowser.browse<br/>NWBrowser, 6 s"] --> SUM["BonjourBrowseSummary"]
    NF --> REP["NetworkAssessment.report<br/>ReportDocument kind .network"]
    DNS --> REP
    LAT --> REP
    TF --> REP
    SUM --> REP

NetworkController.runProbes(on:) starts DNS, latency and TLS concurrently for the host shown on screen; the HTTPS probe and the Bonjour scan each have their own button.

# 1.1 Connectivity monitor

ConnectivityMonitor wraps NWPathMonitor: snapshots() (an AsyncStream), current(timeout:) (2 s default) and a bounded in-memory change log (logCapacity 200, oldest dropped). A ConnectivitySnapshot holds status, interfaceKinds, isExpensive, isConstrained, supportsIPv4/IPv6/DNS, unsatisfiedReason, availableInterfaces. Monitoring runs while the app is active: AppModel.init calls network.startMonitoring() at launch (the dashboard shows the connection) and stopMonitoring() has no caller. The change log is not persisted.

# 1.2 Interfaces, proxy, VPN indicator

  • InterfaceInspector.addresses() lists this device's own IPv4/IPv6 addresses with getifaddrs, each classified by AddressScope (loopback, private, CGNAT, link-local, unique local, global, multicast…).
  • proxyConfiguration() interprets CFNetworkCopySystemProxySettings: HTTP/HTTPS/SOCKS endpoints, PAC URL, auto-discovery, exceptions and the interface names under __SCOPED__. isProxyConfigured is true for an explicit proxy or a PAC script; auto-discovery alone does not count.
  • vpnIndicator(addresses:proxy:) is a heuristic over names with the prefixes utun, ipsec, ppp, tap, tun: (a) such an interface that is up and holds a routable address, and/or (b) such a name in the scoped proxy settings. Up tunnel interfaces holding only link-local addresses are reported separately as systemOnlyTunnelInterfaces and do not trigger the indicator. VPNIndicator.confidence is always .heuristic; the source states it can be wrong in both directions (iOS system utun interfaces, iCloud Private Relay, device management, content filters).

Findings of NetworkAssessment.findings: network.connectivity, network.lowDataMode, network.expensive, network.ipv6, network.addresses, network.proxy (attention/moderate when a proxy is configured), network.vpn (attention with severity low, heuristic, when indicated; verified heuristic otherwise), plus wifi.security when the path may be on Wi-Fi. The public address is not determined. NWPath.supportsDNS is shown as reported but is not turned into a finding: it was observed to be false in the iOS Simulator while names resolved, so the DNS probe is the only source of a DNS conclusion.

# 1.3 DNS

DNSProbe.resolve(_:timeout:) calls getaddrinfo on a dedicated thread with a 5 s default timeout; a lookup that times out is abandoned, not interrupted. Failures are classified (DNSFailure.Kind, including not found, timeout, no network). resolve(hosts:maxConcurrent:) runs at most 4 lookups at a time. Not visible to an app and stated as such: which resolver answered, whether the answer was cached, DNSSEC.

# 1.4 TCP latency

LatencyProbe.measure(host:port:samples:timeout:interval:) — defaults port 443, 5 samples (clamped 1…50), 3 s per attempt, 200 ms pause — opens sequential NWConnections with NWParameters.tcp, sends nothing and cancels each once ready. A sample's duration is the TCP handshake time from the connection's establishment report when available, else wall-clock time. LatencyStatistics: minimum, average, median, maximum, jitter (population standard deviation), loss count. This is not ICMP echo.

# 1.5 TLS inspector

TLSInspector.inspect(_:mode:alpn:allowLegacyProtocols:timeout:now:) performs one handshake over NWConnection (defaults: mode: .reportOnly, ALPN h2 and http/1.1, legacy protocols offered so that an obsolete server can be reported, 10 s). In the sec_protocol_options_set_verify_block it evaluates the chain with SecTrustEvaluateWithError, copies at most 16 certificates as DER, and — in reportOnly mode — lets the handshake finish so the negotiated version, cipher suite and ALPN can be read from sec_protocol_metadata. No application data is sent in either mode; the connection is closed when the handshake ends.

In-house parsing (no OS certificate-field API):

  • DER.swift — definite lengths only, at most 4 length bytes, maxDepth 24, maxElements 50 000, maxInputSize 1 MiB, every access bounds-checked.
  • X509Certificate(der:) — subject, issuer, validity, public key (algorithm, bits, curve), signature algorithm, subject alternative names, basic constraints, key usages, SHA-256 fingerprint; verifySelfSignature() for self-signed leaves.
  • HostnameMatcher — RFC 6125 / 9525: exact DNS SAN match; a wildcard only as the whole left-most label, standing for exactly one label; no wildcard under a TLD or a public-suffix-like two-label name (short built-in list, a heuristic); IP addresses against IP SANs only; no common-name fallback.

TLSAssessment.findings (constants expiryWarningDays 14, publicLeafMaximumValidityDays 398):

Finding id attention condition Severity
tls.handshake Handshake did not complete low without chain or verdict, else moderate
tls.trust SecTrustEvaluateWithError false high
tls.validity Expired / not yet valid; expires within 14 days high; low
tls.hostname SANs do not cover the host high
tls.selfSigned / tls.issuer Self-signed leaf / issuer not trusted by the device moderate
tls.protocol TLS 1.0, TLS 1.1 or DTLS 1.0 negotiated moderate
tls.signature MD2, MD5 or SHA-1 signature high
tls.key RSA under 2048 bits, EC under 224 bits high
tls.validityPeriod Leaf valid for more than 398 days low

Not checked: revocation (independently of iOS), Certificate Transparency, the origin of the trusted root.

# 1.6 HTTPS probe

HTTPSProbe.head(_:timeout:) sends HEAD with an ephemeral URLSession (no cookie storage, no cache, no credential storage, 10 s), refuses automatic redirects through its delegate and requests each hop explicitly, at most maximumRedirects (5). Findings: https.request, https.upgrade (attention/moderate when the site stays on http), https.hsts (attention/low without an effective Strict-Transport-Security), https.redirects. The app calls it only from "Check HTTPS Policy", with https://HOST/.

# 1.7 Bonjour browser

LocalNetworkBrowser.browse(serviceTypes:duration:) runs one NWBrowser per service type for a bounded duration (clamped 1–30 s; the app uses 6 s) and streams .found / .lost / .finished. The 14 defaultServiceTypes are exactly the entries of NSBonjourServices in Info.plist. Error kDNSServiceErr_PolicyDenied (−65570) maps to .permissionRequired. Discovered devices are not contacted; the result is a list of advertised services, not a device inventory.

# 1.8 Wi-Fi inspector

WiFiInspector.currentNetwork(locationAuthorization:isOnWiFi:) calls NEHotspotNetwork.fetchCurrent() and returns SSID (first 64 characters), BSSID, WiFiSecurity (open, wep, personal, enterprise, unknown) and a signal strength only when in (0, 1]. WiFiInspector.requirements restates Apple's conditions: the Access Wi-Fi Information entitlement, plus precise Location authorization, or a network the app configured with NEHotspotConfiguration, or an active VPN or NEDNSSettingsManager configuration of the app. ORIX Secure uses only the Location route. When iOS returns nothing, the unavailability kind tells why: permissionRequired (not authorized, or approximate accuracy only), entitlementRequired (precise location authorized but no network), simulator. wifi.security is attention/moderate for open networks, attention/high for WEP, verified for personal/enterprise, userConfirmationRequired when the type is not reported. iOS does not distinguish WPA2 from WPA3.

# 1.9 Requirements per probe

Probe Info.plist key Entitlement Runtime prompt
Connectivity, interfaces, proxy, VPN indicator none none none
DNS, TCP latency, TLS, HTTPS none none none
Bonjour browser NSLocalNetworkUsageDescription, NSBonjourServices none Local network, at the first browse
Wi-Fi inspector NSLocationWhenInUseUsageDescription com.apple.developer.networking.wifi-info Location, from the "Allow to Read Wi-Fi Security" button

# 1.10 Never done

  • No ICMP echo, no raw sockets, no port scan: the latency probe contacts one port of one host.
  • No interception or proxying of traffic; no certificate is installed; no trust setting is modified.
  • No VPN, no DNS configuration, no content filter. NetworkExtension is imported only for NEHotspotNetwork.fetchCurrent(); the project contains no NetworkExtension provider target and no NEVPNManager, NEHotspotConfiguration or NEDNSSettingsManager use.
  • No throughput test, no "what is my IP" service, no reputation lookup, no probe of a host the user did not enter.

# 2. URL analysis

flowchart TD
    I["Input: typed, pasted, orixsecure:// URL,<br/>share extension, QR payload"] --> EX["extractURLs(from:) when the text has whitespace<br/>NSDataDetector + token pass"]
    EX --> A["URLRiskAnalyzer.analyze(_:)"]
    A --> L{"≤ 100 000 scalars<br/>and not empty?"}
    L -->|no| INV["url.invalid, weight 10"]
    L -->|yes| CH["checkCharacters<br/>invisible / bidi, full-width"]
    CH --> P["URLParser.parse<br/>after removing invisible characters"]
    P -->|failure| INV
    P -->|"hierarchical with host"| H["checkScheme → checkHost (IP, IDN, brands, keywords)<br/>→ checkUserinfo → checkPort → checkEncoding<br/>→ checkRedirects → checkPath"]
    P -->|"opaque scheme"| O["checkOpaqueScheme"]
    H --> S["signals: [URLSignal], one per kind"]
    O --> S
    INV --> S
    S --> SC["URLRiskScoring.score = min(100, Σ weights)"]
    SC --> LV["URLRiskScoring.level(forScore:)"]
    LV --> R["URLAnalysis<br/>decomposition, signals, score, level,<br/>methodology, notInspected"]
    R --> RD["reportDocument() — kind .urlAnalysis"]

The analysis is offline and textual: the link is never opened, fetched or resolved, and no redirect is followed. The same URLRiskAnalyzer runs in the app and in the share extension, which makes no network request and stores nothing.

# 2.1 Scoring

Score URLRiskLevel
0 noSignals ("No signals found")
1 … 29 low
30 … 59 (elevatedThreshold = 30) elevated
≥ 60 (highThreshold = 60), capped at maximumScore = 100 high

Each signal kind appears at most once; if a check fires twice the higher weight is kept and the evidence merged. A weight of 0 is an informational signal (state: .verified, severity none); otherwise the finding is attention with severity low (weight < 20), moderate (< 45) or high (≥ 45). Parsed facts are measured / parsedData; pattern judgments are heuristic. URLRiskScoring.methodology states that the weights are editorial judgments, not measured probabilities. There is no level meaning "safe".

# 2.2 Signal kinds (URLSignalKind) and weights

Group Kinds (raw value → weight)
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)
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
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
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
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
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)

Supporting data is embedded, with its limits listed in URLAnalysis.standardNotInspected: a Public Suffix List subset, BrandList.brands, a confusables table (mainly Cyrillic and Greek) and word lists.

# 2.3 QR payload classifier

QRPayloadClassifier.classify(_:) (also QRPayload(decoding:analyzer:)) sorts a decoded payload into QRPayload.Kind: url, wifi, contact, email, phone, sms, location, calendarEvent, text, empty. A url payload gets a full URLAnalysis; links found inside contact cards, calendar events and free text are analysed as embeddedURLAnalyses. A WIFI: payload is parsed into WiFiConfiguration (open, wep, wpa, enterprise, unknown) with findings qr.wifi.open and qr.wifi.wep (attention/moderate) and qr.wifi.unknown (attention/low). The payload is analysed and displayed; it is never opened and no network is joined.

Decoding happens in the app: QRImageReader (Vision VNDetectBarcodesRequest, QR / Aztec / Data Matrix, on a PhotosPicker image, no photo permission) and QRScannerView (VisionKit DataScannerViewController). LinkAnalyzerView.openScanner() calls AVCaptureDevice.requestAccess(for: .video) when the status is .notDetermined, then presents the scanner sheet.

# 3. Verification status

  • ORIXNetworkLabTests has logic, findings and X.509 suites that run offline, and LiveTests that contact real hosts; ORIXURLRiskTests runs corpora of links, Punycode vectors and QR payloads. They were not re-run while writing this document.
  • Wi-Fi: WiFiInspector returns .unavailable(.simulator) in the Simulator, so NEHotspotNetwork.fetchCurrent(), the entitlement and the precise-location requirement have never been exercised on a device.
  • Bonjour and the local-network prompt, cellular / expensive / constrained paths, real VPN and proxy configurations, and the camera QR scanner were run in the Simulator or compiled only.
  • The camera request (openScanner()), the scanner sheet and its "Camera not available" fallback when DataScannerViewController.isAvailable is false have not been exercised on a physical device.
Files main
Menu

Theme