keyple-card-calypso-crypto-legacysam-cpp-lib - 1.0.2
Component of the Keyple C++ middleware
SymmetricCryptoCardTransactionManagerAdapter.cpp
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (c) 2019 Calypso Networks Association https://calypsonet.org/ *
3 * *
4 * See the NOTICE file(s) distributed with this work for additional *
5 * information regarding copyright ownership. *
6 * *
7 * This program and the accompanying materials are made available under the *
8 * terms of the Eclipse Public License 2.0 which is available at *
9 * http://www.eclipse.org/legal/epl-2.0 *
10 * *
11 * SPDX-License-Identifier: EPL-2.0 *
12 ******************************************************************************/
13
14#include "keyple/card/calypso/crypto/legacysam/SymmetricCryptoCardTransactionManagerAdapter.hpp"
15
16#include <memory>
17#include <string>
18#include <typeinfo>
19#include <utility>
20#include <vector>
21
22#include "keyple/card/calypso/crypto/legacysam/CardTransactionUtil.hpp"
23#include "keyple/card/calypso/crypto/legacysam/CommandCardCipherPin.hpp"
24#include "keyple/card/calypso/crypto/legacysam/CommandCardGenerateKey.hpp"
25#include "keyple/card/calypso/crypto/legacysam/CommandDataCipher.hpp"
26#include "keyple/card/calypso/crypto/legacysam/CommandDigestAuthenticate.hpp"
27#include "keyple/card/calypso/crypto/legacysam/CommandDigestClose.hpp"
28#include "keyple/card/calypso/crypto/legacysam/CommandDigestInit.hpp"
29#include "keyple/card/calypso/crypto/legacysam/CommandDigestInternalAuthenticate.hpp"
30#include "keyple/card/calypso/crypto/legacysam/CommandDigestUpdateMultiple.hpp"
31#include "keyple/card/calypso/crypto/legacysam/CommandGetChallenge.hpp"
32#include "keyple/card/calypso/crypto/legacysam/CommandGiveRandom.hpp"
33#include "keyple/card/calypso/crypto/legacysam/CommandPsoComputeSignature.hpp"
34#include "keyple/card/calypso/crypto/legacysam/CommandPsoVerifySignature.hpp"
35#include "keyple/card/calypso/crypto/legacysam/CommandSelectDiversifier.hpp"
36#include "keyple/card/calypso/crypto/legacysam/CommandSvCheck.hpp"
37#include "keyple/card/calypso/crypto/legacysam/CommandSvPrepareDebitOrUndebit.hpp"
38#include "keyple/card/calypso/crypto/legacysam/CommandSvPrepareLoad.hpp"
39#include "keyple/card/calypso/crypto/legacysam/DtoAdapters.hpp"
40#include "keyple/card/calypso/crypto/legacysam/SecurityDataException.hpp"
41#include "keyple/core/util/ApduUtil.hpp"
42#include "keyple/core/util/ByteArrayUtil.hpp"
43#include "keyple/core/util/HexUtil.hpp"
44#include "keyple/core/util/KeypleAssert.hpp"
45#include "keyple/core/util/cpp/Arrays.hpp"
46#include "keyple/core/util/cpp/System.hpp"
47#include "keyple/core/util/cpp/exception/IllegalStateException.hpp"
48#include "keypop/calypso/card/transaction/InconsistentDataException.hpp"
49#include "keypop/calypso/crypto/legacysam/transaction/InvalidSignatureException.hpp"
50#include "keypop/calypso/crypto/legacysam/transaction/SamRevokedException.hpp"
51#include "keypop/calypso/crypto/legacysam/transaction/SignatureComputationDataBase.hpp"
52#include "keypop/calypso/crypto/symmetric/SymmetricCryptoException.hpp"
53#include "keypop/reader/InvalidCardResponseException.hpp"
54
55namespace keyple {
56namespace card {
57namespace calypso {
58namespace crypto {
59namespace legacysam {
60
61using keyple::core::util::ApduUtil;
62using keyple::core::util::Assert;
63using keyple::core::util::ByteArrayUtil;
64using keyple::core::util::HexUtil;
65using keyple::core::util::cpp::Arrays;
66using keyple::core::util::cpp::System;
67using keyple::core::util::cpp::exception::IllegalStateException;
68using keypop::calypso::card::transaction::InconsistentDataException;
69using keypop::calypso::crypto::legacysam::transaction::
70 InvalidSignatureException;
71using keypop::calypso::crypto::legacysam::transaction::SamRevokedException;
72using keypop::calypso::crypto::legacysam::transaction::
73 SignatureComputationDataBase;
74using keypop::calypso::crypto::symmetric::SymmetricCryptoException;
75using keypop::reader::InvalidCardResponseException;
76
79
80const std::string
81 SymmetricCryptoCardTransactionManagerAdapter::MSG_SAM_INCONSISTENT_DATA
82 = "The number of commands/responses does not match. Expected ";
83const std::string
84 SymmetricCryptoCardTransactionManagerAdapter::MSG_SAM_NB_RESPONSES
85 = " responses, got ";
86const std::string
87 SymmetricCryptoCardTransactionManagerAdapter::MSG_INPUT_OUTPUT_DATA
88 = "input/output data";
89const std::string
90 SymmetricCryptoCardTransactionManagerAdapter::MSG_SIGNATURE_SIZE
91 = "signature size";
92const std::string SymmetricCryptoCardTransactionManagerAdapter ::
93 MSG_KEY_DIVERSIFIER_SIZE_IS_IN_RANGE_1_8
94 = "key diversifier size is in range [1..8]";
95
96SymmetricCryptoCardTransactionManagerAdapter::
97 SymmetricCryptoCardTransactionManagerAdapter(
98 std::shared_ptr<ProxyReaderApi> samReader,
99 std::shared_ptr<LegacySamAdapter> sam,
100 const std::vector<uint8_t>& cardKeyDiversifier,
101 bool useExtendedMode,
102 int maxCardApduLengthSupported,
103 const std::vector<std::vector<uint8_t>>& transactionAuditData)
104: mSamReader(samReader)
105, mSam(sam)
106, mCardKeyDiversifier(cardKeyDiversifier)
107, mIsExtendedModeRequired(useExtendedMode)
108, mMaxCardApduLengthSupported(maxCardApduLengthSupported)
109, mTransactionAuditData(transactionAuditData)
110{
111}
112
113std::shared_ptr<DtoAdapters::CommandContextDto>
114SymmetricCryptoCardTransactionManagerAdapter::getContext()
115{
116 return std::make_shared<DtoAdapters::CommandContextDto>(
117 mSam, nullptr, nullptr);
118}
119
120std::vector<uint8_t>
121SymmetricCryptoCardTransactionManagerAdapter::initTerminalSecureSessionContext()
122{
123 if (isSelectDiversifierNeeded(mCardKeyDiversifier)) {
124 mIsSelectDiversifierNeededOnDigestInit = true;
125 }
126
127 std::vector<uint8_t> challenge = mSam->popChallenge();
128 if (challenge.empty()) {
129 auto cmd = std::make_shared<CommandGetChallenge>(
130 getContext(), mIsExtendedModeRequired ? 8 : 4);
131 mSamCommands.push_back(cmd);
132 processCommands();
133 return mSam->popChallenge();
134
135 } else {
136 return mIsExtendedModeRequired ? challenge
137 : Arrays::copyOf(challenge, 4);
138 }
139}
140
141void
142SymmetricCryptoCardTransactionManagerAdapter::initTerminalSessionMac(
143 const std::vector<uint8_t>& openSecureSessionDataOut,
144 uint8_t kif,
145 uint8_t kvc)
146{
147 mDigestManager = std::make_shared<DigestManager>(
148 this, openSecureSessionDataOut, kif, kvc);
149}
150
151std::vector<uint8_t>
152SymmetricCryptoCardTransactionManagerAdapter::updateTerminalSessionMac(
153 const std::vector<uint8_t>& cardApdu)
154{
155 if (mIsEncryptionActive) {
156 /*
157 * Encrypted mode.
158 * We first prepare any pending plain-text commands in order to optimize
159 * the possible groupings.
160 */
161 mDigestManager->prepareCommands();
162
163 /* We then prepare the command for encryption. */
164 auto samCommand = mDigestManager->prepareCommandForEncryption(cardApdu);
165
166 /* Process commands. */
167 processCommands();
168
169 /* Return the encrypted/decrypted value. */
170 return samCommand->getProcessedData();
171
172 } else {
173 /* Plain mode. */
174 mDigestManager->updateSession(cardApdu);
175 return {};
176 }
177}
178
179std::vector<uint8_t>
180SymmetricCryptoCardTransactionManagerAdapter::finalizeTerminalSessionMac()
181{
182 mDigestManager->prepareAllCommands();
183 mDigestManager.reset();
184
185 auto cmdSamDigestClose = std::dynamic_pointer_cast<CommandDigestClose>(
186 mSamCommands[mSamCommands.size() - 1]);
187
188 processCommands();
189
190 return cmdSamDigestClose->getMac();
191}
192
193std::vector<uint8_t>
194SymmetricCryptoCardTransactionManagerAdapter::generateTerminalSessionMac()
195{
196 /*
197 * We first prepare any pending commands in order to optimize the possible
198 * groupings.
199 */
200 mDigestManager->prepareCommands();
201
202 /* Then we prepare the "Digest Internal Authenticate" command. */
203 auto cmdSamDigestInternalAuthenticate
204 = std::make_shared<CommandDigestInternalAuthenticate>(getContext());
205 mSamCommands.push_back(cmdSamDigestInternalAuthenticate);
206
207 /* Process commands. */
208 processCommands();
209
210 /* Return the terminal session MAC. */
211 return cmdSamDigestInternalAuthenticate->getTerminalSignature();
212}
213
214void
215SymmetricCryptoCardTransactionManagerAdapter::activateEncryption()
216{
217 mIsEncryptionActive = true;
218}
219
220void
221SymmetricCryptoCardTransactionManagerAdapter::deactivateEncryption()
222{
223 mIsEncryptionActive = false;
224}
225
226bool
227SymmetricCryptoCardTransactionManagerAdapter::isCardSessionMacValid(
228 const std::vector<uint8_t>& cardSessionMac)
229{
230 mSamCommands.push_back(
231 std::make_shared<CommandDigestAuthenticate>(
232 getContext(), cardSessionMac));
233 try {
234 processCommands();
235 return true;
236
237 } catch (const InvalidCardMacException&) {
238 return false;
239 }
240}
241
242void
243SymmetricCryptoCardTransactionManagerAdapter::computeSvCommandSecurityData(
244 std::shared_ptr<SvCommandSecurityDataApi> svCommandSecurityData)
245{
246 prepareSelectDiversifierIfNeeded();
247 if ((svCommandSecurityData->getSvCommandPartialRequest())[0] == 0xB8) {
248 mSamCommands.push_back(
249 std::make_shared<CommandSvPrepareLoad>(
250 getContext(), svCommandSecurityData));
251 } else {
252 mSamCommands.push_back(
253 std::make_shared<CommandSvPrepareDebitOrUndebit>(
254 getContext(), svCommandSecurityData));
255 }
256 processCommands();
257}
258
259bool
260SymmetricCryptoCardTransactionManagerAdapter::isCardSvMacValid(
261 const std::vector<uint8_t>& cardSvMac)
262{
263 mSamCommands.push_back(
264 std::make_shared<CommandSvCheck>(getContext(), cardSvMac));
265 try {
266 processCommands();
267 return true;
268
269 } catch (const InvalidCardMacException&) {
270 return false;
271 }
272}
273
274std::vector<uint8_t>
275SymmetricCryptoCardTransactionManagerAdapter::cipherPinForPresentation(
276 const std::vector<uint8_t>& cardChallenge,
277 const std::vector<uint8_t>& pin,
278 const std::shared_ptr<uint8_t> kif,
279 const std::shared_ptr<uint8_t> kvc)
280{
281 return cipherPin(cardChallenge, pin, {}, kif, kvc);
282}
283
284std::vector<uint8_t>
285SymmetricCryptoCardTransactionManagerAdapter::cipherPinForModification(
286 const std::vector<uint8_t>& cardChallenge,
287 const std::vector<uint8_t>& currentPin,
288 const std::vector<uint8_t>& newPin,
289 const std::shared_ptr<uint8_t> kif,
290 const std::shared_ptr<uint8_t> kvc)
291{
292 return cipherPin(cardChallenge, currentPin, newPin, kif, kvc);
293}
294
295std::vector<uint8_t>
296SymmetricCryptoCardTransactionManagerAdapter::generateCipheredCardKey(
297 const std::vector<uint8_t>& cardChallenge,
298 uint8_t issuerKeyKif,
299 uint8_t issuerKeyKvc,
300 uint8_t targetKeyKif,
301 uint8_t targetKeyKvc)
302{
303 prepareGiveRandom(cardChallenge);
304 auto cmd = std::make_shared<CommandCardGenerateKey>(
305 getContext(), issuerKeyKif, issuerKeyKvc, targetKeyKif, targetKeyKvc);
306 mSamCommands.push_back(cmd);
307 processCommands();
308 return cmd->getCipheredData();
309}
310
311void
312SymmetricCryptoCardTransactionManagerAdapter::synchronize()
313{
314 processCommands();
315}
316
317CardTransactionLegacySamExtension&
318SymmetricCryptoCardTransactionManagerAdapter::prepareComputeSignature(
319 std::shared_ptr<SignatureComputationDataBase> data)
320{
321 std::shared_ptr<DtoAdapters::BasicSignatureComputationDataAdapter>
322 basicDataAdapter = std::dynamic_pointer_cast<
324 if (basicDataAdapter) {
325 /* Basic signature */
326 Assert::getInstance()
327 .notNull(basicDataAdapter, MSG_INPUT_OUTPUT_DATA)
328 .isInRange(
329 basicDataAdapter->getData().size(),
330 1,
331 208,
332 "length of data to sign")
333 .isTrue(
334 basicDataAdapter->getData().size() % 8 == 0,
335 "length of data to sign is a multiple of 8")
336 .isInRange(
337 basicDataAdapter->getSignatureSize(), 1, 8, MSG_SIGNATURE_SIZE)
338 .isTrue(
339 basicDataAdapter->getKeyDiversifier().empty()
340 || (basicDataAdapter->getKeyDiversifier().size() >= 1
341 && basicDataAdapter->getKeyDiversifier().size() <= 8),
342 MSG_KEY_DIVERSIFIER_SIZE_IS_IN_RANGE_1_8);
343
344 prepareSelectDiversifierIfNeeded(basicDataAdapter->getKeyDiversifier());
345 mSamCommands.push_back(
346 std::make_shared<CommandDataCipher>(
347 getContext(), basicDataAdapter, nullptr));
348
349 } else {
350 std::shared_ptr<DtoAdapters::TraceableSignatureComputationDataAdapter>
351 traceableDataAdapter = std::dynamic_pointer_cast<
353 if (traceableDataAdapter) {
354 /* Traceable signature */
355 const bool isTracebilityOffsetInRage
356 = !traceableDataAdapter->isSamTraceabilityMode()
357 || (traceableDataAdapter->getTraceabilityOffset() >= 0
358 && traceableDataAdapter->getTraceabilityOffset()
359 <= static_cast<int>(
360 ((traceableDataAdapter->getData().size() * 8)
361 - (traceableDataAdapter
362 ->getSamTraceabilityMode()
363 == SamTraceabilityMode::
364 TRUNCATED_SERIAL_NUMBER
365 ? 7 * 8
366 : 8 * 8))));
367 core::util::Assert::getInstance()
368 .notNull(traceableDataAdapter, MSG_INPUT_OUTPUT_DATA)
369 .isInRange(
370 traceableDataAdapter->getData().size(),
371 1,
372 traceableDataAdapter->isSamTraceabilityMode() ? 206 : 208,
373 "length of data to sign")
374 .isInRange(
375 traceableDataAdapter->getSignatureSize(),
376 1,
377 8,
378 MSG_SIGNATURE_SIZE)
379 .isTrue(
380 isTracebilityOffsetInRage,
381 "traceability offset is in range")
382 .isTrue(
383 traceableDataAdapter->getKeyDiversifier().empty()
384 || (traceableDataAdapter->getKeyDiversifier().size()
385 >= 1
386 && traceableDataAdapter->getKeyDiversifier().size()
387 <= 8),
388 MSG_KEY_DIVERSIFIER_SIZE_IS_IN_RANGE_1_8);
389
390 prepareSelectDiversifierIfNeeded(
391 traceableDataAdapter->getKeyDiversifier());
392 mSamCommands.push_back(
393 std::make_shared<CommandPsoComputeSignature>(
394 getContext(), traceableDataAdapter));
395
396 } else {
397 const SignatureComputationDataBase& dataRef = *data;
398 throw std::invalid_argument(
399 "Cannot cast 'data' to BasicSignatureComputationDataAdapter "
400 "or TraceableSignatureComputationDataAdapter. Actual type: "
401 + std::string(typeid(dataRef).name()));
402 }
403 }
404
405 return *this;
406}
407
408CardTransactionLegacySamExtension&
409SymmetricCryptoCardTransactionManagerAdapter::prepareVerifySignature(
410 std::shared_ptr<SignatureVerificationDataBase> data)
411{
412 std::shared_ptr<DtoAdapters::BasicSignatureVerificationDataAdapter>
413 basicDataAdapter = std::dynamic_pointer_cast<
414 DtoAdapters::BasicSignatureVerificationDataAdapter>(data);
415 if (basicDataAdapter) {
416 /* Basic signature */
417 core::util::Assert::getInstance()
418 .notNull(basicDataAdapter, MSG_INPUT_OUTPUT_DATA)
419 .isInRange(
420 basicDataAdapter->getData().size(),
421 1,
422 208,
423 "length of signed data to verify")
424 .isTrue(
425 basicDataAdapter->getData().size() % 8 == 0,
426 "length of data to verify is a multiple of 8")
427 .isInRange(
428 basicDataAdapter->getSignature().size(),
429 1,
430 8,
431 MSG_SIGNATURE_SIZE)
432 .isTrue(
433 basicDataAdapter->getKeyDiversifier().empty()
434 || (basicDataAdapter->getKeyDiversifier().size() >= 1
435 && basicDataAdapter->getKeyDiversifier().size() <= 8),
436 MSG_KEY_DIVERSIFIER_SIZE_IS_IN_RANGE_1_8);
437
438 prepareSelectDiversifierIfNeeded(basicDataAdapter->getKeyDiversifier());
439 mSamCommands.push_back(
440 std::make_shared<CommandDataCipher>(
441 getContext(), nullptr, basicDataAdapter));
442
443 } else {
444 std::shared_ptr<DtoAdapters::TraceableSignatureVerificationDataAdapter>
445 traceableDataAdapter = std::dynamic_pointer_cast<
446 DtoAdapters::TraceableSignatureVerificationDataAdapter>(data);
447 if (traceableDataAdapter) {
448 /* Traceable signature */
449 const bool isTracebilityOffsetInRange
450 = !traceableDataAdapter->isSamTraceabilityMode()
451 || (traceableDataAdapter->getTraceabilityOffset() >= 0
452 && traceableDataAdapter->getTraceabilityOffset()
453 <= static_cast<int>(
454 ((traceableDataAdapter->getData().size() * 8)
455 - (traceableDataAdapter
456 ->getSamTraceabilityMode()
457 == SamTraceabilityMode::
458 TRUNCATED_SERIAL_NUMBER
459 ? 7 * 8
460 : 8 * 8))));
461 core::util::Assert::getInstance()
462 .notNull(traceableDataAdapter, MSG_INPUT_OUTPUT_DATA)
463 .isInRange(
464 traceableDataAdapter->getData().size(),
465 1,
466 traceableDataAdapter->isSamTraceabilityMode() ? 206 : 208,
467 "length of signed data to verify")
468 .isInRange(
469 traceableDataAdapter->getSignature().size(),
470 1,
471 8,
472 MSG_SIGNATURE_SIZE)
473 .isTrue(
474 isTracebilityOffsetInRange,
475 "traceability offset is in range")
476 .isTrue(
477 traceableDataAdapter->getKeyDiversifier().empty()
478 || (traceableDataAdapter->getKeyDiversifier().size()
479 >= 1
480 && traceableDataAdapter->getKeyDiversifier().size()
481 <= 8),
482 MSG_KEY_DIVERSIFIER_SIZE_IS_IN_RANGE_1_8);
483
484 /* Check SAM revocation status if requested. */
485 if (traceableDataAdapter->getSamRevocationService()) {
486 /*
487 * Extract the SAM serial number and the counter value from the
488 * data.
489 */
490 std::vector<uint8_t> samSerialNumber
491 = ByteArrayUtil::extractBytes(
492 traceableDataAdapter->getData(),
493 traceableDataAdapter->getTraceabilityOffset(),
494 traceableDataAdapter->getSamTraceabilityMode()
495 == SamTraceabilityMode::TRUNCATED_SERIAL_NUMBER
496 ? 3
497 : 4);
498
499 int samCounterValue = ByteArrayUtil::extractInt(
500 ByteArrayUtil::extractBytes(
501 traceableDataAdapter->getData(),
502 traceableDataAdapter->getTraceabilityOffset()
503 + (traceableDataAdapter->getSamTraceabilityMode()
504 == SamTraceabilityMode::
505 TRUNCATED_SERIAL_NUMBER
506 ? 3 * 8
507 : 4 * 8),
508 3),
509 0,
510 3,
511 false);
512
513 // Is SAM revoked ?
514 if (traceableDataAdapter->getSamRevocationService()
515 ->isSamRevoked(samSerialNumber, samCounterValue)) {
516 throw SamRevokedException(
517 "SAM is revoked. Serial number: "
518 + HexUtil::toHex(samSerialNumber) + "h, Counter value: "
519 + std::to_string(samCounterValue));
520 }
521 }
522
523 prepareSelectDiversifierIfNeeded(
524 traceableDataAdapter->getKeyDiversifier());
525 mSamCommands.push_back(
526 std::make_shared<CommandPsoVerifySignature>(
527 getContext(), traceableDataAdapter));
528
529 } else {
530 const SignatureVerificationDataBase& dataRef = *data;
531 throw std::invalid_argument(
532 "Cannot cast 'data' to BasicSignatureVerificationDataAdapter "
533 "or TraceableSignatureVerificationDataAdapter. Actual type: "
534 + std::string(typeid(dataRef).name()));
535 }
536 }
537 return *this;
538}
539
540bool
541SymmetricCryptoCardTransactionManagerAdapter::isSelectDiversifierNeeded(
542 const std::vector<uint8_t>& keyDiversifier)
543{
544 if (!Arrays::equals(mCurrentKeyDiversifier, keyDiversifier)) {
545 mCurrentKeyDiversifier = keyDiversifier;
546 return true;
547 }
548
549 return false;
550}
551
552void
553SymmetricCryptoCardTransactionManagerAdapter::processCommands()
554{
555 /*
556 * If there are pending SAM commands and the secure session is open and the
557 * "Digest Init" command is not already executed, then we need to flush the
558 * session pending commands by executing the pending "digest" commands
559 * "BEFORE" the other SAM commands to make sure that between the session
560 * "Get Challenge" and the "Digest Init", there is no other command
561 * inserted.
562 */
563 if (!mSamCommands.empty() && mDigestManager
564 && !mDigestManager->mIsDigestInitDone) {
565 mDigestManager->prepareDigestInit();
566 }
567
568 if (mSamCommands.empty()) {
569 return;
570 }
571
572 try {
573 /* Get the list of C-APDU to transmit */
574 auto apduRequests = CardTransactionUtil::getApduRequests(mSamCommands);
575
576 /* Wrap the list of C-APDUs into a card request */
577 auto cardRequest = std::make_shared<DtoAdapters::CardRequestAdapter>(
578 apduRequests, true);
579
580 /* Transmit the commands to the SAM */
581 auto cardResponse = CardTransactionUtil::transmitCardRequest(
582 cardRequest, mSamReader, mSam, mTransactionAuditData);
583
584 /* Retrieve the list of R-APDUs */
585 auto apduResponses = cardResponse->getApduResponses();
586
587 /*
588 * If there are more responses than requests, then we are unable to fill
589 * the card image. In this case we stop processing immediately because
590 * it may be a case of fraud, and we throw an exception.
591 */
592 if (apduResponses.size() > apduRequests.size()) {
593 throw SymmetricCryptoException(
594 MSG_SAM_INCONSISTENT_DATA + std::to_string(apduRequests.size())
595 + MSG_SAM_NB_RESPONSES
596 + std::to_string(apduResponses.size()),
597 InconsistentDataException(
598 MSG_SAM_INCONSISTENT_DATA
599 + std::to_string(apduRequests.size()) + MSG_SAM_NB_RESPONSES
600 + std::to_string(apduResponses.size())
601 + CardTransactionUtil::getTransactionAuditDataAsString(
602 mTransactionAuditData, mSam)));
603 }
604
605 for (size_t i = 0; i < apduResponses.size(); i++) {
606 try {
607 mSamCommands[i]->parseResponse(apduResponses[i]);
608 } catch (const CommandException& e) {
609 auto commandRef = mSamCommands[i]->getCommandRef();
610 if (commandRef == CommandRef::DIGEST_AUTHENTICATE
611 && dynamic_cast<const SecurityDataException*>(&e)) {
612 throw InvalidCardMacException("Invalid card signature");
613 } else if (
614 (commandRef == CommandRef::PSO_VERIFY_SIGNATURE
615 || commandRef == CommandRef::DATA_CIPHER)
616 && dynamic_cast<const SecurityDataException*>(&e)) {
617 throw InvalidSignatureException(
618 "Invalid signature",
619 std::make_shared<CommandException>(e));
620 } else if (
621 commandRef == CommandRef::SV_CHECK
622 && dynamic_cast<const SecurityDataException*>(&e)) {
623 throw InvalidCardMacException("Invalid SV card signature");
624 }
625
626 const std::string sw = mSamCommands[i]->getApduResponse()
627 ? HexUtil::toHex(
628 static_cast<std::uint16_t>(
629 mSamCommands[i]
630 ->getApduResponse()
631 ->getStatusWord()))
632 : "null";
633
634 throw SymmetricCryptoException(
635 CardTransactionUtil::MSG_FAILED_TO_PROCESS_SAM_RESPONSE
636 + " Command: " + commandRef.getName() + ", SW: " + sw,
637 InvalidCardResponseException(
638 CardTransactionUtil::MSG_FAILED_TO_PROCESS_SAM_RESPONSE
639 + " Command: " + commandRef.getName()
640 + ", SW: " + sw
641 + CardTransactionUtil::
642 getTransactionAuditDataAsString(
643 mTransactionAuditData, mSam),
644 e));
645 }
646 }
647
648 if (apduResponses.size() < apduRequests.size()) {
649 throw SymmetricCryptoException(
650 MSG_SAM_INCONSISTENT_DATA + std::to_string(apduRequests.size())
651 + MSG_SAM_NB_RESPONSES
652 + std::to_string(apduResponses.size()),
653 InconsistentDataException(
654 MSG_SAM_INCONSISTENT_DATA
655 + std::to_string(apduRequests.size()) + MSG_SAM_NB_RESPONSES
656 + std::to_string(apduResponses.size())
657 + CardTransactionUtil::getTransactionAuditDataAsString(
658 mTransactionAuditData, mSam)));
659 }
660 } catch (...) {
661 mSamCommands.clear();
662 throw;
663 }
664 mSamCommands.clear();
665}
666
667void
668SymmetricCryptoCardTransactionManagerAdapter::prepareGiveRandom(
669 const std::vector<uint8_t>& cardChallenge)
670{
671 prepareSelectDiversifierIfNeeded();
672 mSamCommands.push_back(
673 std::make_shared<CommandGiveRandom>(getContext(), cardChallenge));
674}
675
676std::vector<uint8_t>
677SymmetricCryptoCardTransactionManagerAdapter::cipherPin(
678 const std::vector<uint8_t>& cardChallenge,
679 const std::vector<uint8_t>& currentPin,
680 const std::vector<uint8_t>& newPin,
681 const std::shared_ptr<uint8_t> kif,
682 const std::shared_ptr<uint8_t> kvc)
683{
684 uint8_t pinCipheringKif;
685 uint8_t pinCipheringKvc;
686
687 if (mDigestManager && mDigestManager->mSessionKif != 0) {
688 /* The current work key has been set (a secure session is open) */
689 pinCipheringKif = mDigestManager->mSessionKif;
690 pinCipheringKvc = mDigestManager->mSessionKvc;
691
692 } else {
693 /* No current work key is available (outside secure session) */
694 if (kif == nullptr || kvc == nullptr) {
695 std::string msg = newPin.empty() ? "verification" : "modification";
696 throw IllegalStateException(
697 "KIF and KVC should be set for the PIN " + msg
698 + " ciphering key");
699 }
700 pinCipheringKif = *kif;
701 pinCipheringKvc = *kvc;
702 }
703
704 prepareGiveRandom(cardChallenge);
705
706 /* An empty new PIN means a verification, which has its own constructor
707 * setting P1 to 80h; the modification one sets 40h and rejects it. */
708 std::shared_ptr<CommandCardCipherPin> cmd;
709 if (newPin.empty()) {
710 cmd = std::make_shared<CommandCardCipherPin>(
711 getContext(), pinCipheringKif, pinCipheringKvc, currentPin);
712
713 } else {
714 cmd = std::make_shared<CommandCardCipherPin>(
715 getContext(), pinCipheringKif, pinCipheringKvc, currentPin, newPin);
716 }
717 mSamCommands.push_back(cmd);
718
719 processCommands();
720
721 return cmd->getCipheredData();
722}
723
724void
725SymmetricCryptoCardTransactionManagerAdapter::prepareSelectDiversifier()
726{
727 mSamCommands.push_back(
728 std::make_shared<CommandSelectDiversifier>(
729 getContext(), mCurrentKeyDiversifier));
730}
731
732void
733SymmetricCryptoCardTransactionManagerAdapter::prepareSelectDiversifierIfNeeded(
734 const std::vector<uint8_t>& specificKeyDiversifier)
735{
736 if (!specificKeyDiversifier.empty()) {
737 if (isSelectDiversifierNeeded(specificKeyDiversifier)) {
738 prepareSelectDiversifier();
739 }
740
741 } else {
742 prepareSelectDiversifierIfNeeded();
743 }
744}
745
746void
747SymmetricCryptoCardTransactionManagerAdapter::prepareSelectDiversifierIfNeeded()
748{
749 if (isSelectDiversifierNeeded(mCardKeyDiversifier)) {
750 prepareSelectDiversifier();
751 }
752}
753
755 InvalidCardMacException(const std::string& message)
756: RuntimeException(message)
757{
758}
759
760SymmetricCryptoCardTransactionManagerAdapter::DigestManager::DigestManager(
761 SymmetricCryptoCardTransactionManagerAdapter* parent,
762 const std::vector<std::uint8_t>& openSecureSessionDataOut,
763 std::uint8_t kif,
764 std::uint8_t kvc)
765: mSessionKif(kif)
766, mSessionKvc(kvc)
767, mParent(parent)
768, mOpenSecureSessionDataOut(openSecureSessionDataOut)
769{
770}
771
772void
773SymmetricCryptoCardTransactionManagerAdapter::DigestManager::updateSession(
774 const std::vector<std::uint8_t>& cardApdu)
775{
776 /*
777 * If the request is of case4 type, LE must be excluded from the digest
778 * computation. In this case, we remove here the last byte of the command
779 * buffer.
780 */
781
782 /* CL-C4-MAC.1 */
783 if (mIsRequest) {
784 mCardApdus.push_back(
785 ApduUtil::isCase4(cardApdu)
786 ? Arrays::copyOfRange(cardApdu, 0, cardApdu.size() - 1)
787 : cardApdu);
788 } else {
789 mCardApdus.push_back(cardApdu);
790 }
791
792 mIsRequest = !mIsRequest;
793}
794
795std::shared_ptr<CommandDigestUpdate>
796SymmetricCryptoCardTransactionManagerAdapter ::DigestManager::
797 prepareCommandForEncryption(const std::vector<std::uint8_t>& cardApdu)
798{
799 updateSession(cardApdu);
800
801 /* Prepare the "Digest Update" commands and flush the buffer. */
802 const std::vector<std::uint8_t> apdu = mCardApdus.front();
803 mCardApdus.erase(mCardApdus.begin());
804
805 auto command = std::make_shared<CommandDigestUpdate>(
806 mParent->getContext(), true, apdu);
807
808 mParent->mSamCommands.push_back(command);
809
810 return command;
811}
812
813void
814SymmetricCryptoCardTransactionManagerAdapter ::DigestManager::prepareCommands()
815{
816 /* Prepare the "Digest Init" command if not already done. */
817 if (!mIsDigestInitDone) {
818 prepareDigestInit();
819 }
820
821 /*
822 * Prepare the "Digest Update" commands and flush the buffer.
823 */
824 prepareDigestUpdate();
825 mCardApdus.clear();
826}
827
828void
829SymmetricCryptoCardTransactionManagerAdapter ::DigestManager::
830 prepareAllCommands()
831{
832 prepareCommands();
833
834 /* Prepare the "Digest Close" command. */
835 prepareDigestClose();
836}
837
838void
839SymmetricCryptoCardTransactionManagerAdapter ::DigestManager::
840 prepareDigestInit()
841{
842 if (mParent->mIsSelectDiversifierNeededOnDigestInit) {
843 mParent->mSamCommands.insert(
844 mParent->mSamCommands.begin(),
845 std::make_shared<CommandSelectDiversifier>(
846 mParent->getContext(), mParent->mCardKeyDiversifier));
847 }
848
849 /* CL-SAM-DINIT.1 */
850 mParent->mSamCommands.insert(
851 mParent->mSamCommands.begin() + 1,
852 std::make_shared<CommandDigestInit>(
853 mParent->getContext(),
854 false,
855 mParent->mIsExtendedModeRequired,
856 mSessionKif,
857 mSessionKvc,
858 mOpenSecureSessionDataOut));
859 mIsDigestInitDone = true;
860}
861
862void
863SymmetricCryptoCardTransactionManagerAdapter ::DigestManager::
864 prepareDigestUpdate()
865{
866 if (mCardApdus.empty()) {
867 return;
868 }
869
870 /* CL-SAM-DUPDATE.1 */
871 /* CL-SAM-DMULTI.2 */
872 if (mParent->mSam->getProductType() == LegacySam::ProductType::SAM_C1
873 || mParent->mSam->getProductType()
874 == LegacySam::ProductType::SAM_S1E1) {
875 /* Digest Update Multiple */
876 std::vector<std::uint8_t> buffer(255);
877 int i = 0;
878 for (const auto& cardApdu : mCardApdus) {
879 if (static_cast<int>(i + cardApdu.size() + 1)
880 > mParent->mMaxCardApduLengthSupported) {
881 /* Add command and reset buffer */
882 if (i != 0) {
883 mParent->mSamCommands.push_back(
884 std::make_shared<CommandDigestUpdateMultiple>(
885 mParent->getContext(), Arrays::copyOf(buffer, i)));
886 }
887 i = 0;
888 }
889
890 if (static_cast<int>(cardApdu.size())
891 != mParent->mMaxCardApduLengthSupported) {
892 /* Add [length][apdu] to current buffer */
893 buffer[i++] = static_cast<std::uint8_t>(cardApdu.size());
894 System::arraycopy(cardApdu, 0, buffer, i, cardApdu.size());
895 i += static_cast<int>(cardApdu.size());
896
897 } else {
898 /*
899 * Create a Digest Update (simple) when the command fills
900 * entirely the SAM buffer.
901 */
902 mParent->mSamCommands.push_back(
903 std::make_shared<CommandDigestUpdate>(
904 mParent->getContext(), false, cardApdu));
905 }
906 }
907
908 if (i != 0) {
909 /* Add command */
910 mParent->mSamCommands.push_back(
911 std::make_shared<CommandDigestUpdateMultiple>(
912 mParent->getContext(), Arrays::copyOf(buffer, i)));
913 }
914 } else {
915 /* Digest Update (simple) */
916 for (const auto& cardApdu : mCardApdus) {
917 mParent->mSamCommands.push_back(
918 std::make_shared<CommandDigestUpdate>(
919 mParent->getContext(), false, cardApdu));
920 }
921 }
922}
923
924void
925SymmetricCryptoCardTransactionManagerAdapter ::DigestManager::
926 prepareDigestClose()
927{
928 /* CL-SAM-DCLOSE.1 */
929 mParent->mSamCommands.push_back(
930 std::make_shared<CommandDigestClose>(
931 mParent->getContext(), mParent->mIsExtendedModeRequired ? 8 : 4));
932}
933
934} /* namespace legacysam */
935} /* namespace crypto */
936} /* namespace calypso */
937} /* namespace card */
938} /* namespace keyple */
SymmetricCryptoCardTransactionManagerAdapter::InvalidCardMacException InvalidCardMacException
DtoAdapters::BasicSignatureComputationDataAdapter BasicSignatureComputationDataAdapter
DtoAdapters::TraceableSignatureComputationDataAdapter TraceableSignatureComputationDataAdapter