DomainDig/DomainInsightEngine.swift
561 lines · 21613 bytes
1import Foundation
2
3enum RiskLevel: String, Codable {
4 case low
5 case medium
6 case high
7
8 var title: String { rawValue.capitalized }
9}
10
11enum RiskImpact: String, Codable {
12 case positive
13 case neutral
14 case negative
15}
16
17struct RiskFactor: Codable, Equatable {
18 let description: String
19 let impact: RiskImpact
20}
21
22struct DomainRiskAssessment: Codable, Equatable {
23 let score: Int
24 let level: RiskLevel
25 let factors: [RiskFactor]
26}
27
28enum ChangeImpactClassification: String, Codable {
29 case informational
30 case warning
31 case critical
32
33 var title: String { rawValue.capitalized }
34}
35
36enum EmailSecurityGrade: String, Codable {
37 case a = "A"
38 case b = "B"
39 case c = "C"
40 case f = "F"
41}
42
43struct EmailSecurityAssessment: Codable, Equatable {
44 let grade: EmailSecurityGrade
45 let reasons: [String]
46}
47
48enum TLSGrade: String, Codable {
49 case a = "A"
50 case b = "B"
51 case c = "C"
52 case f = "F"
53}
54
55struct TLSSummaryAssessment: Codable, Equatable {
56 let grade: TLSGrade
57 let highlights: [String]
58}
59
60struct DNSPatternSummary: Codable, Equatable {
61 let providers: [String]
62 let wildcardDetected: Bool
63 let patterns: [String]
64}
65
66struct SubdomainGroup: Codable, Equatable, Identifiable {
67 let label: String
68 let subdomains: [String]
69
70 var id: String { label }
71}
72
73struct WorkflowInsight: Codable, Equatable, Identifiable {
74 let description: String
75 let domainsInvolved: [String]
76
77 var id: String {
78 ([description] + domainsInvolved.sorted()).joined(separator: "|")
79 }
80}
81
82struct DomainAnalysisBundle {
83 let riskAssessment: DomainRiskAssessment
84 let insights: [String]
85 let dnsPatterns: DNSPatternSummary
86 let emailAssessment: EmailSecurityAssessment?
87 let tlsAssessment: TLSSummaryAssessment
88 let subdomainGroups: [SubdomainGroup]
89}
90
91enum DomainInsightEngine {
92 static func analyze(snapshot: LookupSnapshot, previousSnapshot: LookupSnapshot? = nil) -> DomainAnalysisBundle {
93 let dnsPatterns = dnsPatterns(for: snapshot)
94 let emailAssessment = emailAssessment(for: snapshot.emailSecurity)
95 let tlsAssessment = tlsAssessment(for: snapshot)
96 let subdomainGroups = groupedSubdomains(from: snapshot.subdomains.map(\.hostname))
97 let riskAssessment = riskAssessment(
98 for: snapshot,
99 previousSnapshot: previousSnapshot,
100 dnsPatterns: dnsPatterns,
101 emailAssessment: emailAssessment,
102 tlsAssessment: tlsAssessment,
103 subdomainGroups: subdomainGroups
104 )
105 let insights = insights(
106 for: snapshot,
107 previousSnapshot: previousSnapshot,
108 dnsPatterns: dnsPatterns,
109 emailAssessment: emailAssessment,
110 tlsAssessment: tlsAssessment,
111 subdomainGroups: subdomainGroups
112 )
113
114 return DomainAnalysisBundle(
115 riskAssessment: riskAssessment,
116 insights: insights,
117 dnsPatterns: dnsPatterns,
118 emailAssessment: emailAssessment,
119 tlsAssessment: tlsAssessment,
120 subdomainGroups: subdomainGroups
121 )
122 }
123
124 static func workflowInsights(for reports: [DomainReport]) -> [WorkflowInsight] {
125 var insights: [WorkflowInsight] = []
126
127 appendSharedInsights(
128 title: "Shared IP address observed",
129 groups: groupedDomains(for: reports, keyPath: \.dns.primaryIP),
130 into: &insights
131 )
132 appendSharedInsights(
133 title: "Shared nameserver set detected",
134 groups: groupedDomains(for: reports) {
135 let value = $0.ownership?.nameservers.sorted().joined(separator: "|")
136 return value?.nilIfEmpty
137 },
138 into: &insights
139 )
140 appendSharedInsights(
141 title: "Shared registrar detected",
142 groups: groupedDomains(for: reports) { $0.ownership?.registrar?.nilIfEmpty },
143 into: &insights
144 )
145 appendSharedInsights(
146 title: "Shared TLS issuer detected",
147 groups: groupedDomains(for: reports) { $0.web.tls?.issuer.nilIfEmpty },
148 into: &insights
149 )
150
151 return insights
152 }
153
154 static func impactClassification(
155 severity: ChangeSeverity,
156 riskDelta: Int,
157 changedSections: [String]
158 ) -> ChangeImpactClassification {
159 if severity == .high || riskDelta >= 20 || changedSections.contains(where: {
160 $0.localizedCaseInsensitiveContains("availability")
161 || $0.localizedCaseInsensitiveContains("certificate expires")
162 }) {
163 return .critical
164 }
165 if severity == .medium || riskDelta >= 8 || !changedSections.isEmpty {
166 return .warning
167 }
168 return .informational
169 }
170
171 private static func riskAssessment(
172 for snapshot: LookupSnapshot,
173 previousSnapshot: LookupSnapshot?,
174 dnsPatterns: DNSPatternSummary,
175 emailAssessment: EmailSecurityAssessment?,
176 tlsAssessment: TLSSummaryAssessment,
177 subdomainGroups: [SubdomainGroup]
178 ) -> DomainRiskAssessment {
179 var tally = RiskTally()
180 scoreAvailability(snapshot, into: &tally)
181 scoreDNS(snapshot, patterns: dnsPatterns, into: &tally)
182 scoreTLS(snapshot, assessment: tlsAssessment, into: &tally)
183 scoreRedirects(snapshot, into: &tally)
184 scoreEmail(snapshot, assessment: emailAssessment, into: &tally)
185 scorePorts(snapshot, into: &tally)
186 scoreSubdomains(snapshot, groups: subdomainGroups, into: &tally)
187 scoreGeolocation(snapshot, into: &tally)
188 // Compares against the score so far, so it runs after the snapshot's own factors.
189 if let previousSnapshot {
190 let delta = tally.score - analyze(snapshot: previousSnapshot).riskAssessment.score
191 if delta >= 15 {
192 tally.add(4, "Observed risk has increased materially since the previous snapshot", .negative)
193 }
194 }
195
196 let clampedScore = min(max(tally.score, 0), 100)
197 let level: RiskLevel
198 switch clampedScore {
199 case 0..<35:
200 level = .low
201 case 35..<65:
202 level = .medium
203 default:
204 level = .high
205 }
206
207 return DomainRiskAssessment(score: clampedScore, level: level, factors: tally.factors)
208 }
209
210 /// A risk score in progress, from a baseline of 18, and the factors behind it.
211 private struct RiskTally {
212 var score = 18
213 var factors: [RiskFactor] = []
214
215 mutating func add(_ points: Int, _ description: String, _ impact: RiskImpact) {
216 score += points
217 factors.append(RiskFactor(description: description, impact: impact))
218 }
219 }
220
221 private static func scoreAvailability(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
222 switch snapshot.availabilityResult?.status ?? .unknown {
223 case .available:
224 tally.add(-12, "Domain appears available rather than actively deployed", .positive)
225 case .unknown:
226 tally.add(8, "Ownership and availability could not be confirmed", .negative)
227 case .registered:
228 if !snapshot.dnsSections.isEmpty || snapshot.sslInfo != nil || !snapshot.redirectChain.isEmpty {
229 tally.add(6, "Registered domain exposes active infrastructure", .negative)
230 } else {
231 tally.add(0, "Registered domain with limited active surface detected", .neutral)
232 }
233 }
234 }
235
236 private static func scoreDNS(_ snapshot: LookupSnapshot, patterns: DNSPatternSummary, into tally: inout RiskTally) {
237 let recordTypes = snapshot.dnsSections.filter { !$0.records.isEmpty || !$0.wildcardRecords.isEmpty }.count
238 if recordTypes >= 5 {
239 tally.add(8, "DNS configuration is broad across multiple record types", .negative)
240 }
241 if patterns.wildcardDetected {
242 tally.add(12, "Wildcard DNS is enabled", .negative)
243 }
244 if let firstPattern = patterns.patterns.first {
245 tally.add(0, firstPattern, .neutral)
246 }
247 }
248
249 private static func scoreTLS(_ snapshot: LookupSnapshot, assessment: TLSSummaryAssessment, into tally: inout RiskTally) {
250 switch assessment.grade {
251 case .a:
252 tally.add(-8, "TLS configuration looks current and stable", .positive)
253 case .b:
254 tally.add(-3, "TLS is valid with minor concerns", .positive)
255 case .c:
256 tally.add(10, "TLS configuration has visible weaknesses", .negative)
257 case .f:
258 tally.add(22, "TLS is missing, invalid, or near failure", .negative)
259 }
260 if let daysUntilExpiry = snapshot.sslInfo?.daysUntilExpiry, daysUntilExpiry <= 14 {
261 tally.add(10, "Certificate expires within 14 days", .negative)
262 }
263 }
264
265 private static func scoreRedirects(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
266 if snapshot.redirectChain.count >= 3 {
267 tally.add(8, "Redirect chain is longer than expected", .negative)
268 }
269 if redirectLooksSensitive(snapshot.redirectChain.last?.url) {
270 tally.add(6, "Redirect target looks like an auth or account gateway", .negative)
271 }
272 }
273
274 private static func scoreEmail(
275 _ snapshot: LookupSnapshot,
276 assessment: EmailSecurityAssessment?,
277 into tally: inout RiskTally
278 ) {
279 guard let assessment else {
280 if hasMXRecords(snapshot) {
281 tally.add(14, "Mail is configured without enough email security evidence", .negative)
282 }
283 return
284 }
285 switch assessment.grade {
286 case .a:
287 tally.add(-10, "Email protections are strong and aligned", .positive)
288 case .b:
289 tally.add(-4, "Email protections are present with minor gaps", .positive)
290 case .c:
291 tally.add(8, "Email protections are partial", .negative)
292 case .f:
293 tally.add(18, "Email security protections are weak or absent", .negative)
294 }
295 }
296
297 private static func scorePorts(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
298 let openPorts = snapshot.portScanResults.filter(\.open).map(\.port)
299 let sensitivePorts: Set<UInt16> = [21, 22, 23, 25, 3389, 5900]
300 let exposedSensitivePorts = openPorts.filter { sensitivePorts.contains($0) }
301 if !exposedSensitivePorts.isEmpty {
302 tally.add(min(18, exposedSensitivePorts.count * 6), "Sensitive management or mail ports are exposed", .negative)
303 } else if Set(openPorts) == Set([80, 443]) {
304 tally.add(0, "Exposure is limited to standard web ports", .positive)
305 } else if openPorts.count >= 3 {
306 tally.add(8, "Multiple open services expand the attack surface", .negative)
307 }
308 }
309
310 private static func scoreSubdomains(_ snapshot: LookupSnapshot, groups: [SubdomainGroup], into tally: inout RiskTally) {
311 guard !groups.isEmpty else { return }
312 let labels = Set(groups.map(\.label))
313 if labels.contains("dev") || labels.contains("staging") {
314 tally.add(8, "Development or staging subdomains are discoverable", .negative)
315 }
316 if labels.contains("admin") {
317 tally.add(10, "Administrative subdomains are discoverable", .negative)
318 }
319 if snapshot.subdomains.count >= 8 {
320 tally.add(6, "Large passive subdomain footprint detected", .negative)
321 }
322 }
323
324 private static func scoreGeolocation(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
325 if snapshot.ipGeolocation == nil,
326 snapshot.availabilityResult?.status == .registered,
327 snapshot.dnsSections.contains(where: { $0.recordType == .A && !$0.records.isEmpty }) {
328 tally.add(4, "Active host could not be geolocated", .neutral)
329 }
330 }
331
332 private static func insights(
333 for snapshot: LookupSnapshot,
334 previousSnapshot: LookupSnapshot?,
335 dnsPatterns: DNSPatternSummary,
336 emailAssessment: EmailSecurityAssessment?,
337 tlsAssessment: TLSSummaryAssessment,
338 subdomainGroups: [SubdomainGroup]
339 ) -> [String] {
340 var items: [String] = []
341
342 if let group = subdomainGroups.first(where: { $0.label == "staging" || $0.label == "dev" }) {
343 items.append("Multiple \(group.label) subdomains suggest non-production environments are exposed")
344 }
345 if subdomainGroups.contains(where: { $0.label == "admin" }) {
346 items.append("Administrative subdomains are publicly discoverable")
347 }
348 if let emailAssessment, emailAssessment.grade == .f {
349 items.append("Domain lacks email security protections")
350 } else if let emailAssessment, emailAssessment.grade == .c {
351 items.append("Email security is only partially enforced")
352 }
353 if let daysUntilExpiry = snapshot.sslInfo?.daysUntilExpiry, daysUntilExpiry <= 30 {
354 items.append("Certificate expires soon")
355 }
356 if redirectLooksSensitive(snapshot.redirectChain.last?.url) {
357 items.append("Redirect chain may indicate login gateway")
358 }
359 items.append(contentsOf: dnsPatterns.patterns)
360
361 if let tlsVersion = snapshot.sslInfo?.tlsVersion, tlsVersion == "TLS 1.0" || tlsVersion == "TLS 1.1" {
362 items.append("TLS protocol version is outdated")
363 }
364 if tlsAssessment.grade == .f, snapshot.sslInfo == nil, snapshot.availabilityResult?.status == .registered {
365 items.append("HTTPS endpoint could not be validated")
366 }
367 if let previousSnapshot,
368 let previousURL = previousSnapshot.redirectChain.last?.url,
369 let currentURL = snapshot.redirectChain.last?.url,
370 previousURL != currentURL {
371 items.append("Redirect target changed since the previous snapshot")
372 }
373
374 var deduplicated: [String] = []
375 for item in items where !deduplicated.contains(item) {
376 deduplicated.append(item)
377 }
378 return deduplicated
379 }
380
381 private static func dnsPatterns(for snapshot: LookupSnapshot) -> DNSPatternSummary {
382 let nameservers = snapshot.ownership?.nameservers.map { $0.lowercased() } ?? []
383 let headerNames = Set(snapshot.httpHeaders.map { $0.name.lowercased() })
384 let headerValues = snapshot.httpHeaders.map { $0.value.lowercased() }
385 let allValues = snapshot.dnsSections.flatMap { section in
386 (section.records + section.wildcardRecords).map { $0.value.lowercased() }
387 }
388
389 var providers: [String] = []
390 if nameservers.contains(where: { $0.contains("cloudflare") }) || headerNames.contains("cf-ray") || headerNames.contains("cf-cache-status") {
391 providers.append("Cloudflare")
392 }
393 if nameservers.contains(where: { $0.contains("awsdns") }) || allValues.contains(where: { $0.contains("cloudfront.net") || $0.contains("elb.amazonaws.com") || $0.contains("amazonaws.com") }) {
394 providers.append("AWS")
395 }
396 if allValues.contains(where: { $0.contains("fastly.net") }) || headerValues.contains(where: { $0.contains("fastly") || $0.contains("cache-") }) {
397 providers.append("Fastly")
398 }
399
400 var patterns: [String] = []
401 let wildcardDetected = snapshot.dnsSections.contains { !$0.wildcardRecords.isEmpty }
402 if !providers.isEmpty {
403 patterns.append("CDN or edge network detected: \(providers.joined(separator: ", "))")
404 }
405 if wildcardDetected {
406 patterns.append("Wildcard DNS responses are present")
407 }
408 if hasMXRecords(snapshot), snapshot.emailSecurity == nil {
409 patterns.append("MX records exist without corresponding email security records")
410 }
411 if snapshot.sslInfo != nil, snapshot.dnsSections.first(where: { $0.recordType == .CAA })?.records.isEmpty != false {
412 patterns.append("TLS is active but no CAA record was found")
413 }
414
415 return DNSPatternSummary(providers: providers, wildcardDetected: wildcardDetected, patterns: patterns)
416 }
417
418 private static func emailAssessment(for result: EmailSecurityResult?) -> EmailSecurityAssessment? {
419 guard let result else { return nil }
420
421 let spfFound = result.spf.found
422 let dkimFound = result.dkim.found
423 let dmarcFound = result.dmarc.found
424 let dmarcStrict = isStrictDMARC(result.dmarc.value)
425
426 let dmarcReason: String
427 if !dmarcFound {
428 dmarcReason = "DMARC missing"
429 } else {
430 dmarcReason = dmarcStrict ? "DMARC policy is strict" : "DMARC policy is not strict"
431 }
432
433 let reasons = [
434 spfFound ? "SPF present" : "SPF missing",
435 dmarcReason,
436 dkimFound ? "DKIM present" : "DKIM not detected"
437 ]
438
439 let grade: EmailSecurityGrade
440 if spfFound && dkimFound && dmarcStrict {
441 grade = .a
442 } else if spfFound && dmarcFound && (dkimFound || dmarcStrict) {
443 grade = .b
444 } else if spfFound || dmarcFound || dkimFound {
445 grade = .c
446 } else {
447 grade = .f
448 }
449
450 return EmailSecurityAssessment(grade: grade, reasons: reasons)
451 }
452
453 private static func tlsAssessment(for snapshot: LookupSnapshot) -> TLSSummaryAssessment {
454 guard let sslInfo = snapshot.sslInfo else {
455 return TLSSummaryAssessment(grade: .f, highlights: ["TLS handshake failed or no certificate was returned"])
456 }
457
458 var issues: [String] = []
459 if sslInfo.daysUntilExpiry <= 14 {
460 issues.append("Certificate expires within 14 days")
461 } else if sslInfo.daysUntilExpiry <= 30 {
462 issues.append("Certificate expires within 30 days")
463 }
464 if let tlsVersion = sslInfo.tlsVersion, tlsVersion == "TLS 1.0" || tlsVersion == "TLS 1.1" {
465 issues.append("Uses \(tlsVersion)")
466 }
467 if let cipherSuite = sslInfo.cipherSuite?.lowercased(),
468 cipherSuite.contains("_cbc_") || cipherSuite.contains("3des") || cipherSuite.contains("rc4") {
469 issues.append("Negotiated cipher suite looks weak")
470 }
471
472 let grade: TLSGrade
473 if snapshot.sslError != nil {
474 grade = .f
475 } else if issues.contains(where: { $0.contains("14 days") || $0.contains("weak") || $0.contains("TLS 1.0") || $0.contains("TLS 1.1") }) {
476 grade = .c
477 } else if !issues.isEmpty {
478 grade = .b
479 } else {
480 grade = .a
481 }
482
483 return TLSSummaryAssessment(
484 grade: grade,
485 highlights: issues.isEmpty ? ["Certificate is valid and no weak TLS indicators were detected"] : issues
486 )
487 }
488
489 private static func groupedSubdomains(from subdomains: [String]) -> [SubdomainGroup] {
490 let labels = ["api", "dev", "staging", "admin"]
491 let normalized = Array(Set(subdomains.map { $0.lowercased() })).sorted()
492
493 return labels.compactMap { label in
494 let matches = normalized.filter {
495 guard let firstLabel = $0.split(separator: ".").first?.lowercased() else { return false }
496 return firstLabel == label
497 }
498 guard !matches.isEmpty else { return nil }
499 return SubdomainGroup(label: label, subdomains: matches)
500 }
501 }
502
503 private static func isStrictDMARC(_ value: String?) -> Bool {
504 guard let value = value?.lowercased() else { return false }
505 return value.contains("p=reject") || value.contains("p=quarantine")
506 }
507
508 private static func hasMXRecords(_ snapshot: LookupSnapshot) -> Bool {
509 snapshot.dnsSections.contains { $0.recordType == .MX && !$0.records.isEmpty }
510 }
511
512 private static func redirectLooksSensitive(_ urlString: String?) -> Bool {
513 guard let urlString = urlString?.lowercased() else { return false }
514 return urlString.contains("/login")
515 || urlString.contains("/signin")
516 || urlString.contains("/auth")
517 || urlString.contains("/account")
518 || urlString.contains("sso")
519 }
520
521 private static func appendSharedInsights(
522 title: String,
523 groups: [String: [String]],
524 into insights: inout [WorkflowInsight]
525 ) {
526 for domains in groups.values where domains.count >= 2 {
527 insights.append(
528 WorkflowInsight(
529 description: "\(title) across \(domains.count) domains",
530 domainsInvolved: domains.sorted()
531 )
532 )
533 }
534 }
535
536 private static func groupedDomains(
537 for reports: [DomainReport],
538 keyPath: KeyPath<DomainReport, String?>
539 ) -> [String: [String]] {
540 groupedDomains(for: reports) { $0[keyPath: keyPath]?.nilIfEmpty }
541 }
542
543 private static func groupedDomains(
544 for reports: [DomainReport],
545 transform: (DomainReport) -> String?
546 ) -> [String: [String]] {
547 var grouped: [String: [String]] = [:]
548 for report in reports {
549 guard let value = transform(report) else { continue }
550 grouped[value, default: []].append(report.domain)
551 }
552 return grouped
553 }
554}
555
556private extension String {
557 var nilIfEmpty: String? {
558 let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
559 return trimmed.isEmpty ? nil : trimmed
560 }
561}