Add Trusted Devices Authentication

This commit is contained in:
Leon Böttger committed 2025-08-23 11:52:14 +02:00
1 parent 78df7fe227
commit 48164b8095
14 files changed
+621 -70

No files matched your search

@@ -26,6 +26,8 @@ class InboundNearbyConnection: NearbyConnection {
private var cipherCommitment: Data?
private var textPayloadID: Int64 = 0
private var bytesToBeTransferred: Int64 = 0
private var isAuthenticated = false
private var peerCertificate: Sharing_Nearby_PublicCertificate? = nil
var isPlainTextTransfer = false
var wasUserRejected = false
@@ -371,9 +373,11 @@ class InboundNearbyConnection: NearbyConnection {
pairedEncryption.v1 = Sharing_Nearby_V1Frame()
pairedEncryption.v1.type = .pairedKeyEncryption
pairedEncryption.v1.pairedKeyEncryption = Sharing_Nearby_PairedKeyEncryptionFrame()
// Presumably used for all the phone number stuff that no one needs anyway
// For inbound connections, we do not use provide secretIDHash and signedData
pairedEncryption.v1.pairedKeyEncryption.secretIDHash = Data.randomData(length: 6)
pairedEncryption.v1.pairedKeyEncryption.signedData = Data.randomData(length: 72)
try sendTransferSetupFrame(pairedEncryption)
currentState = .sentConnectionResponse
} else {
@@ -381,16 +385,77 @@ class InboundNearbyConnection: NearbyConnection {
}
}
private func processPairedKeyEncryptionFrame(_ frame: Sharing_Nearby_Frame) throws {
guard frame.hasV1, frame.v1.hasPairedKeyEncryption else { throw NearbyError.requiredFieldMissing("shareNearbyFrame.v1.pairedKeyEncryption") }
var pairedResult = Sharing_Nearby_Frame()
pairedResult.version = .v1
pairedResult.v1 = Sharing_Nearby_V1Frame()
pairedResult.v1.type = .pairedKeyResult
pairedResult.v1.pairedKeyResult = Sharing_Nearby_PairedKeyResultFrame()
pairedResult.v1.pairedKeyResult.status = .unable
try sendTransferSetupFrame(pairedResult)
let pkeFrame = frame.v1.pairedKeyEncryption
log("[InboundNearbyConnection \(self.id)] Processing paired key encryption frame with secretIDHash: \(pkeFrame.secretIDHash.hex)")
log("Signed data: " + pkeFrame.signedData.hex)
// Check if we can accept the connection automatically
if !pkeFrame.secretIDHash.isEmpty,
let trustedCertData = TrustStore.shared.findTrustedKey(for: pkeFrame.secretIDHash),
let trustedCert = try? Sharing_Nearby_PublicCertificate(serializedBytes: trustedCertData),
let peerGenericKey = try? Securemessage_GenericPublicKey(serializedBytes: trustedCert.publicKey),
let authKeyData = self.authKey?.data() {
log("[InboundNearbyConnection \(self.id)] Found trusted certificate for secretIDHash: \(pkeFrame.secretIDHash.hex)")
let domain = Domain.instance(curve: .EC256r1)
let ecKey = peerGenericKey.ecP256PublicKey
let point = Point(BInt(magnitude: [UInt8](ecKey.x)), BInt(magnitude: [UInt8](ecKey.y)))
guard let peerPublicKey = try? ECPublicKey(domain: domain, w: point) else {
log("[InboundNearbyConnection \(self.id)] Paired key auth failed: Invalid peer public key.")
try automaticAuthFailed()
return
}
guard pkeFrame.signedData.count == 72 else {
log("[InboundNearbyConnection \(self.id)] Paired key auth failed: Invalid signature length.")
try automaticAuthFailed()
return
}
// Strip header
let signedData = pkeFrame.signedData.subdata(in: 8..<72)
let r = Array(signedData.prefix(32))
let s = Array(signedData.suffix(32))
let signature = ECSignature(domain: domain, r: r, s: s)
if peerPublicKey.verify(signature: signature, msg: authKeyData) {
log("[InboundNearbyConnection \(self.id)] Paired key authentication successful.")
try sendPairedKeyResult(status: .success)
isAuthenticated = true
} else {
log("[InboundNearbyConnection \(self.id)] Paired key auth failed: Signature verification failed.")
try automaticAuthFailed()
}
} else {
try automaticAuthFailed()
}
func automaticAuthFailed() throws {
// Store certificate of peer to let user device later to trust it
if let peerCertificate = frame.v1.certificateInfo.publicCertificate.first {
log("[InboundNearbyConnection \(self.id)] Storing peer certificate for potential later use")
self.peerCertificate = peerCertificate
}
try sendPairedKeyResult(status: .unable)
}
}
private func sendPairedKeyResult(status: Sharing_Nearby_PairedKeyResultFrame.Status) throws {
var resultFrame = Sharing_Nearby_Frame()
resultFrame.version = .v1
resultFrame.v1.type = .pairedKeyResult
resultFrame.v1.pairedKeyResult.status = status
try sendTransferSetupFrame(resultFrame)
currentState = .sentPairedKeyResult
}
@@ -436,10 +501,8 @@ class InboundNearbyConnection: NearbyConnection {
filesToBeReceived[file.payloadID] = info
bytesToBeTransferred += file.size
}
let metadata = TransferMetadata(files: filesToBeReceived.map { $0.value.meta }, id: id, pinCode: pinCode)
DispatchQueue.main.async {
self.delegate?.obtainUserConsent(transfer: metadata, device: self.remoteDeviceInfo!, connection: self)
}
let metadata = TransferMetadata(files: filesToBeReceived.map { $0.value.meta }, id: id, pinCode: pinCode, allowsToBeAddedAsTrustedDevice: self.peerCertificate != nil)
checkIfCanProceed(metadata: metadata)
}
else if let textMetadata = frame.v1.introduction.textMetadata.first {
@@ -447,16 +510,14 @@ class InboundNearbyConnection: NearbyConnection {
let isClipboardText = textMetadata.type == .text
let metadata = TransferMetadata(files: [], id: id, pinCode: pinCode, textDescription: textMetadata.textTitle, transferType: isClipboardText ? .text : .url)
let metadata = TransferMetadata(files: [], id: id, pinCode: pinCode, textDescription: textMetadata.textTitle, transferType: isClipboardText ? .text : .url, allowsToBeAddedAsTrustedDevice: self.peerCertificate != nil)
textPayloadID = textMetadata.payloadID
if isClipboardText {
isPlainTextTransfer = true
}
DispatchQueue.main.async {
self.delegate?.obtainUserConsent(transfer: metadata, device: self.remoteDeviceInfo!, connection: self)
}
checkIfCanProceed(metadata: metadata)
}
else {
rejectDueToUnsupportedFileType(frame)
@@ -464,6 +525,16 @@ class InboundNearbyConnection: NearbyConnection {
} else {
rejectDueToUnsupportedFileType(frame)
}
func checkIfCanProceed(metadata: TransferMetadata) {
let acceptAutomatically = isAuthenticated || UserDefaults.standard.bool(forKey: UserDefaultsKeys.automaticallyAcceptFiles.rawValue)
DispatchQueue.main.async {
self.delegate?.obtainUserConsent(transfer: metadata, device: self.remoteDeviceInfo!, connection: self, acceptAutomatically: acceptAutomatically)
}
}
}
@@ -476,7 +547,12 @@ class InboundNearbyConnection: NearbyConnection {
}
func submitUserConsent(accepted: Bool, storeInTemp: Bool = false) {
func submitUserConsent(accepted: Bool, trustDevice: Bool, storeInTemp: Bool = false) {
if trustDevice, let peerCertificate = peerCertificate {
TrustStore.shared.addTrusted(certificate: peerCertificate)
}
DispatchQueue.global(qos: .utility).async {
if accepted {
self.acceptTransfer(storeInTemp: storeInTemp)
@@ -154,8 +154,8 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
}
func obtainUserConsent(transfer: TransferMetadata, device: RemoteDeviceInfo, connection _: InboundNearbyConnection) {
mainAppDelegate?.obtainUserConsent(transfer: transfer, device: device)
func obtainUserConsent(transfer: TransferMetadata, device: RemoteDeviceInfo, connection _: InboundNearbyConnection, acceptAutomatically: Bool) {
mainAppDelegate?.obtainUserConsent(transfer: transfer, device: device, acceptAutomatically: acceptAutomatically)
}
@@ -173,11 +173,11 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
}
public func submitUserConsent(transferID: String, accept: Bool, storeInTemp: Bool = false) {
public func submitUserConsent(transferID: String, accept: Bool, trustDevice: Bool, storeInTemp: Bool = false) {
guard let conn = incomingConnections[transferID] else { return }
log("[NearbyConnectionManager] Submitting user consent for transfer \(transferID), accepted: \(accept), store in temp: \(storeInTemp)")
conn.submitUserConsent(accepted: accept, storeInTemp: storeInTemp)
conn.submitUserConsent(accepted: accept, trustDevice: trustDevice, storeInTemp: storeInTemp)
}
@@ -271,11 +271,40 @@ class OutboundNearbyConnection: NearbyConnection {
var pairedEncryption = Sharing_Nearby_Frame()
pairedEncryption.version = .v1
pairedEncryption.v1 = Sharing_Nearby_V1Frame()
pairedEncryption.v1.type = .pairedKeyEncryption
pairedEncryption.v1.pairedKeyEncryption = Sharing_Nearby_PairedKeyEncryptionFrame()
pairedEncryption.v1.pairedKeyEncryption.secretIDHash = Data.randomData(length: 6)
pairedEncryption.v1.pairedKeyEncryption.signedData = Data.randomData(length: 72)
// add public key
var cert = Sharing_Nearby_PublicCertificate()
if let signingPrivateKey = IdentityManager.shared.getPrivateKey(),
let publicKey = IdentityManager.shared.getPublicKey()?.toGenericPublicKey(),
let publicKeyData = IdentityManager.shared.getPublicKey()?.toGenericPublicKeyData(),
let publicKeyId = publicKey.id(),
let authKeyData = self.authKey?.data() {
log("[OutboundNearbyConnection \(self.id)] Using private key for signing")
cert.secretID = publicKeyId
cert.publicKey = publicKeyData
let signatureTuple = signingPrivateKey.sign(msg: authKeyData)
let rBytes = signatureTuple.r
let sBytes = signatureTuple.s
// Make sure r and s are 32 bytes each by padding with leading zeros if necessary
let paddedR = Data(repeating: 0, count: 32 - rBytes.count) + rBytes
let paddedS = Data(repeating: 0, count: 32 - sBytes.count) + sBytes
// Signature: Header (8 bytes) + r (32 bytes) + s (32 bytes)
let signatureData = Data(repeating: 0, count: 8) + paddedR + paddedS
pairedEncryption.v1.certificateInfo.publicCertificate.append(cert)
pairedEncryption.v1.pairedKeyEncryption.signedData = signatureData
pairedEncryption.v1.pairedKeyEncryption.secretIDHash = cert.secretID
pairedEncryption.v1.pairedKeyResult.status = .success
}
if let qrKey = qrCodePrivateKey, let authKey = authKey {
let signature = qrKey.sign(msg: authKey.data())
@@ -298,6 +327,7 @@ class OutboundNearbyConnection: NearbyConnection {
pairedResult.v1.type = .pairedKeyResult
pairedResult.v1.pairedKeyResult = Sharing_Nearby_PairedKeyResultFrame()
pairedResult.v1.pairedKeyResult.status = .unable
try sendTransferSetupFrame(pairedResult)
currentState = .sentPairedKeyResult
}
@@ -375,8 +405,7 @@ class OutboundNearbyConnection: NearbyConnection {
if let textToSend = textToSend {
try sendText(text: textToSend)
}
if hasURL() {
} else if hasURL() {
try sendURL()
} else {
try sendNextFileChunk()
+5 -3
View File
@@ -12,7 +12,7 @@ import SwiftECC
protocol InboundNearbyConnectionDelegate {
func obtainUserConsent(transfer: TransferMetadata, device: RemoteDeviceInfo, connection: InboundNearbyConnection)
func obtainUserConsent(transfer: TransferMetadata, device: RemoteDeviceInfo, connection: InboundNearbyConnection, acceptAutomatically: Bool)
func updatedTransferProgress(connection: InboundNearbyConnection, progress: Double)
func connectionWasTerminated(connection: InboundNearbyConnection, error: Error?)
}
@@ -28,7 +28,7 @@ protocol OutboundNearbyConnectionDelegate {
public protocol InboundAppDelegate: AnyObject {
func obtainUserConsent(transfer: TransferMetadata, device: RemoteDeviceInfo)
func obtainUserConsent(transfer: TransferMetadata, device: RemoteDeviceInfo, acceptAutomatically: Bool)
func connectionWasTerminated(from device: RemoteDeviceInfo, wasPlainTextTransfer: Bool, error: Error?)
func transferProgress(progress: Double)
}
@@ -107,13 +107,15 @@ public struct TransferMetadata {
public let pinCode: String?
public let textDescription: String?
public let type: TransferType
public let allowsToBeAddedAsTrustedDevice: Bool
init(files: [FileMetadata], id: String, pinCode: String?, textDescription: String? = nil, transferType: TransferType = .file) {
init(files: [FileMetadata], id: String, pinCode: String?, textDescription: String? = nil, transferType: TransferType = .file, allowsToBeAddedAsTrustedDevice: Bool) {
self.files = files
self.id = id
self.pinCode = pinCode
self.textDescription = textDescription
self.type = transferType
self.allowsToBeAddedAsTrustedDevice = allowsToBeAddedAsTrustedDevice
}
public enum TransferType {
+21
View File
@@ -0,0 +1,21 @@
//
// AppGroup.swift
// QuickDrop
//
// Created by Leon Böttger on 23.08.25.
//
import Foundation
/// Contains information about the app group used to share data between main app and widget
struct AppGroup {
/// Identifier of the app group
static let appGroupName = "group.com.leonboettger.neardrop"
static let appGroupUD = UserDefaults(suiteName: AppGroup.appGroupName)!
/// Returns the shared App Group directory
static var appGroupDirectory: URL? {
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupName)
}
}
+119
View File
@@ -0,0 +1,119 @@
//
// IdentityManager.swift
// QuickDrop
//
// Created by Leon Böttger on 22.08.25.
//
import Foundation
import SwiftECC
import Security
import CryptoKit
class IdentityManager {
static let shared = IdentityManager()
private let signingKeyTag = "com.leonboettger.quickdrop.identity.signingkey"
private var signingPrivateKey: ECPrivateKey?
private var signingPublicKey: ECPublicKey?
private init() {
if let (privateKey, publicKey) = loadKeys() {
log("[IdentityManager] Loaded existing private key.")
self.signingPrivateKey = privateKey
self.signingPublicKey = publicKey
}
else {
log("[IdentityManager] No existing private key found, generating a new one.")
let (newPrivate, newPublic) = generateAndStoreKeyPair()
self.signingPrivateKey = newPrivate
self.signingPublicKey = newPublic
}
}
func getPrivateKey() -> ECPrivateKey? {
return signingPrivateKey
}
func getPublicKey() -> ECPublicKey? {
return signingPublicKey
}
private func generateAndStoreKeyPair() -> (ECPrivateKey, ECPublicKey) {
let domain = Domain.instance(curve: .EC256r1)
let (pubKey, privKey) = domain.makeKeyPair()
AppGroup.appGroupUD.set(Data(privKey.s.asSignedBytes()), forKey: signingKeyTag)
return (privKey, pubKey)
}
private func loadKeys() -> (ECPrivateKey, ECPublicKey)? {
let keyData = AppGroup.appGroupUD.data(forKey: signingKeyTag)
guard let keyData = keyData else { return nil }
let domain = Domain.instance(curve: .EC256r1)
guard let privateKey = try? ECPrivateKey(domain: domain, s: .init(signed: Array(keyData))) else {
log("[IdentityManager] Failed to reconstruct private key from stored data.")
return nil
}
guard let pubPoint = try? domain.multiplyPoint(domain.g, privateKey.s) else {
log("[IdentityManager] Failed to derive public key from private key.")
return nil
}
guard let publicKey = try? ECPublicKey(domain: domain, w: pubPoint) else {
log("[IdentityManager] Failed to reconstruct public key.")
return nil
}
return (privateKey, publicKey)
}
}
extension ECPublicKey {
func toGenericPublicKey() -> Securemessage_GenericPublicKey {
var genericKey = Securemessage_GenericPublicKey()
genericKey.type = .ecP256
genericKey.ecP256PublicKey = Securemessage_EcP256PublicKey()
genericKey.ecP256PublicKey.x = Data(self.w.x.asSignedBytes())
genericKey.ecP256PublicKey.y = Data(self.w.y.asSignedBytes())
return genericKey
}
func toGenericPublicKeyData() -> Data? {
let genericKey = self.toGenericPublicKey()
return try? genericKey.serializedData()
}
}
extension Securemessage_GenericPublicKey {
func id() -> Data? {
var hasher = SHA256()
guard let data = try? self.serializedData() else {
return nil
}
hasher.update(data: data)
let hash = hasher.finalize()
return Data(hash).prefix(6)
}
}
+2 -9
View File
@@ -25,7 +25,7 @@ final class LogManager {
/// Private initializer
private init() {
// Use the App Group container
let directory = getAppGroupDirectory()
let directory = AppGroup.appGroupDirectory
// Create file name from date
let formatter = DateFormatter()
@@ -89,7 +89,7 @@ final class LogManager {
func deleteLogs() {
log("[LUI] Deleting all logs...")
guard let directory = getAppGroupDirectory() else { return }
guard let directory = AppGroup.appGroupDirectory else { return }
let fileManager = FileManager.default
guard let allFiles = try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) else {
@@ -124,10 +124,3 @@ public func log(_ text: String) {
}
}
}
/// Returns the shared App Group directory
func getAppGroupDirectory() -> URL? {
let groupIdentifier = "group.com.leonboettger.neardrop"
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)
}
+33
View File
@@ -0,0 +1,33 @@
//
// TrustStore.swift
// QuickDrop
//
// Created by Leon Böttger on 22.08.25.
//
import Foundation
class TrustStore {
static let shared = TrustStore()
private let trustedKeysKey = "com.leonboettger.quickdrop.identity.trustedKeys"
private func getTrustedKeys() -> [String: Data] {
return AppGroup.appGroupUD.dictionary(forKey: trustedKeysKey) as? [String: Data] ?? [:]
}
func findTrustedKey(for secretIdHash: Data) -> Data? {
return getTrustedKeys()[secretIdHash.hex]
}
func addTrusted(certificate: Sharing_Nearby_PublicCertificate) {
guard let publicKeyData = try? certificate.serializedData() else { return }
var keys = getTrustedKeys()
keys[certificate.secretID.hex] = publicKeyData
AppGroup.appGroupUD.set(keys, forKey: trustedKeysKey)
}
}