Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read passport via bacHash #115

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 37 additions & 9 deletions Sources/NFCPassportReader/BACHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,26 +32,44 @@ public class BACHandler {
public init(tagReader: TagReader) {
self.tagReader = tagReader
}

public func performBACAndGetSessionKeys( mrzKey : String, completed: @escaping (_ error : NFCPassportReaderError?)->() ) {
guard let tagReader = self.tagReader else {
completed( NFCPassportReaderError.NoConnectedTag)
completed(.NoConnectedTag)
return
}

Log.debug( "BACHandler - deriving Document Basic Access Keys" )
do {
_ = try self.deriveDocumentBasicAccessKeys(mrz: mrzKey)
} catch {
Log.error( "ERROR - \(error.localizedDescription)" )
completed( NFCPassportReaderError.InvalidDataPassed("Unable to derive BAC Keys - \(error.localizedDescription)") )
_ = try? self.deriveDocumentBasicAccessKeys(mrz: mrzKey)

// Make sure we clear secure messaging (could happen if we read an invalid DG or we hit a secure error
tagReader.secureMessaging = nil

// get Challenge
getChallenge(completed: completed)
}

public func performBACAndGetSessionKeys( bacHash : [UInt8], completed: @escaping (_ error : NFCPassportReaderError?)->() ) {
guard let tagReader = self.tagReader else {
completed(.NoConnectedTag)
return

}

_ = try? deriveDocumentBasicAccessKeys(bacHash: bacHash)

// Make sure we clear secure messaging (could happen if we read an invalid DG or we hit a secure error
tagReader.secureMessaging = nil

// get Challenge
getChallenge(completed: completed)
}

private func getChallenge(completed: @escaping (_ error : NFCPassportReaderError?)->() ) {

guard let tagReader = self.tagReader else {
completed( NFCPassportReaderError.NoConnectedTag)
return
}

// get Challenge
Log.debug( "BACHandler - Getting initial challenge" )
tagReader.getChallenge() { [unowned self] (response, error) in
Expand Down Expand Up @@ -98,6 +116,16 @@ public class BACHandler {
return (ksenc, ksmac)
}

func deriveDocumentBasicAccessKeys(bacHash: [UInt8]) throws -> ([UInt8], [UInt8]) {

let kseed = Array(bacHash[0..<16])
let smskg = SecureMessagingSessionKeyGenerator()
self.ksenc = try smskg.deriveKey(keySeed: kseed, mode: .ENC_MODE)
self.ksmac = try smskg.deriveKey(keySeed: kseed, mode: .MAC_MODE)

return (ksenc, ksmac)
}

///
/// Calculate the kseed from the kmrz:
/// - Calculate a SHA-1 hash of the kmrz
Expand Down
33 changes: 30 additions & 3 deletions Sources/NFCPassportReader/PACEHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ private enum PACEHandlerError {
switch self {
case .DHKeyAgreementError(let errMsg): return errMsg
case .ECDHKeyAgreementError(let errMsg): return errMsg

}
}
}
Expand Down Expand Up @@ -61,6 +60,9 @@ public class PACEHandler {
private var digestAlg : String = ""
private var keyLength : Int = -1

private var mrzKey: String?
private var bacHash: [UInt8]?

public init(cardAccess : CardAccess, tagReader: TagReader) throws {
self.tagReader = tagReader

Expand All @@ -72,7 +74,18 @@ public class PACEHandler {
isPACESupported = true
}

public func doPACE( mrzKey : String, completed: @escaping (Bool)->() ) {
public func doPace(mrzKey: String, completed: @escaping (Bool)->()) {

self.mrzKey = mrzKey
doPACE(completed: completed)
}

public func doPace(bacHash: [UInt8], completed: @escaping (Bool)->()) {
self.bacHash = bacHash
doPACE(completed: completed)
}

private func doPACE(completed: @escaping (Bool)->() ) {
guard isPACESupported else {
completed( false )
return
Expand All @@ -93,7 +106,12 @@ public class PACEHandler {
keyLength = try paceInfo.getKeyLength() // Get key length the enc cipher. Either 128, 192, or 256.

paceKeyType = PACEHandler.MRZ_PACE_KEY_REFERENCE
paceKey = try createPaceKey( from: mrzKey )

if let mrzKey = mrzKey {
paceKey = try createPaceKey( from: mrzKey )
} else if let bacHash = bacHash {
paceKey = try createPaceKey(from: bacHash)
}

// Temporary logging
Log.verbose("doPace - inpit parameters" )
Expand Down Expand Up @@ -642,6 +660,15 @@ extension PACEHandler {
return key
}

func createPaceKey( from bacHash: [UInt8] ) throws -> [UInt8] {
//let buf: [UInt8] = bacHash//Array(bacHash[0..<16])
let hash = bacHash//Array(bacHash[0..<16])//calcSHA1Hash(bacHash)

let smskg = SecureMessagingSessionKeyGenerator()
let key = try smskg.deriveKey(keySeed: hash, cipherAlgName: cipherAlg, keyLength: keyLength, nonce: nil, mode: .PACE_MODE, paceKeyReference: paceKeyType)
return key
}

/// Performs the ECDH PACE GM key agreement protocol by multiplying a private key with a public key
/// - Parameters:
/// - key: an EVP_PKEY structure containng a ECDH private key
Expand Down
61 changes: 48 additions & 13 deletions Sources/NFCPassportReader/PassportReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ public class PassportReader : NSObject {
private var bacHandler : BACHandler?
private var caHandler : ChipAuthenticationHandler?
private var paceHandler : PACEHandler?
private var mrzKey : String = ""
private var mrzKey : String?
private var bacHash : [UInt8]?
private var dataAmountToReadOverride : Int? = nil

private var scanCompletedHandler: ((NFCPassportModel?, NFCPassportReaderError?)->())!
Expand Down Expand Up @@ -59,10 +60,22 @@ public class PassportReader : NSObject {
public func overrideNFCDataAmountToRead( amount: Int ) {
dataAmountToReadOverride = amount
}

public func readPassport( bacHash : [UInt8], tags: [DataGroupId] = [], skipSecureElements :Bool = true, customDisplayMessage: ((NFCViewDisplayMessage) -> String?)? = nil, completed: @escaping (NFCPassportModel?, NFCPassportReaderError?)->()) {

self.bacHash = bacHash
readPassport(tags: tags, skipSecureElements: skipSecureElements, customDisplayMessage: customDisplayMessage, completed: completed)
}

public func readPassport( mrzKey : String, tags: [DataGroupId] = [], skipSecureElements :Bool = true, customDisplayMessage: ((NFCViewDisplayMessage) -> String?)? = nil, completed: @escaping (NFCPassportModel?, NFCPassportReaderError?)->()) {

public func readPassport( mrzKey : String, tags: [DataGroupId] = [], skipSecureElements :Bool = true, skipCA : Bool = false, skipPACE: Bool = false, customDisplayMessage: ((NFCViewDisplayMessage) -> String?)? = nil, completed: @escaping (NFCPassportModel?, NFCPassportReaderError?)->()) {
self.passport = NFCPassportModel()
self.mrzKey = mrzKey
readPassport(tags: tags, skipSecureElements: skipSecureElements, customDisplayMessage: customDisplayMessage, completed: completed)
}

private func readPassport(tags: [DataGroupId] = [], skipSecureElements :Bool = true, skipCA : Bool = true, skipPACE: Bool = false, customDisplayMessage: ((NFCViewDisplayMessage) -> String?)? = nil, completed: @escaping (NFCPassportModel?, NFCPassportReaderError?)->()) {
self.passport = NFCPassportModel()
//self.mrzKey = mrzKey
self.skipCA = skipCA
self.skipPACE = skipPACE

Expand Down Expand Up @@ -356,9 +369,17 @@ extension PassportReader {
Log.info( "Starting Basic Access Control (BAC)" )

self.bacHandler = BACHandler( tagReader: tagReader )
bacHandler?.performBACAndGetSessionKeys( mrzKey: mrzKey ) { error in
self.bacHandler = nil
completed(error)
if let bacHash = bacHash {
bacHandler?.performBACAndGetSessionKeys( bacHash: bacHash ) { error in
self.bacHandler = nil
completed(error)
}
}
else if let mrzKey = mrzKey {
bacHandler?.performBACAndGetSessionKeys( mrzKey: mrzKey ) { error in
self.bacHandler = nil
completed(error)
}
}
}

Expand All @@ -372,14 +393,28 @@ extension PassportReader {

do {
self.paceHandler = try PACEHandler( cardAccess: cardAccess, tagReader: tagReader )
paceHandler?.doPACE(mrzKey: mrzKey ) { paceSucceeded in
if paceSucceeded {
completed(nil)
} else {
self.paceHandler = nil
completed(NFCPassportReaderError.InvalidDataPassed("PACE Failed"))
}

if let mrzKey = self.mrzKey {
paceHandler?.doPace(mrzKey: mrzKey, completed: { paceSucceeded in

if paceSucceeded {
completed(nil)
} else {
self.paceHandler = nil
completed(NFCPassportReaderError.InvalidDataPassed("PACE Failed"))
}
})
} else if let bacHash = self.bacHash {
paceHandler?.doPace(bacHash: bacHash, completed: { paceSucceeded in
if paceSucceeded {
completed(nil)
} else {
self.paceHandler = nil
completed(NFCPassportReaderError.InvalidDataPassed("PACE Failed"))
}
})
}

} catch let error as NFCPassportReaderError {
completed( error )
} catch {
Expand Down