summaryrefslogtreecommitdiff
path: root/DomainDig/DNSLookupService.swift
blob: 9bbc97bdf642178979531a8774761f4a307ecb82 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import Foundation

enum DNSResolverOption: String, CaseIterable, Identifiable {
    case cloudflare
    case google
    case quad9
    case custom

    static let userDefaultsKey = "dnsResolverURL"
    static let defaultURLString = "https://cloudflare-dns.com/dns-query"

    var id: String { rawValue }

    var title: String {
        switch self {
        case .cloudflare: return "Cloudflare"
        case .google: return "Google"
        case .quad9: return "Quad9"
        case .custom: return "Custom"
        }
    }

    var urlString: String? {
        switch self {
        case .cloudflare: return Self.defaultURLString
        case .google: return "https://dns.google/dns-query"
        case .quad9: return "https://dns.quad9.net/dns-query"
        case .custom: return nil
        }
    }

    static func option(for urlString: String) -> DNSResolverOption {
        let trimmedURL = urlString.trimmingCharacters(in: .whitespacesAndNewlines)
        return Self.allCases.first(where: { $0.urlString == trimmedURL }) ?? .custom
    }

    static func isValidCustomURL(_ urlString: String) -> Bool {
        let trimmedURL = urlString.trimmingCharacters(in: .whitespacesAndNewlines)
        guard trimmedURL.hasPrefix("https://") else {
            return false
        }
        return URL(string: trimmedURL) != nil
    }

    static func resolvedURLString(from storedValue: String?) -> String {
        guard let storedValue else {
            return defaultURLString
        }

        let trimmedURL = storedValue.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmedURL.isEmpty else {
            return defaultURLString
        }

        return isValidCustomURL(trimmedURL) ? trimmedURL : defaultURLString
    }
}

struct DNSLookupService {
    private static let rrsigQueryType = 46
    private static let internetClass = 1

    static func lookup(domain: String, recordType: DNSRecordType) async throws -> [DNSRecord] {
        try await lookup(
            domain: domain,
            recordType: recordType,
            resolverURLString: currentResolverURLString()
        )
    }

    static func lookup(
        domain: String,
        recordType: DNSRecordType,
        resolverURLString: String
    ) async throws -> [DNSRecord] {
        let answers = try await lookupAnswers(
            domain: domain,
            queryType: recordType.queryType,
            resolverURLString: resolverURLString
        )

        return answers
            .filter { $0.type == recordType.queryType }
            .map { answer in
                let value: String
                if recordType.usesRawDataValue {
                    value = answer.data
                } else {
                    value = answer.data.trimmingCharacters(in: CharacterSet(charactersIn: "\""))
                }
                return DNSRecord(value: value, ttl: answer.TTL)
            }
    }

    static func lookupAll(domain: String) async -> [DNSSection] {
        typealias Result = (
            type: DNSRecordType,
            records: [DNSRecord],
            wildcard: [DNSRecord],
            dnssecSigned: Bool?,
            error: String?
        )

        let wildcardTypes: Set<DNSRecordType> = [.A, .AAAA, .MX, .TXT, .SRV, .CAA]
        let resolverURLString = currentResolverURLString()

        return await withTaskGroup(of: Result.self, returning: [DNSSection].self) { group in
            for recordType in DNSRecordType.allCases {
                let shouldQueryWildcard = wildcardTypes.contains(recordType)
                group.addTask {
                    var apexRecords: [DNSRecord] = []
                    var wildcardRecords: [DNSRecord] = []
                    var dnssecSigned: Bool?
                    var lookupError: String?

                    do {
                        apexRecords = try await lookup(
                            domain: domain,
                            recordType: recordType,
                            resolverURLString: resolverURLString
                        )
                        dnssecSigned = try await lookupDNSSECStatus(
                            domain: domain,
                            resolverURLString: resolverURLString
                        )
                    } catch {
                        lookupError = error.localizedDescription
                    }

                    if shouldQueryWildcard && lookupError == nil {
                        do {
                            wildcardRecords = try await lookup(
                                domain: "*.\(domain)",
                                recordType: recordType,
                                resolverURLString: resolverURLString
                            )
                        } catch {
                            // Wildcard failure is non-fatal; just leave empty.
                        }
                    }

                    return (recordType, apexRecords, wildcardRecords, dnssecSigned, lookupError)
                }
            }

            var sections: [DNSSection] = []
            for await result in group {
                sections.append(DNSSection(
                    recordType: result.type,
                    records: result.records,
                    wildcardRecords: result.wildcard,
                    dnssecSigned: result.dnssecSigned,
                    error: result.error
                ))
            }

            let order = DNSRecordType.allCases
            return sections.sorted { a, b in
                (order.firstIndex(of: a.recordType) ?? 0) < (order.firstIndex(of: b.recordType) ?? 0)
            }
        }
    }

