import Foundation import HTTPTypes /// An IPv4 or IPv6 address, parsed from text. Used to find the real client /// behind the proxies in front of the server and to key the rate limiter. struct IPAddress: Hashable, Sendable, CustomStringConvertible { enum Family: Sendable { case v4, v6 } let family: Family /// 4 bytes for IPv4, 16 for IPv6. let bytes: [UInt8] let description: String init?(_ text: String) { var value = text.trimmingCharacters(in: .whitespaces) if value.hasPrefix("["), let close = value.firstIndex(of: "]") { value = String(value[value.index(after: value.startIndex).. [UInt8]? { let parts = text.split(separator: ".", omittingEmptySubsequences: false) guard parts.count == 4 else { return nil } var bytes: [UInt8] = [] for part in parts { guard !part.isEmpty, part.count <= 3, let value = UInt8(part) else { return nil } bytes.append(value) } return bytes } private static func parseV6(_ text: String) -> [UInt8]? { guard text.contains(":"), text.count <= 45 else { return nil } var head = text var tail = "" if let range = text.range(of: "::") { head = String(text[.. [UInt16]? { guard !part.isEmpty else { return [] } var out: [UInt16] = [] let pieces = part.split(separator: ":", omittingEmptySubsequences: false) for (index, piece) in pieces.enumerated() { if index == pieces.count - 1, piece.contains("."), let v4 = parseV4(String(piece)) { out.append(UInt16(v4[0]) << 8 | UInt16(v4[1])) out.append(UInt16(v4[2]) << 8 | UInt16(v4[3])) continue } guard !piece.isEmpty, piece.count <= 4, let value = UInt16(piece, radix: 16) else { return nil } out.append(value) } return out } guard let headGroups = groups(head), let tailGroups = groups(tail) else { return nil } let missing = 8 - headGroups.count - tailGroups.count if text.contains("::") { guard missing >= 1 else { return nil } } else { guard missing == 0 else { return nil } } let all = headGroups + Array(repeating: UInt16(0), count: text.contains("::") ? missing : 0) + tailGroups guard all.count == 8 else { return nil } var bytes: [UInt8] = [] for group in all { bytes.append(UInt8(group >> 8)) bytes.append(UInt8(group & 0xFF)) } return bytes } private static func formatV6(_ bytes: [UInt8]) -> String { var groups: [String] = [] for index in stride(from: 0, to: 16, by: 2) { groups.append(String(UInt16(bytes[index]) << 8 | UInt16(bytes[index + 1]), radix: 16)) } return groups.joined(separator: ":") } } /// A CIDR range such as `10.0.0.0/8` or `fc00::/7`. struct CIDR: Hashable, Sendable { let address: IPAddress let prefixLength: Int init?(_ text: String) { let parts = text.split(separator: "/", omittingEmptySubsequences: false) guard let first = parts.first, let address = IPAddress(String(first)) else { return nil } let maximum = address.family == .v4 ? 32 : 128 let prefix: Int if parts.count == 2 { guard let value = Int(parts[1]), (0...maximum).contains(value) else { return nil } prefix = value } else if parts.count == 1 { prefix = maximum } else { return nil } self.address = address self.prefixLength = prefix } func contains(_ other: IPAddress) -> Bool { guard other.family == address.family else { return false } var remaining = prefixLength for (left, right) in zip(address.bytes, other.bytes) { if remaining <= 0 { return true } if remaining >= 8 { if left != right { return false } remaining -= 8 } else { let mask = UInt8(truncatingIfNeeded: 0xFF << (8 - remaining)) return (left & mask) == (right & mask) } } return true } } /// Works out which address made a request. /// /// Behind a host's edge proxy the socket peer is the proxy, and the client is /// named in a header the proxy wrote. Two kinds of header exist, and the /// resolver handles both: /// /// - `X-Forwarded-For` is a list every hop appends to, and the caller can /// start it with anything. Starting from the peer, the resolver walks it /// from the right and skips every address inside a trusted range; the /// first address that is not trusted is the client. /// - Some edges instead set one header to the caller's address and replace /// whatever the caller sent under that name (`X-Real-IP` on Railway). /// When `EFFEM_CLIENT_ADDRESS_HEADER` names such a header, its value is /// the client and the list is not consulted. /// /// Either way a header is believed only when the socket peer is trusted. /// Loopback, link-local and private ranges always are, which covers a local /// run; `EFFEM_TRUSTED_PROXY_CIDRS` adds the ranges the proxy in front /// connects from (on Railway, `100.64.0.0/10`). An untrusted peer is the /// client whatever any header says, so a forged header that reaches the /// server directly is ignored. struct ClientAddressResolver: Sendable { static let builtInTrustedRanges: [CIDR] = [ "127.0.0.0/8", "::1/128", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "fe80::/10", "fc00::/7", ].compactMap(CIDR.init) let trustedRanges: [CIDR] /// The header the edge sets to the caller's address, when it has one. let assertedHeader: HTTPField.Name? init(additionalTrustedRanges: [CIDR] = [], assertedHeader: HTTPField.Name? = nil) { self.trustedRanges = Self.builtInTrustedRanges + additionalTrustedRanges self.assertedHeader = assertedHeader } func isTrusted(_ address: IPAddress) -> Bool { trustedRanges.contains { $0.contains(address) } } /// Resolves the client of a request from its socket peer and headers. func resolve(peer: IPAddress?, headers: HTTPFields) -> IPAddress? { resolve(peer: peer, forwardedFor: headers[values: HeaderNames.xForwardedFor], asserted: assertedHeader.flatMap { headers[$0] }) } /// - Parameters: /// - peer: The address of the socket peer, nil when unknown (tests). /// - forwardedFor: Every `X-Forwarded-For` header value, in order. /// - asserted: The value of the configured single-address header, if /// one is configured and the request carries it. func resolve(peer: IPAddress?, forwardedFor: [String], asserted: String? = nil) -> IPAddress? { // A peer we do not trust is the client, whatever any header says. if let peer, !isTrusted(peer) { return peer } // The edge's own statement of who called beats a list the caller can start. if let asserted, let address = IPAddress(asserted.trimmingCharacters(in: .whitespaces)) { return address } let chain = forwardedFor .flatMap { $0.split(separator: ",") } .compactMap { IPAddress(String($0)) } for address in chain.reversed() where !isTrusted(address) { return address } // Everything was trusted: the nearest hop is the best answer we have. return chain.first ?? peer } }