session-ios/SignalServiceKit/src/Loki/API/Onion Requests/OnionRequestAPI.swift

294 lines
15 KiB
Swift
Raw Normal View History

2020-04-01 04:32:46 +02:00
import CryptoSwift
2020-03-30 02:35:45 +02:00
import PromiseKit
2020-03-30 06:18:55 +02:00
// TODO: Test path snodes as well
/// See the "Onion Requests" section of [The Session Whitepaper](https://arxiv.org/pdf/2002.04609.pdf) for more information.
2020-03-30 02:35:45 +02:00
internal enum OnionRequestAPI {
2020-03-31 05:52:56 +02:00
private static let urlSession = URLSession(configuration: .ephemeral, delegate: urlSessionDelegate, delegateQueue: nil)
2020-03-31 06:27:28 +02:00
private static let urlSessionDelegate = URLSessionDelegateImplementation()
2020-03-31 05:52:56 +02:00
2020-03-30 02:35:45 +02:00
internal static var guardSnodes: Set<LokiAPITarget> = []
internal static var paths: Set<Path> = []
2020-03-31 06:27:28 +02:00
/// - Note: Exposed for testing purposes.
2020-03-31 07:16:26 +02:00
internal static let workQueue = DispatchQueue(label: "OnionRequestAPI.workQueue", qos: .userInitiated)
2020-03-30 02:35:45 +02:00
2020-03-30 02:38:06 +02:00
// MARK: Settings
2020-03-30 02:35:45 +02:00
private static let pathCount: UInt = 3
/// The number of snodes (including the guard snode) in a path.
private static let pathSize: UInt = 3
2020-03-31 06:27:28 +02:00
private static let timeout: TimeInterval = 20
2020-03-30 02:35:45 +02:00
private static var guardSnodeCount: UInt { return pathCount } // One per path
// MARK: HTTP Verb
private enum HTTPVerb : String {
case get = "GET"
case put = "PUT"
case post = "POST"
case delete = "DELETE"
}
2020-03-31 05:52:56 +02:00
// MARK: URL Session Delegate Implementation
private final class URLSessionDelegateImplementation : NSObject, URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// Snode to snode communication uses self-signed certificates but clients can safely ignore this
completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
}
2020-03-30 02:38:06 +02:00
// MARK: Error
2020-03-30 02:35:45 +02:00
internal enum Error : LocalizedError {
2020-03-31 06:27:28 +02:00
case generic
case httpRequestFailed(statusCode: UInt, json: JSON?)
2020-03-30 02:35:45 +02:00
case insufficientSnodes
2020-03-31 07:16:26 +02:00
case invalidJSON
case missingSnodeVersion
2020-03-31 05:52:56 +02:00
case randomDataGenerationFailed
2020-03-31 06:27:28 +02:00
case snodePublicKeySetMissing
case unsupportedSnodeVersion(String)
2020-03-30 02:35:45 +02:00
var errorDescription: String? {
switch self {
2020-03-31 06:27:28 +02:00
case .generic: return "An error occurred."
case .httpRequestFailed(let statusCode, _): return "HTTP request failed with status code: \(statusCode)."
2020-03-30 02:35:45 +02:00
case .insufficientSnodes: return "Couldn't find enough snodes to build a path."
2020-03-31 07:16:26 +02:00
case .invalidJSON: return "Invalid JSON."
case .missingSnodeVersion: return "Missing snode version."
2020-03-31 05:52:56 +02:00
case .randomDataGenerationFailed: return "Couldn't generate random data."
2020-03-31 06:27:28 +02:00
case .snodePublicKeySetMissing: return "Missing snode public key set."
case .unsupportedSnodeVersion(let version): return "Unsupported snode version: \(version)."
2020-03-30 02:35:45 +02:00
}
}
}
2020-03-30 02:38:06 +02:00
// MARK: Path
2020-03-30 06:18:55 +02:00
internal typealias Path = [LokiAPITarget]
2020-03-30 02:35:45 +02:00
// MARK: Onion Building Result
2020-04-01 04:32:46 +02:00
private typealias OnionBuildingResult = (guardSnode: LokiAPITarget, encryptionResult: EncryptionResult, symmetricKey: Data)
2020-03-30 02:35:45 +02:00
// MARK: Private API
private static func execute(_ verb: HTTPVerb, _ url: String, parameters: JSON? = nil, timeout: TimeInterval = OnionRequestAPI.timeout) -> Promise<Any> {
return Promise<Any> { seal in
let url = URL(string: url)!
var request = URLRequest(url: url)
request.httpMethod = verb.rawValue
if let parameters = parameters {
do {
guard JSONSerialization.isValidJSONObject(parameters) else { return seal.reject(Error.invalidJSON) }
request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
} catch (let error) {
return seal.reject(error)
}
}
request.timeoutInterval = timeout
let task = urlSession.dataTask(with: request) { data, response, error in
guard let data = data, let response = response as? HTTPURLResponse else {
print("[Loki] [Onion Request API] \(verb.rawValue) request to \(url) failed.")
return seal.reject(Error.generic)
}
if let error = error {
print("[Loki] [Onion Request API] \(verb.rawValue) request to \(url) failed due to error: \(error).")
return seal.reject(error)
}
let statusCode = UInt(response.statusCode)
guard 200...299 ~= statusCode else {
var json: JSON? = nil
if let j = try? JSONSerialization.jsonObject(with: data, options: []) as? JSON {
json = j
2020-04-01 04:10:34 +02:00
} else if let result = String(data: data, encoding: .utf8) {
json = [ "result" : result ]
}
let jsonDescription = json?.prettifiedDescription ?? "no debugging info provided"
2020-04-01 03:56:02 +02:00
print("[Loki] [Onion Request API] \(verb.rawValue) request to \(url) failed with status code: \(statusCode) (\(jsonDescription)).")
return seal.reject(Error.httpRequestFailed(statusCode: statusCode, json: json))
}
2020-04-01 04:10:34 +02:00
var json: JSON! = nil
if let j = try? JSONSerialization.jsonObject(with: data, options: []) as? JSON {
json = j
} else if let result = String(data: data, encoding: .utf8) {
json = [ "result" : result ]
} else {
print("[Loki] [Onion Request API] Couldn't parse JSON returned by \(verb.rawValue) request to \(url).")
2020-04-01 04:10:34 +02:00
return seal.reject(Error.invalidJSON)
}
2020-04-01 04:32:46 +02:00
seal.fulfill(json!)
}
task.resume()
}
}
2020-03-30 06:18:55 +02:00
/// Tests the given snode. The returned promise errors out if the snode is faulty; the promise is fulfilled otherwise.
private static func testSnode(_ snode: LokiAPITarget) -> Promise<Void> {
2020-03-31 07:16:26 +02:00
let (promise, seal) = Promise<Void>.pending()
let queue = DispatchQueue(label: UUID().uuidString, qos: .userInitiated) // No need to block the work queue for this
queue.async {
print("[Loki] [Onion Request API] Testing snode: \(snode).")
let url = "\(snode.address):\(snode.port)/get_stats/v1"
let timeout: TimeInterval = 10 // Use a shorter timeout for testing
execute(.get, url, timeout: timeout).done(on: queue) { rawResponse in
guard let json = rawResponse as? JSON, let version = json["version"] as? String else { return seal.reject(Error.missingSnodeVersion) }
if version >= "2.0.0" {
seal.fulfill(())
} else {
print("[Loki] [Onion Request API] Unsupported snode version: \(version).")
seal.reject(Error.unsupportedSnodeVersion(version))
}
}.catch(on: queue) { error in
2020-03-31 07:16:26 +02:00
seal.reject(error)
}
}
return promise
2020-03-30 02:35:45 +02:00
}
2020-03-31 05:52:56 +02:00
/// Finds `guardSnodeCount` guard snodes to use for path building. The returned promise errors out with `Error.insufficientSnodes`
2020-03-30 02:35:45 +02:00
/// if not enough (reliable) snodes are available.
private static func getGuardSnodes() -> Promise<Set<LokiAPITarget>> {
if !guardSnodes.isEmpty {
return Promise<Set<LokiAPITarget>> { $0.fulfill(guardSnodes) }
} else {
2020-03-30 06:18:55 +02:00
print("[Loki] [Onion Request API] Populating guard snode cache.")
2020-03-30 02:47:38 +02:00
return LokiAPI.getRandomSnode().then(on: workQueue) { _ -> Promise<Set<LokiAPITarget>> in // Just used to populate the snode pool
2020-03-30 02:35:45 +02:00
let snodePool = LokiAPI.randomSnodePool
guard !snodePool.isEmpty else { throw Error.insufficientSnodes }
2020-03-30 02:47:38 +02:00
var result: Set<LokiAPITarget> = [] // Sync on DispatchQueue.global()
2020-03-30 02:35:45 +02:00
func getGuardSnode() -> Promise<LokiAPITarget> {
// randomElement() uses the system's default random generator, which is cryptographically secure
guard let candidate = snodePool.randomElement() else { return Promise<LokiAPITarget> { $0.reject(Error.insufficientSnodes) } }
2020-03-31 06:27:28 +02:00
// Loop until a reliable guard snode is found
2020-03-30 06:18:55 +02:00
return testSnode(candidate).map(on: workQueue) { candidate }.recover(on: workQueue) { _ in getGuardSnode() }
2020-03-30 02:35:45 +02:00
}
func getAndStoreGuardSnode() -> Promise<LokiAPITarget> {
2020-03-30 02:47:38 +02:00
return getGuardSnode().then(on: workQueue) { guardSnode -> Promise<LokiAPITarget> in
2020-03-30 02:35:45 +02:00
if !result.contains(guardSnode) {
result.insert(guardSnode)
return Promise { $0.fulfill(guardSnode) }
} else {
return getAndStoreGuardSnode()
}
}
}
let promises = (0..<guardSnodeCount).map { _ in getAndStoreGuardSnode() }
2020-03-30 02:47:38 +02:00
return when(fulfilled: promises).map(on: workQueue) { guardSnodes in
2020-03-30 02:35:45 +02:00
let guardSnodesAsSet = Set(guardSnodes)
OnionRequestAPI.guardSnodes = guardSnodesAsSet
return guardSnodesAsSet
}
}
}
}
2020-03-31 05:52:56 +02:00
/// Builds and returns `pathCount` paths. The returned promise errors out with `Error.insufficientSnodes`
2020-03-30 02:35:45 +02:00
/// if not enough (reliable) snodes are available.
private static func buildPaths() -> Promise<Set<Path>> {
2020-03-30 06:18:55 +02:00
print("[Loki] [Onion Request API] Building onion request paths.")
2020-03-30 02:47:38 +02:00
return LokiAPI.getRandomSnode().then(on: workQueue) { _ -> Promise<Set<Path>> in // Just used to populate the snode pool
2020-03-30 02:35:45 +02:00
let snodePool = LokiAPI.randomSnodePool
2020-03-30 02:47:38 +02:00
return getGuardSnodes().map(on: workQueue) { guardSnodes in
2020-03-30 02:35:45 +02:00
var unusedSnodes = snodePool.subtracting(guardSnodes)
let minSnodeCount = guardSnodeCount * pathSize - guardSnodeCount
guard unusedSnodes.count >= minSnodeCount else { throw Error.insufficientSnodes }
2020-03-30 02:50:28 +02:00
let result: Set<Path> = Set(guardSnodes.map { guardSnode in
2020-03-30 06:18:55 +02:00
// Force unwrapping is safe because of the minSnodeCount check above
2020-03-31 05:52:56 +02:00
// randomElement() uses the system's default random generator, which is cryptographically secure
2020-03-31 07:16:26 +02:00
let result = [ guardSnode ] + (0..<(pathSize - 1)).map { _ in unusedSnodes.randomElement()! }
print("[Loki] [Onion Request API] Built new onion request path: \(result.prettifiedDescription).")
return result
2020-03-30 02:35:45 +02:00
})
return result
}
}
}
2020-03-30 06:58:16 +02:00
2020-03-31 06:27:28 +02:00
/// Returns a `Path` to be used for building an onion request. Builds new paths as needed.
2020-03-31 05:52:56 +02:00
private static func getPath() -> Promise<Path> {
2020-03-30 02:35:45 +02:00
// randomElement() uses the system's default random generator, which is cryptographically secure
if paths.count >= pathCount {
return Promise<Path> { $0.fulfill(paths.randomElement()!) }
} else {
2020-03-30 02:47:38 +02:00
return buildPaths().map(on: workQueue) { paths in
2020-03-30 02:35:45 +02:00
let path = paths.randomElement()!
OnionRequestAPI.paths = paths
return path
}
}
}
2020-03-30 06:18:55 +02:00
2020-03-31 05:52:56 +02:00
/// Builds an onion around `payload` and returns the result.
private static func buildOnion(around payload: Data, targetedAt snode: LokiAPITarget) -> Promise<OnionBuildingResult> {
2020-03-31 05:52:56 +02:00
var guardSnode: LokiAPITarget!
var encryptionResult: EncryptionResult!
2020-04-01 04:32:46 +02:00
var symmetricKey: Data!
2020-03-31 05:52:56 +02:00
return getPath().then(on: workQueue) { path -> Promise<EncryptionResult> in
guardSnode = path.first!
return encrypt(payload, forTargetSnode: snode).then(on: workQueue) { r -> Promise<EncryptionResult> in
encryptionResult = r
2020-04-01 04:32:46 +02:00
symmetricKey = r.symmetricKey
2020-03-31 05:52:56 +02:00
var path = path
2020-03-30 06:18:55 +02:00
var rhs = snode
2020-03-31 05:52:56 +02:00
func addLayer() -> Promise<EncryptionResult> {
2020-03-30 06:18:55 +02:00
if path.isEmpty {
2020-03-31 05:52:56 +02:00
return Promise<EncryptionResult> { $0.fulfill(encryptionResult) }
2020-03-30 06:18:55 +02:00
} else {
let lhs = path.removeLast()
2020-03-31 06:27:28 +02:00
return OnionRequestAPI.encryptHop(from: lhs, to: rhs, using: encryptionResult).then(on: workQueue) { r -> Promise<EncryptionResult> in
encryptionResult = r
2020-03-30 06:18:55 +02:00
rhs = lhs
2020-03-31 05:52:56 +02:00
return addLayer()
2020-03-30 06:18:55 +02:00
}
}
}
2020-03-31 05:52:56 +02:00
return addLayer()
2020-03-30 06:18:55 +02:00
}
2020-04-01 04:32:46 +02:00
}.map(on: workQueue) { _ in (guardSnode: guardSnode, encryptionResult: encryptionResult, symmetricKey: symmetricKey) }
2020-03-31 05:52:56 +02:00
}
// MARK: Internal API
2020-03-31 06:27:28 +02:00
/// Sends an onion request to `snode`. Builds new paths as needed.
internal static func invoke(_ method: LokiAPITarget.Method, on snode: LokiAPITarget, parameters: JSON) -> Promise<Any> {
2020-03-31 07:49:07 +02:00
let (promise, seal) = Promise<Any>.pending()
workQueue.async {
let parameters: JSON = [ "method" : method.rawValue, "params" : parameters ]
let payload: Data
do {
guard JSONSerialization.isValidJSONObject(parameters) else { return seal.reject(Error.invalidJSON) }
payload = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch (let error) {
return seal.reject(error)
}
buildOnion(around: payload, targetedAt: snode).done(on: workQueue) { intermediate in
let guardSnode = intermediate.guardSnode
let url = "\(guardSnode.address):\(guardSnode.port)/onion_req"
2020-03-31 07:49:07 +02:00
let encryptionResult = intermediate.encryptionResult
let onion = encryptionResult.ciphertext
2020-04-01 04:32:46 +02:00
let symmetricKey = intermediate.symmetricKey
2020-03-31 07:49:07 +02:00
let parameters: JSON = [
"ciphertext" : onion.base64EncodedString(),
"ephemeral_key" : encryptionResult.ephemeralPublicKey.toHexString()
]
execute(.post, url, parameters: parameters).done(on: workQueue) { rawResponse in
2020-04-01 04:32:46 +02:00
guard let json = rawResponse as? JSON, let base64EncodedIVAndCiphertext = json["result"] as? String,
let ivAndCiphertext = Data(base64Encoded: base64EncodedIVAndCiphertext) else { return seal.reject(Error.invalidJSON) }
let iv = ivAndCiphertext[0..<Int(ivSize)]
let ciphertext = ivAndCiphertext[Int(ivSize)..<ivAndCiphertext.endIndex]
do {
let gcm = GCM(iv: iv.bytes, tagLength: Int(gcmTagLength), mode: .combined)
let aes = try AES(key: symmetricKey.bytes, blockMode: gcm, padding: .pkcs7)
let result = try aes.decrypt(ciphertext.bytes)
seal.fulfill(result)
} catch (let error) {
seal.reject(error)
}
}.catch(on: workQueue) { error in
seal.reject(error)
2020-03-30 06:18:55 +02:00
}
}.catch(on: workQueue) { error in
seal.reject(error)
2020-03-30 06:18:55 +02:00
}
}
2020-03-31 07:49:07 +02:00
return promise
2020-03-30 06:18:55 +02:00
}
2020-03-30 02:35:45 +02:00
}