CCID: Add support for PC-to-Reader XfrBlock message
[pub/lufa.git] / Demos / Device / LowLevel / CCID / CCID.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2018.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2018 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11 Copyright 2018 Filipe Rodrigues (filipepazrodrigues [at] gmail [dot] com)
12
13 Permission to use, copy, modify, distribute, and sell this
14 software and its documentation for any purpose is hereby granted
15 without fee, provided that the above copyright notice appear in
16 all copies and that both that the copyright notice and this
17 permission notice and warranty disclaimer appear in supporting
18 documentation, and that the name of the author not be used in
19 advertising or publicity pertaining to distribution of the
20 software without specific, written prior permission.
21
22 The author disclaims all warranties with regard to this
23 software, including all implied warranties of merchantability
24 and fitness. In no event shall the author be liable for any
25 special, indirect or consequential damages or any damages
26 whatsoever resulting from loss of use, data or profits, whether
27 in an action of contract, negligence or other tortious action,
28 arising out of or in connection with the use or performance of
29 this software.
30 */
31
32 /** \file
33 *
34 * Main source file for the CCID demo. This file contains the main tasks of the demo and
35 * is responsible for the initial application hardware configuration.
36 *
37 * \warning
38 * LUFA is not a secure USB stack, and has not undergone, not is it expected to pass, any
39 * form of security audit. The CCID class here is presented as-is and is intended for
40 * research purposes only, and *should not* be used in a security critical application
41 * under any circumstances.
42 *
43 * \warning
44 * This code is not production ready and should not by any means be considered safe.
45 * If you plan to integrate it into your application, you should seriously consider strong
46 * encryption algorithms or a secure microprocessor. Since Atmel AVR microprocessors do not
47 * have any security requirement (therefore they don't offer any known protection against
48 * side channel attacks or fault injection) a secure microprocessor is the best option.
49 */
50
51 #include "CCID.h"
52
53 static bool Aborted;
54 static uint8_t AbortedSeq;
55
56
57 /** Main program entry point. This routine configures the hardware required by the application, then
58 * enters a loop to run the application tasks in sequence.
59 */
60 int main(void)
61 {
62 SetupHardware();
63
64 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
65 GlobalInterruptEnable();
66
67 for (;;)
68 {
69 USB_USBTask();
70 CCID_Task();
71 }
72 }
73
74 /** Configures the board hardware and chip peripherals for the demo's functionality. */
75 void SetupHardware(void)
76 {
77 #if (ARCH == ARCH_AVR8)
78 /* Disable watchdog if enabled by bootloader/fuses */
79 MCUSR &= ~(1 << WDRF);
80 wdt_disable();
81
82 /* Disable clock division */
83 clock_prescale_set(clock_div_1);
84 #elif (ARCH == ARCH_XMEGA)
85 /* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
86 XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
87 XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);
88
89 /* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
90 XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
91 XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);
92
93 PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
94 #endif
95
96 /* Hardware Initialization */
97 LEDs_Init();
98 USB_Init();
99 }
100
101 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
102 void EVENT_USB_Device_Connect(void)
103 {
104 /* Indicate USB enumerating */
105 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
106 }
107
108 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
109 * the status LEDs.
110 */
111 void EVENT_USB_Device_Disconnect(void)
112 {
113 /* Indicate USB not ready */
114 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
115 }
116
117 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
118 * of the USB device after enumeration - the device endpoints are configured.
119 */
120 void EVENT_USB_Device_ConfigurationChanged(void)
121 {
122 bool ConfigSuccess = true;
123
124 /* Setup CCID Data Endpoints */
125 ConfigSuccess &= Endpoint_ConfigureEndpoint(CCID_IN_EPADDR, EP_TYPE_BULK, CCID_EPSIZE, 1);
126 ConfigSuccess &= Endpoint_ConfigureEndpoint(CCID_OUT_EPADDR, EP_TYPE_BULK, CCID_EPSIZE, 1);
127
128 /* Indicate endpoint configuration success or failure */
129 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
130 }
131
132 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
133 * the device from the USB host before passing along unhandled control requests to the library for processing
134 * internally.
135 */
136 void EVENT_USB_Device_ControlRequest(void)
137 {
138 switch (USB_ControlRequest.bRequest)
139 {
140 case CCID_ABORT:
141 {
142 // Initiates the abort process
143 // The host should send 2 messages in the following order:
144 // - CCID_ABORT control request
145 // - CCID_PC_t_PCo_RDR_Abort command
146 //
147 // If the device is still processing a message, it should fail it until receiving a CCIRPC_to_RDR_Abort
148 // command.
149 //
150 // When the device receives the CCIRPC_to_RDR_Abort message, it replies with RDR_to_PC_SlotStatus
151 // and the abort process ends
152
153 // The wValue field contains the slot number (bSlot) in the low byte and the sequence number (bSeq) in
154 // the high byte
155 uint8_t Slot = USB_ControlRequest.wValue & 0xFF;
156 uint8_t Seq = USB_ControlRequest.wValue >> 8;
157
158 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE) && Slot == 0)
159 {
160 Endpoint_ClearSETUP();
161
162 Aborted = true;
163 AbortedSeq = Seq;
164
165 Endpoint_ClearOUT();
166 }
167
168 break;
169 }
170 case CCID_GET_CLOCK_FREQUENCIES:
171 {
172 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
173 {
174 Endpoint_ClearSETUP();
175 Endpoint_Write_8(0); // Not supported
176 Endpoint_ClearOUT();
177 }
178
179 break;
180 }
181 case CCID_GET_DATA_RATES:
182 {
183 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
184 {
185 Endpoint_ClearSETUP();
186 Endpoint_Write_8(0); // Not supported
187 Endpoint_ClearOUT();
188 }
189
190 break;
191 }
192 }
193 }
194
195 /** Event handler for the CCID_PC_to_RDR_IccPowerOn message. This message is sent to the device
196 * whenever an application at the host wants to send a power off signal to a slot.
197 * THe slot must reply back with a recognizable ATR (answer to reset)
198 */
199 uint8_t CCID_IccPowerOn(uint8_t slot,
200 uint8_t* const atr,
201 uint8_t* const atrLength,
202 uint8_t* const error)
203 {
204 if (slot == 0)
205 {
206 Iso7816_CreateSimpleAtr(atr, atrLength);
207
208 *error = CCID_ERROR_NO_ERROR;
209 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_PRESENTANDACTIVE;
210 }
211 else
212 {
213 *error = CCID_ERROR_SLOT_NOT_FOUND;
214 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
215 }
216 }
217
218 /** Event handler for the CCID_PC_to_RDR_IccPowerOff message. This message is sent to the device
219 * whenever an application at the host wants to send a power off signal to a slot.
220 */
221 uint8_t CCID_IccPowerOff(uint8_t slot,
222 uint8_t* const error)
223 {
224 if (slot == 0)
225 {
226 *error = CCID_ERROR_NO_ERROR;
227 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_NOICCPRESENT;
228 }
229 else
230 {
231 *error = CCID_ERROR_SLOT_NOT_FOUND;
232 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
233 }
234 }
235
236 /** Event handler for the CCID_PC_to_RDR_GetSlotStatus. THis message is sent to
237 * the device whenever an application at the host wants to the get the current
238 * slot status.
239 */
240 uint8_t CCID_GetSlotStatus(uint8_t slot,
241 uint8_t* const error)
242 {
243 if (slot == 0)
244 {
245 *error = CCID_ERROR_NO_ERROR;
246 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_PRESENTANDACTIVE;
247 }
248 else
249 {
250 *error = CCID_ERROR_SLOT_NOT_FOUND;
251 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
252 }
253 }
254
255 /** Event handler for the CCID_PC_to_RDR_XfrBlock. This message is sent to the device
256 * whenever an application at the host wants to send a block of bytes to the device
257 * THe device reply back with an array of bytes
258 */
259 uint8_t CCID_XfrBlock(uint8_t slot,
260 uint8_t* const receivedBuffer,
261 uint8_t receivedBufferSize,
262 uint8_t* const sendBuffer,
263 uint8_t* const sentBufferSize,
264 uint8_t* const error)
265 {
266 if (slot == 0)
267 {
268 uint8_t okResponse[2] = {0x90, 0x00};
269 memcpy(sendBuffer, okResponse, sizeof(okResponse));
270 *sentBufferSize = sizeof(okResponse);
271
272 *error = CCID_ERROR_NO_ERROR;
273 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_NOICCPRESENT;
274 }
275 else
276 {
277 *error = CCID_ERROR_SLOT_NOT_FOUND;
278 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
279 }
280 }
281
282 /** Event handler for the CCID_PC_to_RDR_ABort message. This message is sent to the device
283 * whenever an application wants to abort the current operation. A previous CCID_ABORT
284 * control message has to be sent before this one in order to start the abort operation.
285 */
286 uint8_t CCID_Abort(uint8_t slot,
287 uint8_t seq,
288 uint8_t* const error)
289 {
290 if (Aborted && slot == 0 && AbortedSeq == seq)
291 {
292 Aborted = false;
293 AbortedSeq = -1;
294 *error = CCID_ERROR_NO_ERROR;
295 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_PRESENTANDACTIVE;
296 }
297 else if (!Aborted)
298 {
299 *error = CCID_ERROR_CMD_NOT_ABORTED;
300 return CCID_COMMANDSTATUS_PROCESSEDWITHOUTERROR | CCID_ICCSTATUS_PRESENTANDACTIVE;
301 }
302 else if (slot != 0)
303 {
304 *error = CCID_ERROR_SLOT_NOT_FOUND;
305 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
306 }
307
308 *error = CCID_ERROR_NOT_SUPPORTED;
309 return CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_NOICCPRESENT;
310 }
311
312 /** Gets and status and verifies whether an error occurred. */
313 bool CCID_CheckStatusNoError(uint8_t status)
314 {
315 return (status & 0xC0) == 0x0;
316 }
317
318 /** Function to manage CCID request parsing and responses back to the host. */
319 void CCID_Task(void)
320 {
321 Endpoint_SelectEndpoint(CCID_OUT_EPADDR);
322
323 uint8_t RequestBuffer[CCID_EPSIZE - sizeof(USB_CCID_BulkMessage_Header_t)];
324 uint8_t ResponseBuffer[CCID_EPSIZE];
325 Aborted = false;
326 AbortedSeq = -1;
327
328 if (Endpoint_IsOUTReceived())
329 {
330 USB_CCID_BulkMessage_Header_t CCIDHeader;
331 CCIDHeader.MessageType = Endpoint_Read_8();
332 CCIDHeader.Length = Endpoint_Read_32_LE();
333 CCIDHeader.Slot = Endpoint_Read_8();
334 CCIDHeader.Seq = Endpoint_Read_8();
335
336 uint8_t Status;
337 uint8_t Error = CCID_ERROR_NO_ERROR;
338
339 switch (CCIDHeader.MessageType)
340 {
341 case CCID_PC_to_RDR_IccPowerOn:
342 {
343 uint8_t AtrLength;
344 USB_CCID_RDR_to_PC_DataBlock_t* ResponseATR = (USB_CCID_RDR_to_PC_DataBlock_t*)&ResponseBuffer;
345
346 ResponseATR->CCIDHeader.MessageType = CCID_RDR_to_PC_DataBlock;
347 ResponseATR->CCIDHeader.Slot = CCIDHeader.Slot;
348 ResponseATR->CCIDHeader.Seq = CCIDHeader.Seq;
349 ResponseATR->ChainParam = 0;
350
351 Status = CCID_IccPowerOn(ResponseATR->CCIDHeader.Slot, (uint8_t* )ResponseATR->Data, &AtrLength, &Error);
352
353 if (CCID_CheckStatusNoError(Status) && !Aborted)
354 {
355 ResponseATR->CCIDHeader.Length = AtrLength;
356 }
357 else if (Aborted)
358 {
359 Status = CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_PRESENTANDACTIVE;
360 Error = CCID_ERROR_CMD_ABORTED;
361 AtrLength = 0;
362 }
363 else
364 {
365 AtrLength = 0;
366 }
367
368 ResponseATR->Status = Status;
369 ResponseATR->Error = Error;
370
371 Endpoint_ClearOUT();
372
373 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
374 Endpoint_Write_Stream_LE(ResponseATR, sizeof(USB_CCID_RDR_to_PC_DataBlock_t) + AtrLength, NULL);
375 Endpoint_ClearIN();
376 break;
377 }
378
379 case CCID_PC_to_RDR_IccPowerOff:
380 {
381 USB_CCID_RDR_to_PC_SlotStatus_t* ResponsePowerOff = (USB_CCID_RDR_to_PC_SlotStatus_t*)&ResponseBuffer;
382 ResponsePowerOff->CCIDHeader.MessageType = CCID_RDR_to_PC_SlotStatus;
383 ResponsePowerOff->CCIDHeader.Length = 0;
384 ResponsePowerOff->CCIDHeader.Slot = CCIDHeader.Slot;
385 ResponsePowerOff->CCIDHeader.Seq = CCIDHeader.Seq;
386
387 ResponsePowerOff->ClockStatus = 0;
388
389 Status = CCID_IccPowerOff(CCIDHeader.Slot, &Error);
390
391 ResponsePowerOff->Status = Status;
392 ResponsePowerOff->Error = Error;
393
394 Endpoint_ClearOUT();
395
396 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
397 Endpoint_Write_Stream_LE(ResponsePowerOff, sizeof(USB_CCID_RDR_to_PC_SlotStatus_t), NULL);
398 Endpoint_ClearIN();
399 break;
400 }
401
402 case CCID_PC_to_RDR_GetSlotStatus:
403 {
404 USB_CCID_RDR_to_PC_SlotStatus_t* ResponseSlotStatus = (USB_CCID_RDR_to_PC_SlotStatus_t*)&ResponseBuffer;
405 ResponseSlotStatus->CCIDHeader.MessageType = CCID_RDR_to_PC_SlotStatus;
406 ResponseSlotStatus->CCIDHeader.Length = 0;
407 ResponseSlotStatus->CCIDHeader.Slot = CCIDHeader.Slot;
408 ResponseSlotStatus->CCIDHeader.Seq = CCIDHeader.Seq;
409
410 ResponseSlotStatus->ClockStatus = 0;
411
412 Status = CCID_GetSlotStatus(CCIDHeader.Slot, &Error);
413
414 ResponseSlotStatus->Status = Status;
415 ResponseSlotStatus->Error = Error;
416
417 Endpoint_ClearOUT();
418
419 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
420 Endpoint_Write_Stream_LE(ResponseSlotStatus, sizeof(USB_CCID_RDR_to_PC_SlotStatus_t), NULL);
421 Endpoint_ClearIN();
422 break;
423 }
424
425 case CCID_PC_to_RDR_XfrBlock:
426 {
427 uint8_t Bwi = Endpoint_Read_8();
428 uint16_t LevelParameter = Endpoint_Read_16_LE();
429
430 (void)Bwi;
431 (void)LevelParameter;
432
433 Endpoint_Read_Stream_LE(RequestBuffer, CCIDHeader.Length * sizeof(uint8_t), NULL);
434
435 uint8_t ResponseDataLength = 0;
436
437 USB_CCID_RDR_to_PC_DataBlock_t* ResponseBlock = (USB_CCID_RDR_to_PC_DataBlock_t*)&ResponseBuffer;
438 ResponseBlock->CCIDHeader.MessageType = CCID_RDR_to_PC_DataBlock;
439 ResponseBlock->CCIDHeader.Slot = CCIDHeader.Slot;
440 ResponseBlock->CCIDHeader.Seq = CCIDHeader.Seq;
441
442 ResponseBlock->ChainParam = 0;
443
444 Status = CCID_XfrBlock(CCIDHeader.Slot, RequestBuffer, CCIDHeader.Length, &ResponseBlock->Data, &ResponseDataLength, &Error);
445
446 if (CCID_CheckStatusNoError(Status) && !Aborted)
447 {
448 ResponseBlock->CCIDHeader.Length = ResponseDataLength;
449 }
450 else if (Aborted)
451 {
452 Status = CCID_COMMANDSTATUS_FAILED | CCID_ICCSTATUS_PRESENTANDACTIVE;
453 Error = CCID_ERROR_CMD_ABORTED;
454 ResponseDataLength = 0;
455 }
456 else
457 {
458 ResponseDataLength = 0;
459 }
460
461 ResponseBlock->Status = Status;
462 ResponseBlock->Error = Error;
463
464 Endpoint_ClearOUT();
465
466 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
467 Endpoint_Write_Stream_LE(ResponseBlock, sizeof(USB_CCID_RDR_to_PC_DataBlock_t) + ResponseDataLength, NULL);
468 Endpoint_ClearIN();
469 break;
470 }
471
472 case CCID_PC_to_RDR_Abort:
473 {
474 USB_CCID_RDR_to_PC_SlotStatus_t* ResponseAbort = (USB_CCID_RDR_to_PC_SlotStatus_t*)&ResponseBuffer;
475 ResponseAbort->CCIDHeader.MessageType = CCID_RDR_to_PC_SlotStatus;
476 ResponseAbort->CCIDHeader.Length = 0;
477 ResponseAbort->CCIDHeader.Slot = CCIDHeader.Slot;
478 ResponseAbort->CCIDHeader.Seq = CCIDHeader.Seq;
479
480 ResponseAbort->ClockStatus = 0;
481
482 Status = CCID_Abort(CCIDHeader.Slot, CCIDHeader.Seq, &Error);
483
484 ResponseAbort->Status = Status;
485 ResponseAbort->Error = Error;
486
487 Endpoint_ClearOUT();
488
489 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
490 Endpoint_Write_Stream_LE(ResponseAbort, sizeof(USB_CCID_RDR_to_PC_SlotStatus_t), NULL);
491 Endpoint_ClearIN();
492 break;
493 }
494 default:
495 {
496 memset(ResponseBuffer, 0x00, sizeof(ResponseBuffer));
497
498 Endpoint_SelectEndpoint(CCID_IN_EPADDR);
499 Endpoint_Write_Stream_LE(ResponseBuffer, sizeof(ResponseBuffer), NULL);
500 Endpoint_ClearIN();
501 }
502 }
503 }
504 }