Files
bundesmessenger-ios/bwi/LoginProtection/LoginProtectionService.swift
2024-07-25 12:51:43 +02:00

69 lines
2.4 KiB
Swift

//
/*
* Copyright (c) 2022 BWI GmbH
*
* 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.
*/
import Foundation
import CryptoKit
@objcMembers class LoginProtectionService : NSObject {
var hashes: [String]?
@objc func isValid(_ homeserverAddress: String) async -> Bool {
// bwi #6162 a homeserveraddress is valid when there is either
// a) no homeserver protection (bwm)
// b) tokenized protection and there is a valid token
// c) hashed protection and there is a valid hash (this will be disabled soon)
// d) b) && c) can be combined for now
var validHomeserver = false
if BWIBuildSettings.shared.bwiEnableTokenizedLoginProtection {
let tokenVerificator = ServerTokenVerificator()
let token = await tokenVerificator.fetchToken(baseURL: homeserverAddress)
if let token = token {
validHomeserver = tokenVerificator.verifyToken(baseURL: homeserverAddress, token: token)
}
}
if BWIBuildSettings.shared.bwiEnableLoginProtection && !validHomeserver {
if let hashes = hashes {
let string = self.normalizeLoginUrl(homeserverAddress)
let hashedString = self.hashedString(string)
validHomeserver = hashes.contains(hashedString)
}
}
return validHomeserver
}
private func normalizeLoginUrl(_ urlString: String) -> String {
var tmpString = urlString.replacingOccurrences(of: "https://", with: "")
tmpString = tmpString.replacingOccurrences(of: "http://", with: "")
return tmpString
}
private func hashedString(_ string: String) -> String {
let data = Data(string.utf8)
let hash = SHA256.hash(data: data)
return hash.compactMap { String(format: "%02x", $0) }.joined()
}
}