DomainDig/PortScanService.swift

254 lines · 8991 bytes

  1import Foundation
  2import Network
  3
  4struct PortScanService {
  5    struct PortInfo: Sendable {
  6        let port: UInt16
  7        let service: String
  8    }
  9
 10    static let ports: [PortInfo] = [
 11        PortInfo(port: 21, service: "FTP"),
 12        PortInfo(port: 22, service: "SSH"),
 13        PortInfo(port: 25, service: "SMTP"),
 14        PortInfo(port: 80, service: "HTTP"),
 15        PortInfo(port: 443, service: "HTTPS"),
 16        PortInfo(port: 587, service: "SMTP (TLS)"),
 17        PortInfo(port: 3306, service: "MySQL"),
 18        PortInfo(port: 5432, service: "PostgreSQL"),
 19        PortInfo(port: 8080, service: "HTTP Alt"),
 20        PortInfo(port: 8443, service: "HTTPS Alt"),
 21    ]
 22
 23    static func scanAll(domain: String) async -> ServiceResult<[PortScanResult]> {
 24        await withTaskGroup(of: PortScanResult.self, returning: [PortScanResult].self) { group in
 25            for info in ports {
 26                group.addTask {
 27                    let result = await probe(domain: domain, port: info.port)
 28                    return PortScanResult(
 29                        port: info.port,
 30                        service: info.service,
 31                        open: result.open,
 32                        kind: .standard,
 33                        durationMs: result.durationMs
 34                    )
 35                }
 36            }
 37
 38            var results: [PortScanResult] = []
 39            for await result in group {
 40                results.append(result)
 41            }
 42
 43            // Sort by port number
 44            let sorted = results.sorted { $0.port < $1.port }
 45            return sorted.isEmpty ? [] : sorted
 46        }
 47        .pipe { $0.isEmpty ? .empty("No port scan results") : .success($0) }
 48    }
 49
 50    static func scanPorts(domain: String, ports: [UInt16], timeout: TimeInterval) async -> ServiceResult<[PortScanResult]> {
 51        await withTaskGroup(of: PortScanResult.self, returning: [PortScanResult].self) { group in
 52            for port in ports {
 53                let service = self.ports.first(where: { $0.port == port })?.service ?? "Custom"
 54                group.addTask {
 55                    let result = await probe(domain: domain, port: port, timeout: timeout)
 56                    return PortScanResult(
 57                        port: port,
 58                        service: service,
 59                        open: result.open,
 60                        kind: .custom,
 61                        durationMs: result.durationMs
 62                    )
 63                }
 64            }
 65
 66            var results: [PortScanResult] = []
 67            for await result in group {
 68                results.append(result)
 69            }
 70
 71            let sorted = results.sorted { $0.port < $1.port }
 72            return sorted.isEmpty ? [] : sorted
 73        }
 74        .pipe { $0.isEmpty ? .empty("No custom port scan results") : .success($0) }
 75    }
 76
 77    /// `results` with each open port's banner, grabbed concurrently.
 78    static func withBanners(_ results: [PortScanResult], host: String) async -> [PortScanResult] {
 79        let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
 80            for result in results where result.open {
 81                group.addTask {
 82                    let banner = await grabBanner(host: host, port: result.port)
 83                    return (result.port, banner)
 84                }
 85            }
 86
 87            var collected: [UInt16: String] = [:]
 88            for await (port, banner) in group {
 89                if let banner {
 90                    collected[port] = banner
 91                }
 92            }
 93            return collected
 94        }
 95
 96        return results.map { result in
 97            var updated = result
 98            updated.banner = banners[result.port]
 99            return updated
100        }
101    }
102
103    static func grabBanner(host: String, port: UInt16, timeout: TimeInterval = 3.0) async -> String? {
104        await withCheckedContinuation { continuation in
105            guard let nwPort = NWEndpoint.Port(rawValue: port) else {
106                continuation.resume(returning: nil)
107                return
108            }
109
110            let connection = NWConnection(host: NWEndpoint.Host(host), port: nwPort, using: .tcp)
111            let context = BannerContext(connection: connection, continuation: continuation)
112            let queue = DispatchQueue(label: "portscan.banner.\(port)")
113
114            connection.stateUpdateHandler = { state in
115                switch state {
116                case .ready:
117                    connection.receive(minimumIncompleteLength: 1, maximumLength: 256) { data, _, _, error in
118                        context.finish(with: printableBanner(from: data, error: error))
119                    }
120                case .failed, .cancelled:
121                    context.finish(with: nil)
122                default:
123                    break
124                }
125            }
126
127            connection.start(queue: queue)
128
129            queue.asyncAfter(deadline: .now() + timeout) {
130                context.finish(with: nil)
131            }
132        }
133    }
134
135    /// Pure data transformation, called from the connection's background queue —
136    /// `nonisolated` opts it out of the project's MainActor default, which would
137    /// otherwise make this call a data-race diagnostic under Swift 6.
138    private nonisolated static func printableBanner(from data: Data?, error: Error?) -> String? {
139        guard error == nil,
140              let data,
141              !data.isEmpty,
142              let rawBanner = String(data: data, encoding: .utf8) else {
143            return nil
144        }
145
146        let printable = rawBanner.filter { character in
147            guard let scalar = character.unicodeScalars.first,
148                  character.unicodeScalars.count == 1 else {
149                return false
150            }
151            return (32...126).contains(scalar.value)
152        }
153
154        let banner = String(printable.prefix(80))
155        return banner.isEmpty ? nil : banner
156    }
157
158    private static func probe(domain: String, port: UInt16) async -> PortProbeResult {
159        await probe(domain: domain, port: port, timeout: 1.5)
160    }
161
162    private static func probe(domain: String, port: UInt16, timeout: TimeInterval) async -> PortProbeResult {
163        await withCheckedContinuation { continuation in
164            let host = NWEndpoint.Host(domain)
165            let nwPort = NWEndpoint.Port(rawValue: port)!
166            let connection = NWConnection(host: host, port: nwPort, using: .tcp)
167            let context = ProbeContext(connection: connection, continuation: continuation)
168
169            connection.stateUpdateHandler = { state in
170                switch state {
171                case .ready:
172                    context.finish(open: true)
173                case .failed, .cancelled:
174                    context.finish(open: false)
175                default:
176                    break
177                }
178            }
179
180            let queue = DispatchQueue(label: "portscan.\(port)")
181            connection.start(queue: queue)
182
183            queue.asyncAfter(deadline: .now() + timeout) {
184                context.finish(open: false)
185            }
186        }
187    }
188}
189
190private struct PortProbeResult: Sendable {
191    let open: Bool
192    let durationMs: Int?
193}
194
195private final class ProbeContext: @unchecked Sendable {
196    private let connection: NWConnection
197    private let continuation: CheckedContinuation<PortProbeResult, Never>
198    private let start = CFAbsoluteTimeGetCurrent()
199    private let lock = NSLock()
200    private nonisolated(unsafe) var resumed = false
201
202    init(connection: NWConnection, continuation: CheckedContinuation<PortProbeResult, Never>) {
203        self.connection = connection
204        self.continuation = continuation
205    }
206
207    nonisolated func finish(open: Bool) {
208        lock.lock()
209        guard !resumed else {
210            lock.unlock()
211            return
212        }
213        resumed = true
214        lock.unlock()
215
216        connection.cancel()
217        let elapsedMs = Int((CFAbsoluteTimeGetCurrent() - start) * 1000)
218        continuation.resume(returning: PortProbeResult(
219            open: open,
220            durationMs: elapsedMs >= 0 ? elapsedMs : nil
221        ))
222    }
223}
224
225private extension Array {
226    func pipe<T>(_ transform: (Self) -> T) -> T {
227        transform(self)
228    }
229}
230
231private final class BannerContext: @unchecked Sendable {
232    private let connection: NWConnection
233    private let continuation: CheckedContinuation<String?, Never>
234    private let lock = NSLock()
235    private nonisolated(unsafe) var resumed = false
236
237    init(connection: NWConnection, continuation: CheckedContinuation<String?, Never>) {
238        self.connection = connection
239        self.continuation = continuation
240    }
241
242    nonisolated func finish(with banner: String?) {
243        lock.lock()
244        guard !resumed else {
245            lock.unlock()
246            return
247        }
248        resumed = true
249        lock.unlock()
250
251        connection.cancel()
252        continuation.resume(returning: banner)
253    }
254}