diff --git a/Xcodes.xcodeproj/project.pbxproj b/Xcodes.xcodeproj/project.pbxproj index 5e9ee95a..9dfe09d5 100644 --- a/Xcodes.xcodeproj/project.pbxproj +++ b/Xcodes.xcodeproj/project.pbxproj @@ -3,10 +3,11 @@ archiveVersion = 1; classes = { }; - objectVersion = 60; + objectVersion = 54; 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,6 @@ E84E4F552B335094003F3959 /* XCRemoteSwiftPackageReference "swift-collections" */, E83FDC422CBB649100679C6B /* XCRemoteSwiftPackageReference "Sparkle" */, 33027E282CA8BB5800CB387C /* XCRemoteSwiftPackageReference "LibFido2Swift" */, - E862D4392CC8B26F00BAA376 /* XCLocalSwiftPackageReference "xcodes-srp" */, ); productRefGroup = CAD2E79F2449574E00113D76 /* Products */; projectDirPath = ""; @@ -1484,13 +1487,6 @@ }; /* 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; diff --git a/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Xcodes.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index e76dc9c8..f90bb44b 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" } }, { @@ -118,6 +118,15 @@ "version": "1.1.7" } }, + { + "package": "swift-srp", + "repositoryURL": "https://github.com/xcodesOrg/swift-srp", + "state": { + "branch": "main", + "revision": "543aa0122a0257b992f6c7d62d18a26e3dffb8fe", + "version": null + } + }, { "package": "SwiftSoup", "repositoryURL": "https://github.com/scinfu/SwiftSoup", diff --git a/Xcodes/AppleAPI/Package.swift b/Xcodes/AppleAPI/Package.swift index 500b9d18..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 @@ -12,13 +12,15 @@ let package = Package( name: "AppleAPI", targets: ["AppleAPI"]), ], - dependencies: [], + dependencies: [ + .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. // 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..0826472d 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,15 +34,13 @@ 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) } .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() @@ -55,29 +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 = 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 sharedSecret = try client.calculateSharedSecret(password: encryptedPassword, salt: [UInt8](decodedSalt), clientKeys: clientKeys, serverPublicKey: .init([UInt8](decodedB))) - 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))) + + 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() } @@ -115,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() } @@ -382,10 +299,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 +319,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/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\ \ 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/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/LICENSE b/xcodes-srp/LICENSE deleted file mode 100644 index 261eeb9e..00000000 --- a/xcodes-srp/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/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/Package.swift b/xcodes-srp/Package.swift deleted file mode 100644 index 890d696c..00000000 --- a/xcodes-srp/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/attaswift/BigInt.git", from: "5.0.0") - ], - targets: [ - .target(name: "SRP", dependencies: ["Crypto", "BigInt"]), - .testTarget( - name: "SRPTests", dependencies: ["SRP"]), - ] -) diff --git a/xcodes-srp/README.md b/xcodes-srp/README.md deleted file mode 100644 index f19c2314..00000000 --- a/xcodes-srp/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/xcodes-srp/Sources/SRP/Array.swift b/xcodes-srp/Sources/SRP/Array.swift deleted file mode 100644 index 8f2a1816..00000000 --- a/xcodes-srp/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.. { - 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/error.swift b/xcodes-srp/Sources/SRP/error.swift deleted file mode 100644 index d0829604..00000000 --- a/xcodes-srp/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/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..(.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 deleted file mode 100644 index 97c4c9fa..00000000 --- a/xcodes-srp/Tests/SRPTests/XCTestManifests.swift +++ /dev/null @@ -1,9 +0,0 @@ -import XCTest - -#if !canImport(ObjectiveC) -public func allTests() -> [XCTestCaseEntry] { - return [ - testCase(SRPTests.allTests), - ] -} -#endif