    private static func lookupAnswers(
        domain: String,
        queryType: Int,
        resolverURLString: String
    ) async throws -> [CloudflareDNSResponse.CloudflareDNSAnswer] {
        let resolverURL = try validatedResolverURL(from: resolverURLString)
        var components = URLComponents(url: resolverURL, resolvingAgainstBaseURL: false)!
        components.queryItems = [
            URLQueryItem(name: "name", value: domain),
            URLQueryItem(name: "type", value: String(queryType))
        ]

        var request = URLRequest(url: components.url!)
        request.setValue("application/dns-json", forHTTPHeaderField: "Accept")

        let (data, response) = try await URLSession.shared.data(for: request)

        guard let httpResponse = response as? HTTPURLResponse,
              httpResponse.statusCode == 200 else {
            return try await lookupAnswersViaRFC8484(
                domain: domain,
                queryType: queryType,
                resolverURL: resolverURL
            )
        }

        let dnsResponse = try JSONDecoder().decode(CloudflareDNSResponse.self, from: data)

        return dnsResponse.Answer ?? []
    }

    private static func lookupDNSSECStatus(
        domain: String,
        resolverURLString: String
    ) async throws -> Bool {
        let answers = try await lookupAnswers(
            domain: domain,
            queryType: rrsigQueryType,
            resolverURLString: resolverURLString
        )
        return answers.contains(where: { $0.type == rrsigQueryType })
    }

    private static func currentResolverURLString() -> String {
        let storedValue = UserDefaults.standard.string(forKey: DNSResolverOption.userDefaultsKey)
        return DNSResolverOption.resolvedURLString(from: storedValue)
    }

    private static func validatedResolverURL(from urlString: String) throws -> URL {
        guard let url = URL(string: urlString) else {
            throw URLError(.badURL)
        }
        return url
    }

    private static func lookupAnswersViaRFC8484(
        domain: String,
        queryType: Int,
        resolverURL: URL
    ) async throws -> [CloudflareDNSResponse.CloudflareDNSAnswer] {
        let queryData = try buildDNSQueryMessage(domain: domain, queryType: queryType)
        let encodedQuery = base64URLEncodedString(for: queryData)

        var components = URLComponents(url: resolverURL, resolvingAgainstBaseURL: false)!
        components.queryItems = [URLQueryItem(name: "dns", value: encodedQuery)]

        var request = URLRequest(url: components.url!)
        request.setValue("application/dns-message", forHTTPHeaderField: "Accept")

        let (data, response) = try await URLSession.shared.data(for: request)

        guard let httpResponse = response as? HTTPURLResponse,
              httpResponse.statusCode == 200 else {
            throw URLError(.badServerResponse)
        }

        return try parseDNSMessage(data)
    }

