keyple-card-calypso-crypto-legacysam-cpp-lib - 1.0.2
Component of the Keyple C++ middleware
LegacySamSelectionExtensionAdapter.cpp
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (c) 2025 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/LegacySamSelectionExtensionAdapter.hpp"
15
16#include <memory>
17#include <string>
18#include <utility>
19#include <vector>
20
21#include "keyple/card/calypso/crypto/legacysam/AccessForbiddenException.hpp"
22#include "keyple/card/calypso/crypto/legacysam/CommandGetData.hpp"
23#include "keyple/card/calypso/crypto/legacysam/CommandReadCeilings.hpp"
24#include "keyple/card/calypso/crypto/legacysam/CommandReadCounter.hpp"
25#include "keyple/card/calypso/crypto/legacysam/CommandReadKeyParameters.hpp"
26#include "keyple/card/calypso/crypto/legacysam/CommandReadParameters.hpp"
27#include "keyple/card/calypso/crypto/legacysam/CommandUnlock.hpp"
28#include "keyple/card/calypso/crypto/legacysam/LegacySamConstants.hpp"
29#include "keyple/core/util/HexUtil.hpp"
30#include "keyple/core/util/KeypleAssert.hpp"
31#include "keyple/core/util/cpp/exception/IllegalStateException.hpp"
32#include "keypop/calypso/card/transaction/InconsistentDataException.hpp"
33#include "keypop/card/ChannelControl.hpp"
34#include "keypop/card/ParseException.hpp"
35#include "keypop/reader/InvalidCardResponseException.hpp"
36
37namespace keyple {
38namespace card {
39namespace calypso {
40namespace crypto {
41namespace legacysam {
42
43using keyple::core::util::Assert;
44using keyple::core::util::HexUtil;
45using keyple::core::util::cpp::exception::IllegalStateException;
46using keypop::calypso::card::transaction::InconsistentDataException;
47using keypop::card::ParseException;
48using keypop::reader::InvalidCardResponseException;
49
52
53const int LegacySamSelectionExtensionAdapter::SW_NOT_LOCKED = 0x6985;
54
55const std::unique_ptr<Logger> LegacySamSelectionExtensionAdapter::mLogger
56 = LoggerFactory::getLogger(typeid(LegacySamSelectionExtensionAdapter));
57
58LegacySamSelectionExtensionAdapter::LegacySamSelectionExtensionAdapter()
59: mLegacySamAdapter(std::make_shared<LegacySamAdapter>(ProductType::SAM_C1))
60, mContext(
61 std::make_shared<DtoAdapters::CommandContextDto>(
62 mLegacySamAdapter, nullptr, nullptr))
63, mUnlockSettingType(UnlockSettingType::UNSET)
64{
65}
66
67std::unique_ptr<CardSelectionRequestSpi>
68LegacySamSelectionExtensionAdapter::getCardSelectionRequest()
69{
70 std::vector<std::shared_ptr<ApduRequestSpi>> cardSelectionApduRequests;
71 switch (mUnlockSettingType) {
72 case UnlockSettingType::UNLOCK_DATA: {
73 auto commandUnlock = std::make_shared<CommandUnlock>(
74 mUnlockProductType, mUnlockDataBytes);
75 commandUnlock->getApduRequest()->addSuccessfulStatusWord(SW_NOT_LOCKED);
76 mCommands.push_back(commandUnlock);
77 }
78 /* No break */
79 /* FALLTHRU */
80 case UnlockSettingType::UNSET:
81 for (const auto& command : mCommands) {
82 cardSelectionApduRequests.push_back(command->getApduRequest());
83 }
84 break;
85 case UnlockSettingType::DYNAMIC_MODE_PROVIDER:
86 /* Do not add command for now when using an Unlock Data provider */
87 mCommandGetChallenge
88 = std::make_shared<CommandGetChallenge>(mContext, 8);
89 cardSelectionApduRequests.push_back(
90 mCommandGetChallenge->getApduRequest());
91 break;
92 default:
93 break;
94 }
95
96 if (cardSelectionApduRequests.empty()) {
97 return std::unique_ptr<CardSelectionRequestAdapter>(
98 new CardSelectionRequestAdapter(nullptr));
99 }
100
101 return std::unique_ptr<CardSelectionRequestAdapter>(
103 std::make_shared<DtoAdapters::CardRequestAdapter>(
104 cardSelectionApduRequests, false)));
105}
106
107std::shared_ptr<SmartCardSpi>
108LegacySamSelectionExtensionAdapter::parse(
109 const std::shared_ptr<CardSelectionResponseApi>& cardSelectionResponseApi)
110{
111 try {
112 mLegacySamAdapter->parseSelectionResponse(cardSelectionResponseApi);
113 auto cardResponse = getCardResponse(cardSelectionResponseApi);
114 parseCardResponse(cardResponse);
115 } catch (const std::exception&) {
116 throw ParseException("Invalid SAM response");
117 }
118 if (mLegacySamAdapter->getProductType() == ProductType::UNKNOWN
119 && cardSelectionResponseApi->getSelectApplicationResponse() == nullptr
120 && cardSelectionResponseApi->getPowerOnData().empty()) {
121 throw ParseException(
122 "No power-on data and no FCI provided. Unable to create a "
123 "LegacySam instance");
124 }
125 return mLegacySamAdapter;
126}
127
128std::shared_ptr<CardResponseApi>
129LegacySamSelectionExtensionAdapter::getCardResponse(
130 std::shared_ptr<CardSelectionResponseApi> cardSelectionResponseApi)
131{
132 std::shared_ptr<CardResponseApi> cardResponse
133 = cardSelectionResponseApi->getCardResponse();
134
135 if (mUnlockSettingType == UnlockSettingType::STATIC_MODE_PROVIDER
136 || mUnlockSettingType == UnlockSettingType::DYNAMIC_MODE_PROVIDER) {
137 if (mTargetSamReader == nullptr) {
138 throw std::logic_error(
139 "'targetSamReader' is not set. Unable to unlock the SAM");
140 }
141
142 std::vector<uint8_t> unlockData;
143 if (mUnlockSettingType == UnlockSettingType::STATIC_MODE_PROVIDER) {
144 unlockData = mStaticUnlockDataProvider->getUnlockData(
145 mLegacySamAdapter->getSerialNumber());
146 } else {
147 mCommandGetChallenge->parseResponse(
148 cardResponse->getApduResponses()[0]);
149 unlockData = mDynamicUnlockDataProvider->getUnlockData(
150 mLegacySamAdapter->getSerialNumber(),
151 mLegacySamAdapter->popChallenge());
152 }
153
154 auto unlockCommand = std::make_shared<CommandUnlock>(
155 mLegacySamAdapter->getProductType(), unlockData);
156 unlockCommand->getApduRequest()->addSuccessfulStatusWord(
157 0x6985); // SW_NOT_LOCKED
158 mCommands.insert(mCommands.begin(), unlockCommand);
159
160 std::vector<std::shared_ptr<ApduRequestSpi>> cardSelectionApduRequests;
161 for (const auto& command : mCommands) {
162 cardSelectionApduRequests.push_back(command->getApduRequest());
163 }
164
165 auto cardRequest = std::make_shared<DtoAdapters::CardRequestAdapter>(
166 cardSelectionApduRequests, false);
167
168 cardResponse
169 = std::dynamic_pointer_cast<ProxyReaderApi>(mTargetSamReader)
170 ->transmitCardRequest(
171 cardRequest, keypop::card::ChannelControl::KEEP_OPEN);
172 }
173 return cardResponse;
174}
175
176void
177LegacySamSelectionExtensionAdapter::parseCardResponse(
178 std::shared_ptr<CardResponseApi> cardResponse)
179{
180 std::vector<std::shared_ptr<ApduResponseApi>> apduResponses;
181 if (cardResponse) {
182 apduResponses = cardResponse->getApduResponses();
183 }
184
185 if (mCommands.size() != apduResponses.size()) {
186 throw std::logic_error(
187 "The number of commands/responses does not match. Expected "
188 + std::to_string(mCommands.size()) + " responses, got "
189 + std::to_string(apduResponses.size()));
190 }
191 if (!mCommands.empty()) {
192 parseApduResponses(mCommands, apduResponses);
193 }
194}
195
196void
197LegacySamSelectionExtensionAdapter::parseApduResponses(
198 const std::vector<std::shared_ptr<Command>>& commands,
199 const std::vector<std::shared_ptr<ApduResponseApi>>& apduResponses)
200{
201 /*
202 * If there are more responses than requests, then we are unable to fill the
203 * card image. In this case we stop processing immediately because it may be
204 * a case of fraud, and we throw adesynchronized exception.
205 */
206 if (apduResponses.size() > commands.size()) {
207 throw InconsistentDataException(
208 "The number of commands/responses does not match. Expected "
209 + std::to_string(commands.size()) + " responses, got "
210 + std::to_string(apduResponses.size()));
211 }
212
213 /*
214 * We go through all the responses (and not the requests) because there may
215 * be fewer in the case of an error that occurred in strict mode. In this
216 * case the last response will raise an exception.
217 */
218 for (size_t i = 0; i < apduResponses.size(); i++) {
219 try {
220 commands[i]->parseResponse(apduResponses[i]);
221
222 } catch (const CommandException& e) {
223 if (dynamic_cast<const AccessForbiddenException*>(&e)
224 && dynamic_cast<const CommandUnlock*>(commands[i].get())) {
225 mLogger->warn("SAM not locked or already unlocked\n");
226
227 } else {
228 const std::string sw = commands[i]->getApduResponse() != nullptr
229 ? HexUtil::toHex(
230 static_cast<std::uint16_t>(
231 commands[i]
232 ->getApduResponse()
233 ->getStatusWord()))
234 : "null";
235 throw InvalidCardResponseException(
236 "Failed to process SAM response. Command: "
237 + commands[i]->getCommandRef().getName()
238 + ", SW: " + sw,
239 e);
240 }
241 }
242 }
243
244 /*
245 * Finally, if no error has occurred and there are fewer responses than
246 * requests, then we throw a desynchronized exception.
247 */
248 if (apduResponses.size() < commands.size()) {
249 throw InconsistentDataException(
250 "The number of commands/responses does not match. Expected "
251 + std::to_string(commands.size()) + " responses, got "
252 + std::to_string(apduResponses.size()));
253 }
254}
255
256LegacySamSelectionExtension&
257LegacySamSelectionExtensionAdapter::setUnlockData(
258 const std::string& unlockData, ProductType productType)
259{
260 if (mUnlockSettingType != UnlockSettingType::UNSET) {
261 throw std::logic_error(
262 "A setting to unlock the SAM has already been set");
263 }
264
265 Assert::getInstance()
266 .notEmpty(unlockData, "unlockData")
267 .isTrue(unlockData.length() == 32, "unlock data length")
268 .isHexString(unlockData, "unlockData");
269
270 mUnlockProductType = productType;
271 mUnlockDataBytes = HexUtil::toByteArray(unlockData);
272 mUnlockSettingType = UnlockSettingType::UNLOCK_DATA;
273
274 return *this;
275}
276
277LegacySamSelectionExtension&
278LegacySamSelectionExtensionAdapter::setUnlockData(const std::string& unlockData)
279{
280 return setUnlockData(unlockData, ProductType::SAM_C1);
281}
282
283LegacySamSelectionExtension&
284LegacySamSelectionExtensionAdapter::setStaticUnlockDataProvider(
285 std::shared_ptr<LegacySamStaticUnlockDataProviderSpi>
286 staticUnlockDataProvider)
287{
288 if (mUnlockSettingType != UnlockSettingType::UNSET) {
289 throw IllegalStateException(
290 "A setting to unlock the SAM has already been set");
291 }
292 Assert::getInstance().notNull(
293 staticUnlockDataProvider, "staticUnlockDataProvider");
294
295 mStaticUnlockDataProvider = std::move(staticUnlockDataProvider);
296 mUnlockSettingType = UnlockSettingType::STATIC_MODE_PROVIDER;
297
298 return *this;
299}
300
301LegacySamSelectionExtension&
302LegacySamSelectionExtensionAdapter::setStaticUnlockDataProvider(
303 std::shared_ptr<LegacySamStaticUnlockDataProviderSpi>
304 staticUnlockDataProvider,
305 std::shared_ptr<CardReader> targetSamReader)
306{
307 Assert::getInstance().notNull(targetSamReader, "targetSamReader");
308
309 mTargetSamReader = std::move(targetSamReader);
310
311 return setStaticUnlockDataProvider(std::move(staticUnlockDataProvider));
312}
313
314LegacySamSelectionExtension&
315LegacySamSelectionExtensionAdapter::setDynamicUnlockDataProvider(
316 std::shared_ptr<LegacySamDynamicUnlockDataProviderSpi>
317 dynamicUnlockDataProvider)
318{
319 if (mUnlockSettingType != UnlockSettingType::UNSET) {
320 throw IllegalStateException(
321 "A setting to unlock the SAM has already been set");
322 }
323
324 Assert::getInstance().notNull(
325 dynamicUnlockDataProvider, "dynamicUnlockDataProvider");
326
327 mDynamicUnlockDataProvider = std::move(dynamicUnlockDataProvider);
328 mUnlockSettingType = UnlockSettingType::DYNAMIC_MODE_PROVIDER;
329
330 return *this;
331}
332
333LegacySamSelectionExtension&
334LegacySamSelectionExtensionAdapter::setDynamicUnlockDataProvider(
335 std::shared_ptr<LegacySamDynamicUnlockDataProviderSpi>
336 dynamicUnlockDataProvider,
337 std::shared_ptr<CardReader> targetSamReader)
338{
339 Assert::getInstance().notNull(targetSamReader, "targetSamReader");
340
341 mTargetSamReader = std::move(targetSamReader);
342
343 return setDynamicUnlockDataProvider(std::move(dynamicUnlockDataProvider));
344}
345
346LegacySamSelectionExtension&
347LegacySamSelectionExtensionAdapter::prepareReadSamParameters()
348{
349 mCommands.push_back(std::make_shared<CommandReadParameters>(mContext));
350
351 return *this;
352}
353
354LegacySamSelectionExtension&
355LegacySamSelectionExtensionAdapter::prepareReadSystemKeyParameters(
356 SystemKeyType systemKeyType)
357{
358 mCommands.push_back(
359 std::make_shared<CommandReadKeyParameters>(mContext, systemKeyType));
360
361 return *this;
362}
363
364LegacySamSelectionExtension&
365LegacySamSelectionExtensionAdapter::prepareReadWorkKeyParameters(
366 int recordNumber)
367{
368 Assert::getInstance().isInRange(
369 recordNumber,
370 LegacySamConstants::MIN_KEY_RECORD_NUMBER,
371 LegacySamConstants::MAX_KEY_RECORD_NUMBER,
372 "recordNumber");
373
374 mCommands.push_back(
375 std::make_shared<CommandReadKeyParameters>(mContext, recordNumber));
376
377 return *this;
378}
379
380LegacySamSelectionExtension&
381LegacySamSelectionExtensionAdapter::prepareReadWorkKeyParameters(
382 uint8_t kif, uint8_t kvc)
383{
384 mCommands.push_back(
385 std::make_shared<CommandReadKeyParameters>(mContext, kif, kvc));
386
387 return *this;
388}
389
390LegacySamSelectionExtension&
391LegacySamSelectionExtensionAdapter::prepareReadCounterStatus(int counterNumber)
392{
393 Assert::getInstance().isInRange(
394 counterNumber,
395 LegacySamConstants::MIN_COUNTER_NUMBER,
396 LegacySamConstants::MAX_COUNTER_NUMBER,
397 "counterNumber");
398
399 for (const auto& command : mCommands) {
400 auto readCounterCommand
401 = std::dynamic_pointer_cast<CommandReadCounter>(command);
402 if (readCounterCommand
403 && readCounterCommand->getCounterFileRecordNumber()
404 == LegacySamConstants::COUNTER_TO_RECORD_LOOKUP
405 [counterNumber]) {
406 // already scheduled
407 return *this;
408 }
409 }
410 mCommands.push_back(
411 std::make_shared<CommandReadCounter>(
412 mContext,
413 LegacySamConstants::COUNTER_TO_RECORD_LOOKUP[counterNumber]));
414 mCommands.push_back(
415 std::make_shared<CommandReadCeilings>(
416 mContext,
417 LegacySamConstants::COUNTER_TO_RECORD_LOOKUP[counterNumber]));
418
419 return *this;
420}
421
422LegacySamSelectionExtension&
423LegacySamSelectionExtensionAdapter::prepareReadAllCountersStatus()
424{
425 for (int i = 0; i < 3; i++) {
426 mCommands.push_back(std::make_shared<CommandReadCounter>(mContext, i));
427 mCommands.push_back(std::make_shared<CommandReadCeilings>(mContext, i));
428 }
429
430 return *this;
431}
432
433LegacySamSelectionExtension&
434LegacySamSelectionExtensionAdapter::prepareGetData(GetDataTag tag)
435{
436 mCommands.push_back(std::make_shared<CommandGetData>(mContext, tag));
437
438 return *this;
439}
440
441LegacySamSelectionExtension&
442LegacySamSelectionExtensionAdapter::prepareGetChallengeIfNeeded()
443{
444 if (mCommands.empty()
445 || mCommands.back()->getCommandRef() != CommandRef::GET_CHALLENGE) {
446 mCommands.push_back(std::make_shared<CommandGetChallenge>(mContext, 8));
447 }
448
449 return *this;
450}
451
452LegacySamSelectionExtension&
453LegacySamSelectionExtensionAdapter::setSamReader(
454 std::shared_ptr<CardReader> targetSamReader)
455{
456 mTargetSamReader = std::move(targetSamReader);
457
458 return *this;
459}
460
461} /* namespace legacysam */
462} /* namespace crypto */
463} /* namespace calypso */
464} /* namespace card */
465} /* namespace keyple */
DtoAdapters::CommandContextDto CommandContextDto
DtoAdapters::CardSelectionRequestAdapter CardSelectionRequestAdapter