From aca4e0ac89c92df2140d785be88a1e220a182aa1 Mon Sep 17 00:00:00 2001 From: Matt Kiazyk Date: Fri, 18 Oct 2024 09:55:36 -0500 Subject: [PATCH 1/7] update readme --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e6c0e42..a5c26de7 100644 --- a/README.md +++ b/README.md @@ -22,11 +22,14 @@ XcodesApp is now part of the `XcodesOrg` - [read more here](nextstep.md) - Just click a button to make a version active with `xcode-select`. - View release notes, OS compatibility, included SDKs and compilers from [Xcode Releases](https://xcodereleases.com). - Dark/Light Mode supported +- Security Key Authentication supported ## Platforms/Runtimes - Xcodes supports downloading the Apple runtimes via the app. Simply click on the Platform, and Xcodes will install automatically for you. +**Note: iOS 18+, tvOS 18+, watchOS 11+, visionOS 2+ requires that Xcode 16.1 Beta 3+ be installed and active.** + ## Experiments - Thanks to the wonderful work of [https://github.com/saagarjha/unxip](https://github.com/saagarjha/unxip), turn on the experiment to increase your unxipping time by up to 70%! More can be found on his repo, but bugs, high memory may occur if used. @@ -160,7 +163,8 @@ popd # Attach the zip that was created in the Product directory to the release # Publish the release -# Update the [Homebrew Cask](https://github.com/RobotsAndPencils/homebrew-cask/blob/master/Casks/xcodes.rb). +shasum -a 256 xcodes.zip +# Update the [Homebrew Cask](https://github.com/XcodesOrg/homebrew-cask/blob/master/Casks/x/xcodes.rb). ``` From e04ed029de01b3599a131dd0c88da54bc616927c Mon Sep 17 00:00:00 2001 From: Matt Kiazyk Date: Tue, 22 Oct 2024 23:35:59 -0500 Subject: [PATCH 2/7] (wip) SRP Login implementation --- Xcodes.xcodeproj/project.pbxproj | 17 +- .../xcshareddata/swiftpm/Package.resolved | 18 ++ Xcodes/AppleAPI/Package.swift | 2 +- Xcodes/AppleAPI/Sources/AppleAPI/Client.swift | 190 +++++++++++++ .../Sources/AppleAPI/URLRequest+Apple.swift | 51 ++++ Xcodes/Backend/AppState.swift | 2 +- Xcodes/Resources/Licenses.rtf | 261 ++++++++++++++++++ xcodes-srp/LICENSE | 201 ++++++++++++++ xcodes-srp/Package.swift | 26 ++ xcodes-srp/README.md | 94 +++++++ xcodes-srp/Sources/SRP/Array.swift | 29 ++ xcodes-srp/Sources/SRP/client.swift | 182 ++++++++++++ xcodes-srp/Sources/SRP/configuration.swift | 201 ++++++++++++++ xcodes-srp/Sources/SRP/error.swift | 21 ++ xcodes-srp/Sources/SRP/keys.swift | 40 +++ xcodes-srp/Sources/SRP/server.swift | 108 ++++++++ xcodes-srp/Sources/SRP/srp.swift | 64 +++++ xcodes-srp/Tests/LinuxMain.swift | 6 + xcodes-srp/Tests/SRPTests/SRPTests.swift | 207 ++++++++++++++ .../Tests/SRPTests/XCTestManifests.swift | 9 + 20 files changed, 1726 insertions(+), 3 deletions(-) create mode 100644 xcodes-srp/LICENSE create mode 100644 xcodes-srp/Package.swift create mode 100644 xcodes-srp/README.md create mode 100644 xcodes-srp/Sources/SRP/Array.swift create mode 100644 xcodes-srp/Sources/SRP/client.swift create mode 100644 xcodes-srp/Sources/SRP/configuration.swift create mode 100644 xcodes-srp/Sources/SRP/error.swift create mode 100644 xcodes-srp/Sources/SRP/keys.swift create mode 100644 xcodes-srp/Sources/SRP/server.swift create mode 100644 xcodes-srp/Sources/SRP/srp.swift create mode 100644 xcodes-srp/Tests/LinuxMain.swift create mode 100644 xcodes-srp/Tests/SRPTests/SRPTests.swift create mode 100644 xcodes-srp/Tests/SRPTests/XCTestManifests.swift diff --git a/Xcodes.xcodeproj/project.pbxproj b/Xcodes.xcodeproj/project.pbxproj index 79e173b8..5e9ee95a 100644 --- a/Xcodes.xcodeproj/project.pbxproj +++ b/Xcodes.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 54; + objectVersion = 60; objects = { /* Begin PBXBuildFile section */ @@ -122,6 +122,7 @@ E84E4F522B323A5F003F3959 /* CornerRadiusModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = E84E4F512B323A5F003F3959 /* CornerRadiusModifier.swift */; }; E84E4F542B333864003F3959 /* PlatformsListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E84E4F532B333864003F3959 /* PlatformsListView.swift */; }; E84E4F572B335094003F3959 /* OrderedCollections in Frameworks */ = {isa = PBXBuildFile; productRef = E84E4F562B335094003F3959 /* OrderedCollections */; }; + E862D43B2CC8B26F00BAA376 /* SRP in Frameworks */ = {isa = PBXBuildFile; productRef = E862D43A2CC8B26F00BAA376 /* SRP */; }; E86671272B309D2F0048559A /* PlatformsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E86671262B309D2F0048559A /* PlatformsView.swift */; }; E87AB3C52939B65E00D72F43 /* Hardware.swift in Sources */ = {isa = PBXBuildFile; fileRef = E87AB3C42939B65E00D72F43 /* Hardware.swift */; }; E87DD6EB25D053FA00D86808 /* Progress+.swift in Sources */ = {isa = PBXBuildFile; fileRef = E87DD6EA25D053FA00D86808 /* Progress+.swift */; }; @@ -358,6 +359,7 @@ CA9FF86D25951C6E00E47BAF /* XCModel in Frameworks */, CABFA9F82592F0F900380FEE /* KeychainAccess in Frameworks */, E83FDC442CBB649100679C6B /* Sparkle in Frameworks */, + E862D43B2CC8B26F00BAA376 /* SRP in Frameworks */, CAA858CD25A3D8BC00ACF8C0 /* ErrorHandling in Frameworks */, E8C0EB1A291EF43E0081528A /* XcodesKit in Frameworks */, E8FD5727291EE4AC001E004C /* AsyncNetworkService in Frameworks */, @@ -723,6 +725,7 @@ E84E4F562B335094003F3959 /* OrderedCollections */, E83FDC432CBB649100679C6B /* Sparkle */, 334A932B2CA885A400A5E079 /* LibFido2Swift */, + E862D43A2CC8B26F00BAA376 /* SRP */, ); productName = XcodesMac; productReference = CAD2E79E2449574E00113D76 /* Xcodes.app */; @@ -812,6 +815,7 @@ E84E4F552B335094003F3959 /* XCRemoteSwiftPackageReference "swift-collections" */, E83FDC422CBB649100679C6B /* XCRemoteSwiftPackageReference "Sparkle" */, 33027E282CA8BB5800CB387C /* XCRemoteSwiftPackageReference "LibFido2Swift" */, + E862D4392CC8B26F00BAA376 /* XCLocalSwiftPackageReference "xcodes-srp" */, ); productRefGroup = CAD2E79F2449574E00113D76 /* Products */; projectDirPath = ""; @@ -1480,6 +1484,13 @@ }; /* End XCConfigurationList section */ +/* Begin XCLocalSwiftPackageReference section */ + E862D4392CC8B26F00BAA376 /* XCLocalSwiftPackageReference "xcodes-srp" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = "xcodes-srp"; + }; +/* End XCLocalSwiftPackageReference section */ + /* Begin XCRemoteSwiftPackageReference section */ 33027E282CA8BB5800CB387C /* XCRemoteSwiftPackageReference "LibFido2Swift" */ = { isa = XCRemoteSwiftPackageReference; @@ -1646,6 +1657,10 @@ package = E84E4F552B335094003F3959 /* XCRemoteSwiftPackageReference "swift-collections" */; productName = OrderedCollections; }; + E862D43A2CC8B26F00BAA376 /* SRP */ = { + isa = XCSwiftPackageProductDependency; + productName = SRP; + }; E8C0EB19291EF43E0081528A /* XcodesKit */ = { isa = XCSwiftPackageProductDependency; productName = XcodesKit; diff --git a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 6acf19b7..89a660f9 100644 --- a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -10,6 +10,15 @@ "version": null } }, + { + "package": "big-num", + "repositoryURL": "https://github.com/adam-fowler/big-num", + "state": { + "branch": null, + "revision": "5c5511ad06aeb2b97d0868f7394e14a624bfb1c7", + "version": "2.0.2" + } + }, { "package": "CombineExpectations", "repositoryURL": "https://github.com/groue/CombineExpectations", @@ -100,6 +109,15 @@ "version": "1.0.5" } }, + { + "package": "swift-crypto", + "repositoryURL": "https://github.com/apple/swift-crypto", + "state": { + "branch": null, + "revision": "ddb07e896a2a8af79512543b1c7eb9797f8898a5", + "version": "1.1.7" + } + }, { "package": "SwiftSoup", "repositoryURL": "https://github.com/scinfu/SwiftSoup", diff --git a/Xcodes/AppleAPI/Package.swift b/Xcodes/AppleAPI/Package.swift index b4c2d5ce..500b9d18 100644 --- a/Xcodes/AppleAPI/Package.swift +++ b/Xcodes/AppleAPI/Package.swift @@ -5,7 +5,7 @@ import PackageDescription let package = Package( name: "AppleAPI", - platforms: [.macOS(.v10_15)], + platforms: [.macOS(.v11)], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( diff --git a/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift b/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift index 4a4cd62f..42698ef9 100644 --- a/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift +++ b/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift @@ -1,5 +1,8 @@ import Foundation import Combine +import SRP +import Crypto +import CommonCrypto public class Client { private static let authTypes = ["sa", "hsa", "non-sa", "hsa2"] @@ -8,6 +11,144 @@ public class Client { // MARK: - Login + public func srpLogin(accountName: String, password: String) -> AnyPublisher { + var serviceKey: String! + + let config = SRPConfiguration(.N2048) + let client = SRPClient(configuration: config) + let clientKeys = client.generateKeys() + + return Current.network.dataTask(with: URLRequest.itcServiceKey) + .map(\.data) + .decode(type: ServiceKeyResponse.self, decoder: JSONDecoder()) + .flatMap { serviceKeyResponse -> AnyPublisher<(String, String), Swift.Error> in + serviceKey = serviceKeyResponse.authServiceKey + + // Fixes issue https://github.com/RobotsAndPencils/XcodesApp/issues/360 + // On 2023-02-23, Apple added a custom implementation of hashcash to their auth flow + // Without this addition, Apple ID's would get set to locked + return self.loadHashcash(accountName: accountName, serviceKey: serviceKey) + .map { return (serviceKey, $0)} + .eraseToAnyPublisher() + } + .flatMap { (serviceKey, hashcash) -> AnyPublisher<(String, String, ServerSRPInitResponse), Swift.Error> in + + return Current.network.dataTask(with: URLRequest.SRPInit(serviceKey: serviceKey, a: clientKeys.private.hex, accountName: accountName)) + .map(\.data) + .decode(type: ServerSRPInitResponse.self, decoder: JSONDecoder()) + .map { return (serviceKey, hashcash, $0) } + .eraseToAnyPublisher() + } + .flatMap { (serviceKey, hashcash, srpInit) -> AnyPublisher in + + guard let decodedB = Data(base64Encoded: srpInit.b) else { + return Fail(error: AuthenticationError.srpInvalidPublicKey) + .eraseToAnyPublisher() + } + + guard let decodedSalt = Data(base64Encoded: srpInit.salt) else { + return Fail(error: AuthenticationError.srpInvalidPublicKey) + .eraseToAnyPublisher() + } + + let iterations = srpInit.iteration + let serverPublic = SRPKey([UInt8](decodedB)) + + guard let encryptedPassword = self.pbkdf2(password: password, saltData: decodedSalt, keyByteCount: 32, prf: CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), rounds: iterations) else { + return Fail(error: AuthenticationError.srpInvalidPublicKey) + .eraseToAnyPublisher() + } + + + let encryptedPasswordArray = encryptedPassword.hexEncodedString() + + print("EncryptedPassword: \(encryptedPasswordArray)") + print("EncryptedPassword: \([UInt8](encryptedPassword))") + do { + + // this calculates "S" + let clientSharedSecret = try client.calculateSharedSecret( + encryptedPassword: encryptedPasswordArray, + salt: [UInt8](decodedSalt), + clientKeys: clientKeys, + serverPublicKey: serverPublic + ) + print("SharedSecret: \(clientSharedSecret)") + + let m1 = client.calculateClientProof( + username: accountName, + salt: [UInt8](decodedSalt), + clientPublicKey: clientKeys.public, + serverPublicKey: serverPublic, + sharedSecret: clientSharedSecret + ) + + let m2 = client.serverProof(clientProof: m1, clientKeys: clientKeys, sharedSecret: clientSharedSecret) + + + print("M1: \(Data(m1).base64EncodedString())") + print("M2: \(Data(m2).base64EncodedString())") + + return Current.network.dataTask(with: URLRequest.SRPComplete(serviceKey: serviceKey, hashcash: hashcash, accountName: accountName, c: srpInit.c, m1: Data(m1).base64EncodedString(), m2: Data(m2).base64EncodedString())) + .mapError { $0 as Swift.Error } + .eraseToAnyPublisher() + } catch { + print("Error: calculateSharedSecret \(error)") + return Fail(error: AuthenticationError.srpInvalidPublicKey) + .eraseToAnyPublisher() + } + } + .flatMap { result -> AnyPublisher in + let (data, response) = result + return Just(data) + .decode(type: SignInResponse.self, decoder: JSONDecoder()) + .flatMap { responseBody -> AnyPublisher in + let httpResponse = response as! HTTPURLResponse + + switch httpResponse.statusCode { + case 200: + return Current.network.dataTask(with: URLRequest.olympusSession) + .map { _ in AuthenticationState.authenticated } + .mapError { $0 as Swift.Error } + .eraseToAnyPublisher() + case 401: + return Fail(error: AuthenticationError.invalidUsernameOrPassword(username: accountName)) + .eraseToAnyPublisher() + case 403: + let errorMessage = responseBody.serviceErrors?.first?.description.replacingOccurrences(of: "-20209: ", with: "") ?? "" + return Fail(error: AuthenticationError.accountLocked(errorMessage)) + .eraseToAnyPublisher() + case 409: + return self.handleTwoStepOrFactor(data: data, response: response, serviceKey: serviceKey) + case 412 where Client.authTypes.contains(responseBody.authType ?? ""): + return Fail(error: AuthenticationError.appleIDAndPrivacyAcknowledgementRequired) + .eraseToAnyPublisher() + default: + return Fail(error: AuthenticationError.unexpectedSignInResponse(statusCode: httpResponse.statusCode, + message: responseBody.serviceErrors?.map { $0.description }.joined(separator: ", "))) + .eraseToAnyPublisher() + } + } + .eraseToAnyPublisher() + } +// .map(\.data) +// .decode(type: ServerSRPInitResponse.self, decoder: JSONDecoder()) +// +// +// +// .flatMap { result -> AnyPublisher in +// return ("") +// } +// .flatMap { serverResponse -> AnyPublisher in +// print(serverResponse) +// return Fail(error: AuthenticationError.accountUsesTwoStepAuthentication) +// .eraseToAnyPublisher() +// } + .mapError { $0 as Swift.Error } + .eraseToAnyPublisher() + } + + public func login(accountName: String, password: String) -> AnyPublisher { var serviceKey: String! @@ -257,6 +398,32 @@ public class Client { .mapError { $0 as Error } .eraseToAnyPublisher() } + + private func pbkdf2(password: String, saltData: Data, keyByteCount: Int, prf: CCPseudoRandomAlgorithm, rounds: Int) -> Data? { + guard let passwordData = password.data(using: .utf8) else { return nil } + + var derivedKeyData = Data(repeating: 0, count: keyByteCount) + let derivedCount = derivedKeyData.count + let derivationStatus: Int32 = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes in + let keyBuffer: UnsafeMutablePointer = + derivedKeyBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + return saltData.withUnsafeBytes { saltBytes -> Int32 in + let saltBuffer: UnsafePointer = saltBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + return CCKeyDerivationPBKDF( + CCPBKDFAlgorithm(kCCPBKDF2), + password, + passwordData.count, + saltBuffer, + saltData.count, + prf, + UInt32(rounds), + keyBuffer, + derivedCount) + } + } + return derivationStatus == kCCSuccess ? derivedKeyData : nil + } + } // MARK: - Types @@ -282,6 +449,7 @@ public enum AuthenticationError: Swift.Error, LocalizedError, Equatable { case notDeveloperAppleId case notAuthorized case invalidResult(resultString: String?) + case srpInvalidPublicKey public var errorDescription: String? { switch self { @@ -316,6 +484,8 @@ public enum AuthenticationError: Swift.Error, LocalizedError, Equatable { return "You are not authorized. Please Sign in with your Apple ID first." case let .invalidResult(resultString): return resultString ?? "If you continue to have problems, please submit a bug report in the Help menu." + case .srpInvalidPublicKey: + return "Invalid Key" } } } @@ -495,3 +665,23 @@ public struct AppleProvider: Decodable, Equatable { public struct AppleUser: Decodable, Equatable { public let fullName: String } + +public struct ServerSRPInitResponse: Decodable { + let iteration: Int + let salt: String + let b: String + let c: String +} + + + +extension String { + func base64ToU8Array() -> Data { + return Data(base64Encoded: self) ?? Data() + } +} +extension Data { + func hexEncodedString() -> String { + return map { String(format: "%02hhx", $0) }.joined() + } +} diff --git a/Xcodes/AppleAPI/Sources/AppleAPI/URLRequest+Apple.swift b/Xcodes/AppleAPI/Sources/AppleAPI/URLRequest+Apple.swift index cc30f3f2..14601503 100644 --- a/Xcodes/AppleAPI/Sources/AppleAPI/URLRequest+Apple.swift +++ b/Xcodes/AppleAPI/Sources/AppleAPI/URLRequest+Apple.swift @@ -10,6 +10,10 @@ public extension URL { static let federate = URL(string: "https://idmsa.apple.com/appleauth/auth/federate")! static let olympusSession = URL(string: "https://appstoreconnect.apple.com/olympus/v1/session")! static let keyAuth = URL(string: "https://idmsa.apple.com/appleauth/auth/verify/security/key")! + + static let srpInit = URL(string: "https://idmsa.apple.com/appleauth/auth/signin/init")! + static let srpComplete = URL(string: "https://idmsa.apple.com/appleauth/auth/signin/complete?isRememberMeEnabled=false")! + } public extension URLRequest { @@ -150,4 +154,51 @@ public extension URLRequest { return request } + + static func SRPInit(serviceKey: String, a: String, accountName: String) -> URLRequest { + struct ServerSRPInitRequest: Encodable { + public let a: String + public let accountName: String + public let protocols: [SRPProtocol] + } + + var request = URLRequest(url: .srpInit) + request.httpMethod = "POST" + request.allHTTPHeaderFields = request.allHTTPHeaderFields ?? [:] + request.allHTTPHeaderFields?["Accept"] = "application/json" + request.allHTTPHeaderFields?["Content-Type"] = "application/json" + request.allHTTPHeaderFields?["X-Requested-With"] = "XMLHttpRequest" + request.allHTTPHeaderFields?["X-Apple-Widget-Key"] = serviceKey + + request.httpBody = try? JSONEncoder().encode(ServerSRPInitRequest(a: a, accountName: accountName, protocols: [.s2k, .s2k_fo])) + return request + } + + static func SRPComplete(serviceKey: String, hashcash: String, accountName: String, c: String, m1: String, m2: String) -> URLRequest { + struct ServerSRPCompleteRequest: Encodable { + let accountName: String + let c: String + let m1: String + let m2: String + let rememberMe: Bool + } + + var request = URLRequest(url: .srpComplete) + request.httpMethod = "POST" + request.allHTTPHeaderFields = request.allHTTPHeaderFields ?? [:] + request.allHTTPHeaderFields?["Accept"] = "application/json" + request.allHTTPHeaderFields?["Content-Type"] = "application/json" + request.allHTTPHeaderFields?["X-Requested-With"] = "XMLHttpRequest" + request.allHTTPHeaderFields?["X-Apple-Widget-Key"] = serviceKey + request.allHTTPHeaderFields?["X-Apple-HC"] = hashcash + + request.httpBody = try? JSONEncoder().encode(ServerSRPCompleteRequest(accountName: accountName, c: c, m1: m1, m2: m2, rememberMe: false)) + return request + } } + +public enum SRPProtocol: String, Codable { + case s2k, s2k_fo +} + + diff --git a/Xcodes/Backend/AppState.swift b/Xcodes/Backend/AppState.swift index b4775496..d18e84a0 100644 --- a/Xcodes/Backend/AppState.swift +++ b/Xcodes/Backend/AppState.swift @@ -288,7 +288,7 @@ class AppState: ObservableObject { Current.defaults.set(username, forKey: "username") isProcessingAuthRequest = true - return client.login(accountName: username, password: password) + return client.srpLogin(accountName: username, password: password) .receive(on: DispatchQueue.main) .handleEvents( receiveOutput: { authenticationState in diff --git a/Xcodes/Resources/Licenses.rtf b/Xcodes/Resources/Licenses.rtf index 2b586eac..7213f22e 100644 --- a/Xcodes/Resources/Licenses.rtf +++ b/Xcodes/Resources/Licenses.rtf @@ -31,6 +31,32 @@ SOFTWARE.\ \ \ +\fs34 BigInt\ +\ + +\fs26 \ +Copyright (c) 2016-2017 K\'e1roly L\uc0\u337 rentey\ +\ +Permission is hereby granted, free of charge, to any person obtaining a copy\ +of this software and associated documentation files (the "Software"), to deal\ +in the Software without restriction, including without limitation the rights\ +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ +copies of the Software, and to permit persons to whom the Software is\ +furnished to do so, subject to the following conditions:\ +\ +The above copyright notice and this permission notice shall be included in all\ +copies or substantial portions of the Software.\ +\ +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\ +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\ +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\ +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\ +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\ +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\ +SOFTWARE.\ +\ +\ + \fs34 SwiftSoup\ \ @@ -113,6 +139,241 @@ SOFTWARE.\ \ \ +\fs34 big-num\ +\ + +\fs26 MIT License\ +\ +Copyright (c) 2019 Adam Fowler\ +\ +Permission is hereby granted, free of charge, to any person obtaining a copy\ +of this software and associated documentation files (the "Software"), to deal\ +in the Software without restriction, including without limitation the rights\ +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ +copies of the Software, and to permit persons to whom the Software is\ +furnished to do so, subject to the following conditions:\ +\ +The above copyright notice and this permission notice shall be included in all\ +copies or substantial portions of the Software.\ +\ +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\ +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\ +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\ +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\ +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\ +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\ +SOFTWARE.\ +\ +\ + +\fs34 swift-crypto\ +\ + +\fs26 \ + Apache License\ + Version 2.0, January 2004\ + http://www.apache.org/licenses/\ +\ + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\ +\ + 1. Definitions.\ +\ + "License" shall mean the terms and conditions for use, reproduction,\ + and distribution as defined by Sections 1 through 9 of this document.\ +\ + "Licensor" shall mean the copyright owner or entity authorized by\ + the copyright owner that is granting the License.\ +\ + "Legal Entity" shall mean the union of the acting entity and all\ + other entities that control, are controlled by, or are under common\ + control with that entity. For the purposes of this definition,\ + "control" means (i) the power, direct or indirect, to cause the\ + direction or management of such entity, whether by contract or\ + otherwise, or (ii) ownership of fifty percent (50%) or more of the\ + outstanding shares, or (iii) beneficial ownership of such entity.\ +\ + "You" (or "Your") shall mean an individual or Legal Entity\ + exercising permissions granted by this License.\ +\ + "Source" form shall mean the preferred form for making modifications,\ + including but not limited to software source code, documentation\ + source, and configuration files.\ +\ + "Object" form shall mean any form resulting from mechanical\ + transformation or translation of a Source form, including but\ + not limited to compiled object code, generated documentation,\ + and conversions to other media types.\ +\ + "Work" shall mean the work of authorship, whether in Source or\ + Object form, made available under the License, as indicated by a\ + copyright notice that is included in or attached to the work\ + (an example is provided in the Appendix below).\ +\ + "Derivative Works" shall mean any work, whether in Source or Object\ + form, that is based on (or derived from) the Work and for which the\ + editorial revisions, annotations, elaborations, or other modifications\ + represent, as a whole, an original work of authorship. For the purposes\ + of this License, Derivative Works shall not include works that remain\ + separable from, or merely link (or bind by name) to the interfaces of,\ + the Work and Derivative Works thereof.\ +\ + "Contribution" shall mean any work of authorship, including\ + the original version of the Work and any modifications or additions\ + to that Work or Derivative Works thereof, that is intentionally\ + submitted to Licensor for inclusion in the Work by the copyright owner\ + or by an individual or Legal Entity authorized to submit on behalf of\ + the copyright owner. For the purposes of this definition, "submitted"\ + means any form of electronic, verbal, or written communication sent\ + to the Licensor or its representatives, including but not limited to\ + communication on electronic mailing lists, source code control systems,\ + and issue tracking systems that are managed by, or on behalf of, the\ + Licensor for the purpose of discussing and improving the Work, but\ + excluding communication that is conspicuously marked or otherwise\ + designated in writing by the copyright owner as "Not a Contribution."\ +\ + "Contributor" shall mean Licensor and any individual or Legal Entity\ + on behalf of whom a Contribution has been received by Licensor and\ + subsequently incorporated within the Work.\ +\ + 2. Grant of Copyright License. Subject to the terms and conditions of\ + this License, each Contributor hereby grants to You a perpetual,\ + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\ + copyright license to reproduce, prepare Derivative Works of,\ + publicly display, publicly perform, sublicense, and distribute the\ + Work and such Derivative Works in Source or Object form.\ +\ + 3. Grant of Patent License. Subject to the terms and conditions of\ + this License, each Contributor hereby grants to You a perpetual,\ + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\ + (except as stated in this section) patent license to make, have made,\ + use, offer to sell, sell, import, and otherwise transfer the Work,\ + where such license applies only to those patent claims licensable\ + by such Contributor that are necessarily infringed by their\ + Contribution(s) alone or by combination of their Contribution(s)\ + with the Work to which such Contribution(s) was submitted. If You\ + institute patent litigation against any entity (including a\ + cross-claim or counterclaim in a lawsuit) alleging that the Work\ + or a Contribution incorporated within the Work constitutes direct\ + or contributory patent infringement, then any patent licenses\ + granted to You under this License for that Work shall terminate\ + as of the date such litigation is filed.\ +\ + 4. Redistribution. You may reproduce and distribute copies of the\ + Work or Derivative Works thereof in any medium, with or without\ + modifications, and in Source or Object form, provided that You\ + meet the following conditions:\ +\ + (a) You must give any other recipients of the Work or\ + Derivative Works a copy of this License; and\ +\ + (b) You must cause any modified files to carry prominent notices\ + stating that You changed the files; and\ +\ + (c) You must retain, in the Source form of any Derivative Works\ + that You distribute, all copyright, patent, trademark, and\ + attribution notices from the Source form of the Work,\ + excluding those notices that do not pertain to any part of\ + the Derivative Works; and\ +\ + (d) If the Work includes a "NOTICE" text file as part of its\ + distribution, then any Derivative Works that You distribute must\ + include a readable copy of the attribution notices contained\ + within such NOTICE file, excluding those notices that do not\ + pertain to any part of the Derivative Works, in at least one\ + of the following places: within a NOTICE text file distributed\ + as part of the Derivative Works; within the Source form or\ + documentation, if provided along with the Derivative Works; or,\ + within a display generated by the Derivative Works, if and\ + wherever such third-party notices normally appear. The contents\ + of the NOTICE file are for informational purposes only and\ + do not modify the License. You may add Your own attribution\ + notices within Derivative Works that You distribute, alongside\ + or as an addendum to the NOTICE text from the Work, provided\ + that such additional attribution notices cannot be construed\ + as modifying the License.\ +\ + You may add Your own copyright statement to Your modifications and\ + may provide additional or different license terms and conditions\ + for use, reproduction, or distribution of Your modifications, or\ + for any such Derivative Works as a whole, provided Your use,\ + reproduction, and distribution of the Work otherwise complies with\ + the conditions stated in this License.\ +\ + 5. Submission of Contributions. Unless You explicitly state otherwise,\ + any Contribution intentionally submitted for inclusion in the Work\ + by You to the Licensor shall be under the terms and conditions of\ + this License, without any additional terms or conditions.\ + Notwithstanding the above, nothing herein shall supersede or modify\ + the terms of any separate license agreement you may have executed\ + with Licensor regarding such Contributions.\ +\ + 6. Trademarks. This License does not grant permission to use the trade\ + names, trademarks, service marks, or product names of the Licensor,\ + except as required for reasonable and customary use in describing the\ + origin of the Work and reproducing the content of the NOTICE file.\ +\ + 7. Disclaimer of Warranty. Unless required by applicable law or\ + agreed to in writing, Licensor provides the Work (and each\ + Contributor provides its Contributions) on an "AS IS" BASIS,\ + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\ + implied, including, without limitation, any warranties or conditions\ + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\ + PARTICULAR PURPOSE. You are solely responsible for determining the\ + appropriateness of using or redistributing the Work and assume any\ + risks associated with Your exercise of permissions under this License.\ +\ + 8. Limitation of Liability. In no event and under no legal theory,\ + whether in tort (including negligence), contract, or otherwise,\ + unless required by applicable law (such as deliberate and grossly\ + negligent acts) or agreed to in writing, shall any Contributor be\ + liable to You for damages, including any direct, indirect, special,\ + incidental, or consequential damages of any character arising as a\ + result of this License or out of the use or inability to use the\ + Work (including but not limited to damages for loss of goodwill,\ + work stoppage, computer failure or malfunction, or any and all\ + other commercial damages or losses), even if such Contributor\ + has been advised of the possibility of such damages.\ +\ + 9. Accepting Warranty or Additional Liability. While redistributing\ + the Work or Derivative Works thereof, You may choose to offer,\ + and charge a fee for, acceptance of support, warranty, indemnity,\ + or other liability obligations and/or rights consistent with this\ + License. However, in accepting such obligations, You may act only\ + on Your own behalf and on Your sole responsibility, not on behalf\ + of any other Contributor, and only if You agree to indemnify,\ + defend, and hold each Contributor harmless for any liability\ + incurred by, or claims asserted against, such Contributor by reason\ + of your accepting any such warranty or additional liability.\ +\ + END OF TERMS AND CONDITIONS\ +\ + APPENDIX: How to apply the Apache License to your work.\ +\ + To apply the Apache License to your work, attach the following\ + boilerplate notice, with the fields enclosed by brackets "[]"\ + replaced with your own identifying information. (Don't include\ + the brackets!) The text should be enclosed in the appropriate\ + comment syntax for the file format. We also recommend that a\ + file or class name and description of purpose be included on the\ + same "printed page" as the copyright notice for easier\ + identification within third-party archives.\ +\ + Copyright [yyyy] [name of copyright owner]\ +\ + Licensed under the Apache License, Version 2.0 (the "License");\ + you may not use this file except in compliance with the License.\ + You may obtain a copy of the License at\ +\ + http://www.apache.org/licenses/LICENSE-2.0\ +\ + Unless required by applicable law or agreed to in writing, software\ + distributed under the License is distributed on an "AS IS" BASIS,\ + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\ + See the License for the specific language governing permissions and\ + limitations under the License.\ +\ +\ + \fs34 Path.swift\ \ diff --git a/xcodes-srp/LICENSE b/xcodes-srp/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/xcodes-srp/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/xcodes-srp/Package.swift b/xcodes-srp/Package.swift new file mode 100644 index 00000000..a4270283 --- /dev/null +++ b/xcodes-srp/Package.swift @@ -0,0 +1,26 @@ +// swift-tools-version:5.1 +// The swift-tools-version declares the minimum version of Swift required to build this package. + +import PackageDescription + +let package = Package( + name: "swift-srp", + platforms: [ + .macOS(.v10_15), + .iOS(.v13), + .watchOS(.v6), + .tvOS(.v13), + ], + products: [ + .library(name: "SRP", targets: ["SRP"]), + ], + dependencies: [ + .package(url: "https://github.com/apple/swift-crypto", from: "1.0.0"), + .package(url: "https://github.com/adam-fowler/big-num", from: "2.0.0"), + ], + targets: [ + .target(name: "SRP", dependencies: ["BigNum", "Crypto"]), + .testTarget( + name: "SRPTests", dependencies: ["SRP"]), + ] +) diff --git a/xcodes-srp/README.md b/xcodes-srp/README.md new file mode 100644 index 00000000..f19c2314 --- /dev/null +++ b/xcodes-srp/README.md @@ -0,0 +1,94 @@ +# Swift SRP + +This library provides a swift implementation of the Secure Remote Password protocol. Secure Remote Password (SRP) provides username and password authentication without needing to provide your password to the server. As the server never sees your password it can never leak it to anyone else. + +The server is provided with a cryptographic verifier that is derived from the password and a salt value that was used in the generation of this verifier. Both client and server generate large private and public keys and with these are able to generate a shared secret. The client then sends a proof they have the secret and if it is verified the server will do the same to verify the server as well. + +The SRP protocol is detailed in [RFC2945](https://tools.ietf.org/html/rfc2945). This library implements version 6a of the protocol which includes the username in the salt to avoid the issue where a malicious server attempting to learn if two users have the same password. I believe it is also compliant with [RFC5054](https://tools.ietf.org/html/rfc5054). + +# Usage + +First you create a configuration object. This will hold the hashing algorithm you are using, the large safe prime number required and a generator value. There is an enum that holds example primes and generators. It is general safer to use these as they are the ones provided in RFC5054 and have been battle tested. The following generates a configuration using SHA256 and a 2048 bit safe prime. You need to be sure both client and server use the same configuration. +```swift +let configuration = SRPConfiguration(.N2048) +``` +When the client wants to create a new user they generate a salt and password verifier for their username and password. +```swift +let client = SRPClient(configuration: configuration) +let (salt, verifier) = client.generateSaltAndVerifier(username: username, password: password) +``` +These are passed to the server who will store them alongside the username in a database. + +When the client wants to authenticate with the server they first need to generate a public/private key pair. These keys should only be used once. If you want to authenticate again you should generate a new pair. +```swift +let client = SRPClient(configuration: configuration) +let clientKeys = client.generateKeys() +let clientPublicKey = clientKeys.public +``` +The contents of the `clientPublicKey` variable is passed to the server alongside the username to initiate authentication. + +The server will then find the username in its database and extract the password verifier and salt that was stored with it. The password verifier is used to generate the servers key pair. +```swift +let server = SRPServer(configuration: configuration) +let serverKeys = server.generateKeys(verifier: values.verifier) +let serverPublicKey = serverKeys.public +``` +The server replies with the `serverPublicKey` and the salt value associated with the user. At this point the server will need to store the `serverKeys` and the public key it received from the client, most likely in a database. + +The client then creates the shared secret using the username, password, salt, its own key pair and the server public key. It then has to generate a proof it has the shared secret. This proof is generated from shared secret plus any of the public data available. +```swift +let clientSharedSecret = try client.calculateSharedSecret( + username: username, + password: password, + salt: salt, + clientKeys: clientKeys, + serverPublicKey: serverPublicKey +) +let clientProof = client.calculateClientProof( + username: username, + salt: salt, + clientPublicKey: clientKeys.public, + serverPublicKey: serverPublicKey, + sharedSecret: clientSharedSecret +) +``` +This `clientProof` is passed to the server. The server then generates its own version of the shared secret and verifies the `clientProof` is valid and if so will respond with it's own proof that it has the shared secret. +```swift +let serverSharedSecret = try server.calculateSharedSecret( + clientPublicKey: clientPublicKey, + serverKeys: serverKeys, + verifier: verifier +) +let serverProof = try server.verifyClientProof( + proof: clientProof, + username: username, + salt: salt, + clientPublicKey: clientPublicKey, + serverPublicKey: serverKeys.public, + sharedSecret: serverSharedSecret +) +``` +And finally the client can verify the server proof is valid +```swift +try client.verifyServerProof( + serverProof: serverProof, + clientProof: clientProof, + clientKeys: clientKeys, + sharedSecret: clientSharedSecret +) +``` +If at any point any of these functions fail the process should be aborted. + +# Compatibility + +The library is compliant with RFC5054 and should work with any server implementing this. The library has been verified against +- example data in RFC5054 +- Mozilla test vectors in https://wiki.mozilla.org/Identity/AttachedServices/KeyServerProtocol#SRP_Verifier +- Python library [srptools](https://github.com/idlesign/srptools) +- Typescript library [tssrp6a](https://github.com/midonet/tssrp6a) + +## Proof of secret + +For generating the proof above I use the method detailed in [RFC2945](https://tools.ietf.org/html/rfc2945#section-3) but not all servers use this method. For this reason I have kept the sharedSecret generation separate from the proof generation, so you can insert your own version. + +I have also supplied a simple proof functions `server.verifySimpleClientProof` and `client.verifySimpleServerProof` which use the proof detailed in the Wikipedia [page](https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol) on Secure Remote Password if you would prefer to use these. diff --git a/xcodes-srp/Sources/SRP/Array.swift b/xcodes-srp/Sources/SRP/Array.swift new file mode 100644 index 00000000..8f2a1816 --- /dev/null +++ b/xcodes-srp/Sources/SRP/Array.swift @@ -0,0 +1,29 @@ + +extension Array where Element: FixedWidthInteger { + /// create array of random bytes + static func random(count: Int) -> [Element] { + var array = self.init() + for _ in 0.. String { + return self.map({ + let characters = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"] + return "\(characters[Int($0 >> 4)])\(characters[Int($0 & 0xf)])" + }).joined() + } +} + +/// xor together the contents of two byte arrays +func ^ (lhs: [UInt8], rhs: [UInt8]) -> [UInt8] { + precondition(lhs.count == rhs.count, "Arrays are required to be the same size") + var result = lhs + for i in 0.. { + /// configuration. This needs to be the same as the server configuration + public let configuration: SRPConfiguration + + /// Initialise a SRPClient object + /// - Parameter configuration: configuration to use + public init(configuration: SRPConfiguration) { + self.configuration = configuration + } + + /// Initiate the authentication process + /// - Returns: An authentication state. The A value from this state should be sent to the server + public func generateKeys() -> SRPKeyPair { + var a = BigNum() + var A = BigNum() + repeat { + a = BigNum(bytes: SymmetricKey(size: .bits256)) + A = configuration.g.power(a, modulus: configuration.N) + } while A % configuration.N == BigNum(0) + + return SRPKeyPair(public: SRPKey(A), private: SRPKey(a)) + } + + /// return shared secret given the username, password, B value and salt from the server + /// - Parameters: + /// - username: user identifier + /// - password: password + /// - salt: salt + /// - clientKeys: client public/private keys + /// - serverPublicKey: server public key + /// - Throws: `nullServerKey` + /// - Returns: shared secret + public func calculateSharedSecret(username: String, password: String, salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> SRPKey { + let message = [UInt8]("\(username):\(password)".utf8) + let sharedSecret = try calculateSharedSecret(message: message, salt: salt, clientKeys: clientKeys, serverPublicKey: serverPublicKey) + return SRPKey(sharedSecret) + } + + /// return shared secret given the username, password, B value and salt from the server + /// - Parameters: + /// - username: user identifier + /// - password: password + /// - salt: salt + /// - clientKeys: client public/private keys + /// - serverPublicKey: server public key + /// - Throws: `nullServerKey` + /// - Returns: shared secret + public func calculateSharedSecret(encryptedPassword: String, salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> SRPKey { + let message = [UInt8](":\(encryptedPassword)".utf8) + let sharedSecret = try calculateSharedSecret(message: message, salt: salt, clientKeys: clientKeys, serverPublicKey: serverPublicKey) + return SRPKey(sharedSecret) + } + + + /// calculate proof of shared secret to send to server + /// - Parameters: + /// - clientPublicKey: client public key + /// - serverPublicKey: server public key + /// - sharedSecret: shared secret + /// - Returns: The client verification code which should be passed to the server + public func calculateSimpleClientProof(clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) -> [UInt8] { + // get verification code + return SRP.calculateSimpleClientProof(clientPublicKey: clientPublicKey, serverPublicKey: serverPublicKey, sharedSecret: sharedSecret) + } + + /// If the server returns that the client verification code was valiid it will also return a server verification code that the client can use to verify the server is correct + /// + /// - Parameters: + /// - code: Verification code returned by server + /// - state: Authentication state + /// - Throws: `requiresVerificationKey`, `invalidServerCode` + public func verifySimpleServerProof(serverProof: [UInt8], clientProof: [UInt8], clientKeys: SRPKeyPair, sharedSecret: SRPKey) throws { + // get out version of server proof + let HAMS = SRP.calculateSimpleServerVerification(clientPublicKey: clientKeys.public, clientProof: clientProof, sharedSecret: sharedSecret) + // is it the same + guard serverProof == HAMS else { throw SRPClientError.invalidServerCode } + } + + /// calculate proof of shared secret to send to server + /// - Parameters: + /// - username: username + /// - salt: The salt value associated with the user returned by the server + /// - clientPublicKey: client public key + /// - serverPublicKey: server public key + /// - sharedSecret: shared secret + /// - Returns: The client verification code which should be passed to the server + public func calculateClientProof(username: String, salt: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) -> [UInt8] { + + let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) + + // get verification code + return SRP.calculateClientProof(configuration: configuration, username: username, salt: salt, clientPublicKey: clientPublicKey, serverPublicKey: serverPublicKey, hashSharedSecret: hashSharedSecret) + } + + /// If the server returns that the client verification code was valiid it will also return a server verification code that the client can use to verify the server is correct + /// + /// - Parameters: + /// - code: Verification code returned by server + /// - state: Authentication state + /// - Throws: `requiresVerificationKey`, `invalidServerCode` + public func verifyServerProof(serverProof: [UInt8], clientProof: [UInt8], clientKeys: SRPKeyPair, sharedSecret: SRPKey) throws { + let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) + // get out version of server proof + let HAMK = SRP.calculateServerVerification(clientPublicKey: clientKeys.public, clientProof: clientProof, sharedSecret: hashSharedSecret) + // is it the same + guard serverProof == HAMK else { throw SRPClientError.invalidServerCode } + } + + + /// If the server returns that the client verification code was valiid it will also return a server verification code that the client can use to verify the server is correct + /// + /// - Parameters: + /// - code: Verification code returned by server + /// - state: Authentication state + /// - Throws: `requiresVerificationKey`, `invalidServerCode` + public func serverProof(clientProof: [UInt8], clientKeys: SRPKeyPair, sharedSecret: SRPKey) -> [UInt8] { + let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) + + return SRP.calculateServerVerification(clientPublicKey: clientKeys.public, clientProof: clientProof, sharedSecret: hashSharedSecret) + } + + /// Generate salt and password verifier from username and password. When creating your user instead of passing your password to the server, you + /// pass the salt and password verifier values. In this way the server never knows your password so can never leak it. + /// + /// - Parameters: + /// - username: username + /// - password: user password + /// - Returns: tuple containing salt and password verifier + public func generateSaltAndVerifier(username: String, password: String) -> (salt: [UInt8], verifier: SRPKey) { + let salt = [UInt8].random(count: 16) + let verifier = generatePasswordVerifier(username: username, password: password, salt: salt) + return (salt: salt, verifier: SRPKey(verifier)) + } +} + +extension SRPClient { + /// return shared secret given the username, password, B value and salt from the server + func calculateSharedSecret(message: [UInt8], salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> BigNum { + guard serverPublicKey.number % configuration.N != BigNum(0) else { throw SRPClientError.nullServerKey } + + // calculate u = H(clientPublicKey | serverPublicKey) + let u = SRP.calculateU(clientPublicKey: clientKeys.public.bytes, serverPublicKey: serverPublicKey.bytes, pad: configuration.sizeN) + + guard u != 0 else { throw SRPClientError.nullServerKey } + + let x = BigNum(bytes: [UInt8](H.hash(data: salt + H.hash(data: message)))) + + // calculate S = (B - k*g^x)^(a+u*x) + let S = (serverPublicKey.number - configuration.k * configuration.g.power(x, modulus: configuration.N)).power(clientKeys.private.number + u * x, modulus: configuration.N) + + return S + } + + /// generate password verifier + public func generatePasswordVerifier(username: String, password: String, salt: [UInt8]) -> BigNum { + let message = "\(username):\(password)" + return generatePasswordVerifier(message: [UInt8](message.utf8), salt: salt) + } + + /// generate password verifier + public func generatePasswordVerifier(message: [UInt8], salt: [UInt8]) -> BigNum { + let x = BigNum(bytes: [UInt8](H.hash(data: salt + H.hash(data: message)))) + let verifier = configuration.g.power(x, modulus: configuration.N) + return verifier + } +} diff --git a/xcodes-srp/Sources/SRP/configuration.swift b/xcodes-srp/Sources/SRP/configuration.swift new file mode 100644 index 00000000..a1fe01a6 --- /dev/null +++ b/xcodes-srp/Sources/SRP/configuration.swift @@ -0,0 +1,201 @@ +import BigNum +import Crypto + +/// SRP Configuration. The same configuration hast to be used by both client and server. Contains a large safe prime N ie a prime where the value (N-1)/2 is also a prime, g the multiplicative group generator and the value k = Hash(N | g) +public struct SRPConfiguration { + /// large safe prime + public let N: BigNum + /// multiplicative group generator + public let g: BigNum + /// derived value from N and g. k = H( N | g ) + public let k: BigNum + /// size in bytes of N + public let sizeN: Int + + /// Initialise SRPConfiguration with known safe prime + /// - Parameter prime: enum indicating size of prime + public init(_ prime: Prime) { + self.N = prime.group + self.sizeN = Int(self.N.numBits() + 7) / 8 + self.g = prime.generator + self.k = BigNum(bytes: [UInt8](H.hash(data: self.N.bytes + SRP.pad(self.g.bytes, to: sizeN)))) + } + + /// Initialise SRPConfiguration with your own prime and multiplicative group generator + /// - Parameters: + /// - N: Large prime + /// - g: multiplicative group generator (usually 2) + public init(N: BigNum, g: BigNum) { + self.N = N + self.sizeN = Int(self.N.numBits() + 7) / 8 + self.g = g + self.k = BigNum(bytes: [UInt8](H.hash(data: self.N.bytes + SRP.pad(self.g.bytes, to: sizeN)))) + } + + public enum Prime { + case N1024 + case N1536 + case N2048 + case N3072 + case N4096 + case N6144 + case N8192 + + /// prime numbers and generators taken from RC 5054 https://tools.ietf.org/html/rfc5054 + var group: BigNum { + switch self { + case .N1024: + return BigNum(hex: + "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" + + "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" + + "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" + + "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" + + "FD5138FE8376435B9FC61D2FC0EB06E3")! + + case .N1536: + return BigNum(hex: + "9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA961" + + "4B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F843" + + "80B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0B" + + "E3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF5" + + "6EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734A" + + "F7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E" + + "8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB")! + + case .N2048: + return BigNum(hex: + "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" + + "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" + + "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" + + "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" + + "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" + + "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" + + "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" + + "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" + + "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" + + "9E4AFF73")! + + case .N3072: + return BigNum(hex: + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF")! + + case .N4096: + return BigNum(hex: + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" + + "FFFFFFFFFFFFFFFF")! + + case .N6144: + return BigNum(hex: + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + + "6DCC4024FFFFFFFFFFFFFFFF")! + + case .N8192: + return BigNum(hex: + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + + "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA" + + "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C" + + "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" + + "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886" + + "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6" + + "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5" + + "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268" + + "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6" + + "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + + "60C980DD98EDD3DFFFFFFFFFFFFFFFFF")! + } + } + + var generator: BigNum { + switch self { + case .N1024, .N1536, .N2048: + return BigNum(2) + case .N3072, .N4096, .N6144: + return BigNum(5) + case .N8192: + return BigNum(19) + } + } + } +} diff --git a/xcodes-srp/Sources/SRP/error.swift b/xcodes-srp/Sources/SRP/error.swift new file mode 100644 index 00000000..d0829604 --- /dev/null +++ b/xcodes-srp/Sources/SRP/error.swift @@ -0,0 +1,21 @@ +/// Errors thrown by SRPClient +public enum SRPClientError: Swift.Error { + /// the key returned by server is invalid, in that either it modulo N is zero or the hash(A,B) is zero + case nullServerKey + /// server verification code was wrong + case invalidServerCode + /// you called verifyServerCode without a verification key + case requiresVerificationKey + /// client key is invalid + case invalidClientKey +} + +/// Errors thrown by SRPServer +///Errors thrown by SRPServer +public enum SRPServerError: Swift.Error { + /// the modulus of the client key and N generated a zero + case nullClientKey + /// client proof of the shared secret was invalid or wrong + case invalidClientProof +} + diff --git a/xcodes-srp/Sources/SRP/keys.swift b/xcodes-srp/Sources/SRP/keys.swift new file mode 100644 index 00000000..c7d08a0b --- /dev/null +++ b/xcodes-srp/Sources/SRP/keys.swift @@ -0,0 +1,40 @@ +import BigNum + +/// Wrapper for keys used by SRP +public struct SRPKey { + public let number: BigNum + public var bytes: [UInt8] { number.bytes } + public var hex: String { number.hex } + + public init(_ bytes: [UInt8]) { + self.number = BigNum(bytes: bytes) + } + + public init(_ number: BigNum) { + self.number = number + } + + public init?(hex: String) { + guard let number = BigNum(hex: hex) else { return nil } + self.number = number + } +} + +extension SRPKey: Equatable { } + +/// Contains a private and a public key +public struct SRPKeyPair { + public let `public`: SRPKey + public let `private`: SRPKey + + + /// Initialise a SRPKeyPair object + /// - Parameters: + /// - public: The public key of the key pair + /// - private: The private key of the key pair + public init(`public`: SRPKey, `private`: SRPKey) { + self.private = `private` + self.public = `public` + } +} + diff --git a/xcodes-srp/Sources/SRP/server.swift b/xcodes-srp/Sources/SRP/server.swift new file mode 100644 index 00000000..c823c06e --- /dev/null +++ b/xcodes-srp/Sources/SRP/server.swift @@ -0,0 +1,108 @@ +import BigNum +import Crypto + +/// Manages the server side of Secure Remote Password. +/// +/// Secure Remote Password (SRP) provides username and password authentication without needing to provide your password to the server. The server +/// has a cryptographic verifier that is derived from the password and a salt that was used to generate this verifier. Both client and server +/// generate a shared secret then the client sends a proof they have the secret and if it is correct the server will do the same to verify the +/// server as well. +/// +/// This version is compliant with SRP version 6a and RFC 5054. +/// +/// Reference reading +/// - https://tools.ietf.org/html/rfc2945 +/// - https://tools.ietf.org/html/rfc5054 +/// +public struct SRPServer { + /// Authentication state. Stores A,B and shared secret + public struct AuthenticationState { + let clientPublicKey: SRPKey + let serverPublicKey: SRPKey + var serverPrivateKey: SRPKey + } + + /// configuration has to be the same as the client configuration + public let configuration: SRPConfiguration + + /// Initialise SRPServer + /// - Parameter configuration: configuration to use + public init(configuration: SRPConfiguration) { + self.configuration = configuration + } + + /// generate public and private keys to be used in srp authentication + /// - Parameter verifier: password verifier used to generate key pair + /// - Returns: return public/private key pair + public func generateKeys(verifier: SRPKey) -> SRPKeyPair { + var b: BigNum + var B: BigNum + repeat { + b = BigNum(bytes: SymmetricKey(size: .bits256)) + B = (configuration.k * verifier.number + configuration.g.power(b, modulus: configuration.N)) % configuration.N + } while B % configuration.N == BigNum(0) + + return SRPKeyPair(public: SRPKey(B), private: SRPKey(b)) + } + + /// calculate the shared secret + /// - Parameters: + /// - clientPublicKey: public key received from client + /// - serverKeys: server key pair + /// - verifier: password verifier + /// - Returns: shared secret + public func calculateSharedSecret(clientPublicKey: SRPKey, serverKeys: SRPKeyPair, verifier: SRPKey) throws -> SRPKey { + guard clientPublicKey.number % configuration.N != BigNum(0) else { throw SRPServerError.nullClientKey } + + // calculate u = H(clientPublicKey | serverPublicKey) + let u = SRP.calculateU(clientPublicKey: clientPublicKey.bytes, serverPublicKey: serverKeys.public.bytes, pad: configuration.sizeN) + + // calculate S + let S = ((clientPublicKey.number * verifier.number.power(u, modulus: configuration.N)).power(serverKeys.private.number, modulus: configuration.N)) + + return SRPKey(S) + } + + /// verify proof that client has shared secret and return a server verification proof. If verification fails a `invalidClientCode` error is thrown + /// + /// - Parameters: + /// - code: verification code sent by user + /// - username: username + /// - salt: salt stored with user + /// - state: authentication state. + /// - Throws: invalidClientCode + /// - Returns: The server verification code + public func verifySimpleClientProof(proof: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) throws -> [UInt8] { + let clientProof = SRP.calculateSimpleClientProof( + clientPublicKey: clientPublicKey, + serverPublicKey: serverPublicKey, + sharedSecret: sharedSecret + ) + guard clientProof == proof else { throw SRPServerError.invalidClientProof } + return SRP.calculateSimpleServerVerification(clientPublicKey: clientPublicKey, clientProof: clientProof, sharedSecret: sharedSecret) + } + + /// verify proof that client has shared secret and return a server verification proof. If verification fails a `invalidClientCode` error is thrown + /// + /// - Parameters: + /// - code: verification code sent by user + /// - username: username + /// - salt: salt stored with user + /// - state: authentication state. + /// - Throws: invalidClientCode + /// - Returns: The server verification code + public func verifyClientProof(proof: [UInt8], username: String, salt: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) throws -> [UInt8] { + let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) + + let clientProof = SRP.calculateClientProof( + configuration: configuration, + username: username, + salt: salt, + clientPublicKey: clientPublicKey, + serverPublicKey: serverPublicKey, + hashSharedSecret: hashSharedSecret + ) + guard clientProof == proof else { throw SRPServerError.invalidClientProof } + return SRP.calculateServerVerification(clientPublicKey: clientPublicKey, clientProof: clientProof, sharedSecret: hashSharedSecret) + } +} diff --git a/xcodes-srp/Sources/SRP/srp.swift b/xcodes-srp/Sources/SRP/srp.swift new file mode 100644 index 00000000..52bcd805 --- /dev/null +++ b/xcodes-srp/Sources/SRP/srp.swift @@ -0,0 +1,64 @@ +import BigNum +import Crypto + +/// Contains common code used by both client and server SRP code +public struct SRP { + + /// pad to a certain size by prefixing with zeros + static func pad(_ data: [UInt8], to size: Int) -> [UInt8] { + let padSize = size - data.count + guard padSize > 0 else { return data } + // create prefix and return prefix + data + let prefix: [UInt8] = (1...padSize).reduce([]) { result,_ in return result + [0] } + return prefix + data + } + + /// calculate u = H(clientPublicKey | serverPublicKey) + public static func calculateU(clientPublicKey: [UInt8], serverPublicKey: [UInt8], pad: Int) -> BigNum { + BigNum(bytes: [UInt8].init(H.hash(data: SRP.pad(clientPublicKey, to: pad) + SRP.pad(serverPublicKey, to: pad)))) + } + + /// Calculate a simpler client verification code H(A | B | S) + static func calculateSimpleClientProof( + clientPublicKey: SRPKey, + serverPublicKey: SRPKey, + sharedSecret: SRPKey) -> [UInt8] + { + let HABK = H.hash(data: clientPublicKey.bytes + serverPublicKey.bytes + sharedSecret.bytes) + return [UInt8](HABK) + } + + /// Calculate a simpler client verification code H(A | M1 | S) + static func calculateSimpleServerVerification( + clientPublicKey: SRPKey, + clientProof: [UInt8], + sharedSecret: SRPKey) -> [UInt8] + { + let HABK = H.hash(data: clientPublicKey.bytes + clientProof + sharedSecret.bytes) + return [UInt8](HABK) + } + + /// Calculate client verification code H(H(N)^ H(g)) | H(username) | salt | A | B | H(S)) + static func calculateClientProof( + configuration: SRPConfiguration, + username: String, + salt: [UInt8], + clientPublicKey: SRPKey, + serverPublicKey: SRPKey, + hashSharedSecret: [UInt8]) -> [UInt8] + { + // M = H(H(N)^ H(g)) | H(username) | salt | client key | server key | H(shared secret)) + let N_xor_g = [UInt8](H.hash(data: configuration.N.bytes)) ^ [UInt8](H.hash(data: configuration.g.bytes)) + let hashUser = H.hash(data: [UInt8](username.utf8)) + let M1 = [UInt8](N_xor_g) + hashUser + salt + let M2 = clientPublicKey.bytes + serverPublicKey.bytes + hashSharedSecret + let M = H.hash(data: M1 + M2) + return [UInt8](M) + } + + /// Calculate server verification code H(A | M1 | K) + static func calculateServerVerification(clientPublicKey: SRPKey, clientProof: [UInt8], sharedSecret: [UInt8]) -> [UInt8] { + let HAMK = H.hash(data: clientPublicKey.bytes + clientProof + sharedSecret) + return [UInt8](HAMK) + } +} diff --git a/xcodes-srp/Tests/LinuxMain.swift b/xcodes-srp/Tests/LinuxMain.swift new file mode 100644 index 00000000..f87f4e99 --- /dev/null +++ b/xcodes-srp/Tests/LinuxMain.swift @@ -0,0 +1,6 @@ +import XCTest +import SRPTests + +var tests = [XCTestCaseEntry]() +tests += SRPTests.allTests() +XCTMain(tests) diff --git a/xcodes-srp/Tests/SRPTests/SRPTests.swift b/xcodes-srp/Tests/SRPTests/SRPTests.swift new file mode 100644 index 00000000..ab15098d --- /dev/null +++ b/xcodes-srp/Tests/SRPTests/SRPTests.swift @@ -0,0 +1,207 @@ +import XCTest +import BigNum +import Crypto +@testable import SRP + +final class SRPTests: XCTestCase { + + func testSRPSharedSecret() { + let username = "adamfowler" + let password = "testpassword" + let configuration = SRPConfiguration(.N2048) + let client = SRPClient(configuration: configuration) + let server = SRPServer(configuration: configuration) + + let (salt, verifier) = client.generateSaltAndVerifier(username: username, password: password) + + let clientKeys = client.generateKeys() + let serverKeys = server.generateKeys(verifier: verifier) + + do { + let sharedSecret = try client.calculateSharedSecret( + username: username, + password: password, + salt: salt, + clientKeys: clientKeys, + serverPublicKey: serverKeys.public) + + let serverSharedSecret = try server.calculateSharedSecret( + clientPublicKey: clientKeys.public, + serverKeys: serverKeys, + verifier: verifier) + + XCTAssertEqual(sharedSecret, serverSharedSecret) + } catch { + XCTFail("\(error)") + } + } + + func testVerifySRP(configuration: SRPConfiguration) { + let username = "adamfowler" + let password = "testpassword" + let client = SRPClient(configuration: configuration) + let server = SRPServer(configuration: configuration) + + let (salt, verifier) = client.generateSaltAndVerifier(username: username, password: password) + + do { + // client initiates authentication + let clientKeys = client.generateKeys() + // provides the server with an A value and username from which it gets the password verifier. + // server initiates authentication + let serverKeys = server.generateKeys(verifier: verifier) + // server passes back B value and a salt which was attached to the user + // client calculates verification code from username, password, current authenticator state, B and salt + let clientSharedSecret = try client.calculateSharedSecret(username: username, password: password, salt: salt, clientKeys: clientKeys, serverPublicKey: serverKeys.public) + let clientProof = client.calculateClientProof(username: username, salt: salt, clientPublicKey: clientKeys.public, serverPublicKey: serverKeys.public, sharedSecret: clientSharedSecret) + // client passes proof key to server + // server validates the key and then returns a server validation key + let serverSharedSecret = try server.calculateSharedSecret(clientPublicKey: clientKeys.public, serverKeys: serverKeys, verifier: verifier) + let serverProof = try server.verifyClientProof(proof: clientProof, username: username, salt: salt, clientPublicKey: clientKeys.public, serverPublicKey: serverKeys.public, sharedSecret: serverSharedSecret) + // client verifies server validation key + try client.verifyServerProof(serverProof: serverProof, clientProof: clientProof, clientKeys: clientKeys, sharedSecret: clientSharedSecret) + } catch { + XCTFail("\(error)") + } + } + + func testVerifySRP() { + testVerifySRP(configuration: SRPConfiguration(.N1024)) + testVerifySRP(configuration: SRPConfiguration(.N1536)) + testVerifySRP(configuration: SRPConfiguration(.N2048)) + testVerifySRP(configuration: SRPConfiguration(.N3072)) + testVerifySRP(configuration: SRPConfiguration(.N4096)) + testVerifySRP(configuration: SRPConfiguration(.N6144)) + testVerifySRP(configuration: SRPConfiguration(.N8192)) + } + + func testVerifySRPCustomConfiguration() { + testVerifySRP(configuration: SRPConfiguration(N: BigNum(37), g: BigNum(3))) + } + + func testClientSessionProof() { + let configuration = SRPConfiguration(.N1024) + let username = "alice" + let salt = "bafa3be2813c9326".bytes(using: .hexadecimal)! + let A = BigNum(hex: "b525e8fe2eac8f5da6b3220e66a0ab6f833a59d5f079fe9ddcdf111a22eaec95850374d9d7597f45497eb429bcde5057a450948de7d48edc034264916a01e6c0690e14b0a527f107d3207fd2214653c9162f5745e7cbeb19a550a072d4600ce8f4ef778f6d6899ba718adf0a462e7d981ed689de93ea1bda773333f23ebb4a9b")! + let B = BigNum(hex: "2bfc8559a022497f1254af3c76786b95cb0dfb449af15501aa51eefe78947d7ef06df4fcc07a899bcaae0e552ca72c7a1f3016f3ec357a86a1428dad9f98cb8a69d405404e57e9aaf01e51a46a73b3fc7bc1d212569e4a882ae6d878599e098c89033838ec069fe368a49461f531e5b4662700d56d8c252d0aea9da6abe9b014")! + let secret = "b6288955afd690a13686d65886b5f82018515df3".bytes(using: .hexadecimal)! + let clientProof = SRP.calculateClientProof(configuration: configuration, username: username, salt: salt, clientPublicKey: SRPKey(A), serverPublicKey: SRPKey(B), hashSharedSecret: secret) + + XCTAssertEqual(clientProof.hexdigest(), "e4c5c2e145ea2de18d0cc1ac9dc2a0d0988706d6") + } + + func testServerSessionProof() { + let A = BigNum(hex: "eade4992a46182e9ffe2e69f3e2639ca5f8c29b2868083c45d0972b72bb6003911b64a7ea6738061d705d368ddbe2bdb251bec63184db09b8990d8a7415dc449fbab720626fc25d6bd33c32234973c1e41c25b18d1824590c807c491221be5493878bd27a5ca507fd3963c849b07a9ec413e13253c6c61e7f3219b247cfa574a")! + let secret = "d89740e18a9fb597aef8f2ecc0e66f4b31c2ae08".bytes(using: .hexadecimal)! + let clientProof = "e1a8629a723039a61be91a173ab6260fc582192f".bytes(using: .hexadecimal)! + + let serverProof = SRP.calculateServerVerification(clientPublicKey: SRPKey(A), clientProof: clientProof, sharedSecret: secret) + + XCTAssertEqual(serverProof.hexdigest(), "8342bd06bdf4d263de2df9a56da8e581fb38c769") + } + + // Test results against RFC5054 Appendix B + func testRFC5054Appendix() throws { + let username = "alice" + let password = "password123" + let salt = "BEB25379D1A8581EB5A727673A2441EE".bytes(using: .hexadecimal)! + let configuration = SRPConfiguration(.N1024) + let client = SRPClient(configuration: configuration) + + XCTAssertEqual(configuration.k.hex, "7556AA045AEF2CDD07ABAF0F665C3E818913186F".lowercased()) + + let verifier = client.generatePasswordVerifier(username: username, password: password, salt: salt) + + XCTAssertEqual(verifier.hex, "7E273DE8696FFC4F4E337D05B4B375BEB0DDE1569E8FA00A9886D8129BADA1F1822223CA1A605B530E379BA4729FDC59F105B4787E5186F5C671085A1447B52A48CF1970B4FB6F8400BBF4CEBFBB168152E08AB5EA53D15C1AFF87B2B9DA6E04E058AD51CC72BFC9033B564E26480D78E955A5E29E7AB245DB2BE315E2099AFB".lowercased()) + + let a = BigNum(hex: "60975527035CF2AD1989806F0407210BC81EDC04E2762A56AFD529DDDA2D4393")! + // copied from client.swift + let A = configuration.g.power(a, modulus: configuration.N) + + XCTAssertEqual(A.hex, "61D5E490F6F1B79547B0704C436F523DD0E560F0C64115BB72557EC44352E8903211C04692272D8B2D1A5358A2CF1B6E0BFCF99F921530EC8E39356179EAE45E42BA92AEACED825171E1E8B9AF6D9C03E1327F44BE087EF06530E69F66615261EEF54073CA11CF5858F0EDFDFE15EFEAB349EF5D76988A3672FAC47B0769447B".lowercased()) + + let b = BigNum(hex: "E487CB59D31AC550471E81F00F6928E01DDA08E974A004F49E61F5D105284D20")! + // copied from server.swift + let B = (configuration.k * verifier + configuration.g.power(b, modulus: configuration.N)) % configuration.N + + XCTAssertEqual(B.hex, "BD0C61512C692C0CB6D041FA01BB152D4916A1E77AF46AE105393011BAF38964DC46A0670DD125B95A981652236F99D9B681CBF87837EC996C6DA04453728610D0C6DDB58B318885D7D82C7F8DEB75CE7BD4FBAA37089E6F9C6059F388838E7A00030B331EB76840910440B1B27AAEAEEB4012B7D7665238A8E3FB004B117B58".lowercased()) + + let u = SRP.calculateU(clientPublicKey: A.bytes, serverPublicKey: B.bytes, pad: configuration.sizeN) + + XCTAssertEqual(u.hex, "CE38B9593487DA98554ED47D70A7AE5F462EF019".lowercased()) + + let sharedSecret = try client.calculateSharedSecret(username: username, password: password, salt: salt, clientKeys: SRPKeyPair(public: SRPKey(A), private: SRPKey(a)), serverPublicKey: SRPKey(B)) + + XCTAssertEqual(sharedSecret.number.hex, "B0DC82BABCF30674AE450C0287745E7990A3381F63B387AAF271A10D233861E359B48220F7C4693C9AE12B0A6F67809F0876E2D013800D6C41BB59B6D5979B5C00A172B4A2A5903A0BDCAF8A709585EB2AFAFA8F3499B200210DCC1F10EB33943CD67FC88A2F39A4BE5BEC4EC0A3212DC346D7E474B29EDE8A469FFECA686E5A".lowercased()) + } + + /// Test library against Mozilla test vectors https://wiki.mozilla.org/Identity/AttachedServices/KeyServerProtocol#SRP_Verifier + func testMozillaTestVectors() throws { + let username = "andré@example.org" + let password = "00f9b71800ab5337d51177d8fbc682a3653fa6dae5b87628eeec43a18af59a9d".bytes(using: .hexadecimal)! + let salt = "00f1000000000000000000000000000000000000000000000000000000000179".bytes(using: .hexadecimal)! + let configuration = SRPConfiguration(.N2048) + let client = SRPClient(configuration: configuration) + + XCTAssertEqual(configuration.k.dec, "2590038599070950300691544216303772122846747035652616593381637186118123578112") + + let message = [UInt8]("\(username):".utf8) + password + let verifier = client.generatePasswordVerifier(message: message, salt: salt) + + XCTAssertEqual(verifier.hex, "173ffa0263e63ccfd6791b8ee2a40f048ec94cd95aa8a3125726f9805e0c8283c658dc0b607fbb25db68e68e93f2658483049c68af7e8214c49fde2712a775b63e545160d64b00189a86708c69657da7a1678eda0cd79f86b8560ebdb1ffc221db360eab901d643a75bf1205070a5791230ae56466b8c3c1eb656e19b794f1ea0d2a077b3a755350208ea0118fec8c4b2ec344a05c66ae1449b32609ca7189451c259d65bd15b34d8729afdb5faff8af1f3437bbdc0c3d0b069a8ab2a959c90c5a43d42082c77490f3afcc10ef5648625c0605cdaace6c6fdc9e9a7e6635d619f50af7734522470502cab26a52a198f5b00a279858916507b0b4e9ef9524d6") + + let b = BigNum(hex: "00f3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f")! + // copied from server.swift + let B = (configuration.k * verifier + configuration.g.power(b, modulus: configuration.N)) % configuration.N + + XCTAssertEqual(B.hex, "22ce5a7b9d81277172caa20b0f1efb4643b3becc53566473959b07b790d3c3f08650d5531c19ad30ebb67bdb481d1d9cf61bf272f8439848fdda58a4e6abc5abb2ac496da5098d5cbf90e29b4b110e4e2c033c70af73925fa37457ee13ea3e8fde4ab516dff1c2ae8e57a6b264fb9db637eeeae9b5e43dfaba9b329d3b8770ce89888709e026270e474eef822436e6397562f284778673a1a7bc12b6883d1c21fbc27ffb3dbeb85efda279a69a19414969113f10451603065f0a012666645651dde44a52f4d8de113e2131321df1bf4369d2585364f9e536c39a4dce33221be57d50ddccb4384e3612bbfd03a268a36e4f7e01de651401e108cc247db50392") + + let a = BigNum(hex: "00f2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d3d7")! + // copied from client.swift + let A = configuration.g.power(a, modulus: configuration.N) + + XCTAssertEqual(A.hex, "7da76cb7e77af5ab61f334dbd5a958513afcdf0f47ab99271fc5f7860fe2132e5802ca79d2e5c064bb80a38ee08771c98a937696698d878d78571568c98a1c40cc6e7cb101988a2f9ba3d65679027d4d9068cb8aad6ebff0101bab6d52b5fdfa81d2ed48bba119d4ecdb7f3f478bd236d5749f2275e9484f2d0a9259d05e49d78a23dd26c60bfba04fd346e5146469a8c3f010a627be81c58ded1caaef2363635a45f97ca0d895cc92ace1d09a99d6beb6b0dc0829535c857a419e834db12864cd6ee8a843563b0240520ff0195735cd9d316842d5d3f8ef7209a0bb4b54ad7374d73e79be2c3975632de562c596470bb27bad79c3e2fcddf194e1666cb9fc") + + let u = SRP.calculateU(clientPublicKey: A.bytes, serverPublicKey: B.bytes, pad: configuration.sizeN) + + XCTAssertEqual(u.hex, "b284aa1064e8775150da6b5e2147b47ca7df505bed94a6f4bb2ad873332ad732") + + let sharedSecret = try client.calculateSharedSecret(message: message, salt: salt, clientKeys: SRPKeyPair(public: SRPKey(A), private: SRPKey(a)), serverPublicKey: SRPKey(B)) + + XCTAssertEqual(sharedSecret.hex, "92aaf0f527906aa5e8601f5d707907a03137e1b601e04b5a1deb02a981f4be037b39829a27dba50f1b27545ff2e28729c2b79dcbdd32c9d6b20d340affab91a626a8075806c26fe39df91d0ad979f9b2ee8aad1bc783e7097407b63bfe58d9118b9b0b2a7c5c4cdebaf8e9a460f4bf6247b0da34b760a59fac891757ddedcaf08eed823b090586c63009b2d740cc9f5397be89a2c32cdcfe6d6251ce11e44e6ecbdd9b6d93f30e90896d2527564c7eb9ff70aa91acc0bac1740a11cd184ffb989554ab58117c2196b353d70c356160100ef5f4c28d19f6e59ea2508e8e8aac6001497c27f362edbafb25e0f045bfdf9fb02db9c908f10340a639fe84c31b27") + } + + static var allTests = [ + ("testSRPSharedSecret", testSRPSharedSecret), + ("testVerifySRP", testVerifySRP), + ("testVerifySRPCustomConfiguration", testVerifySRPCustomConfiguration), + ("testClientSessionProof", testClientSessionProof), + ("testServerSessionProof", testServerSessionProof), + ("testRFC5054Appendix", testRFC5054Appendix), + ("testMozillaTestVectors", testMozillaTestVectors), + ] +} + +extension String { + enum ExtendedEncoding { + case hexadecimal + } + + func bytes(using encoding:ExtendedEncoding) -> [UInt8]? { + guard self.count % 2 == 0 else { return nil } + + var bytes: [UInt8] = [] + + var indexIsEven = true + for i in self.indices { + if indexIsEven { + let byteRange = i...self.index(after: i) + guard let byte = UInt8(self[byteRange], radix: 16) else { return nil } + bytes.append(byte) + } + indexIsEven.toggle() + } + return bytes + } +} diff --git a/xcodes-srp/Tests/SRPTests/XCTestManifests.swift b/xcodes-srp/Tests/SRPTests/XCTestManifests.swift new file mode 100644 index 00000000..97c4c9fa --- /dev/null +++ b/xcodes-srp/Tests/SRPTests/XCTestManifests.swift @@ -0,0 +1,9 @@ +import XCTest + +#if !canImport(ObjectiveC) +public func allTests() -> [XCTestCaseEntry] { + return [ + testCase(SRPTests.allTests), + ] +} +#endif From 2ed84ef7922d20746dcc9fcc57f34f5312c5e4a1 Mon Sep 17 00:00:00 2001 From: Matt Kiazyk Date: Thu, 24 Oct 2024 19:34:26 -0500 Subject: [PATCH 3/7] clean up srp client, still not working --- .../xcshareddata/swiftpm/Package.resolved | 8 +- Xcodes/AppleAPI/Sources/AppleAPI/Client.swift | 60 ++- .../contents.xcworkspacedata | 7 + xcodes-srp/Package.resolved | 34 ++ xcodes-srp/Package.swift | 4 +- xcodes-srp/Sources/SRP/client.swift | 352 ++++++++++-------- xcodes-srp/Sources/SRP/configuration.swift | 201 ---------- xcodes-srp/Sources/SRP/group.swift | 248 ++++++++++++ xcodes-srp/Sources/SRP/keys.swift | 40 -- xcodes-srp/Sources/SRP/server.swift | 108 ------ xcodes-srp/Sources/SRP/srp.swift | 165 +++++--- 11 files changed, 627 insertions(+), 600 deletions(-) create mode 100644 xcodes-srp/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata create mode 100644 xcodes-srp/Package.resolved delete mode 100644 xcodes-srp/Sources/SRP/configuration.swift create mode 100644 xcodes-srp/Sources/SRP/group.swift delete mode 100644 xcodes-srp/Sources/SRP/keys.swift delete mode 100644 xcodes-srp/Sources/SRP/server.swift diff --git a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 89a660f9..e76dc9c8 100644 --- a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -11,12 +11,12 @@ } }, { - "package": "big-num", - "repositoryURL": "https://github.com/adam-fowler/big-num", + "package": "BigInt", + "repositoryURL": "https://github.com/attaswift/BigInt", "state": { "branch": null, - "revision": "5c5511ad06aeb2b97d0868f7394e14a624bfb1c7", - "version": "2.0.2" + "revision": "793a7fac0bfc318e85994bf6900652e827aef33e", + "version": "5.4.1" } }, { diff --git a/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift b/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift index 42698ef9..09f7c084 100644 --- a/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift +++ b/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift @@ -4,6 +4,7 @@ import SRP import Crypto import CommonCrypto + public class Client { private static let authTypes = ["sa", "hsa", "non-sa", "hsa2"] @@ -14,9 +15,8 @@ public class Client { public func srpLogin(accountName: String, password: String) -> AnyPublisher { var serviceKey: String! - let config = SRPConfiguration(.N2048) - let client = SRPClient(configuration: config) - let clientKeys = client.generateKeys() + let client = SRPClient(username: accountName, password: password) + let a = client.startAuthentication() return Current.network.dataTask(with: URLRequest.itcServiceKey) .map(\.data) @@ -33,13 +33,14 @@ public class Client { } .flatMap { (serviceKey, hashcash) -> AnyPublisher<(String, String, ServerSRPInitResponse), Swift.Error> in - return Current.network.dataTask(with: URLRequest.SRPInit(serviceKey: serviceKey, a: clientKeys.private.hex, accountName: accountName)) + return Current.network.dataTask(with: URLRequest.SRPInit(serviceKey: serviceKey, a: a.base64EncodedString(), accountName: accountName)) .map(\.data) .decode(type: ServerSRPInitResponse.self, decoder: JSONDecoder()) .map { return (serviceKey, hashcash, $0) } .eraseToAnyPublisher() } .flatMap { (serviceKey, hashcash, srpInit) -> AnyPublisher in + print("SRP INIT REsponse: \(srpInit)") guard let decodedB = Data(base64Encoded: srpInit.b) else { return Fail(error: AuthenticationError.srpInvalidPublicKey) @@ -52,46 +53,29 @@ public class Client { } let iterations = srpInit.iteration - let serverPublic = SRPKey([UInt8](decodedB)) - guard let encryptedPassword = self.pbkdf2(password: password, saltData: decodedSalt, keyByteCount: 32, prf: CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), rounds: iterations) else { - return Fail(error: AuthenticationError.srpInvalidPublicKey) - .eraseToAnyPublisher() - } - - - let encryptedPasswordArray = encryptedPassword.hexEncodedString() - - print("EncryptedPassword: \(encryptedPasswordArray)") - print("EncryptedPassword: \([UInt8](encryptedPassword))") do { - // this calculates "S" - let clientSharedSecret = try client.calculateSharedSecret( - encryptedPassword: encryptedPasswordArray, - salt: [UInt8](decodedSalt), - clientKeys: clientKeys, - serverPublicKey: serverPublic - ) - print("SharedSecret: \(clientSharedSecret)") + guard let encryptedPassword = self.pbkdf2(password: password, saltData: decodedSalt, keyByteCount: 32, prf: CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), rounds: iterations) else { + return Fail(error: AuthenticationError.srpInvalidPublicKey) + .eraseToAnyPublisher() + } - let m1 = client.calculateClientProof( - username: accountName, - salt: [UInt8](decodedSalt), - clientPublicKey: clientKeys.public, - serverPublicKey: serverPublic, - sharedSecret: clientSharedSecret - ) - - let m2 = client.serverProof(clientProof: m1, clientKeys: clientKeys, sharedSecret: clientSharedSecret) - +// let m1 = try client.processChallenge(salt: decodedSalt, publicKey: decodedB, isEncryptedPassword: true, encryptedPassword: encryptedPassword.hexEncodedString()) + let encryptedPasswordString = String(data: encryptedPassword, encoding: .utf8) + let m1 = try client.processChallenge(salt: decodedSalt, publicKey: decodedB, isEncryptedPassword: true, encryptedPassword: encryptedPasswordString) - print("M1: \(Data(m1).base64EncodedString())") - print("M2: \(Data(m2).base64EncodedString())") + guard let m2 = client.HAMK else { + return Fail(error: AuthenticationError.srpInvalidPublicKey) + .eraseToAnyPublisher() + } - return Current.network.dataTask(with: URLRequest.SRPComplete(serviceKey: serviceKey, hashcash: hashcash, accountName: accountName, c: srpInit.c, m1: Data(m1).base64EncodedString(), m2: Data(m2).base64EncodedString())) - .mapError { $0 as Swift.Error } - .eraseToAnyPublisher() + print("m1: \(m1.base64EncodedString())") + print("m2: \(m2.base64EncodedString())") + + return Current.network.dataTask(with: URLRequest.SRPComplete(serviceKey: serviceKey, hashcash: hashcash, accountName: accountName, c: srpInit.c, m1: m1.base64EncodedString(), m2: m2.base64EncodedString())) + .mapError { $0 as Swift.Error } + .eraseToAnyPublisher() } catch { print("Error: calculateSharedSecret \(error)") return Fail(error: AuthenticationError.srpInvalidPublicKey) diff --git a/xcodes-srp/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/xcodes-srp/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..919434a6 --- /dev/null +++ b/xcodes-srp/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/xcodes-srp/Package.resolved b/xcodes-srp/Package.resolved new file mode 100644 index 00000000..8c65785c --- /dev/null +++ b/xcodes-srp/Package.resolved @@ -0,0 +1,34 @@ +{ + "object": { + "pins": [ + { + "package": "big-num", + "repositoryURL": "https://github.com/adam-fowler/big-num", + "state": { + "branch": null, + "revision": "5c5511ad06aeb2b97d0868f7394e14a624bfb1c7", + "version": "2.0.2" + } + }, + { + "package": "BigInt", + "repositoryURL": "https://github.com/attaswift/BigInt.git", + "state": { + "branch": null, + "revision": "793a7fac0bfc318e85994bf6900652e827aef33e", + "version": "5.4.1" + } + }, + { + "package": "swift-crypto", + "repositoryURL": "https://github.com/apple/swift-crypto", + "state": { + "branch": null, + "revision": "ddb07e896a2a8af79512543b1c7eb9797f8898a5", + "version": "1.1.7" + } + } + ] + }, + "version": 1 +} diff --git a/xcodes-srp/Package.swift b/xcodes-srp/Package.swift index a4270283..890d696c 100644 --- a/xcodes-srp/Package.swift +++ b/xcodes-srp/Package.swift @@ -16,10 +16,10 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/apple/swift-crypto", from: "1.0.0"), - .package(url: "https://github.com/adam-fowler/big-num", from: "2.0.0"), + .package(url: "https://github.com/attaswift/BigInt.git", from: "5.0.0") ], targets: [ - .target(name: "SRP", dependencies: ["BigNum", "Crypto"]), + .target(name: "SRP", dependencies: ["Crypto", "BigInt"]), .testTarget( name: "SRPTests", dependencies: ["SRP"]), ] diff --git a/xcodes-srp/Sources/SRP/client.swift b/xcodes-srp/Sources/SRP/client.swift index 98e01905..38702526 100644 --- a/xcodes-srp/Sources/SRP/client.swift +++ b/xcodes-srp/Sources/SRP/client.swift @@ -1,182 +1,224 @@ -import BigNum + +import Foundation +import BigInt import Crypto -/// Manages the client side of Secure Remote Password -/// -/// Secure Remote Password (SRP) provides username and password authentication without needing to provide your password to the server. The server -/// has a cryptographic verifier that is derived from the password and a salt that was used to generate this verifier. Both client and server -/// generate a shared secret then the client sends a proof they have the secret and if it is correct the server will do the same to verify the -/// server as well. -/// -/// This version is compliant with SRP version 6a and RFC 5054. -/// -/// Reference reading -/// - https://tools.ietf.org/html/rfc2945 -/// - https://tools.ietf.org/html/rfc5054 -/// -public struct SRPClient { - /// configuration. This needs to be the same as the server configuration - public let configuration: SRPConfiguration - - /// Initialise a SRPClient object - /// - Parameter configuration: configuration to use - public init(configuration: SRPConfiguration) { - self.configuration = configuration - } - - /// Initiate the authentication process - /// - Returns: An authentication state. The A value from this state should be sent to the server - public func generateKeys() -> SRPKeyPair { - var a = BigNum() - var A = BigNum() - repeat { - a = BigNum(bytes: SymmetricKey(size: .bits256)) - A = configuration.g.power(a, modulus: configuration.N) - } while A % configuration.N == BigNum(0) - - return SRPKeyPair(public: SRPKey(A), private: SRPKey(a)) - } - - /// return shared secret given the username, password, B value and salt from the server - /// - Parameters: - /// - username: user identifier - /// - password: password - /// - salt: salt - /// - clientKeys: client public/private keys - /// - serverPublicKey: server public key - /// - Throws: `nullServerKey` - /// - Returns: shared secret - public func calculateSharedSecret(username: String, password: String, salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> SRPKey { - let message = [UInt8]("\(username):\(password)".utf8) - let sharedSecret = try calculateSharedSecret(message: message, salt: salt, clientKeys: clientKeys, serverPublicKey: serverPublicKey) - return SRPKey(sharedSecret) - } +/// SRP Client; the party that initializes the authentication and +/// must proof possession of the correct password. +public class SRPClient { + let a: BigUInt + let A: BigUInt - /// return shared secret given the username, password, B value and salt from the server - /// - Parameters: - /// - username: user identifier - /// - password: password - /// - salt: salt - /// - clientKeys: client public/private keys - /// - serverPublicKey: server public key - /// - Throws: `nullServerKey` - /// - Returns: shared secret - public func calculateSharedSecret(encryptedPassword: String, salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> SRPKey { - let message = [UInt8](":\(encryptedPassword)".utf8) - let sharedSecret = try calculateSharedSecret(message: message, salt: salt, clientKeys: clientKeys, serverPublicKey: serverPublicKey) - return SRPKey(sharedSecret) - } - - - /// calculate proof of shared secret to send to server - /// - Parameters: - /// - clientPublicKey: client public key - /// - serverPublicKey: server public key - /// - sharedSecret: shared secret - /// - Returns: The client verification code which should be passed to the server - public func calculateSimpleClientProof(clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) -> [UInt8] { - // get verification code - return SRP.calculateSimpleClientProof(clientPublicKey: clientPublicKey, serverPublicKey: serverPublicKey, sharedSecret: sharedSecret) + let group: Group + typealias impl = Implementation // swiftlint:disable:this type_name + + let username: String + var password: String? + var precomputedX: BigUInt? + + public var HAMK: Data? + var K: Data? + + /// Whether the session is authenticated, i.e. the password + /// was verified by the server and proof of a valid session + /// key was provided by the server. If `true`, `sessionKey` + /// is also available. + public private(set) var isAuthenticated = false + + private init( + username: String, + group: Group = .N2048, + privateKey: Data? = nil) + { + self.username = username + self.group = group + if let privateKey = privateKey { + a = BigUInt(privateKey) + } else { + a = BigUInt(Curve25519.KeyAgreement.PrivateKey().rawRepresentation) + } + // A = g^a % N + A = group.g.power(a, modulus: group.N) } - - /// If the server returns that the client verification code was valiid it will also return a server verification code that the client can use to verify the server is correct + + /// Initialize the Client SRP party with a password. /// /// - Parameters: - /// - code: Verification code returned by server - /// - state: Authentication state - /// - Throws: `requiresVerificationKey`, `invalidServerCode` - public func verifySimpleServerProof(serverProof: [UInt8], clientProof: [UInt8], clientKeys: SRPKeyPair, sharedSecret: SRPKey) throws { - // get out version of server proof - let HAMS = SRP.calculateSimpleServerVerification(clientPublicKey: clientKeys.public, clientProof: clientProof, sharedSecret: sharedSecret) - // is it the same - guard serverProof == HAMS else { throw SRPClientError.invalidServerCode } + /// - username: user's username. + /// - password: user's password. + /// - group: which `Group` to use, must be the same for the + /// server as well as the pre-stored verificationKey. + /// - privateKey: (optional) custom private key (a); if providing + /// the private key of the `Client`, make sure to provide a + /// good random key of at least 32 bytes. Default is to + /// generate a private key of 128 bytes. You MUST not re-use + /// the private key between sessions. + public convenience init( + username: String, + password: String, + group: Group = .N2048, + privateKey: Data? = nil) + { + self.init(username: username, group: group, privateKey: privateKey) + self.password = password } - /// calculate proof of shared secret to send to server + /// Initialize the Client SRP party with a precomputed x. + /// /// - Parameters: - /// - username: username - /// - salt: The salt value associated with the user returned by the server - /// - clientPublicKey: client public key - /// - serverPublicKey: server public key - /// - sharedSecret: shared secret - /// - Returns: The client verification code which should be passed to the server - public func calculateClientProof(username: String, salt: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) -> [UInt8] { - - let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) - - // get verification code - return SRP.calculateClientProof(configuration: configuration, username: username, salt: salt, clientPublicKey: clientPublicKey, serverPublicKey: serverPublicKey, hashSharedSecret: hashSharedSecret) + /// - username: user's username. + /// - precomputedX: precomputed SRP x. + /// - group: which `Group` to use, must be the same for the + /// server as well as the pre-stored verificationKey. + /// - privateKey: (optional) custom private key (a); if providing + /// the private key of the `Client`, make sure to provide a + /// good random key of at least 32 bytes. Default is to + /// generate a private key of 128 bytes. You MUST not re-use + /// the private key between sessions. + public convenience init( + username: String, + precomputedX: Data, + group: Group = .N2048, + privateKey: Data? = nil) + { + self.init(username: username, group: group, privateKey: privateKey) + self.precomputedX = BigUInt(precomputedX) } - /// If the server returns that the client verification code was valiid it will also return a server verification code that the client can use to verify the server is correct + /// Starts authentication. This method is a no-op. /// - /// - Parameters: - /// - code: Verification code returned by server - /// - state: Authentication state - /// - Throws: `requiresVerificationKey`, `invalidServerCode` - public func verifyServerProof(serverProof: [UInt8], clientProof: [UInt8], clientKeys: SRPKeyPair, sharedSecret: SRPKey) throws { - let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) - // get out version of server proof - let HAMK = SRP.calculateServerVerification(clientPublicKey: clientKeys.public, clientProof: clientProof, sharedSecret: hashSharedSecret) - // is it the same - guard serverProof == HAMK else { throw SRPClientError.invalidServerCode } + /// - Returns: `publicKey` (A) + public func startAuthentication() -> Data { + return publicKey } - - /// If the server returns that the client verification code was valiid it will also return a server verification code that the client can use to verify the server is correct + /// Process the challenge provided by the server. This sets the `sessionKey` + /// and generates proof that it generated the correct key from the password + /// and the challenge. After the server has also proven the validity of their + /// key, the `sessionKey` can be used. /// /// - Parameters: - /// - code: Verification code returned by server - /// - state: Authentication state - /// - Throws: `requiresVerificationKey`, `invalidServerCode` - public func serverProof(clientProof: [UInt8], clientKeys: SRPKeyPair, sharedSecret: SRPKey) -> [UInt8] { - let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) + /// - salt: user-specific salt (s) + /// - publicKey: server's public key (B) + /// - Returns: key proof (M) + /// - Throws: `AuthenticationFailure.invalidPublicKey` if the server's + /// public key is invalid (i.e. B % N is zero). + public func processChallenge(salt: Data, publicKey serverPublicKey: Data, isEncryptedPassword: Bool, encryptedPassword: String? = nil) throws -> Data { + let H = impl.H + let N = group.N + + let B = BigUInt(serverPublicKey) + + guard B % N != 0 else { + throw AuthenticationFailure.invalidPublicKey + } + + let u = impl.calculate_u(group: group, A: publicKey, B: serverPublicKey) + let k = impl.calculate_k(group: group) - return SRP.calculateServerVerification(clientPublicKey: clientKeys.public, clientProof: clientProof, sharedSecret: hashSharedSecret) + let x = self.precomputedX ?? (isEncryptedPassword ? impl.calculate_x(salt: salt, username: "", password: encryptedPassword!) : impl.calculate_x(salt: salt, username: username, password: password!)) + let v = calculate_v(group: group, x: x) + + // shared secret + // S = (B - kg^x) ^ (a + ux) + // Note that v = g^x, and that B - kg^x might become negative, which + // cannot be stored in BigUInt. So we'll add N to B_ and make sure kv + // isn't greater than N. + let S = (B + N - k * v % N).power(a + u * x, modulus: N) + + // session key + K = H(S.serialize()) + + // client verification + let M = impl.calculate_M(group: group, username: username, salt: salt, A: publicKey, B: serverPublicKey, K: K!) + + // server verification + HAMK = impl.calculate_HAMK(A: publicKey, M: M, K: K!) + return M } - - /// Generate salt and password verifier from username and password. When creating your user instead of passing your password to the server, you - /// pass the salt and password verifier values. In this way the server never knows your password so can never leak it. + + /// After the server has verified that the password is correct, + /// it will send proof of the derived session key. This is verified + /// on our end and finalizes the authentication session. After this + /// step, the `sessionKey` is available. /// - /// - Parameters: - /// - username: username - /// - password: user password - /// - Returns: tuple containing salt and password verifier - public func generateSaltAndVerifier(username: String, password: String) -> (salt: [UInt8], verifier: SRPKey) { - let salt = [UInt8].random(count: 16) - let verifier = generatePasswordVerifier(username: username, password: password, salt: salt) - return (salt: salt, verifier: SRPKey(verifier)) + /// - Parameter HAMK: proof of the server that it derived the same + /// session key. + /// - Throws: + /// - `AuthenticationFailure.missingChallenge` if this method + /// is called before calling `processChallenge`. + /// - `AuthenticationFailure.keyProofMismatch` if the proof + /// doesn't match our own. + public func verifySession(keyProof serverKeyProof: Data) throws { + guard let HAMK = HAMK else { + throw AuthenticationFailure.missingChallenge + } + guard HAMK == serverKeyProof else { + throw AuthenticationFailure.keyProofMismatch + } + isAuthenticated = true } -} -extension SRPClient { - /// return shared secret given the username, password, B value and salt from the server - func calculateSharedSecret(message: [UInt8], salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> BigNum { - guard serverPublicKey.number % configuration.N != BigNum(0) else { throw SRPClientError.nullServerKey } + /// The client's public key (A). For every authentication + /// session a new public key is generated. + public var publicKey: Data { + return A.serialize() + } - // calculate u = H(clientPublicKey | serverPublicKey) - let u = SRP.calculateU(clientPublicKey: clientKeys.public.bytes, serverPublicKey: serverPublicKey.bytes, pad: configuration.sizeN) + /// The client's private key (a). For every authentication + /// session a new random private key is generated. + public var privateKey: Data { + return a.serialize() + } - guard u != 0 else { throw SRPClientError.nullServerKey } - - let x = BigNum(bytes: [UInt8](H.hash(data: salt + H.hash(data: message)))) - - // calculate S = (B - k*g^x)^(a+u*x) - let S = (serverPublicKey.number - configuration.k * configuration.g.power(x, modulus: configuration.N)).power(clientKeys.private.number + u * x, modulus: configuration.N) - - return S + /// The session key (K) that is exchanged during authentication. + /// This key can be used to encrypt further communication + /// between client and server. + public var sessionKey: Data? { + guard isAuthenticated else { + return nil + } + return K } - - /// generate password verifier - public func generatePasswordVerifier(username: String, password: String, salt: [UInt8]) -> BigNum { - let message = "\(username):\(password)" - return generatePasswordVerifier(message: [UInt8](message.utf8), salt: salt) +} + +/// Possible authentication failure modes. +public enum AuthenticationFailure: Error { + /// Security breach: the provided public key is empty (i.e. PK % N is zero). + case invalidPublicKey + + /// Invalid client state: call `processChallenge` before `verifySession`. + case missingChallenge + + /// Failed authentication: the key proof didn't match our own. + case keyProofMismatch +} + +extension AuthenticationFailure: CustomStringConvertible { + /// A textual representation of this instance. + /// + /// Instead of accessing this property directly, convert an instance of any + /// type to a string by using the `String(describing:)` initializer. + public var description: String { + switch self { + case .invalidPublicKey: return "security breach - the provided public key is invalid" + case .missingChallenge: return "invalid client state - call `processChallenge` before `verifySession`" + case .keyProofMismatch: return "failed authentication - the key proof didn't match our own" + } } - - /// generate password verifier - public func generatePasswordVerifier(message: [UInt8], salt: [UInt8]) -> BigNum { - let x = BigNum(bytes: [UInt8](H.hash(data: salt + H.hash(data: message)))) - let verifier = configuration.g.power(x, modulus: configuration.N) - return verifier +} +func ^ (lhs: Data, rhs: Data) -> Data? { + guard lhs.count == rhs.count else { return nil } + var result = Data(count: lhs.count) + for index in lhs.indices { + result[index] = lhs[index] ^ rhs[index] } + return result +} + +// Removed in Xcode 8 beta 3 +func + (lhs: Data, rhs: Data) -> Data { + var result = lhs + result.append(rhs) + return result } diff --git a/xcodes-srp/Sources/SRP/configuration.swift b/xcodes-srp/Sources/SRP/configuration.swift deleted file mode 100644 index a1fe01a6..00000000 --- a/xcodes-srp/Sources/SRP/configuration.swift +++ /dev/null @@ -1,201 +0,0 @@ -import BigNum -import Crypto - -/// SRP Configuration. The same configuration hast to be used by both client and server. Contains a large safe prime N ie a prime where the value (N-1)/2 is also a prime, g the multiplicative group generator and the value k = Hash(N | g) -public struct SRPConfiguration { - /// large safe prime - public let N: BigNum - /// multiplicative group generator - public let g: BigNum - /// derived value from N and g. k = H( N | g ) - public let k: BigNum - /// size in bytes of N - public let sizeN: Int - - /// Initialise SRPConfiguration with known safe prime - /// - Parameter prime: enum indicating size of prime - public init(_ prime: Prime) { - self.N = prime.group - self.sizeN = Int(self.N.numBits() + 7) / 8 - self.g = prime.generator - self.k = BigNum(bytes: [UInt8](H.hash(data: self.N.bytes + SRP.pad(self.g.bytes, to: sizeN)))) - } - - /// Initialise SRPConfiguration with your own prime and multiplicative group generator - /// - Parameters: - /// - N: Large prime - /// - g: multiplicative group generator (usually 2) - public init(N: BigNum, g: BigNum) { - self.N = N - self.sizeN = Int(self.N.numBits() + 7) / 8 - self.g = g - self.k = BigNum(bytes: [UInt8](H.hash(data: self.N.bytes + SRP.pad(self.g.bytes, to: sizeN)))) - } - - public enum Prime { - case N1024 - case N1536 - case N2048 - case N3072 - case N4096 - case N6144 - case N8192 - - /// prime numbers and generators taken from RC 5054 https://tools.ietf.org/html/rfc5054 - var group: BigNum { - switch self { - case .N1024: - return BigNum(hex: - "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" + - "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" + - "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" + - "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" + - "FD5138FE8376435B9FC61D2FC0EB06E3")! - - case .N1536: - return BigNum(hex: - "9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA961" + - "4B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F843" + - "80B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0B" + - "E3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF5" + - "6EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734A" + - "F7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E" + - "8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB")! - - case .N2048: - return BigNum(hex: - "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" + - "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" + - "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" + - "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" + - "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" + - "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" + - "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" + - "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" + - "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" + - "9E4AFF73")! - - case .N3072: - return BigNum(hex: - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF")! - - case .N4096: - return BigNum(hex: - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" + - "FFFFFFFFFFFFFFFF")! - - case .N6144: - return BigNum(hex: - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + - "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + - "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + - "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + - "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + - "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + - "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + - "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + - "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + - "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + - "6DCC4024FFFFFFFFFFFFFFFF")! - - case .N8192: - return BigNum(hex: - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + - "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + - "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + - "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + - "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + - "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + - "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + - "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + - "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + - "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + - "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA" + - "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C" + - "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" + - "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886" + - "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6" + - "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5" + - "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268" + - "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6" + - "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + - "60C980DD98EDD3DFFFFFFFFFFFFFFFFF")! - } - } - - var generator: BigNum { - switch self { - case .N1024, .N1536, .N2048: - return BigNum(2) - case .N3072, .N4096, .N6144: - return BigNum(5) - case .N8192: - return BigNum(19) - } - } - } -} diff --git a/xcodes-srp/Sources/SRP/group.swift b/xcodes-srp/Sources/SRP/group.swift new file mode 100644 index 00000000..9712acb2 --- /dev/null +++ b/xcodes-srp/Sources/SRP/group.swift @@ -0,0 +1,248 @@ +// +// must.swift +// swift-srp +// +// Created by Matt Kiazyk on 2024-10-24. +// + + +import BigInt + +/// SRP Group Parameters +/// +/// The 1024-, 1536-, and 2048-bit groups are taken from software +/// developed by Tom Wu and Eugene Jhong for the Stanford SRP +/// distribution, and subsequently proven to be prime. The larger primes +/// are taken from [MODP], but generators have been calculated that are +/// primitive roots of N, unlike the generators in [MODP]. +/// +/// The values of N and g used in this protocol must be agreed upon by +/// the two parties in question. They can be set in advance, or the host +/// can supply them to the client. In the latter case, the host should +/// send the parameters in the first message along with the salt. For +/// maximum security, N should be a safe prime (i.e. a number of the form +/// N = 2q + 1, where q is also prime). Also, g should be a generator +/// modulo N (see [SRP] for details), which means that for any X where 0 +/// < X < N, there exists a value x for which g^x % N == X. +/// +/// [MODP] Kivinen, T. and M. Kojo, "More Modular Exponentiation +/// (MODP) Diffie-Hellman groups for Internet Key Exchange +/// (IKE)", RFC 3526, May 2003. +/// +/// [SRP] T. Wu, "The Secure Remote Password Protocol", In +/// Proceedings of the 1998 Internet Society Symposium on +/// Network and Distributed Systems Security, San Diego, CA, +/// pp. 97-111. +public enum Group { + /// 1024-bits group + case N1024 + + /// 2048-bits group + case N2048 + + /// 1536-bits group + case N1536 + + /// 3072-bits group + case N3072 + + /// 4096-bits group + case N4096 + + /// 6144-bits group + case N6144 + + /// 8192-bits group + case N8192 + + /// Custom group parameters. See `init(prime:generator:)` for more information. + public struct CustomGroup { + let N: BigUInt + let g: BigUInt + } + + /// Custom group parameters. See `init(prime:generator:)` for more information. + case custom(CustomGroup) + + /// Create custom group parameters. See the enum's documentation for + /// considerations on good parameters. + /// - Parameters: + /// - prime: hex-encoded prime + /// - generator: hex-encoded generator + /// - Returns: nil if one of the parameters chould not be decoded + public init?(prime: String, generator: String) { + guard let N = BigUInt(prime, radix: 16), let g = BigUInt(generator, radix: 16) else { + return nil + } + self = .custom(CustomGroup(N: N, g: g)) + } + + var N: BigUInt { + switch self { + case .N1024: + return BigUInt( + "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" + + "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" + + "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" + + "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" + + "FD5138FE8376435B9FC61D2FC0EB06E3", + radix: 16)! + case .N1536: + return BigUInt( + "9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA961" + + "4B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F843" + + "80B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0B" + + "E3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF5" + + "6EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734A" + + "F7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E" + + "8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB", + radix: 16)! + case .N2048: + return BigUInt( + "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" + + "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" + + "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" + + "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" + + "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" + + "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" + + "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" + + "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" + + "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" + + "9E4AFF73", + radix: 16)! + case .N3072: + return BigUInt( + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF", + radix: 16)! + case .N4096: + return BigUInt( + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" + + "FFFFFFFFFFFFFFFF", + radix: 16)! + case .N6144: + return BigUInt( + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + + "6DCC4024FFFFFFFFFFFFFFFF", + radix: 16)! + case .N8192: + return BigUInt( + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + + "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA" + + "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C" + + "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" + + "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886" + + "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6" + + "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5" + + "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268" + + "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6" + + "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + + "60C980DD98EDD3DFFFFFFFFFFFFFFFFF", + radix: 16)! + case .custom(let custom): + return custom.N + } + } + + var g: BigUInt { + switch self { + case .N1024: + return BigUInt(2) + case .N1536: + return BigUInt(2) + case .N2048: + return BigUInt(2) + case .N3072: + return BigUInt(5) + case .N4096: + return BigUInt(5) + case .N6144: + return BigUInt(5) + case .N8192: + return BigUInt(19) + case .custom(let custom): + return custom.g + } + } +} \ No newline at end of file diff --git a/xcodes-srp/Sources/SRP/keys.swift b/xcodes-srp/Sources/SRP/keys.swift deleted file mode 100644 index c7d08a0b..00000000 --- a/xcodes-srp/Sources/SRP/keys.swift +++ /dev/null @@ -1,40 +0,0 @@ -import BigNum - -/// Wrapper for keys used by SRP -public struct SRPKey { - public let number: BigNum - public var bytes: [UInt8] { number.bytes } - public var hex: String { number.hex } - - public init(_ bytes: [UInt8]) { - self.number = BigNum(bytes: bytes) - } - - public init(_ number: BigNum) { - self.number = number - } - - public init?(hex: String) { - guard let number = BigNum(hex: hex) else { return nil } - self.number = number - } -} - -extension SRPKey: Equatable { } - -/// Contains a private and a public key -public struct SRPKeyPair { - public let `public`: SRPKey - public let `private`: SRPKey - - - /// Initialise a SRPKeyPair object - /// - Parameters: - /// - public: The public key of the key pair - /// - private: The private key of the key pair - public init(`public`: SRPKey, `private`: SRPKey) { - self.private = `private` - self.public = `public` - } -} - diff --git a/xcodes-srp/Sources/SRP/server.swift b/xcodes-srp/Sources/SRP/server.swift deleted file mode 100644 index c823c06e..00000000 --- a/xcodes-srp/Sources/SRP/server.swift +++ /dev/null @@ -1,108 +0,0 @@ -import BigNum -import Crypto - -/// Manages the server side of Secure Remote Password. -/// -/// Secure Remote Password (SRP) provides username and password authentication without needing to provide your password to the server. The server -/// has a cryptographic verifier that is derived from the password and a salt that was used to generate this verifier. Both client and server -/// generate a shared secret then the client sends a proof they have the secret and if it is correct the server will do the same to verify the -/// server as well. -/// -/// This version is compliant with SRP version 6a and RFC 5054. -/// -/// Reference reading -/// - https://tools.ietf.org/html/rfc2945 -/// - https://tools.ietf.org/html/rfc5054 -/// -public struct SRPServer { - /// Authentication state. Stores A,B and shared secret - public struct AuthenticationState { - let clientPublicKey: SRPKey - let serverPublicKey: SRPKey - var serverPrivateKey: SRPKey - } - - /// configuration has to be the same as the client configuration - public let configuration: SRPConfiguration - - /// Initialise SRPServer - /// - Parameter configuration: configuration to use - public init(configuration: SRPConfiguration) { - self.configuration = configuration - } - - /// generate public and private keys to be used in srp authentication - /// - Parameter verifier: password verifier used to generate key pair - /// - Returns: return public/private key pair - public func generateKeys(verifier: SRPKey) -> SRPKeyPair { - var b: BigNum - var B: BigNum - repeat { - b = BigNum(bytes: SymmetricKey(size: .bits256)) - B = (configuration.k * verifier.number + configuration.g.power(b, modulus: configuration.N)) % configuration.N - } while B % configuration.N == BigNum(0) - - return SRPKeyPair(public: SRPKey(B), private: SRPKey(b)) - } - - /// calculate the shared secret - /// - Parameters: - /// - clientPublicKey: public key received from client - /// - serverKeys: server key pair - /// - verifier: password verifier - /// - Returns: shared secret - public func calculateSharedSecret(clientPublicKey: SRPKey, serverKeys: SRPKeyPair, verifier: SRPKey) throws -> SRPKey { - guard clientPublicKey.number % configuration.N != BigNum(0) else { throw SRPServerError.nullClientKey } - - // calculate u = H(clientPublicKey | serverPublicKey) - let u = SRP.calculateU(clientPublicKey: clientPublicKey.bytes, serverPublicKey: serverKeys.public.bytes, pad: configuration.sizeN) - - // calculate S - let S = ((clientPublicKey.number * verifier.number.power(u, modulus: configuration.N)).power(serverKeys.private.number, modulus: configuration.N)) - - return SRPKey(S) - } - - /// verify proof that client has shared secret and return a server verification proof. If verification fails a `invalidClientCode` error is thrown - /// - /// - Parameters: - /// - code: verification code sent by user - /// - username: username - /// - salt: salt stored with user - /// - state: authentication state. - /// - Throws: invalidClientCode - /// - Returns: The server verification code - public func verifySimpleClientProof(proof: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) throws -> [UInt8] { - let clientProof = SRP.calculateSimpleClientProof( - clientPublicKey: clientPublicKey, - serverPublicKey: serverPublicKey, - sharedSecret: sharedSecret - ) - guard clientProof == proof else { throw SRPServerError.invalidClientProof } - return SRP.calculateSimpleServerVerification(clientPublicKey: clientPublicKey, clientProof: clientProof, sharedSecret: sharedSecret) - } - - /// verify proof that client has shared secret and return a server verification proof. If verification fails a `invalidClientCode` error is thrown - /// - /// - Parameters: - /// - code: verification code sent by user - /// - username: username - /// - salt: salt stored with user - /// - state: authentication state. - /// - Throws: invalidClientCode - /// - Returns: The server verification code - public func verifyClientProof(proof: [UInt8], username: String, salt: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) throws -> [UInt8] { - let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) - - let clientProof = SRP.calculateClientProof( - configuration: configuration, - username: username, - salt: salt, - clientPublicKey: clientPublicKey, - serverPublicKey: serverPublicKey, - hashSharedSecret: hashSharedSecret - ) - guard clientProof == proof else { throw SRPServerError.invalidClientProof } - return SRP.calculateServerVerification(clientPublicKey: clientPublicKey, clientProof: clientProof, sharedSecret: hashSharedSecret) - } -} diff --git a/xcodes-srp/Sources/SRP/srp.swift b/xcodes-srp/Sources/SRP/srp.swift index 52bcd805..9ffdf5d5 100644 --- a/xcodes-srp/Sources/SRP/srp.swift +++ b/xcodes-srp/Sources/SRP/srp.swift @@ -1,64 +1,125 @@ -import BigNum +// +// Implementation.swift +// swift-srp +// +// Created by Matt Kiazyk on 2024-10-24. +// + + +import Foundation +import BigInt import Crypto -/// Contains common code used by both client and server SRP code -public struct SRP { +/// Creates the salted verification key based on a user's username and +/// password. Only the salt and verification key need to be stored on the +/// server, there's no need to keep the plain-text password. +/// +/// Keep the verification key private, as it can be used to brute-force +/// the password from. +/// +/// - Parameters: +/// - using: hash function to use +/// - username: user's username +/// - password: user's password +/// - salt: (optional) custom salt value; if providing a salt, make sure to +/// provide a good random salt of at least 16 bytes. Default is to +/// generate a salt of 16 bytes. +/// - group: `Group` parameters; default is 2048-bits group. +/// - algorithm: which `Digest.Algorithm` to use; default is SHA1. +/// - Returns: salt (s) and verification key (v) +public func createSaltedVerificationKey( + using hashFunction: H.Type, + group: Group = .N2048, + username: String, + password: String, + salt: Data? = nil) + -> (salt: Data, verificationKey: Data) +{ + let salt = salt ?? randomBytes(16) + let x = Implementation.calculate_x(salt: salt, username: username, password: password) + return createSaltedVerificationKey(from: x, salt: salt, group: group) +} + +/// Creates the salted verification key based on a precomputed SRP x value. +/// Only the salt and verification key need to be stored on the +/// server, there's no need to keep the plain-text password. +/// +/// Keep the verification key private, as it can be used to brute-force +/// the password from. +/// +/// - Parameters: +/// - x: precomputed SRP x +/// - salt: (optional) custom salt value; if providing a salt, make sure to +/// provide a good random salt of at least 16 bytes. Default is to +/// generate a salt of 16 bytes. +/// - group: `Group` parameters; default is 2048-bits group. +/// - Returns: salt (s) and verification key (v) +public func createSaltedVerificationKey( + from x: Data, + salt: Data? = nil, + group: Group = .N2048) + -> (salt: Data, verificationKey: Data) +{ + return createSaltedVerificationKey(from: BigUInt(x), salt: salt, group: group) +} + +func createSaltedVerificationKey( + from x: BigUInt, + salt: Data? = nil, + group: Group = .N2048) + -> (salt: Data, verificationKey: Data) +{ + let salt = salt ?? randomBytes(16) + let v = calculate_v(group: group, x: x) + return (salt, v.serialize()) +} - /// pad to a certain size by prefixing with zeros - static func pad(_ data: [UInt8], to size: Int) -> [UInt8] { - let padSize = size - data.count - guard padSize > 0 else { return data } - // create prefix and return prefix + data - let prefix: [UInt8] = (1...padSize).reduce([]) { result,_ in return result + [0] } - return prefix + data +func pad(_ data: Data, to size: Int) -> Data { + precondition(size >= data.count, "Negative padding not possible") + return Data(count: size - data.count) + data +} + +enum Implementation { + // swiftlint:disable:next identifier_name + static func H(_ data: Data) -> Data { + return Data(HF.hash(data: data)) } - - /// calculate u = H(clientPublicKey | serverPublicKey) - public static func calculateU(clientPublicKey: [UInt8], serverPublicKey: [UInt8], pad: Int) -> BigNum { - BigNum(bytes: [UInt8].init(H.hash(data: SRP.pad(clientPublicKey, to: pad) + SRP.pad(serverPublicKey, to: pad)))) + + //u = H(PAD(A) | PAD(B)) + static func calculate_u(group: Group, A: Data, B: Data) -> BigUInt { + let size = group.N.serialize().count + return BigUInt(H(pad(A, to: size) + pad(B, to: size))) } - - /// Calculate a simpler client verification code H(A | B | S) - static func calculateSimpleClientProof( - clientPublicKey: SRPKey, - serverPublicKey: SRPKey, - sharedSecret: SRPKey) -> [UInt8] - { - let HABK = H.hash(data: clientPublicKey.bytes + serverPublicKey.bytes + sharedSecret.bytes) - return [UInt8](HABK) + + //M1 = H(H(N) XOR H(g) | H(I) | s | A | B | K) + static func calculate_M(group: Group, username: String, salt: Data, A: Data, B: Data, K: Data) -> Data { + let HN_xor_Hg = (H(group.N.serialize()) ^ H(group.g.serialize()))! + let HI = H(username.data(using: .utf8)!) + return H(HN_xor_Hg + HI + salt + A + B + K) } - - /// Calculate a simpler client verification code H(A | M1 | S) - static func calculateSimpleServerVerification( - clientPublicKey: SRPKey, - clientProof: [UInt8], - sharedSecret: SRPKey) -> [UInt8] - { - let HABK = H.hash(data: clientPublicKey.bytes + clientProof + sharedSecret.bytes) - return [UInt8](HABK) + + //HAMK = H(A | M | K) + static func calculate_HAMK(A: Data, M: Data, K: Data) -> Data { + return H(A + M + K) } - /// Calculate client verification code H(H(N)^ H(g)) | H(username) | salt | A | B | H(S)) - static func calculateClientProof( - configuration: SRPConfiguration, - username: String, - salt: [UInt8], - clientPublicKey: SRPKey, - serverPublicKey: SRPKey, - hashSharedSecret: [UInt8]) -> [UInt8] - { - // M = H(H(N)^ H(g)) | H(username) | salt | client key | server key | H(shared secret)) - let N_xor_g = [UInt8](H.hash(data: configuration.N.bytes)) ^ [UInt8](H.hash(data: configuration.g.bytes)) - let hashUser = H.hash(data: [UInt8](username.utf8)) - let M1 = [UInt8](N_xor_g) + hashUser + salt - let M2 = clientPublicKey.bytes + serverPublicKey.bytes + hashSharedSecret - let M = H.hash(data: M1 + M2) - return [UInt8](M) + //k = H(N | PAD(g)) + static func calculate_k(group: Group) -> BigUInt { + let size = group.N.serialize().count + return BigUInt(H(group.N.serialize() + pad(group.g.serialize(), to: size))) } - /// Calculate server verification code H(A | M1 | K) - static func calculateServerVerification(clientPublicKey: SRPKey, clientProof: [UInt8], sharedSecret: [UInt8]) -> [UInt8] { - let HAMK = H.hash(data: clientPublicKey.bytes + clientProof + sharedSecret) - return [UInt8](HAMK) + //x = H(s | H(I | ":" | P)) + static func calculate_x(salt: Data, username: String, password: String) -> BigUInt { + return BigUInt(H(salt + H("\(username):\(password)".data(using: .utf8)!))) } } + +// v = g^x % N +func calculate_v(group: Group, x: BigUInt) -> BigUInt { + return group.g.power(x, modulus: group.N) +} + +func randomBytes(_ count: Int) -> Data { + return Data((0.. Date: Mon, 28 Oct 2024 13:25:17 -0700 Subject: [PATCH 4/7] SRP Login works now - Switch to use https://github.com/adam-fowler/swift-srp with some modifications that are local - Pad g value to equal size of N while calculating clientProof - Use SHA256(plain-text-password) while computing key using PBKDF2 - Added a unit test with some sample values --- Xcodes.xcodeproj/project.pbxproj | 10 +- .../xcshareddata/swiftpm/Package.resolved | 8 +- Xcodes/AppleAPI/Package.swift | 6 +- Xcodes/AppleAPI/Sources/AppleAPI/Client.swift | 65 +++-- XcodesTests/AppStateUpdateTests.swift | 81 ++++++ swift-srp-main/.github/FUNDING.yml | 1 + swift-srp-main/.github/workflows/swift.yml | 39 +++ swift-srp-main/.gitignore | 7 + {xcodes-srp => swift-srp-main}/LICENSE | 0 {xcodes-srp => swift-srp-main}/Package.swift | 4 +- {xcodes-srp => swift-srp-main}/README.md | 0 .../Sources/SRP/Array.swift | 0 swift-srp-main/Sources/SRP/client.swift | 178 +++++++++++++ .../Sources/SRP/configuration.swift | 201 ++++++++++++++ .../Sources/SRP/error.swift | 0 swift-srp-main/Sources/SRP/keys.swift | 40 +++ swift-srp-main/Sources/SRP/server.swift | 110 ++++++++ swift-srp-main/Sources/SRP/srp.swift | 66 +++++ .../Tests/LinuxMain.swift | 0 .../Tests/SRPTests/SRPTests.swift | 0 .../Tests/SRPTests/XCTestManifests.swift | 0 .../contents.xcworkspacedata | 7 - xcodes-srp/Package.resolved | 34 --- xcodes-srp/Sources/SRP/client.swift | 224 ---------------- xcodes-srp/Sources/SRP/group.swift | 248 ------------------ xcodes-srp/Sources/SRP/srp.swift | 125 --------- 26 files changed, 778 insertions(+), 676 deletions(-) create mode 100644 swift-srp-main/.github/FUNDING.yml create mode 100644 swift-srp-main/.github/workflows/swift.yml create mode 100644 swift-srp-main/.gitignore rename {xcodes-srp => swift-srp-main}/LICENSE (100%) rename {xcodes-srp => swift-srp-main}/Package.swift (80%) rename {xcodes-srp => swift-srp-main}/README.md (100%) rename {xcodes-srp => swift-srp-main}/Sources/SRP/Array.swift (100%) create mode 100644 swift-srp-main/Sources/SRP/client.swift create mode 100644 swift-srp-main/Sources/SRP/configuration.swift rename {xcodes-srp => swift-srp-main}/Sources/SRP/error.swift (100%) create mode 100644 swift-srp-main/Sources/SRP/keys.swift create mode 100644 swift-srp-main/Sources/SRP/server.swift create mode 100644 swift-srp-main/Sources/SRP/srp.swift rename {xcodes-srp => swift-srp-main}/Tests/LinuxMain.swift (100%) rename {xcodes-srp => swift-srp-main}/Tests/SRPTests/SRPTests.swift (100%) rename {xcodes-srp => swift-srp-main}/Tests/SRPTests/XCTestManifests.swift (100%) delete mode 100644 xcodes-srp/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata delete mode 100644 xcodes-srp/Package.resolved delete mode 100644 xcodes-srp/Sources/SRP/client.swift delete mode 100644 xcodes-srp/Sources/SRP/group.swift delete mode 100644 xcodes-srp/Sources/SRP/srp.swift diff --git a/Xcodes.xcodeproj/project.pbxproj b/Xcodes.xcodeproj/project.pbxproj index 5e9ee95a..b177caf3 100644 --- a/Xcodes.xcodeproj/project.pbxproj +++ b/Xcodes.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 15F5B8902CCF09B900705E2F /* CryptoKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 15F5B88F2CCF09B900705E2F /* CryptoKit.framework */; }; 33027E342CA8C18800CB387C /* LibFido2Swift in Frameworks */ = {isa = PBXBuildFile; productRef = 334A932B2CA885A400A5E079 /* LibFido2Swift */; }; 3328073F2CA5E2C80036F691 /* SignInSecurityKeyPinView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3328073E2CA5E2C80036F691 /* SignInSecurityKeyPinView.swift */; }; 332807412CA5EA820036F691 /* SignInSecurityKeyTouchView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 332807402CA5EA820036F691 /* SignInSecurityKeyTouchView.swift */; }; @@ -196,6 +197,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 15F5B88F2CCF09B900705E2F /* CryptoKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CryptoKit.framework; path = System/Library/Frameworks/CryptoKit.framework; sourceTree = SDKROOT; }; 3328073E2CA5E2C80036F691 /* SignInSecurityKeyPinView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SignInSecurityKeyPinView.swift; sourceTree = ""; }; 332807402CA5EA820036F691 /* SignInSecurityKeyTouchView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SignInSecurityKeyTouchView.swift; sourceTree = ""; }; 36741BFC291E4FDB00A85AAE /* DownloadPreferencePane.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DownloadPreferencePane.swift; sourceTree = ""; }; @@ -352,6 +354,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 15F5B8902CCF09B900705E2F /* CryptoKit.framework in Frameworks */, 33027E342CA8C18800CB387C /* LibFido2Swift in Frameworks */, CABFA9E42592F08E00380FEE /* Version in Frameworks */, CABFA9FD2592F13300380FEE /* LegibleError in Frameworks */, @@ -416,6 +419,7 @@ CA538A12255A4F7C00E64DD7 /* Frameworks */ = { isa = PBXGroup; children = ( + 15F5B88F2CCF09B900705E2F /* CryptoKit.framework */, ); name = Frameworks; sourceTree = ""; @@ -815,7 +819,7 @@ E84E4F552B335094003F3959 /* XCRemoteSwiftPackageReference "swift-collections" */, E83FDC422CBB649100679C6B /* XCRemoteSwiftPackageReference "Sparkle" */, 33027E282CA8BB5800CB387C /* XCRemoteSwiftPackageReference "LibFido2Swift" */, - E862D4392CC8B26F00BAA376 /* XCLocalSwiftPackageReference "xcodes-srp" */, + 15F5B8912CCF44B700705E2F /* XCLocalSwiftPackageReference "swift-srp-main" */, ); productRefGroup = CAD2E79F2449574E00113D76 /* Products */; projectDirPath = ""; @@ -1485,9 +1489,9 @@ /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ - E862D4392CC8B26F00BAA376 /* XCLocalSwiftPackageReference "xcodes-srp" */ = { + 15F5B8912CCF44B700705E2F /* XCLocalSwiftPackageReference "swift-srp-main" */ = { isa = XCLocalSwiftPackageReference; - relativePath = "xcodes-srp"; + relativePath = "swift-srp-main"; }; /* End XCLocalSwiftPackageReference section */ diff --git a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index e76dc9c8..89a660f9 100644 --- a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -11,12 +11,12 @@ } }, { - "package": "BigInt", - "repositoryURL": "https://github.com/attaswift/BigInt", + "package": "big-num", + "repositoryURL": "https://github.com/adam-fowler/big-num", "state": { "branch": null, - "revision": "793a7fac0bfc318e85994bf6900652e827aef33e", - "version": "5.4.1" + "revision": "5c5511ad06aeb2b97d0868f7394e14a624bfb1c7", + "version": "2.0.2" } }, { diff --git a/Xcodes/AppleAPI/Package.swift b/Xcodes/AppleAPI/Package.swift index 500b9d18..02f3b5ce 100644 --- a/Xcodes/AppleAPI/Package.swift +++ b/Xcodes/AppleAPI/Package.swift @@ -12,13 +12,15 @@ let package = Package( name: "AppleAPI", targets: ["AppleAPI"]), ], - dependencies: [], + dependencies: [ + .package(name: "swift-srp", path: "swift-srp-main") + ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "AppleAPI", - dependencies: []), + dependencies: [.product(name: "SRP", package: "swift-srp")]), .testTarget( name: "AppleAPITests", dependencies: ["AppleAPI"]), diff --git a/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift b/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift index 09f7c084..78c80ee6 100644 --- a/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift +++ b/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift @@ -15,9 +15,10 @@ public class Client { public func srpLogin(accountName: String, password: String) -> AnyPublisher { var serviceKey: String! - let client = SRPClient(username: accountName, password: password) - let a = client.startAuthentication() - + let client = SRPClient(configuration: SRPConfiguration(.N2048)) + let clientKeys = client.generateKeys() + let a = clientKeys.public + return Current.network.dataTask(with: URLRequest.itcServiceKey) .map(\.data) .decode(type: ServiceKeyResponse.self, decoder: JSONDecoder()) @@ -33,7 +34,7 @@ public class Client { } .flatMap { (serviceKey, hashcash) -> AnyPublisher<(String, String, ServerSRPInitResponse), Swift.Error> in - return Current.network.dataTask(with: URLRequest.SRPInit(serviceKey: serviceKey, a: a.base64EncodedString(), accountName: accountName)) + return Current.network.dataTask(with: URLRequest.SRPInit(serviceKey: serviceKey, a: Data(a.bytes).base64EncodedString(), accountName: accountName)) .map(\.data) .decode(type: ServerSRPInitResponse.self, decoder: JSONDecoder()) .map { return (serviceKey, hashcash, $0) } @@ -62,18 +63,16 @@ public class Client { } // let m1 = try client.processChallenge(salt: decodedSalt, publicKey: decodedB, isEncryptedPassword: true, encryptedPassword: encryptedPassword.hexEncodedString()) - let encryptedPasswordString = String(data: encryptedPassword, encoding: .utf8) - let m1 = try client.processChallenge(salt: decodedSalt, publicKey: decodedB, isEncryptedPassword: true, encryptedPassword: encryptedPasswordString) - - guard let m2 = client.HAMK else { - return Fail(error: AuthenticationError.srpInvalidPublicKey) - .eraseToAnyPublisher() - } + let encryptedPasswordString = encryptedPassword.base64EncodedString() + let sharedSecret = try client.calculateSharedSecret(password: encryptedPassword, salt: [UInt8](decodedSalt), clientKeys: clientKeys, serverPublicKey: .init([UInt8](decodedB))) +// let m1 = try client.processChallenge(salt: decodedSalt, publicKey: decodedB, encryptedPassword: encryptedPasswordString) - print("m1: \(m1.base64EncodedString())") - print("m2: \(m2.base64EncodedString())") - - return Current.network.dataTask(with: URLRequest.SRPComplete(serviceKey: serviceKey, hashcash: hashcash, accountName: accountName, c: srpInit.c, m1: m1.base64EncodedString(), m2: m2.base64EncodedString())) + let m1 = client.calculateClientProof(username: accountName, salt: [UInt8](decodedSalt), clientPublicKey: a, serverPublicKey: .init([UInt8](decodedB)), sharedSecret: .init(sharedSecret.bytes)) + let m2 = client.calculateServerProof(clientPublicKey: a, clientProof: m1, sharedSecret: .init([UInt8](sharedSecret.bytes))) + print("m1: \(Data(m1).base64EncodedString())") + print("m2: \(Data(m2).base64EncodedString())") + + return Current.network.dataTask(with: URLRequest.SRPComplete(serviceKey: serviceKey, hashcash: hashcash, accountName: accountName, c: srpInit.c, m1: Data(m1).base64EncodedString(), m2: Data(m2).base64EncodedString())) .mapError { $0 as Swift.Error } .eraseToAnyPublisher() } catch { @@ -382,10 +381,19 @@ public class Client { .mapError { $0 as Error } .eraseToAnyPublisher() } - + + func sha256(data : Data) -> Data { + var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) + data.withUnsafeBytes { + _ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash) + } + return Data(hash) + } + private func pbkdf2(password: String, saltData: Data, keyByteCount: Int, prf: CCPseudoRandomAlgorithm, rounds: Int) -> Data? { guard let passwordData = password.data(using: .utf8) else { return nil } - + let hashedPasswordData = sha256(data: passwordData) + var derivedKeyData = Data(repeating: 0, count: keyByteCount) let derivedCount = derivedKeyData.count let derivationStatus: Int32 = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes in @@ -393,16 +401,19 @@ public class Client { derivedKeyBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) return saltData.withUnsafeBytes { saltBytes -> Int32 in let saltBuffer: UnsafePointer = saltBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) - return CCKeyDerivationPBKDF( - CCPBKDFAlgorithm(kCCPBKDF2), - password, - passwordData.count, - saltBuffer, - saltData.count, - prf, - UInt32(rounds), - keyBuffer, - derivedCount) + return hashedPasswordData.withUnsafeBytes { hashedPasswordBytes -> Int32 in + let passwordBuffer: UnsafePointer = hashedPasswordBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + return CCKeyDerivationPBKDF( + CCPBKDFAlgorithm(kCCPBKDF2), + passwordBuffer, + hashedPasswordData.count, + saltBuffer, + saltData.count, + prf, + UInt32(rounds), + keyBuffer, + derivedCount) + } } } return derivationStatus == kCCSuccess ? derivedKeyData : nil diff --git a/XcodesTests/AppStateUpdateTests.swift b/XcodesTests/AppStateUpdateTests.swift index 39d0d219..b510652a 100644 --- a/XcodesTests/AppStateUpdateTests.swift +++ b/XcodesTests/AppStateUpdateTests.swift @@ -1,7 +1,11 @@ import Path +import CryptoKit import Version @testable import Xcodes import XCTest +import CommonCrypto +import BigNum +import SRP class AppStateUpdateTests: XCTestCase { var subject: AppState! @@ -258,4 +262,81 @@ class AppStateUpdateTests: XCTestCase { XCTAssertEqual(subject.allXcodes.map(\.version), [Version("12.4.0")!, Version("12.3.0-RC")!]) XCTAssertEqual(subject.allXcodes.map(\.identicalBuilds), [[], []]) } + + func sha256(data : Data) -> Data { + var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) + data.withUnsafeBytes { + _ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash) + } + return Data(hash) + } + + func testSIRP() throws { + /* + Obtaind by running fastlane spaceauth --verbose -u anand.appleseed@example.com with some custom logging + + Starting SIRP Apple ID login + a: {"a":"VLEKLa+n2cyeYNWbECm45CuS4kCdCxodlTDGlW1FKaUyOrv/RbtN2sM0pVE12zI7k3VkocPC3rN5DZBIkahR6I8JHj/J97dtTvzsR+aNRWTYCT2HGP1PBI0QArp3eitAbFqTWI4+Zw+oOnV8+AYdH/wjbq7gOK4C4dvIHE+FzRwIlmguPb5qu2r47R9W3y1msVdoUGlFBOMOMb7Gyq7F0MaEIFH63lNzGomwq74mfss/cFqurd6fxU+Y7tdVTPZw1GWyBEPiXWpk8sNm2zE+S6zWo5tOsICprU75IC9galh1igfzN7VNe0SUFLNFTbFK+Bb1SFAOrAbBZOmyOG5uSQ==","accountName":"anand.appleseed@example.com","protocols":["s2k","s2k_fo"]} + Received SIRP signin init response: {"iteration"=>20309, "salt"=>"fIjNflgqSJXACWwwvhDU+w==", "protocol"=>"s2k", "b"=>"PMbU75wwG6rDTySXn2ASWyfQuPoW5ham15SzIscpInwOPE2uk7sePsW4ra0dHcLDUMFQn/LgBggIKOo7YZ9hf1VReiAzXwSKSHdJHjHUURTC2eNpANGUPO1qzuXYgc/MP3MR+GipKHsz+KTLT+8wLjNaiCIHsL/7evJBMw9QqiwhyXlAIm5mGZfhdTVbGpLz2/QzrFmI6pUTrHpio6m1Q74DH3FBxxIeiIcuEdGdeVt9iUweowBRyf2woasTvSV1fbMQbl+lsWPwzt/a73+J30eOGFdSubqSVYh2pV0OLqRz7zPzJars12teCWUV+0WUIaxb14Mp7tlmqcTPuqZe9w==", "c"=>"d-533-eccbc4e9-9564-11ef-84a6-018111c8cc60:PRN"} + encrypted_password: 40532b4de9353fc537dc62ee84eacebd7ecb5ec26efca98bd01b0380e302100f 32 + bb: 7672345903537871991962715758896796468138571329014139041563495295907370682045347022183702983061785424983278857706335295545994877883818377653653442007828499221881058994644619578239367613808278802931379172730746665773282250642455690715139985911303055104847971308813151718669484181874342088801251592138154023949370621963319928723678385968989085032385411532317797659749008135679504901238396934480214258070495365760319076978872181485178648397361564241555189629889320567561713407566532187413091018319494367244540399242523126294027225387432028960726767445027313453858210115810946641002311734776929442587065438110307439763191 + x: 726436461883978586175291668001486484510457416477927591386889224605776454162 + u: 49415306980415573732801389514223606278850554555635359953422678270536095422201 + private 23161374166158551996079451276150657702422963034121842124445818241826569345033578345120284496449280736328513302994568402583647660370960353252836732307301957364261384324957527103960720408713825427474127658415917826326829664923997096839970397226662116904369925262192683131695683487505523842260218490007066160096482662715246662018133837725691586205535995663334471723776536640973591229093933458552240634178864509015968350855952558520147559154646484379002445961375384929682566525908284011230815908584648931495968206840416022306138033496705677078512266958633477047047323620540878121579549170392075029336954975132431417099801 + S: 4f75b6ea99c2d7d121357cce80c75c8e1bf74a65e8f66f75f8f66a481301afb8bebf0e54a3fac4f8bfdd60c77d6e670c87968b341f62175e25eb1d4f496e4e6596e1a387f2840688a35002419b70115b7902a46544cc7b31eb4c909c0acaeb752835d1562a687c431421510ebc7535c007a2bd12a4f7696c8c96a75a491b1eb9189ade2bef23dd5b0bb962b4f03e7fba7f6ba6fe67ba34cc18647daf3e474876f85dac5a15eb51c99d1ed78783579ffd6c8b6911f72564d87dc8f76519c8fc1535b83743ed5f7d6b8461d7154ce2a874cbb45bf63018352b9b997fbafbd6b15eac2a544a801c0152470796f3b69a84a4a653e5186b30efeeb148ff3c32ab8e08 + K: c5207f707186a52f1adee41bf0a7bc41e51e6dffc25cdaeca8acb7de2710b20a + hN: 65908899099613711898698321155848703477601840791750658211391687862255842366922 + hG: 23094592799618609623465742609366149076596436609130823198107630312273622653270 + hxor 73599884097654065452785151481733181870375477364472235597514429707329935690908 + response: {"accountName":"anand.appleseed@example.com","c":"d-533-eccbc4e9-9564-11ef-84a6-018111c8cc60:PRN","m1":"f/Bkq8gBTYxl7SyiRd4SXTyE/jM/g6E0mVyZIQDIsPg=","m2":"R2rgqC9cMAtWiXUImOrvs4oF+ccibf8KaFsZQ22WokM=","rememberMe":false} + */ + + let publicKey = Data(base64Encoded: "VLEKLa+n2cyeYNWbECm45CuS4kCdCxodlTDGlW1FKaUyOrv/RbtN2sM0pVE12zI7k3VkocPC3rN5DZBIkahR6I8JHj/J97dtTvzsR+aNRWTYCT2HGP1PBI0QArp3eitAbFqTWI4+Zw+oOnV8+AYdH/wjbq7gOK4C4dvIHE+FzRwIlmguPb5qu2r47R9W3y1msVdoUGlFBOMOMb7Gyq7F0MaEIFH63lNzGomwq74mfss/cFqurd6fxU+Y7tdVTPZw1GWyBEPiXWpk8sNm2zE+S6zWo5tOsICprU75IC9galh1igfzN7VNe0SUFLNFTbFK+Bb1SFAOrAbBZOmyOG5uSQ==".data(using: .utf8)!) + + let clientKeys = SRPKeyPair(public: .init([UInt8](publicKey!)), + private: .init(BigNum("23161374166158551996079451276150657702422963034121842124445818241826569345033578345120284496449280736328513302994568402583647660370960353252836732307301957364261384324957527103960720408713825427474127658415917826326829664923997096839970397226662116904369925262192683131695683487505523842260218490007066160096482662715246662018133837725691586205535995663334471723776536640973591229093933458552240634178864509015968350855952558520147559154646484379002445961375384929682566525908284011230815908584648931495968206840416022306138033496705677078512266958633477047047323620540878121579549170392075029336954975132431417099801")!)) + + let password = sha256(data: "example".data(using: .utf8)!) + let salt = Data(base64Encoded: "fIjNflgqSJXACWwwvhDU+w==".data(using: .utf8)!)! + let iterations: Int = 20309 + let derivedKeyLength: Int = 32 + var keyArray = Array(repeating: 0, count: derivedKeyLength) + + let result:Int32 = keyArray.withUnsafeMutableBytes { keyBytes -> Int32 in + let keyBuffer = UnsafeMutablePointer(keyBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)) + return password.withUnsafeBytes { passwordDigestBytes -> Int32 in + let passwordBuffer = UnsafePointer(passwordDigestBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)) + return salt.withUnsafeBytes { saltBytes -> Int32 in + let saltBuffer = UnsafePointer(saltBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)) + return CCKeyDerivationPBKDF( + CCPBKDFAlgorithm(kCCPBKDF2), + passwordBuffer, + password.count, + saltBuffer, + salt.count, + CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), + UInt32(iterations), + keyBuffer, + derivedKeyLength) + + } + } + } + + let expectedKey: [UInt8] = [0x40, 0x53, 0x2b, 0x4d, 0xe9, 0x35, 0x3f, 0xc5, 0x37, 0xdc, 0x62, 0xee, 0x84, 0xea, 0xce, 0xbd, 0x7e, 0xcb, 0x5e, 0xc2, 0x6e, 0xfc, 0xa9, 0x8b, 0xd0, 0x1b, 0x03, 0x80, 0xe3, 0x02, 0x10, 0x0f] + + XCTAssertEqual(expectedKey, keyArray) + + let decodedB = Data(base64Encoded: "PMbU75wwG6rDTySXn2ASWyfQuPoW5ham15SzIscpInwOPE2uk7sePsW4ra0dHcLDUMFQn/LgBggIKOo7YZ9hf1VReiAzXwSKSHdJHjHUURTC2eNpANGUPO1qzuXYgc/MP3MR+GipKHsz+KTLT+8wLjNaiCIHsL/7evJBMw9QqiwhyXlAIm5mGZfhdTVbGpLz2/QzrFmI6pUTrHpio6m1Q74DH3FBxxIeiIcuEdGdeVt9iUweowBRyf2woasTvSV1fbMQbl+lsWPwzt/a73+J30eOGFdSubqSVYh2pV0OLqRz7zPzJars12teCWUV+0WUIaxb14Mp7tlmqcTPuqZe9w==".data(using: .utf8)!)! + + let client = SRPClient(configuration: SRPConfiguration(.N2048)) + let sharedSecret = try client.calculateSharedSecret(password: Data(keyArray), salt: [UInt8](salt), clientKeys: clientKeys, serverPublicKey: .init([UInt8](decodedB))) + + let accountName = "anand.appleseed@example.com" + let m1 = client.calculateClientProof(username: accountName, salt: [UInt8](salt), clientPublicKey: clientKeys.public, serverPublicKey: .init([UInt8](decodedB)), sharedSecret: .init(sharedSecret.bytes)) + let m2 = client.calculateServerProof(clientPublicKey: clientKeys.public, clientProof: m1, sharedSecret: .init([UInt8](sharedSecret.bytes))) + + XCTAssertEqual(Data(m1).base64EncodedString(), "f/Bkq8gBTYxl7SyiRd4SXTyE/jM/g6E0mVyZIQDIsPg=") + XCTAssertEqual(Data(m2).base64EncodedString(), "R2rgqC9cMAtWiXUImOrvs4oF+ccibf8KaFsZQ22WokM=") + } } diff --git a/swift-srp-main/.github/FUNDING.yml b/swift-srp-main/.github/FUNDING.yml new file mode 100644 index 00000000..7fc910b7 --- /dev/null +++ b/swift-srp-main/.github/FUNDING.yml @@ -0,0 +1 @@ +github: adam-fowler diff --git a/swift-srp-main/.github/workflows/swift.yml b/swift-srp-main/.github/workflows/swift.yml new file mode 100644 index 00000000..9a734f63 --- /dev/null +++ b/swift-srp-main/.github/workflows/swift.yml @@ -0,0 +1,39 @@ +name: CI + +on: + push: + branches: + - main + pull_request: + branches: + - main + release: + types: [published] + workflow_dispatch: + +jobs: + macOS: + runs-on: macOS-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Build + run: swift build + - name: Run tests + run: swift test + + linux: + runs-on: ubuntu-latest + strategy: + matrix: + image: ['swift:5.9', 'swift:5.10', 'swift:6.0'] + container: + image: ${{ matrix.image }} + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Test + run: swift test --parallel --enable-code-coverage diff --git a/swift-srp-main/.gitignore b/swift-srp-main/.gitignore new file mode 100644 index 00000000..4c741c05 --- /dev/null +++ b/swift-srp-main/.gitignore @@ -0,0 +1,7 @@ +.DS_Store +/.build +/.swiftpm +/Packages +/*.xcodeproj +xcuserdata/ +Package.resolved \ No newline at end of file diff --git a/xcodes-srp/LICENSE b/swift-srp-main/LICENSE similarity index 100% rename from xcodes-srp/LICENSE rename to swift-srp-main/LICENSE diff --git a/xcodes-srp/Package.swift b/swift-srp-main/Package.swift similarity index 80% rename from xcodes-srp/Package.swift rename to swift-srp-main/Package.swift index 890d696c..a4270283 100644 --- a/xcodes-srp/Package.swift +++ b/swift-srp-main/Package.swift @@ -16,10 +16,10 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/apple/swift-crypto", from: "1.0.0"), - .package(url: "https://github.com/attaswift/BigInt.git", from: "5.0.0") + .package(url: "https://github.com/adam-fowler/big-num", from: "2.0.0"), ], targets: [ - .target(name: "SRP", dependencies: ["Crypto", "BigInt"]), + .target(name: "SRP", dependencies: ["BigNum", "Crypto"]), .testTarget( name: "SRPTests", dependencies: ["SRP"]), ] diff --git a/xcodes-srp/README.md b/swift-srp-main/README.md similarity index 100% rename from xcodes-srp/README.md rename to swift-srp-main/README.md diff --git a/xcodes-srp/Sources/SRP/Array.swift b/swift-srp-main/Sources/SRP/Array.swift similarity index 100% rename from xcodes-srp/Sources/SRP/Array.swift rename to swift-srp-main/Sources/SRP/Array.swift diff --git a/swift-srp-main/Sources/SRP/client.swift b/swift-srp-main/Sources/SRP/client.swift new file mode 100644 index 00000000..d4c34b45 --- /dev/null +++ b/swift-srp-main/Sources/SRP/client.swift @@ -0,0 +1,178 @@ +import BigNum +import Crypto +import Foundation + +/// Manages the client side of Secure Remote Password +/// +/// Secure Remote Password (SRP) provides username and password authentication without needing to provide your password to the server. The server +/// has a cryptographic verifier that is derived from the password and a salt that was used to generate this verifier. Both client and server +/// generate a shared secret then the client sends a proof they have the secret and if it is correct the server will do the same to verify the +/// server as well. +/// +/// This version is compliant with SRP version 6a and RFC 5054. +/// +/// Reference reading +/// - https://tools.ietf.org/html/rfc2945 +/// - https://tools.ietf.org/html/rfc5054 +/// +public struct SRPClient { + /// configuration. This needs to be the same as the server configuration + public let configuration: SRPConfiguration + + /// Initialise a SRPClient object + /// - Parameter configuration: configuration to use + public init(configuration: SRPConfiguration) { + self.configuration = configuration + } + + /// Initiate the authentication process + /// - Returns: An authentication state. The A value from this state should be sent to the server + public func generateKeys() -> SRPKeyPair { + var a = BigNum() + var A = BigNum() + repeat { + a = BigNum(bytes: SymmetricKey(size: .bits256)) + A = configuration.g.power(a, modulus: configuration.N) + } while A % configuration.N == BigNum(0) + + return SRPKeyPair(public: SRPKey(A), private: SRPKey(a)) + } + + /// return shared secret given the username, password, B value and salt from the server + /// - Parameters: + /// - username: user identifier + /// - password: password + /// - salt: salt + /// - clientKeys: client public/private keys + /// - serverPublicKey: server public key + /// - Throws: `nullServerKey` + /// - Returns: shared secret + public func calculateSharedSecret(username: String, password: String, salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> SRPKey { + let message = [UInt8]("\(username):\(password)".utf8) + let sharedSecret = try calculateSharedSecret(message: message, salt: salt, clientKeys: clientKeys, serverPublicKey: serverPublicKey) + return SRPKey(sharedSecret) + } + + public func calculateSharedSecret(password: Data, salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> SRPKey { + let message = [UInt8](Data([0x3a]) + password) + let sharedSecret = try calculateSharedSecret(message: message, salt: salt, clientKeys: clientKeys, serverPublicKey: serverPublicKey) + return SRPKey(sharedSecret) + } + + + /// calculate proof of shared secret to send to server + /// - Parameters: + /// - clientPublicKey: client public key + /// - serverPublicKey: server public key + /// - sharedSecret: shared secret + /// - Returns: The client verification code which should be passed to the server + public func calculateSimpleClientProof(clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) -> [UInt8] { + // get verification code + return SRP.calculateSimpleClientProof(clientPublicKey: clientPublicKey, serverPublicKey: serverPublicKey, sharedSecret: sharedSecret) + } + + /// If the server returns that the client verification code was valiid it will also return a server verification code that the client can use to verify the server is correct + /// + /// - Parameters: + /// - code: Verification code returned by server + /// - state: Authentication state + /// - Throws: `requiresVerificationKey`, `invalidServerCode` + public func verifySimpleServerProof(serverProof: [UInt8], clientProof: [UInt8], clientKeys: SRPKeyPair, sharedSecret: SRPKey) throws { + // get out version of server proof + let HAMS = SRP.calculateSimpleServerVerification(clientPublicKey: clientKeys.public, clientProof: clientProof, sharedSecret: sharedSecret) + // is it the same + guard serverProof == HAMS else { throw SRPClientError.invalidServerCode } + } + + /// calculate proof of shared secret to send to server + /// - Parameters: + /// - username: username + /// - salt: The salt value associated with the user returned by the server + /// - clientPublicKey: client public key + /// - serverPublicKey: server public key + /// - sharedSecret: shared secret + /// - Returns: The client verification code which should be passed to the server + public func calculateClientProof(username: String, salt: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) -> [UInt8] { + + let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) + + // get verification code + return SRP.calculateClientProof(configuration: configuration, username: username, salt: salt, clientPublicKey: clientPublicKey, serverPublicKey: serverPublicKey, hashSharedSecret: hashSharedSecret) + } + + /// If the server returns that the client verification code was valid it will also return a server + /// verification code that the client can use to verify the server is correct. This is the calculation + /// to verify it is correct + /// + /// - Parameters: + /// - clientPublicKey: Client public key + /// - clientProof: Client proof + /// - sharedSecret: Shared secret + public func calculateServerProof(clientPublicKey: SRPKey, clientProof: [UInt8], sharedSecret: SRPKey) -> [UInt8] { + let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) + // get out version of server proof + return SRP.calculateServerVerification(clientPublicKey: clientPublicKey, clientProof: clientProof, sharedSecret: hashSharedSecret) + } + + /// If the server returns that the client verification code was valid it will also return a server + /// verification code that the client can use to verify the server is correct + /// + /// - Parameters: + /// - clientProof: Server proof + /// - clientProof: Client proof + /// - clientKeys: Client keys + /// - sharedSecret: Shared secret + /// - Throws: `requiresVerificationKey`, `invalidServerCode` + public func verifyServerProof(serverProof: [UInt8], clientProof: [UInt8], clientKeys: SRPKeyPair, sharedSecret: SRPKey) throws { + // get our version of server proof + let HAMK = calculateServerProof(clientPublicKey: clientKeys.public, clientProof: clientProof, sharedSecret: sharedSecret) + // is it the same + guard serverProof == HAMK else { throw SRPClientError.invalidServerCode } + } + + /// Generate salt and password verifier from username and password. When creating your user instead of + /// passing your password to the server, you pass the salt and password verifier values. In this way the + /// server never knows your password so can never leak it. + /// + /// - Parameters: + /// - username: username + /// - password: user password + /// - Returns: tuple containing salt and password verifier + public func generateSaltAndVerifier(username: String, password: String) -> (salt: [UInt8], verifier: SRPKey) { + let salt = [UInt8].random(count: 16) + let verifier = generatePasswordVerifier(username: username, password: password, salt: salt) + return (salt: salt, verifier: SRPKey(verifier)) + } +} + +extension SRPClient { + /// return shared secret given the username, password, B value and salt from the server + func calculateSharedSecret(message: [UInt8], salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> BigNum { + guard serverPublicKey.number % configuration.N != BigNum(0) else { throw SRPClientError.nullServerKey } + + // calculate u = H(clientPublicKey | serverPublicKey) + let u = SRP.calculateU(clientPublicKey: clientKeys.public.bytes, serverPublicKey: serverPublicKey.bytes, pad: configuration.sizeN) + + guard u != 0 else { throw SRPClientError.nullServerKey } + + let x = BigNum(bytes: [UInt8](H.hash(data: salt + H.hash(data: message)))) + + // calculate S = (B - k*g^x)^(a+u*x) + let S = (serverPublicKey.number - configuration.k * configuration.g.power(x, modulus: configuration.N)).power(clientKeys.private.number + u * x, modulus: configuration.N) + + return S + } + + /// generate password verifier + public func generatePasswordVerifier(username: String, password: String, salt: [UInt8]) -> BigNum { + let message = "\(username):\(password)" + return generatePasswordVerifier(message: [UInt8](message.utf8), salt: salt) + } + + /// generate password verifier + public func generatePasswordVerifier(message: [UInt8], salt: [UInt8]) -> BigNum { + let x = BigNum(bytes: [UInt8](H.hash(data: salt + H.hash(data: message)))) + let verifier = configuration.g.power(x, modulus: configuration.N) + return verifier + } +} diff --git a/swift-srp-main/Sources/SRP/configuration.swift b/swift-srp-main/Sources/SRP/configuration.swift new file mode 100644 index 00000000..a1fe01a6 --- /dev/null +++ b/swift-srp-main/Sources/SRP/configuration.swift @@ -0,0 +1,201 @@ +import BigNum +import Crypto + +/// SRP Configuration. The same configuration hast to be used by both client and server. Contains a large safe prime N ie a prime where the value (N-1)/2 is also a prime, g the multiplicative group generator and the value k = Hash(N | g) +public struct SRPConfiguration { + /// large safe prime + public let N: BigNum + /// multiplicative group generator + public let g: BigNum + /// derived value from N and g. k = H( N | g ) + public let k: BigNum + /// size in bytes of N + public let sizeN: Int + + /// Initialise SRPConfiguration with known safe prime + /// - Parameter prime: enum indicating size of prime + public init(_ prime: Prime) { + self.N = prime.group + self.sizeN = Int(self.N.numBits() + 7) / 8 + self.g = prime.generator + self.k = BigNum(bytes: [UInt8](H.hash(data: self.N.bytes + SRP.pad(self.g.bytes, to: sizeN)))) + } + + /// Initialise SRPConfiguration with your own prime and multiplicative group generator + /// - Parameters: + /// - N: Large prime + /// - g: multiplicative group generator (usually 2) + public init(N: BigNum, g: BigNum) { + self.N = N + self.sizeN = Int(self.N.numBits() + 7) / 8 + self.g = g + self.k = BigNum(bytes: [UInt8](H.hash(data: self.N.bytes + SRP.pad(self.g.bytes, to: sizeN)))) + } + + public enum Prime { + case N1024 + case N1536 + case N2048 + case N3072 + case N4096 + case N6144 + case N8192 + + /// prime numbers and generators taken from RC 5054 https://tools.ietf.org/html/rfc5054 + var group: BigNum { + switch self { + case .N1024: + return BigNum(hex: + "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" + + "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" + + "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" + + "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" + + "FD5138FE8376435B9FC61D2FC0EB06E3")! + + case .N1536: + return BigNum(hex: + "9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA961" + + "4B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F843" + + "80B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0B" + + "E3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF5" + + "6EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734A" + + "F7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E" + + "8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB")! + + case .N2048: + return BigNum(hex: + "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" + + "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" + + "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" + + "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" + + "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" + + "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" + + "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" + + "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" + + "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" + + "9E4AFF73")! + + case .N3072: + return BigNum(hex: + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF")! + + case .N4096: + return BigNum(hex: + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" + + "FFFFFFFFFFFFFFFF")! + + case .N6144: + return BigNum(hex: + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + + "6DCC4024FFFFFFFFFFFFFFFF")! + + case .N8192: + return BigNum(hex: + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + + "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA" + + "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C" + + "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" + + "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886" + + "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6" + + "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5" + + "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268" + + "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6" + + "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + + "60C980DD98EDD3DFFFFFFFFFFFFFFFFF")! + } + } + + var generator: BigNum { + switch self { + case .N1024, .N1536, .N2048: + return BigNum(2) + case .N3072, .N4096, .N6144: + return BigNum(5) + case .N8192: + return BigNum(19) + } + } + } +} diff --git a/xcodes-srp/Sources/SRP/error.swift b/swift-srp-main/Sources/SRP/error.swift similarity index 100% rename from xcodes-srp/Sources/SRP/error.swift rename to swift-srp-main/Sources/SRP/error.swift diff --git a/swift-srp-main/Sources/SRP/keys.swift b/swift-srp-main/Sources/SRP/keys.swift new file mode 100644 index 00000000..c7d08a0b --- /dev/null +++ b/swift-srp-main/Sources/SRP/keys.swift @@ -0,0 +1,40 @@ +import BigNum + +/// Wrapper for keys used by SRP +public struct SRPKey { + public let number: BigNum + public var bytes: [UInt8] { number.bytes } + public var hex: String { number.hex } + + public init(_ bytes: [UInt8]) { + self.number = BigNum(bytes: bytes) + } + + public init(_ number: BigNum) { + self.number = number + } + + public init?(hex: String) { + guard let number = BigNum(hex: hex) else { return nil } + self.number = number + } +} + +extension SRPKey: Equatable { } + +/// Contains a private and a public key +public struct SRPKeyPair { + public let `public`: SRPKey + public let `private`: SRPKey + + + /// Initialise a SRPKeyPair object + /// - Parameters: + /// - public: The public key of the key pair + /// - private: The private key of the key pair + public init(`public`: SRPKey, `private`: SRPKey) { + self.private = `private` + self.public = `public` + } +} + diff --git a/swift-srp-main/Sources/SRP/server.swift b/swift-srp-main/Sources/SRP/server.swift new file mode 100644 index 00000000..1e1931c7 --- /dev/null +++ b/swift-srp-main/Sources/SRP/server.swift @@ -0,0 +1,110 @@ +import BigNum +import Crypto + +/// Manages the server side of Secure Remote Password. +/// +/// Secure Remote Password (SRP) provides username and password authentication without needing to provide your password to the server. The server +/// has a cryptographic verifier that is derived from the password and a salt that was used to generate this verifier. Both client and server +/// generate a shared secret then the client sends a proof they have the secret and if it is correct the server will do the same to verify the +/// server as well. +/// +/// This version is compliant with SRP version 6a and RFC 5054. +/// +/// Reference reading +/// - https://tools.ietf.org/html/rfc2945 +/// - https://tools.ietf.org/html/rfc5054 +/// +public struct SRPServer { + /// Authentication state. Stores A,B and shared secret + public struct AuthenticationState { + let clientPublicKey: SRPKey + let serverPublicKey: SRPKey + var serverPrivateKey: SRPKey + } + + /// configuration has to be the same as the client configuration + public let configuration: SRPConfiguration + + /// Initialise SRPServer + /// - Parameter configuration: configuration to use + public init(configuration: SRPConfiguration) { + self.configuration = configuration + } + + /// generate public and private keys to be used in srp authentication + /// - Parameter verifier: password verifier used to generate key pair + /// - Returns: return public/private key pair + public func generateKeys(verifier: SRPKey) -> SRPKeyPair { + var b: BigNum + var B: BigNum + repeat { + b = BigNum(bytes: SymmetricKey(size: .bits256)) + B = (configuration.k * verifier.number + configuration.g.power(b, modulus: configuration.N)) % configuration.N + } while B % configuration.N == BigNum(0) + + return SRPKeyPair(public: SRPKey(B), private: SRPKey(b)) + } + + /// calculate the shared secret + /// - Parameters: + /// - clientPublicKey: public key received from client + /// - serverKeys: server key pair + /// - verifier: password verifier + /// - Returns: shared secret + public func calculateSharedSecret(clientPublicKey: SRPKey, serverKeys: SRPKeyPair, verifier: SRPKey) throws -> SRPKey { + guard clientPublicKey.number % configuration.N != BigNum(0) else { throw SRPServerError.nullClientKey } + + // calculate u = H(clientPublicKey | serverPublicKey) + let u = SRP.calculateU(clientPublicKey: clientPublicKey.bytes, serverPublicKey: serverKeys.public.bytes, pad: configuration.sizeN) + + // calculate S + let S = ((clientPublicKey.number * verifier.number.power(u, modulus: configuration.N)).power(serverKeys.private.number, modulus: configuration.N)) + + return SRPKey(S) + } + + /// verify proof that client has shared secret and return a server verification proof. If verification fails a `invalidClientCode` error is thrown + /// + /// - Parameters: + /// - proof: Client proof + /// - clientPublicKey: Client public key + /// - serverPublicKey: Server public key + /// - sharedSecret: Shared secret + /// - Throws: invalidClientCode + /// - Returns: The server verification code + public func verifySimpleClientProof(proof: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) throws -> [UInt8] { + let clientProof = SRP.calculateSimpleClientProof( + clientPublicKey: clientPublicKey, + serverPublicKey: serverPublicKey, + sharedSecret: sharedSecret + ) + guard clientProof == proof else { throw SRPServerError.invalidClientProof } + return SRP.calculateSimpleServerVerification(clientPublicKey: clientPublicKey, clientProof: clientProof, sharedSecret: sharedSecret) + } + + /// verify proof that client has shared secret and return a server verification proof. If verification fails a `invalidClientCode` error is thrown + /// + /// - Parameters: + /// - code: verification code sent by user + /// - username: username + /// - salt: salt stored with user + /// - clientPublicKey: Client public key + /// - serverPublicKey: Server public key + /// - sharedSecret: Shared secret + /// - Throws: invalidClientCode + /// - Returns: The server verification code + public func verifyClientProof(proof: [UInt8], username: String, salt: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) throws -> [UInt8] { + let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) + + let clientProof = SRP.calculateClientProof( + configuration: configuration, + username: username, + salt: salt, + clientPublicKey: clientPublicKey, + serverPublicKey: serverPublicKey, + hashSharedSecret: hashSharedSecret + ) + guard clientProof == proof else { throw SRPServerError.invalidClientProof } + return SRP.calculateServerVerification(clientPublicKey: clientPublicKey, clientProof: clientProof, sharedSecret: hashSharedSecret) + } +} diff --git a/swift-srp-main/Sources/SRP/srp.swift b/swift-srp-main/Sources/SRP/srp.swift new file mode 100644 index 00000000..6e192c30 --- /dev/null +++ b/swift-srp-main/Sources/SRP/srp.swift @@ -0,0 +1,66 @@ +import BigNum +import Crypto + +/// Contains common code used by both client and server SRP code +public struct SRP { + + /// pad to a certain size by prefixing with zeros + static func pad(_ data: [UInt8], to size: Int) -> [UInt8] { + let padSize = size - data.count + guard padSize > 0 else { return data } + // create prefix and return prefix + data + let prefix: [UInt8] = (1...padSize).reduce([]) { result,_ in return result + [0] } + return prefix + data + } + + /// calculate u = H(clientPublicKey | serverPublicKey) + public static func calculateU(clientPublicKey: [UInt8], serverPublicKey: [UInt8], pad: Int) -> BigNum { + BigNum(bytes: [UInt8].init(H.hash(data: SRP.pad(clientPublicKey, to: pad) + SRP.pad(serverPublicKey, to: pad)))) + } + + /// Calculate a simpler client verification code H(A | B | S) + static func calculateSimpleClientProof( + clientPublicKey: SRPKey, + serverPublicKey: SRPKey, + sharedSecret: SRPKey) -> [UInt8] + { + let HABK = H.hash(data: clientPublicKey.bytes + serverPublicKey.bytes + sharedSecret.bytes) + return [UInt8](HABK) + } + + /// Calculate a simpler client verification code H(A | M1 | S) + static func calculateSimpleServerVerification( + clientPublicKey: SRPKey, + clientProof: [UInt8], + sharedSecret: SRPKey) -> [UInt8] + { + let HABK = H.hash(data: clientPublicKey.bytes + clientProof + sharedSecret.bytes) + return [UInt8](HABK) + } + + /// Calculate client verification code H(H(N)^ H(g)) | H(username) | salt | A | B | H(S)) + static func calculateClientProof( + configuration: SRPConfiguration, + username: String, + salt: [UInt8], + clientPublicKey: SRPKey, + serverPublicKey: SRPKey, + hashSharedSecret: [UInt8]) -> [UInt8] + { + // M = H(H(N)^ H(g)) | H(username) | salt | client key | server key | H(shared secret)) + let hashN = BigNum(bytes: H.hash(data: configuration.N.bytes)) + let hashG = BigNum(bytes: H.hash(data: SRP.pad(configuration.g.bytes, to: configuration.sizeN))) + let N_xor_g = hashN.bytes ^ hashG.bytes + let hashUser = H.hash(data: [UInt8](username.utf8)) + let M1 = [UInt8](N_xor_g) + hashUser + salt + let M2 = clientPublicKey.bytes + serverPublicKey.bytes + hashSharedSecret + let M = H.hash(data: M1 + M2) + return [UInt8](M) + } + + /// Calculate server verification code H(A | M1 | K) + static func calculateServerVerification(clientPublicKey: SRPKey, clientProof: [UInt8], sharedSecret: [UInt8]) -> [UInt8] { + let HAMK = H.hash(data: clientPublicKey.bytes + clientProof + sharedSecret) + return [UInt8](HAMK) + } +} diff --git a/xcodes-srp/Tests/LinuxMain.swift b/swift-srp-main/Tests/LinuxMain.swift similarity index 100% rename from xcodes-srp/Tests/LinuxMain.swift rename to swift-srp-main/Tests/LinuxMain.swift diff --git a/xcodes-srp/Tests/SRPTests/SRPTests.swift b/swift-srp-main/Tests/SRPTests/SRPTests.swift similarity index 100% rename from xcodes-srp/Tests/SRPTests/SRPTests.swift rename to swift-srp-main/Tests/SRPTests/SRPTests.swift diff --git a/xcodes-srp/Tests/SRPTests/XCTestManifests.swift b/swift-srp-main/Tests/SRPTests/XCTestManifests.swift similarity index 100% rename from xcodes-srp/Tests/SRPTests/XCTestManifests.swift rename to swift-srp-main/Tests/SRPTests/XCTestManifests.swift diff --git a/xcodes-srp/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/xcodes-srp/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 919434a6..00000000 --- a/xcodes-srp/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/xcodes-srp/Package.resolved b/xcodes-srp/Package.resolved deleted file mode 100644 index 8c65785c..00000000 --- a/xcodes-srp/Package.resolved +++ /dev/null @@ -1,34 +0,0 @@ -{ - "object": { - "pins": [ - { - "package": "big-num", - "repositoryURL": "https://github.com/adam-fowler/big-num", - "state": { - "branch": null, - "revision": "5c5511ad06aeb2b97d0868f7394e14a624bfb1c7", - "version": "2.0.2" - } - }, - { - "package": "BigInt", - "repositoryURL": "https://github.com/attaswift/BigInt.git", - "state": { - "branch": null, - "revision": "793a7fac0bfc318e85994bf6900652e827aef33e", - "version": "5.4.1" - } - }, - { - "package": "swift-crypto", - "repositoryURL": "https://github.com/apple/swift-crypto", - "state": { - "branch": null, - "revision": "ddb07e896a2a8af79512543b1c7eb9797f8898a5", - "version": "1.1.7" - } - } - ] - }, - "version": 1 -} diff --git a/xcodes-srp/Sources/SRP/client.swift b/xcodes-srp/Sources/SRP/client.swift deleted file mode 100644 index 38702526..00000000 --- a/xcodes-srp/Sources/SRP/client.swift +++ /dev/null @@ -1,224 +0,0 @@ - -import Foundation -import BigInt -import Crypto - -/// SRP Client; the party that initializes the authentication and -/// must proof possession of the correct password. -public class SRPClient { - let a: BigUInt - let A: BigUInt - - let group: Group - typealias impl = Implementation // swiftlint:disable:this type_name - - let username: String - var password: String? - var precomputedX: BigUInt? - - public var HAMK: Data? - var K: Data? - - /// Whether the session is authenticated, i.e. the password - /// was verified by the server and proof of a valid session - /// key was provided by the server. If `true`, `sessionKey` - /// is also available. - public private(set) var isAuthenticated = false - - private init( - username: String, - group: Group = .N2048, - privateKey: Data? = nil) - { - self.username = username - self.group = group - if let privateKey = privateKey { - a = BigUInt(privateKey) - } else { - a = BigUInt(Curve25519.KeyAgreement.PrivateKey().rawRepresentation) - } - // A = g^a % N - A = group.g.power(a, modulus: group.N) - } - - /// Initialize the Client SRP party with a password. - /// - /// - Parameters: - /// - username: user's username. - /// - password: user's password. - /// - group: which `Group` to use, must be the same for the - /// server as well as the pre-stored verificationKey. - /// - privateKey: (optional) custom private key (a); if providing - /// the private key of the `Client`, make sure to provide a - /// good random key of at least 32 bytes. Default is to - /// generate a private key of 128 bytes. You MUST not re-use - /// the private key between sessions. - public convenience init( - username: String, - password: String, - group: Group = .N2048, - privateKey: Data? = nil) - { - self.init(username: username, group: group, privateKey: privateKey) - self.password = password - } - - /// Initialize the Client SRP party with a precomputed x. - /// - /// - Parameters: - /// - username: user's username. - /// - precomputedX: precomputed SRP x. - /// - group: which `Group` to use, must be the same for the - /// server as well as the pre-stored verificationKey. - /// - privateKey: (optional) custom private key (a); if providing - /// the private key of the `Client`, make sure to provide a - /// good random key of at least 32 bytes. Default is to - /// generate a private key of 128 bytes. You MUST not re-use - /// the private key between sessions. - public convenience init( - username: String, - precomputedX: Data, - group: Group = .N2048, - privateKey: Data? = nil) - { - self.init(username: username, group: group, privateKey: privateKey) - self.precomputedX = BigUInt(precomputedX) - } - - /// Starts authentication. This method is a no-op. - /// - /// - Returns: `publicKey` (A) - public func startAuthentication() -> Data { - return publicKey - } - - /// Process the challenge provided by the server. This sets the `sessionKey` - /// and generates proof that it generated the correct key from the password - /// and the challenge. After the server has also proven the validity of their - /// key, the `sessionKey` can be used. - /// - /// - Parameters: - /// - salt: user-specific salt (s) - /// - publicKey: server's public key (B) - /// - Returns: key proof (M) - /// - Throws: `AuthenticationFailure.invalidPublicKey` if the server's - /// public key is invalid (i.e. B % N is zero). - public func processChallenge(salt: Data, publicKey serverPublicKey: Data, isEncryptedPassword: Bool, encryptedPassword: String? = nil) throws -> Data { - let H = impl.H - let N = group.N - - let B = BigUInt(serverPublicKey) - - guard B % N != 0 else { - throw AuthenticationFailure.invalidPublicKey - } - - let u = impl.calculate_u(group: group, A: publicKey, B: serverPublicKey) - let k = impl.calculate_k(group: group) - - let x = self.precomputedX ?? (isEncryptedPassword ? impl.calculate_x(salt: salt, username: "", password: encryptedPassword!) : impl.calculate_x(salt: salt, username: username, password: password!)) - let v = calculate_v(group: group, x: x) - - // shared secret - // S = (B - kg^x) ^ (a + ux) - // Note that v = g^x, and that B - kg^x might become negative, which - // cannot be stored in BigUInt. So we'll add N to B_ and make sure kv - // isn't greater than N. - let S = (B + N - k * v % N).power(a + u * x, modulus: N) - - // session key - K = H(S.serialize()) - - // client verification - let M = impl.calculate_M(group: group, username: username, salt: salt, A: publicKey, B: serverPublicKey, K: K!) - - // server verification - HAMK = impl.calculate_HAMK(A: publicKey, M: M, K: K!) - return M - } - - /// After the server has verified that the password is correct, - /// it will send proof of the derived session key. This is verified - /// on our end and finalizes the authentication session. After this - /// step, the `sessionKey` is available. - /// - /// - Parameter HAMK: proof of the server that it derived the same - /// session key. - /// - Throws: - /// - `AuthenticationFailure.missingChallenge` if this method - /// is called before calling `processChallenge`. - /// - `AuthenticationFailure.keyProofMismatch` if the proof - /// doesn't match our own. - public func verifySession(keyProof serverKeyProof: Data) throws { - guard let HAMK = HAMK else { - throw AuthenticationFailure.missingChallenge - } - guard HAMK == serverKeyProof else { - throw AuthenticationFailure.keyProofMismatch - } - isAuthenticated = true - } - - /// The client's public key (A). For every authentication - /// session a new public key is generated. - public var publicKey: Data { - return A.serialize() - } - - /// The client's private key (a). For every authentication - /// session a new random private key is generated. - public var privateKey: Data { - return a.serialize() - } - - /// The session key (K) that is exchanged during authentication. - /// This key can be used to encrypt further communication - /// between client and server. - public var sessionKey: Data? { - guard isAuthenticated else { - return nil - } - return K - } -} - -/// Possible authentication failure modes. -public enum AuthenticationFailure: Error { - /// Security breach: the provided public key is empty (i.e. PK % N is zero). - case invalidPublicKey - - /// Invalid client state: call `processChallenge` before `verifySession`. - case missingChallenge - - /// Failed authentication: the key proof didn't match our own. - case keyProofMismatch -} - -extension AuthenticationFailure: CustomStringConvertible { - /// A textual representation of this instance. - /// - /// Instead of accessing this property directly, convert an instance of any - /// type to a string by using the `String(describing:)` initializer. - public var description: String { - switch self { - case .invalidPublicKey: return "security breach - the provided public key is invalid" - case .missingChallenge: return "invalid client state - call `processChallenge` before `verifySession`" - case .keyProofMismatch: return "failed authentication - the key proof didn't match our own" - } - } -} -func ^ (lhs: Data, rhs: Data) -> Data? { - guard lhs.count == rhs.count else { return nil } - var result = Data(count: lhs.count) - for index in lhs.indices { - result[index] = lhs[index] ^ rhs[index] - } - return result -} - -// Removed in Xcode 8 beta 3 -func + (lhs: Data, rhs: Data) -> Data { - var result = lhs - result.append(rhs) - return result -} diff --git a/xcodes-srp/Sources/SRP/group.swift b/xcodes-srp/Sources/SRP/group.swift deleted file mode 100644 index 9712acb2..00000000 --- a/xcodes-srp/Sources/SRP/group.swift +++ /dev/null @@ -1,248 +0,0 @@ -// -// must.swift -// swift-srp -// -// Created by Matt Kiazyk on 2024-10-24. -// - - -import BigInt - -/// SRP Group Parameters -/// -/// The 1024-, 1536-, and 2048-bit groups are taken from software -/// developed by Tom Wu and Eugene Jhong for the Stanford SRP -/// distribution, and subsequently proven to be prime. The larger primes -/// are taken from [MODP], but generators have been calculated that are -/// primitive roots of N, unlike the generators in [MODP]. -/// -/// The values of N and g used in this protocol must be agreed upon by -/// the two parties in question. They can be set in advance, or the host -/// can supply them to the client. In the latter case, the host should -/// send the parameters in the first message along with the salt. For -/// maximum security, N should be a safe prime (i.e. a number of the form -/// N = 2q + 1, where q is also prime). Also, g should be a generator -/// modulo N (see [SRP] for details), which means that for any X where 0 -/// < X < N, there exists a value x for which g^x % N == X. -/// -/// [MODP] Kivinen, T. and M. Kojo, "More Modular Exponentiation -/// (MODP) Diffie-Hellman groups for Internet Key Exchange -/// (IKE)", RFC 3526, May 2003. -/// -/// [SRP] T. Wu, "The Secure Remote Password Protocol", In -/// Proceedings of the 1998 Internet Society Symposium on -/// Network and Distributed Systems Security, San Diego, CA, -/// pp. 97-111. -public enum Group { - /// 1024-bits group - case N1024 - - /// 2048-bits group - case N2048 - - /// 1536-bits group - case N1536 - - /// 3072-bits group - case N3072 - - /// 4096-bits group - case N4096 - - /// 6144-bits group - case N6144 - - /// 8192-bits group - case N8192 - - /// Custom group parameters. See `init(prime:generator:)` for more information. - public struct CustomGroup { - let N: BigUInt - let g: BigUInt - } - - /// Custom group parameters. See `init(prime:generator:)` for more information. - case custom(CustomGroup) - - /// Create custom group parameters. See the enum's documentation for - /// considerations on good parameters. - /// - Parameters: - /// - prime: hex-encoded prime - /// - generator: hex-encoded generator - /// - Returns: nil if one of the parameters chould not be decoded - public init?(prime: String, generator: String) { - guard let N = BigUInt(prime, radix: 16), let g = BigUInt(generator, radix: 16) else { - return nil - } - self = .custom(CustomGroup(N: N, g: g)) - } - - var N: BigUInt { - switch self { - case .N1024: - return BigUInt( - "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" + - "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" + - "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" + - "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" + - "FD5138FE8376435B9FC61D2FC0EB06E3", - radix: 16)! - case .N1536: - return BigUInt( - "9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA961" + - "4B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F843" + - "80B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0B" + - "E3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF5" + - "6EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734A" + - "F7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E" + - "8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB", - radix: 16)! - case .N2048: - return BigUInt( - "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" + - "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" + - "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" + - "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" + - "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" + - "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" + - "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" + - "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" + - "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" + - "9E4AFF73", - radix: 16)! - case .N3072: - return BigUInt( - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF", - radix: 16)! - case .N4096: - return BigUInt( - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" + - "FFFFFFFFFFFFFFFF", - radix: 16)! - case .N6144: - return BigUInt( - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + - "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + - "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + - "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + - "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + - "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + - "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + - "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + - "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + - "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + - "6DCC4024FFFFFFFFFFFFFFFF", - radix: 16)! - case .N8192: - return BigUInt( - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + - "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + - "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + - "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + - "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + - "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + - "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + - "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + - "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + - "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + - "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA" + - "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C" + - "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" + - "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886" + - "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6" + - "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5" + - "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268" + - "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6" + - "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + - "60C980DD98EDD3DFFFFFFFFFFFFFFFFF", - radix: 16)! - case .custom(let custom): - return custom.N - } - } - - var g: BigUInt { - switch self { - case .N1024: - return BigUInt(2) - case .N1536: - return BigUInt(2) - case .N2048: - return BigUInt(2) - case .N3072: - return BigUInt(5) - case .N4096: - return BigUInt(5) - case .N6144: - return BigUInt(5) - case .N8192: - return BigUInt(19) - case .custom(let custom): - return custom.g - } - } -} \ No newline at end of file diff --git a/xcodes-srp/Sources/SRP/srp.swift b/xcodes-srp/Sources/SRP/srp.swift deleted file mode 100644 index 9ffdf5d5..00000000 --- a/xcodes-srp/Sources/SRP/srp.swift +++ /dev/null @@ -1,125 +0,0 @@ -// -// Implementation.swift -// swift-srp -// -// Created by Matt Kiazyk on 2024-10-24. -// - - -import Foundation -import BigInt -import Crypto - -/// Creates the salted verification key based on a user's username and -/// password. Only the salt and verification key need to be stored on the -/// server, there's no need to keep the plain-text password. -/// -/// Keep the verification key private, as it can be used to brute-force -/// the password from. -/// -/// - Parameters: -/// - using: hash function to use -/// - username: user's username -/// - password: user's password -/// - salt: (optional) custom salt value; if providing a salt, make sure to -/// provide a good random salt of at least 16 bytes. Default is to -/// generate a salt of 16 bytes. -/// - group: `Group` parameters; default is 2048-bits group. -/// - algorithm: which `Digest.Algorithm` to use; default is SHA1. -/// - Returns: salt (s) and verification key (v) -public func createSaltedVerificationKey( - using hashFunction: H.Type, - group: Group = .N2048, - username: String, - password: String, - salt: Data? = nil) - -> (salt: Data, verificationKey: Data) -{ - let salt = salt ?? randomBytes(16) - let x = Implementation.calculate_x(salt: salt, username: username, password: password) - return createSaltedVerificationKey(from: x, salt: salt, group: group) -} - -/// Creates the salted verification key based on a precomputed SRP x value. -/// Only the salt and verification key need to be stored on the -/// server, there's no need to keep the plain-text password. -/// -/// Keep the verification key private, as it can be used to brute-force -/// the password from. -/// -/// - Parameters: -/// - x: precomputed SRP x -/// - salt: (optional) custom salt value; if providing a salt, make sure to -/// provide a good random salt of at least 16 bytes. Default is to -/// generate a salt of 16 bytes. -/// - group: `Group` parameters; default is 2048-bits group. -/// - Returns: salt (s) and verification key (v) -public func createSaltedVerificationKey( - from x: Data, - salt: Data? = nil, - group: Group = .N2048) - -> (salt: Data, verificationKey: Data) -{ - return createSaltedVerificationKey(from: BigUInt(x), salt: salt, group: group) -} - -func createSaltedVerificationKey( - from x: BigUInt, - salt: Data? = nil, - group: Group = .N2048) - -> (salt: Data, verificationKey: Data) -{ - let salt = salt ?? randomBytes(16) - let v = calculate_v(group: group, x: x) - return (salt, v.serialize()) -} - -func pad(_ data: Data, to size: Int) -> Data { - precondition(size >= data.count, "Negative padding not possible") - return Data(count: size - data.count) + data -} - -enum Implementation { - // swiftlint:disable:next identifier_name - static func H(_ data: Data) -> Data { - return Data(HF.hash(data: data)) - } - - //u = H(PAD(A) | PAD(B)) - static func calculate_u(group: Group, A: Data, B: Data) -> BigUInt { - let size = group.N.serialize().count - return BigUInt(H(pad(A, to: size) + pad(B, to: size))) - } - - //M1 = H(H(N) XOR H(g) | H(I) | s | A | B | K) - static func calculate_M(group: Group, username: String, salt: Data, A: Data, B: Data, K: Data) -> Data { - let HN_xor_Hg = (H(group.N.serialize()) ^ H(group.g.serialize()))! - let HI = H(username.data(using: .utf8)!) - return H(HN_xor_Hg + HI + salt + A + B + K) - } - - //HAMK = H(A | M | K) - static func calculate_HAMK(A: Data, M: Data, K: Data) -> Data { - return H(A + M + K) - } - - //k = H(N | PAD(g)) - static func calculate_k(group: Group) -> BigUInt { - let size = group.N.serialize().count - return BigUInt(H(group.N.serialize() + pad(group.g.serialize(), to: size))) - } - - //x = H(s | H(I | ":" | P)) - static func calculate_x(salt: Data, username: String, password: String) -> BigUInt { - return BigUInt(H(salt + H("\(username):\(password)".data(using: .utf8)!))) - } -} - -// v = g^x % N -func calculate_v(group: Group, x: BigUInt) -> BigUInt { - return group.g.power(x, modulus: group.N) -} - -func randomBytes(_ count: Int) -> Data { - return Data((0.. Date: Mon, 28 Oct 2024 16:52:25 -0700 Subject: [PATCH 5/7] Use swift-srp from remote source - Use from https://github.com/abiligiri/swift-srp, version 1.1.0 This is based on latest from upstream with changes required - Remove local copy of swift-srp --- Xcodes.xcodeproj/project.pbxproj | 10 +- .../xcshareddata/swiftpm/Package.resolved | 9 + Xcodes/AppleAPI/Package.swift | 2 +- swift-srp-main/.github/FUNDING.yml | 1 - swift-srp-main/.github/workflows/swift.yml | 39 ---- swift-srp-main/.gitignore | 7 - swift-srp-main/LICENSE | 201 ----------------- swift-srp-main/Package.swift | 26 --- swift-srp-main/README.md | 94 -------- swift-srp-main/Sources/SRP/Array.swift | 29 --- swift-srp-main/Sources/SRP/client.swift | 178 --------------- .../Sources/SRP/configuration.swift | 201 ----------------- swift-srp-main/Sources/SRP/error.swift | 21 -- swift-srp-main/Sources/SRP/keys.swift | 40 ---- swift-srp-main/Sources/SRP/server.swift | 110 ---------- swift-srp-main/Sources/SRP/srp.swift | 66 ------ swift-srp-main/Tests/LinuxMain.swift | 6 - swift-srp-main/Tests/SRPTests/SRPTests.swift | 207 ------------------ .../Tests/SRPTests/XCTestManifests.swift | 9 - 19 files changed, 11 insertions(+), 1245 deletions(-) delete mode 100644 swift-srp-main/.github/FUNDING.yml delete mode 100644 swift-srp-main/.github/workflows/swift.yml delete mode 100644 swift-srp-main/.gitignore delete mode 100644 swift-srp-main/LICENSE delete mode 100644 swift-srp-main/Package.swift delete mode 100644 swift-srp-main/README.md delete mode 100644 swift-srp-main/Sources/SRP/Array.swift delete mode 100644 swift-srp-main/Sources/SRP/client.swift delete mode 100644 swift-srp-main/Sources/SRP/configuration.swift delete mode 100644 swift-srp-main/Sources/SRP/error.swift delete mode 100644 swift-srp-main/Sources/SRP/keys.swift delete mode 100644 swift-srp-main/Sources/SRP/server.swift delete mode 100644 swift-srp-main/Sources/SRP/srp.swift delete mode 100644 swift-srp-main/Tests/LinuxMain.swift delete mode 100644 swift-srp-main/Tests/SRPTests/SRPTests.swift delete mode 100644 swift-srp-main/Tests/SRPTests/XCTestManifests.swift diff --git a/Xcodes.xcodeproj/project.pbxproj b/Xcodes.xcodeproj/project.pbxproj index b177caf3..9dfe09d5 100644 --- a/Xcodes.xcodeproj/project.pbxproj +++ b/Xcodes.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 60; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -819,7 +819,6 @@ E84E4F552B335094003F3959 /* XCRemoteSwiftPackageReference "swift-collections" */, E83FDC422CBB649100679C6B /* XCRemoteSwiftPackageReference "Sparkle" */, 33027E282CA8BB5800CB387C /* XCRemoteSwiftPackageReference "LibFido2Swift" */, - 15F5B8912CCF44B700705E2F /* XCLocalSwiftPackageReference "swift-srp-main" */, ); productRefGroup = CAD2E79F2449574E00113D76 /* Products */; projectDirPath = ""; @@ -1488,13 +1487,6 @@ }; /* End XCConfigurationList section */ -/* Begin XCLocalSwiftPackageReference section */ - 15F5B8912CCF44B700705E2F /* XCLocalSwiftPackageReference "swift-srp-main" */ = { - isa = XCLocalSwiftPackageReference; - relativePath = "swift-srp-main"; - }; -/* End XCLocalSwiftPackageReference section */ - /* Begin XCRemoteSwiftPackageReference section */ 33027E282CA8BB5800CB387C /* XCRemoteSwiftPackageReference "LibFido2Swift" */ = { isa = XCRemoteSwiftPackageReference; diff --git a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 89a660f9..19fa71ed 100644 --- a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -118,6 +118,15 @@ "version": "1.1.7" } }, + { + "package": "swift-srp", + "repositoryURL": "https://github.com/abiligiri/swift-srp", + "state": { + "branch": null, + "revision": "ca452b0b557021ca8af305bbce504bcd13d32b15", + "version": "1.1.0" + } + }, { "package": "SwiftSoup", "repositoryURL": "https://github.com/scinfu/SwiftSoup", diff --git a/Xcodes/AppleAPI/Package.swift b/Xcodes/AppleAPI/Package.swift index 02f3b5ce..2b572ff0 100644 --- a/Xcodes/AppleAPI/Package.swift +++ b/Xcodes/AppleAPI/Package.swift @@ -13,7 +13,7 @@ let package = Package( targets: ["AppleAPI"]), ], dependencies: [ - .package(name: "swift-srp", path: "swift-srp-main") + .package(url: "https://github.com/abiligiri/swift-srp", from: "1.1.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/swift-srp-main/.github/FUNDING.yml b/swift-srp-main/.github/FUNDING.yml deleted file mode 100644 index 7fc910b7..00000000 --- a/swift-srp-main/.github/FUNDING.yml +++ /dev/null @@ -1 +0,0 @@ -github: adam-fowler diff --git a/swift-srp-main/.github/workflows/swift.yml b/swift-srp-main/.github/workflows/swift.yml deleted file mode 100644 index 9a734f63..00000000 --- a/swift-srp-main/.github/workflows/swift.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: CI - -on: - push: - branches: - - main - pull_request: - branches: - - main - release: - types: [published] - workflow_dispatch: - -jobs: - macOS: - runs-on: macOS-latest - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 1 - - name: Build - run: swift build - - name: Run tests - run: swift test - - linux: - runs-on: ubuntu-latest - strategy: - matrix: - image: ['swift:5.9', 'swift:5.10', 'swift:6.0'] - container: - image: ${{ matrix.image }} - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 1 - - name: Test - run: swift test --parallel --enable-code-coverage diff --git a/swift-srp-main/.gitignore b/swift-srp-main/.gitignore deleted file mode 100644 index 4c741c05..00000000 --- a/swift-srp-main/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -.DS_Store -/.build -/.swiftpm -/Packages -/*.xcodeproj -xcuserdata/ -Package.resolved \ No newline at end of file diff --git a/swift-srp-main/LICENSE b/swift-srp-main/LICENSE deleted file mode 100644 index 261eeb9e..00000000 --- a/swift-srp-main/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/swift-srp-main/Package.swift b/swift-srp-main/Package.swift deleted file mode 100644 index a4270283..00000000 --- a/swift-srp-main/Package.swift +++ /dev/null @@ -1,26 +0,0 @@ -// swift-tools-version:5.1 -// The swift-tools-version declares the minimum version of Swift required to build this package. - -import PackageDescription - -let package = Package( - name: "swift-srp", - platforms: [ - .macOS(.v10_15), - .iOS(.v13), - .watchOS(.v6), - .tvOS(.v13), - ], - products: [ - .library(name: "SRP", targets: ["SRP"]), - ], - dependencies: [ - .package(url: "https://github.com/apple/swift-crypto", from: "1.0.0"), - .package(url: "https://github.com/adam-fowler/big-num", from: "2.0.0"), - ], - targets: [ - .target(name: "SRP", dependencies: ["BigNum", "Crypto"]), - .testTarget( - name: "SRPTests", dependencies: ["SRP"]), - ] -) diff --git a/swift-srp-main/README.md b/swift-srp-main/README.md deleted file mode 100644 index f19c2314..00000000 --- a/swift-srp-main/README.md +++ /dev/null @@ -1,94 +0,0 @@ -# Swift SRP - -This library provides a swift implementation of the Secure Remote Password protocol. Secure Remote Password (SRP) provides username and password authentication without needing to provide your password to the server. As the server never sees your password it can never leak it to anyone else. - -The server is provided with a cryptographic verifier that is derived from the password and a salt value that was used in the generation of this verifier. Both client and server generate large private and public keys and with these are able to generate a shared secret. The client then sends a proof they have the secret and if it is verified the server will do the same to verify the server as well. - -The SRP protocol is detailed in [RFC2945](https://tools.ietf.org/html/rfc2945). This library implements version 6a of the protocol which includes the username in the salt to avoid the issue where a malicious server attempting to learn if two users have the same password. I believe it is also compliant with [RFC5054](https://tools.ietf.org/html/rfc5054). - -# Usage - -First you create a configuration object. This will hold the hashing algorithm you are using, the large safe prime number required and a generator value. There is an enum that holds example primes and generators. It is general safer to use these as they are the ones provided in RFC5054 and have been battle tested. The following generates a configuration using SHA256 and a 2048 bit safe prime. You need to be sure both client and server use the same configuration. -```swift -let configuration = SRPConfiguration(.N2048) -``` -When the client wants to create a new user they generate a salt and password verifier for their username and password. -```swift -let client = SRPClient(configuration: configuration) -let (salt, verifier) = client.generateSaltAndVerifier(username: username, password: password) -``` -These are passed to the server who will store them alongside the username in a database. - -When the client wants to authenticate with the server they first need to generate a public/private key pair. These keys should only be used once. If you want to authenticate again you should generate a new pair. -```swift -let client = SRPClient(configuration: configuration) -let clientKeys = client.generateKeys() -let clientPublicKey = clientKeys.public -``` -The contents of the `clientPublicKey` variable is passed to the server alongside the username to initiate authentication. - -The server will then find the username in its database and extract the password verifier and salt that was stored with it. The password verifier is used to generate the servers key pair. -```swift -let server = SRPServer(configuration: configuration) -let serverKeys = server.generateKeys(verifier: values.verifier) -let serverPublicKey = serverKeys.public -``` -The server replies with the `serverPublicKey` and the salt value associated with the user. At this point the server will need to store the `serverKeys` and the public key it received from the client, most likely in a database. - -The client then creates the shared secret using the username, password, salt, its own key pair and the server public key. It then has to generate a proof it has the shared secret. This proof is generated from shared secret plus any of the public data available. -```swift -let clientSharedSecret = try client.calculateSharedSecret( - username: username, - password: password, - salt: salt, - clientKeys: clientKeys, - serverPublicKey: serverPublicKey -) -let clientProof = client.calculateClientProof( - username: username, - salt: salt, - clientPublicKey: clientKeys.public, - serverPublicKey: serverPublicKey, - sharedSecret: clientSharedSecret -) -``` -This `clientProof` is passed to the server. The server then generates its own version of the shared secret and verifies the `clientProof` is valid and if so will respond with it's own proof that it has the shared secret. -```swift -let serverSharedSecret = try server.calculateSharedSecret( - clientPublicKey: clientPublicKey, - serverKeys: serverKeys, - verifier: verifier -) -let serverProof = try server.verifyClientProof( - proof: clientProof, - username: username, - salt: salt, - clientPublicKey: clientPublicKey, - serverPublicKey: serverKeys.public, - sharedSecret: serverSharedSecret -) -``` -And finally the client can verify the server proof is valid -```swift -try client.verifyServerProof( - serverProof: serverProof, - clientProof: clientProof, - clientKeys: clientKeys, - sharedSecret: clientSharedSecret -) -``` -If at any point any of these functions fail the process should be aborted. - -# Compatibility - -The library is compliant with RFC5054 and should work with any server implementing this. The library has been verified against -- example data in RFC5054 -- Mozilla test vectors in https://wiki.mozilla.org/Identity/AttachedServices/KeyServerProtocol#SRP_Verifier -- Python library [srptools](https://github.com/idlesign/srptools) -- Typescript library [tssrp6a](https://github.com/midonet/tssrp6a) - -## Proof of secret - -For generating the proof above I use the method detailed in [RFC2945](https://tools.ietf.org/html/rfc2945#section-3) but not all servers use this method. For this reason I have kept the sharedSecret generation separate from the proof generation, so you can insert your own version. - -I have also supplied a simple proof functions `server.verifySimpleClientProof` and `client.verifySimpleServerProof` which use the proof detailed in the Wikipedia [page](https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol) on Secure Remote Password if you would prefer to use these. diff --git a/swift-srp-main/Sources/SRP/Array.swift b/swift-srp-main/Sources/SRP/Array.swift deleted file mode 100644 index 8f2a1816..00000000 --- a/swift-srp-main/Sources/SRP/Array.swift +++ /dev/null @@ -1,29 +0,0 @@ - -extension Array where Element: FixedWidthInteger { - /// create array of random bytes - static func random(count: Int) -> [Element] { - var array = self.init() - for _ in 0.. String { - return self.map({ - let characters = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"] - return "\(characters[Int($0 >> 4)])\(characters[Int($0 & 0xf)])" - }).joined() - } -} - -/// xor together the contents of two byte arrays -func ^ (lhs: [UInt8], rhs: [UInt8]) -> [UInt8] { - precondition(lhs.count == rhs.count, "Arrays are required to be the same size") - var result = lhs - for i in 0.. { - /// configuration. This needs to be the same as the server configuration - public let configuration: SRPConfiguration - - /// Initialise a SRPClient object - /// - Parameter configuration: configuration to use - public init(configuration: SRPConfiguration) { - self.configuration = configuration - } - - /// Initiate the authentication process - /// - Returns: An authentication state. The A value from this state should be sent to the server - public func generateKeys() -> SRPKeyPair { - var a = BigNum() - var A = BigNum() - repeat { - a = BigNum(bytes: SymmetricKey(size: .bits256)) - A = configuration.g.power(a, modulus: configuration.N) - } while A % configuration.N == BigNum(0) - - return SRPKeyPair(public: SRPKey(A), private: SRPKey(a)) - } - - /// return shared secret given the username, password, B value and salt from the server - /// - Parameters: - /// - username: user identifier - /// - password: password - /// - salt: salt - /// - clientKeys: client public/private keys - /// - serverPublicKey: server public key - /// - Throws: `nullServerKey` - /// - Returns: shared secret - public func calculateSharedSecret(username: String, password: String, salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> SRPKey { - let message = [UInt8]("\(username):\(password)".utf8) - let sharedSecret = try calculateSharedSecret(message: message, salt: salt, clientKeys: clientKeys, serverPublicKey: serverPublicKey) - return SRPKey(sharedSecret) - } - - public func calculateSharedSecret(password: Data, salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> SRPKey { - let message = [UInt8](Data([0x3a]) + password) - let sharedSecret = try calculateSharedSecret(message: message, salt: salt, clientKeys: clientKeys, serverPublicKey: serverPublicKey) - return SRPKey(sharedSecret) - } - - - /// calculate proof of shared secret to send to server - /// - Parameters: - /// - clientPublicKey: client public key - /// - serverPublicKey: server public key - /// - sharedSecret: shared secret - /// - Returns: The client verification code which should be passed to the server - public func calculateSimpleClientProof(clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) -> [UInt8] { - // get verification code - return SRP.calculateSimpleClientProof(clientPublicKey: clientPublicKey, serverPublicKey: serverPublicKey, sharedSecret: sharedSecret) - } - - /// If the server returns that the client verification code was valiid it will also return a server verification code that the client can use to verify the server is correct - /// - /// - Parameters: - /// - code: Verification code returned by server - /// - state: Authentication state - /// - Throws: `requiresVerificationKey`, `invalidServerCode` - public func verifySimpleServerProof(serverProof: [UInt8], clientProof: [UInt8], clientKeys: SRPKeyPair, sharedSecret: SRPKey) throws { - // get out version of server proof - let HAMS = SRP.calculateSimpleServerVerification(clientPublicKey: clientKeys.public, clientProof: clientProof, sharedSecret: sharedSecret) - // is it the same - guard serverProof == HAMS else { throw SRPClientError.invalidServerCode } - } - - /// calculate proof of shared secret to send to server - /// - Parameters: - /// - username: username - /// - salt: The salt value associated with the user returned by the server - /// - clientPublicKey: client public key - /// - serverPublicKey: server public key - /// - sharedSecret: shared secret - /// - Returns: The client verification code which should be passed to the server - public func calculateClientProof(username: String, salt: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) -> [UInt8] { - - let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) - - // get verification code - return SRP.calculateClientProof(configuration: configuration, username: username, salt: salt, clientPublicKey: clientPublicKey, serverPublicKey: serverPublicKey, hashSharedSecret: hashSharedSecret) - } - - /// If the server returns that the client verification code was valid it will also return a server - /// verification code that the client can use to verify the server is correct. This is the calculation - /// to verify it is correct - /// - /// - Parameters: - /// - clientPublicKey: Client public key - /// - clientProof: Client proof - /// - sharedSecret: Shared secret - public func calculateServerProof(clientPublicKey: SRPKey, clientProof: [UInt8], sharedSecret: SRPKey) -> [UInt8] { - let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) - // get out version of server proof - return SRP.calculateServerVerification(clientPublicKey: clientPublicKey, clientProof: clientProof, sharedSecret: hashSharedSecret) - } - - /// If the server returns that the client verification code was valid it will also return a server - /// verification code that the client can use to verify the server is correct - /// - /// - Parameters: - /// - clientProof: Server proof - /// - clientProof: Client proof - /// - clientKeys: Client keys - /// - sharedSecret: Shared secret - /// - Throws: `requiresVerificationKey`, `invalidServerCode` - public func verifyServerProof(serverProof: [UInt8], clientProof: [UInt8], clientKeys: SRPKeyPair, sharedSecret: SRPKey) throws { - // get our version of server proof - let HAMK = calculateServerProof(clientPublicKey: clientKeys.public, clientProof: clientProof, sharedSecret: sharedSecret) - // is it the same - guard serverProof == HAMK else { throw SRPClientError.invalidServerCode } - } - - /// Generate salt and password verifier from username and password. When creating your user instead of - /// passing your password to the server, you pass the salt and password verifier values. In this way the - /// server never knows your password so can never leak it. - /// - /// - Parameters: - /// - username: username - /// - password: user password - /// - Returns: tuple containing salt and password verifier - public func generateSaltAndVerifier(username: String, password: String) -> (salt: [UInt8], verifier: SRPKey) { - let salt = [UInt8].random(count: 16) - let verifier = generatePasswordVerifier(username: username, password: password, salt: salt) - return (salt: salt, verifier: SRPKey(verifier)) - } -} - -extension SRPClient { - /// return shared secret given the username, password, B value and salt from the server - func calculateSharedSecret(message: [UInt8], salt: [UInt8], clientKeys: SRPKeyPair, serverPublicKey: SRPKey) throws -> BigNum { - guard serverPublicKey.number % configuration.N != BigNum(0) else { throw SRPClientError.nullServerKey } - - // calculate u = H(clientPublicKey | serverPublicKey) - let u = SRP.calculateU(clientPublicKey: clientKeys.public.bytes, serverPublicKey: serverPublicKey.bytes, pad: configuration.sizeN) - - guard u != 0 else { throw SRPClientError.nullServerKey } - - let x = BigNum(bytes: [UInt8](H.hash(data: salt + H.hash(data: message)))) - - // calculate S = (B - k*g^x)^(a+u*x) - let S = (serverPublicKey.number - configuration.k * configuration.g.power(x, modulus: configuration.N)).power(clientKeys.private.number + u * x, modulus: configuration.N) - - return S - } - - /// generate password verifier - public func generatePasswordVerifier(username: String, password: String, salt: [UInt8]) -> BigNum { - let message = "\(username):\(password)" - return generatePasswordVerifier(message: [UInt8](message.utf8), salt: salt) - } - - /// generate password verifier - public func generatePasswordVerifier(message: [UInt8], salt: [UInt8]) -> BigNum { - let x = BigNum(bytes: [UInt8](H.hash(data: salt + H.hash(data: message)))) - let verifier = configuration.g.power(x, modulus: configuration.N) - return verifier - } -} diff --git a/swift-srp-main/Sources/SRP/configuration.swift b/swift-srp-main/Sources/SRP/configuration.swift deleted file mode 100644 index a1fe01a6..00000000 --- a/swift-srp-main/Sources/SRP/configuration.swift +++ /dev/null @@ -1,201 +0,0 @@ -import BigNum -import Crypto - -/// SRP Configuration. The same configuration hast to be used by both client and server. Contains a large safe prime N ie a prime where the value (N-1)/2 is also a prime, g the multiplicative group generator and the value k = Hash(N | g) -public struct SRPConfiguration { - /// large safe prime - public let N: BigNum - /// multiplicative group generator - public let g: BigNum - /// derived value from N and g. k = H( N | g ) - public let k: BigNum - /// size in bytes of N - public let sizeN: Int - - /// Initialise SRPConfiguration with known safe prime - /// - Parameter prime: enum indicating size of prime - public init(_ prime: Prime) { - self.N = prime.group - self.sizeN = Int(self.N.numBits() + 7) / 8 - self.g = prime.generator - self.k = BigNum(bytes: [UInt8](H.hash(data: self.N.bytes + SRP.pad(self.g.bytes, to: sizeN)))) - } - - /// Initialise SRPConfiguration with your own prime and multiplicative group generator - /// - Parameters: - /// - N: Large prime - /// - g: multiplicative group generator (usually 2) - public init(N: BigNum, g: BigNum) { - self.N = N - self.sizeN = Int(self.N.numBits() + 7) / 8 - self.g = g - self.k = BigNum(bytes: [UInt8](H.hash(data: self.N.bytes + SRP.pad(self.g.bytes, to: sizeN)))) - } - - public enum Prime { - case N1024 - case N1536 - case N2048 - case N3072 - case N4096 - case N6144 - case N8192 - - /// prime numbers and generators taken from RC 5054 https://tools.ietf.org/html/rfc5054 - var group: BigNum { - switch self { - case .N1024: - return BigNum(hex: - "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" + - "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" + - "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" + - "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" + - "FD5138FE8376435B9FC61D2FC0EB06E3")! - - case .N1536: - return BigNum(hex: - "9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA961" + - "4B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F843" + - "80B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0B" + - "E3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF5" + - "6EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734A" + - "F7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E" + - "8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB")! - - case .N2048: - return BigNum(hex: - "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" + - "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" + - "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" + - "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" + - "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" + - "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" + - "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" + - "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" + - "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" + - "9E4AFF73")! - - case .N3072: - return BigNum(hex: - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF")! - - case .N4096: - return BigNum(hex: - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" + - "FFFFFFFFFFFFFFFF")! - - case .N6144: - return BigNum(hex: - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + - "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + - "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + - "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + - "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + - "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + - "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + - "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + - "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + - "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + - "6DCC4024FFFFFFFFFFFFFFFF")! - - case .N8192: - return BigNum(hex: - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + - "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + - "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + - "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + - "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + - "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + - "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + - "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + - "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + - "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + - "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA" + - "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C" + - "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" + - "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886" + - "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6" + - "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5" + - "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268" + - "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6" + - "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + - "60C980DD98EDD3DFFFFFFFFFFFFFFFFF")! - } - } - - var generator: BigNum { - switch self { - case .N1024, .N1536, .N2048: - return BigNum(2) - case .N3072, .N4096, .N6144: - return BigNum(5) - case .N8192: - return BigNum(19) - } - } - } -} diff --git a/swift-srp-main/Sources/SRP/error.swift b/swift-srp-main/Sources/SRP/error.swift deleted file mode 100644 index d0829604..00000000 --- a/swift-srp-main/Sources/SRP/error.swift +++ /dev/null @@ -1,21 +0,0 @@ -/// Errors thrown by SRPClient -public enum SRPClientError: Swift.Error { - /// the key returned by server is invalid, in that either it modulo N is zero or the hash(A,B) is zero - case nullServerKey - /// server verification code was wrong - case invalidServerCode - /// you called verifyServerCode without a verification key - case requiresVerificationKey - /// client key is invalid - case invalidClientKey -} - -/// Errors thrown by SRPServer -///Errors thrown by SRPServer -public enum SRPServerError: Swift.Error { - /// the modulus of the client key and N generated a zero - case nullClientKey - /// client proof of the shared secret was invalid or wrong - case invalidClientProof -} - diff --git a/swift-srp-main/Sources/SRP/keys.swift b/swift-srp-main/Sources/SRP/keys.swift deleted file mode 100644 index c7d08a0b..00000000 --- a/swift-srp-main/Sources/SRP/keys.swift +++ /dev/null @@ -1,40 +0,0 @@ -import BigNum - -/// Wrapper for keys used by SRP -public struct SRPKey { - public let number: BigNum - public var bytes: [UInt8] { number.bytes } - public var hex: String { number.hex } - - public init(_ bytes: [UInt8]) { - self.number = BigNum(bytes: bytes) - } - - public init(_ number: BigNum) { - self.number = number - } - - public init?(hex: String) { - guard let number = BigNum(hex: hex) else { return nil } - self.number = number - } -} - -extension SRPKey: Equatable { } - -/// Contains a private and a public key -public struct SRPKeyPair { - public let `public`: SRPKey - public let `private`: SRPKey - - - /// Initialise a SRPKeyPair object - /// - Parameters: - /// - public: The public key of the key pair - /// - private: The private key of the key pair - public init(`public`: SRPKey, `private`: SRPKey) { - self.private = `private` - self.public = `public` - } -} - diff --git a/swift-srp-main/Sources/SRP/server.swift b/swift-srp-main/Sources/SRP/server.swift deleted file mode 100644 index 1e1931c7..00000000 --- a/swift-srp-main/Sources/SRP/server.swift +++ /dev/null @@ -1,110 +0,0 @@ -import BigNum -import Crypto - -/// Manages the server side of Secure Remote Password. -/// -/// Secure Remote Password (SRP) provides username and password authentication without needing to provide your password to the server. The server -/// has a cryptographic verifier that is derived from the password and a salt that was used to generate this verifier. Both client and server -/// generate a shared secret then the client sends a proof they have the secret and if it is correct the server will do the same to verify the -/// server as well. -/// -/// This version is compliant with SRP version 6a and RFC 5054. -/// -/// Reference reading -/// - https://tools.ietf.org/html/rfc2945 -/// - https://tools.ietf.org/html/rfc5054 -/// -public struct SRPServer { - /// Authentication state. Stores A,B and shared secret - public struct AuthenticationState { - let clientPublicKey: SRPKey - let serverPublicKey: SRPKey - var serverPrivateKey: SRPKey - } - - /// configuration has to be the same as the client configuration - public let configuration: SRPConfiguration - - /// Initialise SRPServer - /// - Parameter configuration: configuration to use - public init(configuration: SRPConfiguration) { - self.configuration = configuration - } - - /// generate public and private keys to be used in srp authentication - /// - Parameter verifier: password verifier used to generate key pair - /// - Returns: return public/private key pair - public func generateKeys(verifier: SRPKey) -> SRPKeyPair { - var b: BigNum - var B: BigNum - repeat { - b = BigNum(bytes: SymmetricKey(size: .bits256)) - B = (configuration.k * verifier.number + configuration.g.power(b, modulus: configuration.N)) % configuration.N - } while B % configuration.N == BigNum(0) - - return SRPKeyPair(public: SRPKey(B), private: SRPKey(b)) - } - - /// calculate the shared secret - /// - Parameters: - /// - clientPublicKey: public key received from client - /// - serverKeys: server key pair - /// - verifier: password verifier - /// - Returns: shared secret - public func calculateSharedSecret(clientPublicKey: SRPKey, serverKeys: SRPKeyPair, verifier: SRPKey) throws -> SRPKey { - guard clientPublicKey.number % configuration.N != BigNum(0) else { throw SRPServerError.nullClientKey } - - // calculate u = H(clientPublicKey | serverPublicKey) - let u = SRP.calculateU(clientPublicKey: clientPublicKey.bytes, serverPublicKey: serverKeys.public.bytes, pad: configuration.sizeN) - - // calculate S - let S = ((clientPublicKey.number * verifier.number.power(u, modulus: configuration.N)).power(serverKeys.private.number, modulus: configuration.N)) - - return SRPKey(S) - } - - /// verify proof that client has shared secret and return a server verification proof. If verification fails a `invalidClientCode` error is thrown - /// - /// - Parameters: - /// - proof: Client proof - /// - clientPublicKey: Client public key - /// - serverPublicKey: Server public key - /// - sharedSecret: Shared secret - /// - Throws: invalidClientCode - /// - Returns: The server verification code - public func verifySimpleClientProof(proof: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) throws -> [UInt8] { - let clientProof = SRP.calculateSimpleClientProof( - clientPublicKey: clientPublicKey, - serverPublicKey: serverPublicKey, - sharedSecret: sharedSecret - ) - guard clientProof == proof else { throw SRPServerError.invalidClientProof } - return SRP.calculateSimpleServerVerification(clientPublicKey: clientPublicKey, clientProof: clientProof, sharedSecret: sharedSecret) - } - - /// verify proof that client has shared secret and return a server verification proof. If verification fails a `invalidClientCode` error is thrown - /// - /// - Parameters: - /// - code: verification code sent by user - /// - username: username - /// - salt: salt stored with user - /// - clientPublicKey: Client public key - /// - serverPublicKey: Server public key - /// - sharedSecret: Shared secret - /// - Throws: invalidClientCode - /// - Returns: The server verification code - public func verifyClientProof(proof: [UInt8], username: String, salt: [UInt8], clientPublicKey: SRPKey, serverPublicKey: SRPKey, sharedSecret: SRPKey) throws -> [UInt8] { - let hashSharedSecret = [UInt8](H.hash(data: sharedSecret.bytes)) - - let clientProof = SRP.calculateClientProof( - configuration: configuration, - username: username, - salt: salt, - clientPublicKey: clientPublicKey, - serverPublicKey: serverPublicKey, - hashSharedSecret: hashSharedSecret - ) - guard clientProof == proof else { throw SRPServerError.invalidClientProof } - return SRP.calculateServerVerification(clientPublicKey: clientPublicKey, clientProof: clientProof, sharedSecret: hashSharedSecret) - } -} diff --git a/swift-srp-main/Sources/SRP/srp.swift b/swift-srp-main/Sources/SRP/srp.swift deleted file mode 100644 index 6e192c30..00000000 --- a/swift-srp-main/Sources/SRP/srp.swift +++ /dev/null @@ -1,66 +0,0 @@ -import BigNum -import Crypto - -/// Contains common code used by both client and server SRP code -public struct SRP { - - /// pad to a certain size by prefixing with zeros - static func pad(_ data: [UInt8], to size: Int) -> [UInt8] { - let padSize = size - data.count - guard padSize > 0 else { return data } - // create prefix and return prefix + data - let prefix: [UInt8] = (1...padSize).reduce([]) { result,_ in return result + [0] } - return prefix + data - } - - /// calculate u = H(clientPublicKey | serverPublicKey) - public static func calculateU(clientPublicKey: [UInt8], serverPublicKey: [UInt8], pad: Int) -> BigNum { - BigNum(bytes: [UInt8].init(H.hash(data: SRP.pad(clientPublicKey, to: pad) + SRP.pad(serverPublicKey, to: pad)))) - } - - /// Calculate a simpler client verification code H(A | B | S) - static func calculateSimpleClientProof( - clientPublicKey: SRPKey, - serverPublicKey: SRPKey, - sharedSecret: SRPKey) -> [UInt8] - { - let HABK = H.hash(data: clientPublicKey.bytes + serverPublicKey.bytes + sharedSecret.bytes) - return [UInt8](HABK) - } - - /// Calculate a simpler client verification code H(A | M1 | S) - static func calculateSimpleServerVerification( - clientPublicKey: SRPKey, - clientProof: [UInt8], - sharedSecret: SRPKey) -> [UInt8] - { - let HABK = H.hash(data: clientPublicKey.bytes + clientProof + sharedSecret.bytes) - return [UInt8](HABK) - } - - /// Calculate client verification code H(H(N)^ H(g)) | H(username) | salt | A | B | H(S)) - static func calculateClientProof( - configuration: SRPConfiguration, - username: String, - salt: [UInt8], - clientPublicKey: SRPKey, - serverPublicKey: SRPKey, - hashSharedSecret: [UInt8]) -> [UInt8] - { - // M = H(H(N)^ H(g)) | H(username) | salt | client key | server key | H(shared secret)) - let hashN = BigNum(bytes: H.hash(data: configuration.N.bytes)) - let hashG = BigNum(bytes: H.hash(data: SRP.pad(configuration.g.bytes, to: configuration.sizeN))) - let N_xor_g = hashN.bytes ^ hashG.bytes - let hashUser = H.hash(data: [UInt8](username.utf8)) - let M1 = [UInt8](N_xor_g) + hashUser + salt - let M2 = clientPublicKey.bytes + serverPublicKey.bytes + hashSharedSecret - let M = H.hash(data: M1 + M2) - return [UInt8](M) - } - - /// Calculate server verification code H(A | M1 | K) - static func calculateServerVerification(clientPublicKey: SRPKey, clientProof: [UInt8], sharedSecret: [UInt8]) -> [UInt8] { - let HAMK = H.hash(data: clientPublicKey.bytes + clientProof + sharedSecret) - return [UInt8](HAMK) - } -} diff --git a/swift-srp-main/Tests/LinuxMain.swift b/swift-srp-main/Tests/LinuxMain.swift deleted file mode 100644 index f87f4e99..00000000 --- a/swift-srp-main/Tests/LinuxMain.swift +++ /dev/null @@ -1,6 +0,0 @@ -import XCTest -import SRPTests - -var tests = [XCTestCaseEntry]() -tests += SRPTests.allTests() -XCTMain(tests) diff --git a/swift-srp-main/Tests/SRPTests/SRPTests.swift b/swift-srp-main/Tests/SRPTests/SRPTests.swift deleted file mode 100644 index ab15098d..00000000 --- a/swift-srp-main/Tests/SRPTests/SRPTests.swift +++ /dev/null @@ -1,207 +0,0 @@ -import XCTest -import BigNum -import Crypto -@testable import SRP - -final class SRPTests: XCTestCase { - - func testSRPSharedSecret() { - let username = "adamfowler" - let password = "testpassword" - let configuration = SRPConfiguration(.N2048) - let client = SRPClient(configuration: configuration) - let server = SRPServer(configuration: configuration) - - let (salt, verifier) = client.generateSaltAndVerifier(username: username, password: password) - - let clientKeys = client.generateKeys() - let serverKeys = server.generateKeys(verifier: verifier) - - do { - let sharedSecret = try client.calculateSharedSecret( - username: username, - password: password, - salt: salt, - clientKeys: clientKeys, - serverPublicKey: serverKeys.public) - - let serverSharedSecret = try server.calculateSharedSecret( - clientPublicKey: clientKeys.public, - serverKeys: serverKeys, - verifier: verifier) - - XCTAssertEqual(sharedSecret, serverSharedSecret) - } catch { - XCTFail("\(error)") - } - } - - func testVerifySRP(configuration: SRPConfiguration) { - let username = "adamfowler" - let password = "testpassword" - let client = SRPClient(configuration: configuration) - let server = SRPServer(configuration: configuration) - - let (salt, verifier) = client.generateSaltAndVerifier(username: username, password: password) - - do { - // client initiates authentication - let clientKeys = client.generateKeys() - // provides the server with an A value and username from which it gets the password verifier. - // server initiates authentication - let serverKeys = server.generateKeys(verifier: verifier) - // server passes back B value and a salt which was attached to the user - // client calculates verification code from username, password, current authenticator state, B and salt - let clientSharedSecret = try client.calculateSharedSecret(username: username, password: password, salt: salt, clientKeys: clientKeys, serverPublicKey: serverKeys.public) - let clientProof = client.calculateClientProof(username: username, salt: salt, clientPublicKey: clientKeys.public, serverPublicKey: serverKeys.public, sharedSecret: clientSharedSecret) - // client passes proof key to server - // server validates the key and then returns a server validation key - let serverSharedSecret = try server.calculateSharedSecret(clientPublicKey: clientKeys.public, serverKeys: serverKeys, verifier: verifier) - let serverProof = try server.verifyClientProof(proof: clientProof, username: username, salt: salt, clientPublicKey: clientKeys.public, serverPublicKey: serverKeys.public, sharedSecret: serverSharedSecret) - // client verifies server validation key - try client.verifyServerProof(serverProof: serverProof, clientProof: clientProof, clientKeys: clientKeys, sharedSecret: clientSharedSecret) - } catch { - XCTFail("\(error)") - } - } - - func testVerifySRP() { - testVerifySRP(configuration: SRPConfiguration(.N1024)) - testVerifySRP(configuration: SRPConfiguration(.N1536)) - testVerifySRP(configuration: SRPConfiguration(.N2048)) - testVerifySRP(configuration: SRPConfiguration(.N3072)) - testVerifySRP(configuration: SRPConfiguration(.N4096)) - testVerifySRP(configuration: SRPConfiguration(.N6144)) - testVerifySRP(configuration: SRPConfiguration(.N8192)) - } - - func testVerifySRPCustomConfiguration() { - testVerifySRP(configuration: SRPConfiguration(N: BigNum(37), g: BigNum(3))) - } - - func testClientSessionProof() { - let configuration = SRPConfiguration(.N1024) - let username = "alice" - let salt = "bafa3be2813c9326".bytes(using: .hexadecimal)! - let A = BigNum(hex: "b525e8fe2eac8f5da6b3220e66a0ab6f833a59d5f079fe9ddcdf111a22eaec95850374d9d7597f45497eb429bcde5057a450948de7d48edc034264916a01e6c0690e14b0a527f107d3207fd2214653c9162f5745e7cbeb19a550a072d4600ce8f4ef778f6d6899ba718adf0a462e7d981ed689de93ea1bda773333f23ebb4a9b")! - let B = BigNum(hex: "2bfc8559a022497f1254af3c76786b95cb0dfb449af15501aa51eefe78947d7ef06df4fcc07a899bcaae0e552ca72c7a1f3016f3ec357a86a1428dad9f98cb8a69d405404e57e9aaf01e51a46a73b3fc7bc1d212569e4a882ae6d878599e098c89033838ec069fe368a49461f531e5b4662700d56d8c252d0aea9da6abe9b014")! - let secret = "b6288955afd690a13686d65886b5f82018515df3".bytes(using: .hexadecimal)! - let clientProof = SRP.calculateClientProof(configuration: configuration, username: username, salt: salt, clientPublicKey: SRPKey(A), serverPublicKey: SRPKey(B), hashSharedSecret: secret) - - XCTAssertEqual(clientProof.hexdigest(), "e4c5c2e145ea2de18d0cc1ac9dc2a0d0988706d6") - } - - func testServerSessionProof() { - let A = BigNum(hex: "eade4992a46182e9ffe2e69f3e2639ca5f8c29b2868083c45d0972b72bb6003911b64a7ea6738061d705d368ddbe2bdb251bec63184db09b8990d8a7415dc449fbab720626fc25d6bd33c32234973c1e41c25b18d1824590c807c491221be5493878bd27a5ca507fd3963c849b07a9ec413e13253c6c61e7f3219b247cfa574a")! - let secret = "d89740e18a9fb597aef8f2ecc0e66f4b31c2ae08".bytes(using: .hexadecimal)! - let clientProof = "e1a8629a723039a61be91a173ab6260fc582192f".bytes(using: .hexadecimal)! - - let serverProof = SRP.calculateServerVerification(clientPublicKey: SRPKey(A), clientProof: clientProof, sharedSecret: secret) - - XCTAssertEqual(serverProof.hexdigest(), "8342bd06bdf4d263de2df9a56da8e581fb38c769") - } - - // Test results against RFC5054 Appendix B - func testRFC5054Appendix() throws { - let username = "alice" - let password = "password123" - let salt = "BEB25379D1A8581EB5A727673A2441EE".bytes(using: .hexadecimal)! - let configuration = SRPConfiguration(.N1024) - let client = SRPClient(configuration: configuration) - - XCTAssertEqual(configuration.k.hex, "7556AA045AEF2CDD07ABAF0F665C3E818913186F".lowercased()) - - let verifier = client.generatePasswordVerifier(username: username, password: password, salt: salt) - - XCTAssertEqual(verifier.hex, "7E273DE8696FFC4F4E337D05B4B375BEB0DDE1569E8FA00A9886D8129BADA1F1822223CA1A605B530E379BA4729FDC59F105B4787E5186F5C671085A1447B52A48CF1970B4FB6F8400BBF4CEBFBB168152E08AB5EA53D15C1AFF87B2B9DA6E04E058AD51CC72BFC9033B564E26480D78E955A5E29E7AB245DB2BE315E2099AFB".lowercased()) - - let a = BigNum(hex: "60975527035CF2AD1989806F0407210BC81EDC04E2762A56AFD529DDDA2D4393")! - // copied from client.swift - let A = configuration.g.power(a, modulus: configuration.N) - - XCTAssertEqual(A.hex, "61D5E490F6F1B79547B0704C436F523DD0E560F0C64115BB72557EC44352E8903211C04692272D8B2D1A5358A2CF1B6E0BFCF99F921530EC8E39356179EAE45E42BA92AEACED825171E1E8B9AF6D9C03E1327F44BE087EF06530E69F66615261EEF54073CA11CF5858F0EDFDFE15EFEAB349EF5D76988A3672FAC47B0769447B".lowercased()) - - let b = BigNum(hex: "E487CB59D31AC550471E81F00F6928E01DDA08E974A004F49E61F5D105284D20")! - // copied from server.swift - let B = (configuration.k * verifier + configuration.g.power(b, modulus: configuration.N)) % configuration.N - - XCTAssertEqual(B.hex, "BD0C61512C692C0CB6D041FA01BB152D4916A1E77AF46AE105393011BAF38964DC46A0670DD125B95A981652236F99D9B681CBF87837EC996C6DA04453728610D0C6DDB58B318885D7D82C7F8DEB75CE7BD4FBAA37089E6F9C6059F388838E7A00030B331EB76840910440B1B27AAEAEEB4012B7D7665238A8E3FB004B117B58".lowercased()) - - let u = SRP.calculateU(clientPublicKey: A.bytes, serverPublicKey: B.bytes, pad: configuration.sizeN) - - XCTAssertEqual(u.hex, "CE38B9593487DA98554ED47D70A7AE5F462EF019".lowercased()) - - let sharedSecret = try client.calculateSharedSecret(username: username, password: password, salt: salt, clientKeys: SRPKeyPair(public: SRPKey(A), private: SRPKey(a)), serverPublicKey: SRPKey(B)) - - XCTAssertEqual(sharedSecret.number.hex, "B0DC82BABCF30674AE450C0287745E7990A3381F63B387AAF271A10D233861E359B48220F7C4693C9AE12B0A6F67809F0876E2D013800D6C41BB59B6D5979B5C00A172B4A2A5903A0BDCAF8A709585EB2AFAFA8F3499B200210DCC1F10EB33943CD67FC88A2F39A4BE5BEC4EC0A3212DC346D7E474B29EDE8A469FFECA686E5A".lowercased()) - } - - /// Test library against Mozilla test vectors https://wiki.mozilla.org/Identity/AttachedServices/KeyServerProtocol#SRP_Verifier - func testMozillaTestVectors() throws { - let username = "andré@example.org" - let password = "00f9b71800ab5337d51177d8fbc682a3653fa6dae5b87628eeec43a18af59a9d".bytes(using: .hexadecimal)! - let salt = "00f1000000000000000000000000000000000000000000000000000000000179".bytes(using: .hexadecimal)! - let configuration = SRPConfiguration(.N2048) - let client = SRPClient(configuration: configuration) - - XCTAssertEqual(configuration.k.dec, "2590038599070950300691544216303772122846747035652616593381637186118123578112") - - let message = [UInt8]("\(username):".utf8) + password - let verifier = client.generatePasswordVerifier(message: message, salt: salt) - - XCTAssertEqual(verifier.hex, "173ffa0263e63ccfd6791b8ee2a40f048ec94cd95aa8a3125726f9805e0c8283c658dc0b607fbb25db68e68e93f2658483049c68af7e8214c49fde2712a775b63e545160d64b00189a86708c69657da7a1678eda0cd79f86b8560ebdb1ffc221db360eab901d643a75bf1205070a5791230ae56466b8c3c1eb656e19b794f1ea0d2a077b3a755350208ea0118fec8c4b2ec344a05c66ae1449b32609ca7189451c259d65bd15b34d8729afdb5faff8af1f3437bbdc0c3d0b069a8ab2a959c90c5a43d42082c77490f3afcc10ef5648625c0605cdaace6c6fdc9e9a7e6635d619f50af7734522470502cab26a52a198f5b00a279858916507b0b4e9ef9524d6") - - let b = BigNum(hex: "00f3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f")! - // copied from server.swift - let B = (configuration.k * verifier + configuration.g.power(b, modulus: configuration.N)) % configuration.N - - XCTAssertEqual(B.hex, "22ce5a7b9d81277172caa20b0f1efb4643b3becc53566473959b07b790d3c3f08650d5531c19ad30ebb67bdb481d1d9cf61bf272f8439848fdda58a4e6abc5abb2ac496da5098d5cbf90e29b4b110e4e2c033c70af73925fa37457ee13ea3e8fde4ab516dff1c2ae8e57a6b264fb9db637eeeae9b5e43dfaba9b329d3b8770ce89888709e026270e474eef822436e6397562f284778673a1a7bc12b6883d1c21fbc27ffb3dbeb85efda279a69a19414969113f10451603065f0a012666645651dde44a52f4d8de113e2131321df1bf4369d2585364f9e536c39a4dce33221be57d50ddccb4384e3612bbfd03a268a36e4f7e01de651401e108cc247db50392") - - let a = BigNum(hex: "00f2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d3d7")! - // copied from client.swift - let A = configuration.g.power(a, modulus: configuration.N) - - XCTAssertEqual(A.hex, "7da76cb7e77af5ab61f334dbd5a958513afcdf0f47ab99271fc5f7860fe2132e5802ca79d2e5c064bb80a38ee08771c98a937696698d878d78571568c98a1c40cc6e7cb101988a2f9ba3d65679027d4d9068cb8aad6ebff0101bab6d52b5fdfa81d2ed48bba119d4ecdb7f3f478bd236d5749f2275e9484f2d0a9259d05e49d78a23dd26c60bfba04fd346e5146469a8c3f010a627be81c58ded1caaef2363635a45f97ca0d895cc92ace1d09a99d6beb6b0dc0829535c857a419e834db12864cd6ee8a843563b0240520ff0195735cd9d316842d5d3f8ef7209a0bb4b54ad7374d73e79be2c3975632de562c596470bb27bad79c3e2fcddf194e1666cb9fc") - - let u = SRP.calculateU(clientPublicKey: A.bytes, serverPublicKey: B.bytes, pad: configuration.sizeN) - - XCTAssertEqual(u.hex, "b284aa1064e8775150da6b5e2147b47ca7df505bed94a6f4bb2ad873332ad732") - - let sharedSecret = try client.calculateSharedSecret(message: message, salt: salt, clientKeys: SRPKeyPair(public: SRPKey(A), private: SRPKey(a)), serverPublicKey: SRPKey(B)) - - XCTAssertEqual(sharedSecret.hex, "92aaf0f527906aa5e8601f5d707907a03137e1b601e04b5a1deb02a981f4be037b39829a27dba50f1b27545ff2e28729c2b79dcbdd32c9d6b20d340affab91a626a8075806c26fe39df91d0ad979f9b2ee8aad1bc783e7097407b63bfe58d9118b9b0b2a7c5c4cdebaf8e9a460f4bf6247b0da34b760a59fac891757ddedcaf08eed823b090586c63009b2d740cc9f5397be89a2c32cdcfe6d6251ce11e44e6ecbdd9b6d93f30e90896d2527564c7eb9ff70aa91acc0bac1740a11cd184ffb989554ab58117c2196b353d70c356160100ef5f4c28d19f6e59ea2508e8e8aac6001497c27f362edbafb25e0f045bfdf9fb02db9c908f10340a639fe84c31b27") - } - - static var allTests = [ - ("testSRPSharedSecret", testSRPSharedSecret), - ("testVerifySRP", testVerifySRP), - ("testVerifySRPCustomConfiguration", testVerifySRPCustomConfiguration), - ("testClientSessionProof", testClientSessionProof), - ("testServerSessionProof", testServerSessionProof), - ("testRFC5054Appendix", testRFC5054Appendix), - ("testMozillaTestVectors", testMozillaTestVectors), - ] -} - -extension String { - enum ExtendedEncoding { - case hexadecimal - } - - func bytes(using encoding:ExtendedEncoding) -> [UInt8]? { - guard self.count % 2 == 0 else { return nil } - - var bytes: [UInt8] = [] - - var indexIsEven = true - for i in self.indices { - if indexIsEven { - let byteRange = i...self.index(after: i) - guard let byte = UInt8(self[byteRange], radix: 16) else { return nil } - bytes.append(byte) - } - indexIsEven.toggle() - } - return bytes - } -} diff --git a/swift-srp-main/Tests/SRPTests/XCTestManifests.swift b/swift-srp-main/Tests/SRPTests/XCTestManifests.swift deleted file mode 100644 index 97c4c9fa..00000000 --- a/swift-srp-main/Tests/SRPTests/XCTestManifests.swift +++ /dev/null @@ -1,9 +0,0 @@ -import XCTest - -#if !canImport(ObjectiveC) -public func allTests() -> [XCTestCaseEntry] { - return [ - testCase(SRPTests.allTests), - ] -} -#endif From 69e667cf872b823c87a095f56d85a9b947782c44 Mon Sep 17 00:00:00 2001 From: Matt Kiazyk Date: Mon, 28 Oct 2024 21:34:41 -0500 Subject: [PATCH 6/7] some cleanup of extra prints and old code --- Xcodes/AppleAPI/Sources/AppleAPI/Client.swift | 82 ------------------- 1 file changed, 82 deletions(-) diff --git a/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift b/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift index 78c80ee6..0826472d 100644 --- a/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift +++ b/Xcodes/AppleAPI/Sources/AppleAPI/Client.swift @@ -41,8 +41,6 @@ public class Client { .eraseToAnyPublisher() } .flatMap { (serviceKey, hashcash, srpInit) -> AnyPublisher in - print("SRP INIT REsponse: \(srpInit)") - guard let decodedB = Data(base64Encoded: srpInit.b) else { return Fail(error: AuthenticationError.srpInvalidPublicKey) .eraseToAnyPublisher() @@ -56,27 +54,20 @@ public class Client { let iterations = srpInit.iteration do { - guard let encryptedPassword = self.pbkdf2(password: password, saltData: decodedSalt, keyByteCount: 32, prf: CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), rounds: iterations) else { return Fail(error: AuthenticationError.srpInvalidPublicKey) .eraseToAnyPublisher() } -// let m1 = try client.processChallenge(salt: decodedSalt, publicKey: decodedB, isEncryptedPassword: true, encryptedPassword: encryptedPassword.hexEncodedString()) - let encryptedPasswordString = encryptedPassword.base64EncodedString() let sharedSecret = try client.calculateSharedSecret(password: encryptedPassword, salt: [UInt8](decodedSalt), clientKeys: clientKeys, serverPublicKey: .init([UInt8](decodedB))) -// let m1 = try client.processChallenge(salt: decodedSalt, publicKey: decodedB, encryptedPassword: encryptedPasswordString) let m1 = client.calculateClientProof(username: accountName, salt: [UInt8](decodedSalt), clientPublicKey: a, serverPublicKey: .init([UInt8](decodedB)), sharedSecret: .init(sharedSecret.bytes)) let m2 = client.calculateServerProof(clientPublicKey: a, clientProof: m1, sharedSecret: .init([UInt8](sharedSecret.bytes))) - print("m1: \(Data(m1).base64EncodedString())") - print("m2: \(Data(m2).base64EncodedString())") return Current.network.dataTask(with: URLRequest.SRPComplete(serviceKey: serviceKey, hashcash: hashcash, accountName: accountName, c: srpInit.c, m1: Data(m1).base64EncodedString(), m2: Data(m2).base64EncodedString())) .mapError { $0 as Swift.Error } .eraseToAnyPublisher() } catch { - print("Error: calculateSharedSecret \(error)") return Fail(error: AuthenticationError.srpInvalidPublicKey) .eraseToAnyPublisher() } @@ -114,79 +105,6 @@ public class Client { } .eraseToAnyPublisher() } -// .map(\.data) -// .decode(type: ServerSRPInitResponse.self, decoder: JSONDecoder()) -// -// -// -// .flatMap { result -> AnyPublisher in -// return ("") -// } -// .flatMap { serverResponse -> AnyPublisher in -// print(serverResponse) -// return Fail(error: AuthenticationError.accountUsesTwoStepAuthentication) -// .eraseToAnyPublisher() -// } - .mapError { $0 as Swift.Error } - .eraseToAnyPublisher() - } - - - public func login(accountName: String, password: String) -> AnyPublisher { - var serviceKey: String! - - return Current.network.dataTask(with: URLRequest.itcServiceKey) - .map(\.data) - .decode(type: ServiceKeyResponse.self, decoder: JSONDecoder()) - .flatMap { serviceKeyResponse -> AnyPublisher<(String, String), Swift.Error> in - serviceKey = serviceKeyResponse.authServiceKey - - // Fixes issue https://github.com/RobotsAndPencils/XcodesApp/issues/360 - // On 2023-02-23, Apple added a custom implementation of hashcash to their auth flow - // Without this addition, Apple ID's would get set to locked - return self.loadHashcash(accountName: accountName, serviceKey: serviceKey) - .map { return (serviceKey, $0)} - .eraseToAnyPublisher() - } - .flatMap { (serviceKey, hashcash) -> AnyPublisher in - - return Current.network.dataTask(with: URLRequest.signIn(serviceKey: serviceKey, accountName: accountName, password: password, hashcash: hashcash)) - .mapError { $0 as Swift.Error } - .eraseToAnyPublisher() - } - .flatMap { result -> AnyPublisher in - let (data, response) = result - return Just(data) - .decode(type: SignInResponse.self, decoder: JSONDecoder()) - .flatMap { responseBody -> AnyPublisher in - let httpResponse = response as! HTTPURLResponse - - switch httpResponse.statusCode { - case 200: - return Current.network.dataTask(with: URLRequest.olympusSession) - .map { _ in AuthenticationState.authenticated } - .mapError { $0 as Swift.Error } - .eraseToAnyPublisher() - case 401: - return Fail(error: AuthenticationError.invalidUsernameOrPassword(username: accountName)) - .eraseToAnyPublisher() - case 403: - let errorMessage = responseBody.serviceErrors?.first?.description.replacingOccurrences(of: "-20209: ", with: "") ?? "" - return Fail(error: AuthenticationError.accountLocked(errorMessage)) - .eraseToAnyPublisher() - case 409: - return self.handleTwoStepOrFactor(data: data, response: response, serviceKey: serviceKey) - case 412 where Client.authTypes.contains(responseBody.authType ?? ""): - return Fail(error: AuthenticationError.appleIDAndPrivacyAcknowledgementRequired) - .eraseToAnyPublisher() - default: - return Fail(error: AuthenticationError.unexpectedSignInResponse(statusCode: httpResponse.statusCode, - message: responseBody.serviceErrors?.map { $0.description }.joined(separator: ", "))) - .eraseToAnyPublisher() - } - } - .eraseToAnyPublisher() - } .mapError { $0 as Swift.Error } .eraseToAnyPublisher() } From 42c2c6bfc059f44c7add27e3ac425ff3278d1ddd Mon Sep 17 00:00:00 2001 From: Matt Kiazyk Date: Mon, 28 Oct 2024 21:45:07 -0500 Subject: [PATCH 7/7] move to xcodesOrg/swift-srp fork --- .../xcshareddata/swiftpm/Package.resolved | 8 +- Xcodes/AppleAPI/Package.swift | 4 +- Xcodes/Resources/Licenses.rtf | 233 ++++++++++++++++-- 3 files changed, 213 insertions(+), 32 deletions(-) diff --git a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 19fa71ed..f90bb44b 100644 --- a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -120,11 +120,11 @@ }, { "package": "swift-srp", - "repositoryURL": "https://github.com/abiligiri/swift-srp", + "repositoryURL": "https://github.com/xcodesOrg/swift-srp", "state": { - "branch": null, - "revision": "ca452b0b557021ca8af305bbce504bcd13d32b15", - "version": "1.1.0" + "branch": "main", + "revision": "543aa0122a0257b992f6c7d62d18a26e3dffb8fe", + "version": null } }, { diff --git a/Xcodes/AppleAPI/Package.swift b/Xcodes/AppleAPI/Package.swift index 2b572ff0..f3eb5b75 100644 --- a/Xcodes/AppleAPI/Package.swift +++ b/Xcodes/AppleAPI/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.3 +// swift-tools-version:5.7 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription @@ -13,7 +13,7 @@ let package = Package( targets: ["AppleAPI"]), ], dependencies: [ - .package(url: "https://github.com/abiligiri/swift-srp", from: "1.1.0") + .package(url: "https://github.com/xcodesOrg/swift-srp", branch: "main") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/Xcodes/Resources/Licenses.rtf b/Xcodes/Resources/Licenses.rtf index 7213f22e..a10eda3c 100644 --- a/Xcodes/Resources/Licenses.rtf +++ b/Xcodes/Resources/Licenses.rtf @@ -31,32 +31,6 @@ SOFTWARE.\ \ \ -\fs34 BigInt\ -\ - -\fs26 \ -Copyright (c) 2016-2017 K\'e1roly L\uc0\u337 rentey\ -\ -Permission is hereby granted, free of charge, to any person obtaining a copy\ -of this software and associated documentation files (the "Software"), to deal\ -in the Software without restriction, including without limitation the rights\ -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ -copies of the Software, and to permit persons to whom the Software is\ -furnished to do so, subject to the following conditions:\ -\ -The above copyright notice and this permission notice shall be included in all\ -copies or substantial portions of the Software.\ -\ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\ -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\ -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\ -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\ -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\ -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\ -SOFTWARE.\ -\ -\ - \fs34 SwiftSoup\ \ @@ -840,6 +814,213 @@ For more information, please refer to <>\ \ \ +\fs34 swift-srp\ +\ + +\fs26 Apache License\ + Version 2.0, January 2004\ + http://www.apache.org/licenses/\ +\ + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\ +\ + 1. Definitions.\ +\ + "License" shall mean the terms and conditions for use, reproduction,\ + and distribution as defined by Sections 1 through 9 of this document.\ +\ + "Licensor" shall mean the copyright owner or entity authorized by\ + the copyright owner that is granting the License.\ +\ + "Legal Entity" shall mean the union of the acting entity and all\ + other entities that control, are controlled by, or are under common\ + control with that entity. For the purposes of this definition,\ + "control" means (i) the power, direct or indirect, to cause the\ + direction or management of such entity, whether by contract or\ + otherwise, or (ii) ownership of fifty percent (50%) or more of the\ + outstanding shares, or (iii) beneficial ownership of such entity.\ +\ + "You" (or "Your") shall mean an individual or Legal Entity\ + exercising permissions granted by this License.\ +\ + "Source" form shall mean the preferred form for making modifications,\ + including but not limited to software source code, documentation\ + source, and configuration files.\ +\ + "Object" form shall mean any form resulting from mechanical\ + transformation or translation of a Source form, including but\ + not limited to compiled object code, generated documentation,\ + and conversions to other media types.\ +\ + "Work" shall mean the work of authorship, whether in Source or\ + Object form, made available under the License, as indicated by a\ + copyright notice that is included in or attached to the work\ + (an example is provided in the Appendix below).\ +\ + "Derivative Works" shall mean any work, whether in Source or Object\ + form, that is based on (or derived from) the Work and for which the\ + editorial revisions, annotations, elaborations, or other modifications\ + represent, as a whole, an original work of authorship. For the purposes\ + of this License, Derivative Works shall not include works that remain\ + separable from, or merely link (or bind by name) to the interfaces of,\ + the Work and Derivative Works thereof.\ +\ + "Contribution" shall mean any work of authorship, including\ + the original version of the Work and any modifications or additions\ + to that Work or Derivative Works thereof, that is intentionally\ + submitted to Licensor for inclusion in the Work by the copyright owner\ + or by an individual or Legal Entity authorized to submit on behalf of\ + the copyright owner. For the purposes of this definition, "submitted"\ + means any form of electronic, verbal, or written communication sent\ + to the Licensor or its representatives, including but not limited to\ + communication on electronic mailing lists, source code control systems,\ + and issue tracking systems that are managed by, or on behalf of, the\ + Licensor for the purpose of discussing and improving the Work, but\ + excluding communication that is conspicuously marked or otherwise\ + designated in writing by the copyright owner as "Not a Contribution."\ +\ + "Contributor" shall mean Licensor and any individual or Legal Entity\ + on behalf of whom a Contribution has been received by Licensor and\ + subsequently incorporated within the Work.\ +\ + 2. Grant of Copyright License. Subject to the terms and conditions of\ + this License, each Contributor hereby grants to You a perpetual,\ + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\ + copyright license to reproduce, prepare Derivative Works of,\ + publicly display, publicly perform, sublicense, and distribute the\ + Work and such Derivative Works in Source or Object form.\ +\ + 3. Grant of Patent License. Subject to the terms and conditions of\ + this License, each Contributor hereby grants to You a perpetual,\ + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\ + (except as stated in this section) patent license to make, have made,\ + use, offer to sell, sell, import, and otherwise transfer the Work,\ + where such license applies only to those patent claims licensable\ + by such Contributor that are necessarily infringed by their\ + Contribution(s) alone or by combination of their Contribution(s)\ + with the Work to which such Contribution(s) was submitted. If You\ + institute patent litigation against any entity (including a\ + cross-claim or counterclaim in a lawsuit) alleging that the Work\ + or a Contribution incorporated within the Work constitutes direct\ + or contributory patent infringement, then any patent licenses\ + granted to You under this License for that Work shall terminate\ + as of the date such litigation is filed.\ +\ + 4. Redistribution. You may reproduce and distribute copies of the\ + Work or Derivative Works thereof in any medium, with or without\ + modifications, and in Source or Object form, provided that You\ + meet the following conditions:\ +\ + (a) You must give any other recipients of the Work or\ + Derivative Works a copy of this License; and\ +\ + (b) You must cause any modified files to carry prominent notices\ + stating that You changed the files; and\ +\ + (c) You must retain, in the Source form of any Derivative Works\ + that You distribute, all copyright, patent, trademark, and\ + attribution notices from the Source form of the Work,\ + excluding those notices that do not pertain to any part of\ + the Derivative Works; and\ +\ + (d) If the Work includes a "NOTICE" text file as part of its\ + distribution, then any Derivative Works that You distribute must\ + include a readable copy of the attribution notices contained\ + within such NOTICE file, excluding those notices that do not\ + pertain to any part of the Derivative Works, in at least one\ + of the following places: within a NOTICE text file distributed\ + as part of the Derivative Works; within the Source form or\ + documentation, if provided along with the Derivative Works; or,\ + within a display generated by the Derivative Works, if and\ + wherever such third-party notices normally appear. The contents\ + of the NOTICE file are for informational purposes only and\ + do not modify the License. You may add Your own attribution\ + notices within Derivative Works that You distribute, alongside\ + or as an addendum to the NOTICE text from the Work, provided\ + that such additional attribution notices cannot be construed\ + as modifying the License.\ +\ + You may add Your own copyright statement to Your modifications and\ + may provide additional or different license terms and conditions\ + for use, reproduction, or distribution of Your modifications, or\ + for any such Derivative Works as a whole, provided Your use,\ + reproduction, and distribution of the Work otherwise complies with\ + the conditions stated in this License.\ +\ + 5. Submission of Contributions. Unless You explicitly state otherwise,\ + any Contribution intentionally submitted for inclusion in the Work\ + by You to the Licensor shall be under the terms and conditions of\ + this License, without any additional terms or conditions.\ + Notwithstanding the above, nothing herein shall supersede or modify\ + the terms of any separate license agreement you may have executed\ + with Licensor regarding such Contributions.\ +\ + 6. Trademarks. This License does not grant permission to use the trade\ + names, trademarks, service marks, or product names of the Licensor,\ + except as required for reasonable and customary use in describing the\ + origin of the Work and reproducing the content of the NOTICE file.\ +\ + 7. Disclaimer of Warranty. Unless required by applicable law or\ + agreed to in writing, Licensor provides the Work (and each\ + Contributor provides its Contributions) on an "AS IS" BASIS,\ + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\ + implied, including, without limitation, any warranties or conditions\ + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\ + PARTICULAR PURPOSE. You are solely responsible for determining the\ + appropriateness of using or redistributing the Work and assume any\ + risks associated with Your exercise of permissions under this License.\ +\ + 8. Limitation of Liability. In no event and under no legal theory,\ + whether in tort (including negligence), contract, or otherwise,\ + unless required by applicable law (such as deliberate and grossly\ + negligent acts) or agreed to in writing, shall any Contributor be\ + liable to You for damages, including any direct, indirect, special,\ + incidental, or consequential damages of any character arising as a\ + result of this License or out of the use or inability to use the\ + Work (including but not limited to damages for loss of goodwill,\ + work stoppage, computer failure or malfunction, or any and all\ + other commercial damages or losses), even if such Contributor\ + has been advised of the possibility of such damages.\ +\ + 9. Accepting Warranty or Additional Liability. While redistributing\ + the Work or Derivative Works thereof, You may choose to offer,\ + and charge a fee for, acceptance of support, warranty, indemnity,\ + or other liability obligations and/or rights consistent with this\ + License. However, in accepting such obligations, You may act only\ + on Your own behalf and on Your sole responsibility, not on behalf\ + of any other Contributor, and only if You agree to indemnify,\ + defend, and hold each Contributor harmless for any liability\ + incurred by, or claims asserted against, such Contributor by reason\ + of your accepting any such warranty or additional liability.\ +\ + END OF TERMS AND CONDITIONS\ +\ + APPENDIX: How to apply the Apache License to your work.\ +\ + To apply the Apache License to your work, attach the following\ + boilerplate notice, with the fields enclosed by brackets "[]"\ + replaced with your own identifying information. (Don't include\ + the brackets!) The text should be enclosed in the appropriate\ + comment syntax for the file format. We also recommend that a\ + file or class name and description of purpose be included on the\ + same "printed page" as the copyright notice for easier\ + identification within third-party archives.\ +\ + Copyright [yyyy] [name of copyright owner]\ +\ + Licensed under the Apache License, Version 2.0 (the "License");\ + you may not use this file except in compliance with the License.\ + You may obtain a copy of the License at\ +\ + http://www.apache.org/licenses/LICENSE-2.0\ +\ + Unless required by applicable law or agreed to in writing, software\ + distributed under the License is distributed on an "AS IS" BASIS,\ + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\ + See the License for the specific language governing permissions and\ + limitations under the License.\ +\ +\ + \fs34 DockProgress\ \