    private static func buildDNSQueryMessage(domain: String, queryType: Int) throws -> Data {
        let normalizedName = domain.trimmingCharacters(in: .whitespacesAndNewlines)
        let labels = normalizedName.split(separator: ".")

        var data = Data()
        data.appendUInt16(UInt16.random(in: UInt16.min ... UInt16.max))
        data.appendUInt16(0x0100)
        data.appendUInt16(1)
        data.appendUInt16(0)
        data.appendUInt16(0)
        data.appendUInt16(0)

        for label in labels {
            guard let labelData = label.data(using: .utf8),
                  labelData.count <= 63 else {
                throw URLError(.badURL)
            }
            data.append(UInt8(labelData.count))
            data.append(labelData)
        }

        data.append(0)
        data.appendUInt16(UInt16(queryType))
        data.appendUInt16(UInt16(internetClass))

        return data
    }

    private static func base64URLEncodedString(for data: Data) -> String {
        data.base64EncodedString()
            .replacingOccurrences(of: "+", with: "-")
            .replacingOccurrences(of: "/", with: "_")
            .replacingOccurrences(of: "=", with: "")
    }

    private static func parseDNSMessage(_ data: Data) throws -> [CloudflareDNSResponse.CloudflareDNSAnswer] {
        guard data.count >= 12 else {
            throw URLError(.cannotParseResponse)
        }

        let answerCount = Int(readUInt16(in: data, at: 6))
        let questionCount = Int(readUInt16(in: data, at: 4))
        var offset = 12

        for _ in 0 ..< questionCount {
            _ = try readDomainName(in: data, offset: &offset)
            offset += 4
        }

        var answers: [CloudflareDNSResponse.CloudflareDNSAnswer] = []
        for _ in 0 ..< answerCount {
            let name = try readDomainName(in: data, offset: &offset)
            let type = Int(readUInt16(in: data, at: offset))
            offset += 2
            _ = readUInt16(in: data, at: offset)
            offset += 2
            let ttl = Int(readUInt32(in: data, at: offset))
            offset += 4
            let dataLength = Int(readUInt16(in: data, at: offset))
            offset += 2

            guard offset + dataLength <= data.count else {
                throw URLError(.cannotParseResponse)
            }

            let recordDataOffset = offset
            let recordData = data.subdata(in: recordDataOffset ..< (recordDataOffset + dataLength))
            offset += dataLength

            let parsedValue = try parseRecordData(
                from: data,
                recordType: type,
                recordDataOffset: recordDataOffset,
                recordData: recordData
            )

            answers.append(.init(
                name: name,
                type: type,
                TTL: ttl,
                data: parsedValue
            ))
        }

        return answers
    }

    private static func parseRecordData(
        from message: Data,
        recordType: Int,
        recordDataOffset: Int,
        recordData: Data
    ) throws -> String {
        switch recordType {
        case 1:
            guard recordData.count == 4 else { throw URLError(.cannotParseResponse) }
            return recordData.map(String.init).joined(separator: ".")
        case 2, 5:
            var offset = recordDataOffset
            return try readDomainName(in: message, offset: &offset)
        case 15:
            guard recordData.count >= 3 else { throw URLError(.cannotParseResponse) }
            let preference = readUInt16(in: recordData, at: 0)
            var exchangeOffset = recordDataOffset + 2
            let exchange = try readDomainName(in: message, offset: &exchangeOffset)
            return "\(preference) \(exchange)"
        case 16:
            return try parseTXTData(recordData)
        case 28:
            guard recordData.count == 16 else { throw URLError(.cannotParseResponse) }
            return stride(from: 0, to: 16, by: 2)
                .map { index in
                    String(format: "%x", readUInt16(in: recordData, at: index))
                }
                .joined(separator: ":")
        case 6:
            var offset = recordDataOffset
            let mname = try readDomainName(in: message, offset: &offset)
            let rname = try readDomainName(in: message, offset: &offset)
            let serial = readUInt32(in: message, at: offset)
            let refresh = readUInt32(in: message, at: offset + 4)
            let retry = readUInt32(in: message, at: offset + 8)
            let expire = readUInt32(in: message, at: offset + 12)
            let minimum = readUInt32(in: message, at: offset + 16)
            return "\(mname) \(rname) \(serial) \(refresh) \(retry) \(expire) \(minimum)"
        case 33:
            guard recordData.count >= 7 else { throw URLError(.cannotParseResponse) }
            let priority = readUInt16(in: recordData, at: 0)
            let weight = readUInt16(in: recordData, at: 2)
            let port = readUInt16(in: recordData, at: 4)
            var targetOffset = recordDataOffset + 6
            let target = try readDomainName(in: message, offset: &targetOffset)
            return "\(priority) \(weight) \(port) \(target)"
        case 43:
            guard recordData.count >= 4 else { throw URLError(.cannotParseResponse) }
            let keyTag = readUInt16(in: recordData, at: 0)
            let algorithm = recordData[2]
            let digestType = recordData[3]
            let digest = recordData.dropFirst(4).map { String(format: "%02X", $0) }.joined()
            return "\(keyTag) \(algorithm) \(digestType) \(digest)"
        case 46:
            return "RRSIG"
        case 257:
            guard recordData.count >= 2 else { throw URLError(.cannotParseResponse) }
            let flags = recordData[0]
            let tagLength = Int(recordData[1])
            guard recordData.count >= 2 + tagLength else {
                throw URLError(.cannotParseResponse)
            }
            let tagData = recordData.subdata(in: 2 ..< (2 + tagLength))
            let valueData = recordData.dropFirst(2 + tagLength)
            let tag = String(decoding: tagData, as: UTF8.self)
            let value = String(decoding: valueData, as: UTF8.self)
            return "\(flags) \(tag) \"\(value)\""
        default:
            return recordData.base64EncodedString()
        }
    }

