DomainDig/DNSLookupService.swift
557 lines · 20257 bytes
1import Foundation
2
3enum DNSResolverOption: String, CaseIterable, Identifiable {
4 case cloudflare
5 case google
6 case quad9
7 case custom
8
9 static let userDefaultsKey = "dnsResolverURL"
10 static let defaultURLString = "https://cloudflare-dns.com/dns-query"
11
12 var id: String { rawValue }
13
14 var title: String {
15 switch self {
16 case .cloudflare: return "Cloudflare"
17 case .google: return "Google"
18 case .quad9: return "Quad9"
19 case .custom: return "Custom"
20 }
21 }
22
23 var urlString: String? {
24 switch self {
25 case .cloudflare: return Self.defaultURLString
26 case .google: return "https://dns.google/dns-query"
27 case .quad9: return "https://dns.quad9.net/dns-query"
28 case .custom: return nil
29 }
30 }
31
32 static func option(for urlString: String) -> DNSResolverOption {
33 let trimmedURL = urlString.trimmingCharacters(in: .whitespacesAndNewlines)
34 return Self.allCases.first(where: { $0.urlString == trimmedURL }) ?? .custom
35 }
36
37 static func isValidCustomURL(_ urlString: String) -> Bool {
38 let trimmedURL = urlString.trimmingCharacters(in: .whitespacesAndNewlines)
39 guard trimmedURL.hasPrefix("https://") else {
40 return false
41 }
42 return URL(string: trimmedURL) != nil
43 }
44
45 static func resolvedURLString(from storedValue: String?) -> String {
46 guard let storedValue else {
47 return defaultURLString
48 }
49
50 let trimmedURL = storedValue.trimmingCharacters(in: .whitespacesAndNewlines)
51 guard !trimmedURL.isEmpty else {
52 return defaultURLString
53 }
54
55 return isValidCustomURL(trimmedURL) ? trimmedURL : defaultURLString
56 }
57}
58
59/// A single record lookup, injectable so callers that branch on its result can
60/// be exercised without network.
61protocol DNSLookup {
62 func lookup(domain: String, recordType: DNSRecordType) async throws -> [DNSRecord]
63}
64
65struct DNSLookupService {
66 private static let internetClass = 1
67
68 static func lookup(domain: String, recordType: DNSRecordType) async throws -> [DNSRecord] {
69 try await lookup(
70 domain: domain,
71 recordType: recordType,
72 resolverURLString: currentResolverURLString()
73 )
74 }
75
76 static func lookup(
77 domain: String,
78 recordType: DNSRecordType,
79 resolverURLString: String
80 ) async throws -> [DNSRecord] {
81 let response = try await lookupResponse(
82 domain: domain,
83 queryType: recordType.queryType,
84 resolverURLString: resolverURLString
85 )
86
87 return response.answers
88 .filter { $0.type == recordType.queryType }
89 .map { answer in
90 let value: String
91 if recordType.usesRawDataValue {
92 value = answer.data
93 } else {
94 value = answer.data.trimmingCharacters(in: CharacterSet(charactersIn: "\""))
95 }
96 return DNSRecord(value: value, ttl: answer.ttl)
97 }
98 }
99
100 static func lookupAll(domain: String) async -> ServiceResult<[DNSSection]> {
101 typealias Result = (
102 type: DNSRecordType,
103 records: [DNSRecord],
104 wildcard: [DNSRecord],
105 dnssecSigned: Bool?,
106 error: String?
107 )
108
109 let wildcardTypes: Set<DNSRecordType> = [.A, .AAAA, .MX, .TXT, .SRV, .CAA]
110 let resolverURLString = currentResolverURLString()
111 let dnssecSigned = try? await lookupDNSSECStatus(
112 domain: domain,
113 resolverURLString: resolverURLString
114 )
115
116 let sections = await withTaskGroup(of: Result.self, returning: [DNSSection].self) { group in
117 for recordType in DNSRecordType.allCases {
118 guard recordType != .PTR else {
119 continue
120 }
121 let shouldQueryWildcard = wildcardTypes.contains(recordType)
122 group.addTask {
123 var apexRecords: [DNSRecord] = []
124 var wildcardRecords: [DNSRecord] = []
125 var lookupError: String?
126
127 do {
128 apexRecords = try await lookup(
129 domain: domain,
130 recordType: recordType,
131 resolverURLString: resolverURLString
132 )
133 } catch {
134 lookupError = error.localizedDescription
135 }
136
137 if shouldQueryWildcard && lookupError == nil {
138 do {
139 wildcardRecords = try await lookup(
140 domain: "*.\(domain)",
141 recordType: recordType,
142 resolverURLString: resolverURLString
143 )
144 } catch {
145 // Wildcard failure is non-fatal; just leave empty.
146 }
147 }
148
149 return (recordType, apexRecords, wildcardRecords, dnssecSigned, lookupError)
150 }
151 }
152
153 var sections: [DNSSection] = []
154 for await result in group {
155 sections.append(DNSSection(
156 recordType: result.type,
157 records: result.records,
158 wildcardRecords: result.wildcard,
159 dnssecSigned: result.dnssecSigned,
160 error: result.error
161 ))
162 }
163
164 let order = DNSRecordType.allCases
165 return sections.sorted { a, b in
166 (order.firstIndex(of: a.recordType) ?? 0) < (order.firstIndex(of: b.recordType) ?? 0)
167 }
168 }
169
170 if sections.contains(where: { !$0.records.isEmpty || !$0.wildcardRecords.isEmpty || $0.error != nil }) {
171 return .success(sections)
172 }
173
174 return .empty("No DNS records found")
175 }
176
177 private static func lookupResponse(
178 domain: String,
179 queryType: Int,
180 resolverURLString: String,
181 includeDNSSECData: Bool = false
182 ) async throws -> DNSLookupResponse {
183 let resolverURL = try validatedResolverURL(from: resolverURLString)
184 var components = URLComponents(url: resolverURL, resolvingAgainstBaseURL: false)!
185 components.queryItems = [
186 URLQueryItem(name: "name", value: domain),
187 URLQueryItem(name: "type", value: String(queryType))
188 ]
189 if includeDNSSECData {
190 components.queryItems?.append(URLQueryItem(name: "do", value: "1"))
191 }
192
193 var request = URLRequest(url: components.url!)
194 request.setValue("application/dns-json", forHTTPHeaderField: "Accept")
195
196 let (data, response) = try await URLSession.shared.data(for: request)
197
198 guard let httpResponse = response as? HTTPURLResponse,
199 httpResponse.statusCode == 200 else {
200 return try await lookupResponseViaRFC8484(
201 domain: domain,
202 queryType: queryType,
203 resolverURL: resolverURL,
204 includeDNSSECData: includeDNSSECData
205 )
206 }
207
208 let dnsResponse = try JSONDecoder().decode(CloudflareDNSResponse.self, from: data)
209
210 return DNSLookupResponse(
211 answers: dnsResponse.answer ?? [],
212 authenticatedData: dnsResponse.authenticatedData ?? false
213 )
214 }
215
216 private static func lookupDNSSECStatus(
217 domain: String,
218 resolverURLString: String
219 ) async throws -> Bool {
220 // Query SOA with the DNSSEC OK bit set. The resolver validates the full
221 // DNSSEC chain and reflects the result in the AD (Authenticated Data) bit
222 // of the response flags. This is more reliable than querying DNSKEY directly,
223 // because resolvers don't always set AD on DNSKEY queries and many zones
224 // don't return DNSKEY records via DoH JSON.
225 let response = try await lookupResponse(
226 domain: domain,
227 queryType: 6, // SOA
228 resolverURLString: resolverURLString,
229 includeDNSSECData: true
230 )
231 return response.authenticatedData
232 }
233
234 static func currentResolverURLString() -> String {
235 let storedValue = UserDefaults.standard.string(forKey: DNSResolverOption.userDefaultsKey)
236 return DNSResolverOption.resolvedURLString(from: storedValue)
237 }
238
239 static func currentResolverDisplayName() -> String {
240 let resolverURLString = currentResolverURLString()
241 let option = DNSResolverOption.option(for: resolverURLString)
242 return option == .custom ? resolverURLString : option.title
243 }
244
245 private static func validatedResolverURL(from urlString: String) throws -> URL {
246 guard let url = URL(string: urlString) else {
247 throw URLError(.badURL)
248 }
249 return url
250 }
251
252 private static func lookupResponseViaRFC8484(
253 domain: String,
254 queryType: Int,
255 resolverURL: URL,
256 includeDNSSECData: Bool
257 ) async throws -> DNSLookupResponse {
258 let queryData = try buildDNSQueryMessage(
259 domain: domain,
260 queryType: queryType,
261 dnssecOK: includeDNSSECData
262 )
263 let encodedQuery = base64URLEncodedString(for: queryData)
264
265 var components = URLComponents(url: resolverURL, resolvingAgainstBaseURL: false)!
266 components.queryItems = [URLQueryItem(name: "dns", value: encodedQuery)]
267
268 var request = URLRequest(url: components.url!)
269 request.setValue("application/dns-message", forHTTPHeaderField: "Accept")
270
271 let (data, response) = try await URLSession.shared.data(for: request)
272
273 guard let httpResponse = response as? HTTPURLResponse,
274 httpResponse.statusCode == 200 else {
275 throw URLError(.badServerResponse)
276 }
277
278 return try parseDNSMessage(data)
279 }
280
281 private static func buildDNSQueryMessage(domain: String, queryType: Int, dnssecOK: Bool = false) throws -> Data {
282 let normalizedName = domain.trimmingCharacters(in: .whitespacesAndNewlines)
283 let labels = normalizedName.split(separator: ".")
284
285 var data = Data()
286 data.appendUInt16(UInt16.random(in: UInt16.min ... UInt16.max))
287 data.appendUInt16(0x0100)
288 data.appendUInt16(1)
289 data.appendUInt16(0)
290 data.appendUInt16(0)
291 data.appendUInt16(dnssecOK ? 1 : 0)
292
293 for label in labels {
294 guard let labelData = label.data(using: .utf8),
295 labelData.count <= 63 else {
296 throw URLError(.badURL)
297 }
298 data.append(UInt8(labelData.count))
299 data.append(labelData)
300 }
301
302 data.append(0)
303 data.appendUInt16(UInt16(queryType))
304 data.appendUInt16(UInt16(internetClass))
305
306 if dnssecOK {
307 data.appendUInt16(0)
308 data.appendUInt16(1)
309 data.appendUInt16(0)
310 data.appendUInt16(0)
311 data.appendUInt16(11)
312 data.appendUInt16(10)
313 data.appendUInt16(8_192)
314 data.appendUInt16(32_768)
315 data.appendUInt16(0)
316 }
317
318 return data
319 }
320
321 private static func base64URLEncodedString(for data: Data) -> String {
322 data.base64EncodedString()
323 .replacingOccurrences(of: "+", with: "-")
324 .replacingOccurrences(of: "/", with: "_")
325 .replacingOccurrences(of: "=", with: "")
326 }
327
328 private static func parseDNSMessage(_ data: Data) throws -> DNSLookupResponse {
329 guard data.count >= 12 else {
330 throw URLError(.cannotParseResponse)
331 }
332
333 let flags = readUInt16(in: data, at: 2)
334 let answerCount = Int(readUInt16(in: data, at: 6))
335 let questionCount = Int(readUInt16(in: data, at: 4))
336 var offset = 12
337
338 for _ in 0 ..< questionCount {
339 _ = try readDomainName(in: data, offset: &offset)
340 offset += 4
341 }
342
343 var answers: [CloudflareDNSResponse.CloudflareDNSAnswer] = []
344 for _ in 0 ..< answerCount {
345 let name = try readDomainName(in: data, offset: &offset)
346 let type = Int(readUInt16(in: data, at: offset))
347 offset += 2
348 _ = readUInt16(in: data, at: offset)
349 offset += 2
350 let ttl = Int(readUInt32(in: data, at: offset))
351 offset += 4
352 let dataLength = Int(readUInt16(in: data, at: offset))
353 offset += 2
354
355 guard offset + dataLength <= data.count else {
356 throw URLError(.cannotParseResponse)
357 }
358
359 let recordDataOffset = offset
360 let recordData = data.subdata(in: recordDataOffset ..< (recordDataOffset + dataLength))
361 offset += dataLength
362
363 let parsedValue = try parseRecordData(
364 from: data,
365 recordType: type,
366 recordDataOffset: recordDataOffset,
367 recordData: recordData
368 )
369
370 answers.append(.init(
371 name: name,
372 type: type,
373 ttl: ttl,
374 data: parsedValue
375 ))
376 }
377
378 return DNSLookupResponse(
379 answers: answers,
380 authenticatedData: (flags & 0x0020) != 0
381 )
382 }
383
384 private static func parseRecordData(
385 from message: Data,
386 recordType: Int,
387 recordDataOffset: Int,
388 recordData: Data
389 ) throws -> String {
390 switch recordType {
391 case 1:
392 guard recordData.count == 4 else { throw URLError(.cannotParseResponse) }
393 return recordData.map(String.init).joined(separator: ".")
394 case 2, 5:
395 var offset = recordDataOffset
396 return try readDomainName(in: message, offset: &offset)
397 case 15:
398 guard recordData.count >= 3 else { throw URLError(.cannotParseResponse) }
399 let preference = readUInt16(in: recordData, at: 0)
400 var exchangeOffset = recordDataOffset + 2
401 let exchange = try readDomainName(in: message, offset: &exchangeOffset)
402 return "\(preference) \(exchange)"
403 case 16:
404 return try parseTXTData(recordData)
405 case 28:
406 guard recordData.count == 16 else { throw URLError(.cannotParseResponse) }
407 return stride(from: 0, to: 16, by: 2)
408 .map { index in
409 String(format: "%x", readUInt16(in: recordData, at: index))
410 }
411 .joined(separator: ":")
412 case 6:
413 var offset = recordDataOffset
414 let mname = try readDomainName(in: message, offset: &offset)
415 let rname = try readDomainName(in: message, offset: &offset)
416 let serial = readUInt32(in: message, at: offset)
417 let refresh = readUInt32(in: message, at: offset + 4)
418 let retry = readUInt32(in: message, at: offset + 8)
419 let expire = readUInt32(in: message, at: offset + 12)
420 let minimum = readUInt32(in: message, at: offset + 16)
421 return "\(mname) \(rname) \(serial) \(refresh) \(retry) \(expire) \(minimum)"
422 case 33:
423 guard recordData.count >= 7 else { throw URLError(.cannotParseResponse) }
424 let priority = readUInt16(in: recordData, at: 0)
425 let weight = readUInt16(in: recordData, at: 2)
426 let port = readUInt16(in: recordData, at: 4)
427 var targetOffset = recordDataOffset + 6
428 let target = try readDomainName(in: message, offset: &targetOffset)
429 return "\(priority) \(weight) \(port) \(target)"
430 case 43:
431 guard recordData.count >= 4 else { throw URLError(.cannotParseResponse) }
432 let keyTag = readUInt16(in: recordData, at: 0)
433 let algorithm = recordData[2]
434 let digestType = recordData[3]
435 let digest = recordData.dropFirst(4).map { String(format: "%02X", $0) }.joined()
436 return "\(keyTag) \(algorithm) \(digestType) \(digest)"
437 case 46:
438 return "RRSIG"
439 case 257:
440 guard recordData.count >= 2 else { throw URLError(.cannotParseResponse) }
441 let flags = recordData[0]
442 let tagLength = Int(recordData[1])
443 guard recordData.count >= 2 + tagLength else {
444 throw URLError(.cannotParseResponse)
445 }
446 let tagData = recordData.subdata(in: 2 ..< (2 + tagLength))
447 let valueData = recordData.dropFirst(2 + tagLength)
448 let tag = String(decoding: tagData, as: UTF8.self)
449 let value = String(decoding: valueData, as: UTF8.self)
450 return "\(flags) \(tag) \"\(value)\""
451 default:
452 return recordData.base64EncodedString()
453 }
454 }
455
456 private static func parseTXTData(_ data: Data) throws -> String {
457 var offset = 0
458 var strings: [String] = []
459
460 while offset < data.count {
461 let count = Int(data[offset])
462 offset += 1
463 guard offset + count <= data.count else {
464 throw URLError(.cannotParseResponse)
465 }
466 let stringData = data.subdata(in: offset ..< (offset + count))
467 strings.append(String(decoding: stringData, as: UTF8.self))
468 offset += count
469 }
470
471 return strings.joined()
472 }
473
474 private static func readDomainName(in data: Data, offset: inout Int) throws -> String {
475 var labels: [String] = []
476 var currentOffset = offset
477 var jumped = false
478 var seenOffsets = Set<Int>()
479
480 while true {
481 guard currentOffset < data.count else {
482 throw URLError(.cannotParseResponse)
483 }
484
485 let length = Int(data[currentOffset])
486
487 if length == 0 {
488 if !jumped {
489 offset = currentOffset + 1
490 }
491 break
492 }
493
494 if length & 0xC0 == 0xC0 {
495 guard currentOffset + 1 < data.count else {
496 throw URLError(.cannotParseResponse)
497 }
498
499 let pointer = ((length & 0x3F) << 8) | Int(data[currentOffset + 1])
500 guard seenOffsets.insert(pointer).inserted else {
501 throw URLError(.cannotParseResponse)
502 }
503
504 if !jumped {
505 offset = currentOffset + 2
506 }
507 currentOffset = pointer
508 jumped = true
509 continue
510 }
511
512 let labelStart = currentOffset + 1
513 let labelEnd = labelStart + length
514 guard labelEnd <= data.count else {
515 throw URLError(.cannotParseResponse)
516 }
517
518 let labelData = data.subdata(in: labelStart ..< labelEnd)
519 labels.append(String(decoding: labelData, as: UTF8.self))
520 currentOffset = labelEnd
521 }
522
523 return labels.joined(separator: ".")
524 }
525
526 private static func readUInt16(in data: Data, at offset: Int) -> UInt16 {
527 let upper = UInt16(data[offset]) << 8
528 let lower = UInt16(data[offset + 1])
529 return upper | lower
530 }
531
532 private static func readUInt32(in data: Data, at offset: Int) -> UInt32 {
533 let first = UInt32(data[offset]) << 24
534 let second = UInt32(data[offset + 1]) << 16
535 let third = UInt32(data[offset + 2]) << 8
536 let fourth = UInt32(data[offset + 3])
537 return first | second | third | fourth
538 }
539}
540
541extension DNSLookupService: DNSLookup {
542 func lookup(domain: String, recordType: DNSRecordType) async throws -> [DNSRecord] {
543 try await Self.lookup(domain: domain, recordType: recordType)
544 }
545}
546
547private struct DNSLookupResponse {
548 let answers: [CloudflareDNSResponse.CloudflareDNSAnswer]
549 let authenticatedData: Bool
550}
551
552private extension Data {
553 mutating func appendUInt16(_ value: UInt16) {
554 append(UInt8((value >> 8) & 0xFF))
555 append(UInt8(value & 0xFF))
556 }
557}