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

273 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
/// 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-04-07 03:18:55 +02:00
/// - Note: Must only be modified from `LokiAPI.workQueue`.
internal static var guardSnodes: Set<LokiAPITarget> = []
2020-04-07 03:18:55 +02:00
/// - Note: Must only be modified from `LokiAPI.workQueue`.
internal static var paths: Set<Path> = []
private static var snodePool: Set<LokiAPITarget> {
let unreliableSnodes = Set(LokiAPI.failureCount.keys)
return LokiAPI.randomSnodePool.subtracting(unreliableSnodes)
}
2020-03-30 02:35:45 +02:00
2020-03-30 02:38:06 +02:00
// MARK: Settings
2020-04-02 00:53:03 +02:00
private static let pathCount: UInt = 2
2020-03-30 02:35:45 +02:00
/// The number of snodes (including the guard snode) in a path.
private static let pathSize: UInt = 1
2020-03-30 02:35:45 +02:00
private static var guardSnodeCount: UInt { return pathCount } // One per path
2020-03-30 02:38:06 +02:00
// MARK: Error
2020-03-30 02:35:45 +02:00
internal enum Error : LocalizedError {
2020-04-06 05:26:26 +02:00
case httpRequestFailedAtTargetSnode(statusCode: UInt, json: JSON)
2020-03-30 02:35:45 +02:00
case insufficientSnodes
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-04-06 05:26:26 +02:00
case .httpRequestFailedAtTargetSnode(let statusCode): return "HTTP request failed at target snode with status code: \(statusCode)."
2020-03-30 02:35:45 +02:00
case .insufficientSnodes: return "Couldn't find enough snodes to build a path."
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-02 03:19:10 +02:00
private typealias OnionBuildingResult = (guardSnode: LokiAPITarget, finalEncryptionResult: EncryptionResult, targetSnodeSymmetricKey: Data)
2020-03-30 02:35:45 +02:00
// MARK: Private API
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()
2020-04-07 02:52:41 +02:00
let queue = DispatchQueue.global() // No need to block the work queue for this
2020-03-31 07:16:26 +02:00
queue.async {
let url = "\(snode.address):\(snode.port)/get_stats/v1"
let timeout: TimeInterval = 6 // Use a shorter timeout for testing
HTTP.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.count >= guardSnodeCount {
2020-03-30 02:35:45 +02:00
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-04-07 03:18:55 +02:00
return LokiAPI.getRandomSnode().then(on: LokiAPI.workQueue) { _ -> Promise<Set<LokiAPITarget>> in // Just used to populate the snode pool
var unusedSnodes = snodePool // Sync on LokiAPI.workQueue
guard unusedSnodes.count >= guardSnodeCount else { throw Error.insufficientSnodes }
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 = unusedSnodes.randomElement() else { return Promise<LokiAPITarget> { $0.reject(Error.insufficientSnodes) } }
unusedSnodes.remove(candidate) // All used snodes should be unique
print("[Loki] [Onion Request API] Testing guard snode: \(candidate).")
2020-03-31 06:27:28 +02:00
// Loop until a reliable guard snode is found
2020-04-07 03:18:55 +02:00
return testSnode(candidate).map(on: LokiAPI.workQueue) { candidate }.recover(on: LokiAPI.workQueue) { _ in getGuardSnode() }
2020-03-30 02:35:45 +02:00
}
let promises = (0..<guardSnodeCount).map { _ in getGuardSnode() }
2020-04-07 03:18:55 +02:00
return when(fulfilled: promises).map(on: LokiAPI.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-04-07 03:18:55 +02:00
return LokiAPI.getRandomSnode().then(on: LokiAPI.workQueue) { _ -> Promise<Set<Path>> in // Just used to populate the snode pool
return getGuardSnodes().map(on: LokiAPI.workQueue) { guardSnodes in
var unusedSnodes = snodePool.subtracting(guardSnodes)
2020-04-01 06:31:04 +02:00
let pathSnodeCount = guardSnodeCount * pathSize - guardSnodeCount
guard unusedSnodes.count >= pathSnodeCount else { throw Error.insufficientSnodes }
// Don't test path snodes as this would reveal the user's IP to them
return Set(guardSnodes.map { guardSnode in
let result = [ guardSnode ] + (0..<(pathSize - 1)).map { _ in
// randomElement() uses the system's default random generator, which is cryptographically secure
let pathSnode = unusedSnodes.randomElement()! // Safe because of the minSnodeCount check above
unusedSnodes.remove(pathSnode) // All used snodes should be unique
return pathSnode
}
2020-03-31 07:16:26 +02:00
print("[Loki] [Onion Request API] Built new onion request path: \(result.prettifiedDescription).")
return result
2020-03-30 02:35:45 +02:00
})
}
}
}
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-04-02 07:10:34 +02:00
///
/// - Note: Exposed for testing purposes.
internal static func getPath(excluding snode: LokiAPITarget) -> Promise<Path> {
2020-04-02 07:30:42 +02:00
guard pathSize >= 1 else { preconditionFailure("Can't build path of size zero.") }
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> { seal in
seal.fulfill(paths.filter { !$0.contains(snode) }.randomElement()!)
}
2020-03-30 02:35:45 +02:00
} else {
2020-04-07 03:18:55 +02:00
return buildPaths().map(on: LokiAPI.workQueue) { paths in
let path = paths.filter { !$0.contains(snode) }.randomElement()!
2020-03-30 02:35:45 +02:00
OnionRequestAPI.paths = paths
return path
}
}
}
2020-03-30 06:18:55 +02:00
private static func dropPath(containing snode: LokiAPITarget) {
paths = paths.filter { !$0.contains(snode) }
}
2020-03-31 05:52:56 +02:00
/// Builds an onion around `payload` and returns the result.
2020-04-02 03:19:10 +02:00
private static func buildOnion(around payload: JSON, targetedAt snode: LokiAPITarget) -> Promise<OnionBuildingResult> {
2020-03-31 05:52:56 +02:00
var guardSnode: LokiAPITarget!
2020-04-02 00:53:03 +02:00
var targetSnodeSymmetricKey: Data! // Needed by invoke(_:on:with:) to decrypt the response sent back by the target snode
var encryptionResult: EncryptionResult!
2020-04-07 03:18:55 +02:00
return getPath(excluding: snode).then(on: LokiAPI.workQueue) { path -> Promise<EncryptionResult> in
2020-03-31 05:52:56 +02:00
guardSnode = path.first!
2020-04-02 00:53:03 +02:00
// Encrypt in reverse order, i.e. the target snode first
2020-04-07 03:18:55 +02:00
return encrypt(payload, forTargetSnode: snode).then(on: LokiAPI.workQueue) { r -> Promise<EncryptionResult> in
2020-04-02 00:53:03 +02:00
targetSnodeSymmetricKey = r.symmetricKey
// Recursively encrypt the layers of the onion (again in reverse order)
encryptionResult = r
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-04-07 03:18:55 +02:00
return OnionRequestAPI.encryptHop(from: lhs, to: rhs, using: encryptionResult).then(on: LokiAPI.workQueue) { r -> Promise<EncryptionResult> in
2020-03-31 06:27:28 +02:00
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-07 03:18:55 +02:00
}.map(on: LokiAPI.workQueue) { _ in (guardSnode, encryptionResult, targetSnodeSymmetricKey) }
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.
2020-04-06 05:26:26 +02:00
internal static func sendOnionRequest(invoking method: LokiAPITarget.Method, on snode: LokiAPITarget, with parameters: JSON, associatedWith hexEncodedPublicKey: String) -> Promise<JSON> {
2020-04-06 03:47:04 +02:00
let (promise, seal) = Promise<JSON>.pending()
2020-04-06 05:26:26 +02:00
var guardSnode: LokiAPITarget!
2020-04-07 03:18:55 +02:00
LokiAPI.workQueue.async {
2020-04-02 03:19:10 +02:00
let payload: JSON = [ "method" : method.rawValue, "params" : parameters ]
2020-04-07 03:18:55 +02:00
buildOnion(around: payload, targetedAt: snode).done(on: LokiAPI.workQueue) { intermediate in
2020-04-06 05:26:26 +02:00
guardSnode = intermediate.guardSnode
let url = "\(guardSnode.address):\(guardSnode.port)/onion_req"
2020-04-02 03:19:10 +02:00
let finalEncryptionResult = intermediate.finalEncryptionResult
let onion = finalEncryptionResult.ciphertext
2020-03-31 07:49:07 +02:00
let parameters: JSON = [
"ciphertext" : onion.base64EncodedString(),
2020-04-02 03:19:10 +02:00
"ephemeral_key" : finalEncryptionResult.ephemeralPublicKey.toHexString()
2020-03-31 07:49:07 +02:00
]
2020-04-02 00:53:03 +02:00
let targetSnodeSymmetricKey = intermediate.targetSnodeSymmetricKey
2020-04-07 03:18:55 +02:00
HTTP.execute(.post, url, parameters: parameters).done(on: LokiAPI.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(HTTP.Error.invalidJSON) }
2020-04-01 04:32:46 +02:00
let iv = ivAndCiphertext[0..<Int(ivSize)]
2020-04-01 05:40:15 +02:00
let ciphertext = ivAndCiphertext[Int(ivSize)...]
2020-04-01 04:32:46 +02:00
do {
2020-04-01 05:40:15 +02:00
let gcm = GCM(iv: iv.bytes, tagLength: Int(gcmTagSize), mode: .combined)
2020-04-06 03:11:24 +02:00
let aes = try AES(key: targetSnodeSymmetricKey.bytes, blockMode: gcm, padding: .noPadding)
2020-04-06 03:47:04 +02:00
let data = Data(try aes.decrypt(ciphertext.bytes))
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? JSON,
let bodyAsString = json["body"] as? String, let bodyAsData = bodyAsString.data(using: .utf8),
2020-04-06 05:26:26 +02:00
let body = try JSONSerialization.jsonObject(with: bodyAsData, options: []) as? JSON,
let statusCode = json["status"] as? Int else { return seal.reject(HTTP.Error.invalidJSON) }
guard 200...299 ~= statusCode else { return seal.reject(Error.httpRequestFailedAtTargetSnode(statusCode: UInt(statusCode), json: body)) }
2020-04-06 03:47:04 +02:00
seal.fulfill(body)
2020-04-01 04:32:46 +02:00
} catch (let error) {
seal.reject(error)
}
2020-04-07 03:18:55 +02:00
}.catch(on: LokiAPI.workQueue) { error in
seal.reject(error)
2020-03-30 06:18:55 +02:00
}
2020-04-07 03:18:55 +02:00
}.catch(on: LokiAPI.workQueue) { error in
seal.reject(error)
2020-03-30 06:18:55 +02:00
}
}
2020-04-07 03:18:55 +02:00
promise.catch(on: LokiAPI.workQueue) { error in // Must be invoked on LokiAPI.workQueue
2020-04-06 05:26:26 +02:00
guard case HTTP.Error.httpRequestFailed(_, _) = error else { return }
dropPath(containing: guardSnode) // A snode in the path is bad; retry with a different path
}
2020-04-06 05:33:15 +02:00
promise.handlingErrorsIfNeeded(forTargetSnode: snode, associatedWith: hexEncodedPublicKey)
return promise
}
}
// MARK: Target Snode Error Handling
private extension Promise where T == JSON {
func handlingErrorsIfNeeded(forTargetSnode snode: LokiAPITarget, associatedWith hexEncodedPublicKey: String) -> Promise<JSON> {
return recover(on: LokiAPI.errorHandlingQueue) { error -> Promise<JSON> in // Must be invoked on LokiAPI.errorHandlingQueue
2020-04-06 05:26:26 +02:00
// The code below is very similar to that in LokiAPI.handlingSnodeErrorsIfNeeded(for:associatedWith:), but unfortunately slightly
// different due to the fact that OnionRequestAPI uses the newer HTTP API, whereas LokiAPI still uses TSNetworkManager
2020-04-06 05:33:15 +02:00
guard case OnionRequestAPI.Error.httpRequestFailedAtTargetSnode(let statusCode, let json) = error else { throw error }
2020-04-06 05:26:26 +02:00
switch statusCode {
case 0, 400, 500, 503:
// The snode is unreachable
let oldFailureCount = LokiAPI.failureCount[snode] ?? 0
let newFailureCount = oldFailureCount + 1
LokiAPI.failureCount[snode] = newFailureCount
print("[Loki] Couldn't reach snode at: \(snode); setting failure count to \(newFailureCount).")
if newFailureCount >= LokiAPI.failureThreshold {
print("[Loki] Failure threshold reached for: \(snode); dropping it.")
LokiAPI.dropIfNeeded(snode, hexEncodedPublicKey: hexEncodedPublicKey) // Remove it from the swarm cache associated with the given public key
LokiAPI.randomSnodePool.remove(snode) // Remove it from the random snode pool
LokiAPI.failureCount[snode] = 0
}
case 406:
print("[Loki] The user's clock is out of sync with the service node network.")
throw LokiAPI.LokiAPIError.clockOutOfSync
case 421:
// The snode isn't associated with the given public key anymore
print("[Loki] Invalidating swarm for: \(hexEncodedPublicKey).")
LokiAPI.dropIfNeeded(snode, hexEncodedPublicKey: hexEncodedPublicKey)
case 432:
// The proof of work difficulty is too low
if let powDifficulty = json["difficulty"] as? Int {
print("[Loki] Setting proof of work difficulty to \(powDifficulty).")
LokiAPI.powDifficulty = UInt(powDifficulty)
} else {
print("[Loki] Failed to update proof of work difficulty.")
}
break
default: break
}
throw error
}
2020-03-30 06:18:55 +02:00
}
2020-03-30 02:35:45 +02:00
}