    private static func parseTXTData(_ data: Data) throws -> String {
        var offset = 0
        var strings: [String] = []

        while offset < data.count {
            let count = Int(data[offset])
            offset += 1
            guard offset + count <= data.count else {
                throw URLError(.cannotParseResponse)
            }
            let stringData = data.subdata(in: offset ..< (offset + count))
            strings.append(String(decoding: stringData, as: UTF8.self))
            offset += count
        }

        return strings.joined()
    }

    private static func readDomainName(in data: Data, offset: inout Int) throws -> String {
        var labels: [String] = []
        var currentOffset = offset
        var jumped = false
        var seenOffsets = Set<Int>()

        while true {
            guard currentOffset < data.count else {
                throw URLError(.cannotParseResponse)
            }

            let length = Int(data[currentOffset])

            if length == 0 {
                if !jumped {
                    offset = currentOffset + 1
                }
                break
            }

            if length & 0xC0 == 0xC0 {
                guard currentOffset + 1 < data.count else {
                    throw URLError(.cannotParseResponse)
                }

                let pointer = ((length & 0x3F) << 8) | Int(data[currentOffset + 1])
                guard seenOffsets.insert(pointer).inserted else {
                    throw URLError(.cannotParseResponse)
                }

                if !jumped {
                    offset = currentOffset + 2
                }
                currentOffset = pointer
                jumped = true
                continue
            }

            let labelStart = currentOffset + 1
            let labelEnd = labelStart + length
            guard labelEnd <= data.count else {
                throw URLError(.cannotParseResponse)
            }

            let labelData = data.subdata(in: labelStart ..< labelEnd)
            labels.append(String(decoding: labelData, as: UTF8.self))
            currentOffset = labelEnd
        }

        return labels.joined(separator: ".")
    }

    private static func readUInt16(in data: Data, at offset: Int) -> UInt16 {
        let upper = UInt16(data[offset]) << 8
        let lower = UInt16(data[offset + 1])
        return upper | lower
    }

    private static func readUInt32(in data: Data, at offset: Int) -> UInt32 {
        let first = UInt32(data[offset]) << 24
        let second = UInt32(data[offset + 1]) << 16
        let third = UInt32(data[offset + 2]) << 8
        let fourth = UInt32(data[offset + 3])
        return first | second | third | fourth
    }
}

private extension Data {
    mutating func appendUInt16(_ value: UInt16) {
        append(UInt8((value >> 8) & 0xFF))
        append(UInt8(value & 0xFF))
    }
}