DomainDig/SubdomainDiscoveryService.swift
79 lines · 2900 bytes
1import Foundation
2
3enum SubdomainDiscoveryService {
4 static func discover(for domain: String, limit: Int = 25) async -> ServiceResult<[DiscoveredSubdomain]> {
5 let normalizedDomain = normalize(domain)
6 guard !normalizedDomain.isEmpty else {
7 return .empty("No passive subdomains found")
8 }
9
10 return await fetchSubdomains(for: normalizedDomain, limit: limit)
11 }
12
13 private static func normalize(_ domain: String) -> String {
14 domain
15 .trimmingCharacters(in: .whitespacesAndNewlines)
16 .lowercased()
17 }
18
19 private static func fetchSubdomains(for domain: String, limit: Int) async -> ServiceResult<[DiscoveredSubdomain]> {
20 var components = URLComponents(string: "https://crt.sh/")!
21 components.queryItems = [
22 URLQueryItem(name: "q", value: "%.\(domain)"),
23 URLQueryItem(name: "output", value: "json")
24 ]
25
26 guard let url = components.url else {
27 return .error("Subdomain discovery unavailable")
28 }
29
30 do {
31 let request = URLRequest(url: url, timeoutInterval: 10)
32 let (data, response) = try await URLSession.shared.data(for: request)
33 guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
34 return .error("Subdomain discovery unavailable")
35 }
36
37 let entries = try JSONDecoder().decode([CRTShEntry].self, from: data)
38 let subdomains = parseSubdomains(from: entries, domain: domain, limit: limit)
39 return subdomains.isEmpty ? .empty("No passive subdomains found") : .success(subdomains)
40 } catch {
41 return .error(error.localizedDescription)
42 }
43 }
44
45 private static func parseSubdomains(from entries: [CRTShEntry], domain: String, limit: Int) -> [DiscoveredSubdomain] {
46 var seen = Set<String>()
47 var results: [DiscoveredSubdomain] = []
48
49 for entry in entries {
50 let names = entry.nameValue
51 .split(separator: "\n")
52 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
53
54 for name in names {
55 let sanitized = name.hasPrefix("*.") ? String(name.dropFirst(2)) : name
56 guard sanitized != domain, sanitized.hasSuffix(".\(domain)") else {
57 continue
58 }
59 guard seen.insert(sanitized).inserted else {
60 continue
61 }
62 results.append(DiscoveredSubdomain(hostname: sanitized))
63 if results.count == limit {
64 return results
65 }
66 }
67 }
68
69 return results
70 }
71}
72
73private struct CRTShEntry: Decodable {
74 let nameValue: String
75
76 enum CodingKeys: String, CodingKey {
77 case nameValue = "name_value"
78 }
79}