1 //-----------------------------------------------------------------------------
3 // Edits by Iceman, July 2018
5 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
6 // at your option, any later version. See the LICENSE.txt file for the text of
8 //-----------------------------------------------------------------------------
9 // The main i2c code, for communications with smart card module
10 //-----------------------------------------------------------------------------
16 #include "string.h" //for memset memcmp
17 #include "proxmark3.h"
18 #include "mifareutil.h" // for MF_DBGLEVEL
26 #include "smartcard.h"
30 #define GPIO_RST AT91C_PIO_PA1
31 #define GPIO_SCL AT91C_PIO_PA5
32 #define GPIO_SDA AT91C_PIO_PA7
34 #define SCL_H HIGH(GPIO_SCL)
35 #define SCL_L LOW(GPIO_SCL)
36 #define SDA_H HIGH(GPIO_SDA)
37 #define SDA_L LOW(GPIO_SDA)
39 #define SCL_read (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SCL)
40 #define SDA_read (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SDA)
42 #define I2C_ERROR "I2C_WaitAck Error"
44 static volatile unsigned long c
;
46 // Ö±½ÓʹÓÃÑ»·À´ÑÓʱ£¬Ò»¸öÑ»· 6 ÌõÖ¸Á48M£¬ Delay=1 ´ó¸ÅΪ 200kbps
48 // I2CSpinDelayClk(4) = 12.31us
49 // I2CSpinDelayClk(1) = 3.07us
50 static void __attribute__((optimize("O0"))) I2CSpinDelayClk(uint16_t delay
) {
51 for (c
= delay
* 2; c
; c
--) {};
54 // communication delay functions
55 #define I2C_DELAY_1CLK I2CSpinDelayClk(1)
56 #define I2C_DELAY_2CLK I2CSpinDelayClk(2)
57 #define I2C_DELAY_XCLK(x) I2CSpinDelayClk((x))
59 #define ISO7618_MAX_FRAME 255
61 // try i2c bus recovery at 100kHz = 5uS high, 5uS low
62 static void I2C_recovery(void) {
64 DbpString("Performing i2c bus recovery");
69 //9nth cycle acts as NACK
70 for (int i
= 0; i
< 10; i
++) {
75 //a STOP signal (SDA from low to high while CLK is high)
80 bool isok
= (SCL_read
&& SDA_read
);
82 DbpString("I2C bus recovery error: SDA still LOW");
84 DbpString("I2C bus recovery error: SCL still LOW");
86 DbpString("I2C bus recovery complete");
89 static void I2C_init(void) {
90 // Configure reset pin
91 AT91C_BASE_PIOA
->PIO_PPUDR
= GPIO_RST
; // disable pull up resistor
92 AT91C_BASE_PIOA
->PIO_MDDR
= GPIO_RST
; // push-pull output (multidriver disabled)
94 // Configure SCL and SDA pins
95 AT91C_BASE_PIOA
->PIO_PPUER
|= (GPIO_SCL
| GPIO_SDA
); // enable pull up resistor
96 AT91C_BASE_PIOA
->PIO_MDER
|= (GPIO_SCL
| GPIO_SDA
); // open drain output (multidriver enabled) - requires external pull up resistor
98 // set all three outputs to high
99 AT91C_BASE_PIOA
->PIO_SODR
|= (GPIO_SCL
| GPIO_SDA
| GPIO_RST
);
101 // configure all three pins as output, controlled by PIOA
102 AT91C_BASE_PIOA
->PIO_OER
|= (GPIO_SCL
| GPIO_SDA
| GPIO_RST
);
103 AT91C_BASE_PIOA
->PIO_PER
|= (GPIO_SCL
| GPIO_SDA
| GPIO_RST
);
105 bool isok
= (SCL_read
&& SDA_read
);
111 // set the reset state
112 static void I2C_SetResetStatus(uint8_t LineRST
, uint8_t LineSCK
, uint8_t LineSDA
) {
129 // Reset the SIM_Adapter, then enter the main program
130 // Note: the SIM_Adapter will not enter the main program after power up. Please run this function before use SIM_Adapter.
131 static void I2C_Reset_EnterMainProgram(void) {
134 I2C_SetResetStatus(0, 0, 0);
136 I2C_SetResetStatus(1, 0, 0);
138 I2C_SetResetStatus(1, 1, 1);
142 // Wait for the clock to go High.
143 static bool WaitSCL_H_delay(uint32_t delay
) {
153 // 15000 * 3.07us = 46050us. 46.05ms
154 static bool WaitSCL_H(void) {
155 return WaitSCL_H_delay(15000);
158 bool WaitSCL_L_delay(uint32_t delay
) {
168 bool WaitSCL_L(void) {
169 return WaitSCL_L_delay(15000);
172 static bool I2C_Start(void) {
175 SDA_H
; I2C_DELAY_1CLK
;
177 if (!WaitSCL_H()) return false;
181 if (!SCL_read
) return false;
182 if (!SDA_read
) return false;
184 SDA_L
; I2C_DELAY_2CLK
;
189 static void I2C_Stop(void) {
190 SCL_L
; I2C_DELAY_2CLK
;
191 SDA_L
; I2C_DELAY_2CLK
;
192 SCL_H
; I2C_DELAY_2CLK
;
193 if (!WaitSCL_H()) return;
198 static bool I2C_WaitAck(void) {
199 SCL_L
; I2C_DELAY_1CLK
;
200 SDA_H
; I2C_DELAY_1CLK
;
215 static void I2C_SendByte(uint8_t data
) {
240 bool I2C_is_available(void) {
241 I2C_Reset_EnterMainProgram();
242 if (!I2C_Start()) // some other device is active on the bus
244 I2C_SendByte(I2C_DEVICE_ADDRESS_MAIN
& 0xFE);
245 if (!I2C_WaitAck()) { // no response from smartcard reader
253 #ifdef WITH_SMARTCARD
254 // Reset the SIM_Adapter, then enter the bootloader program
255 // Reserve£ºFor firmware update.
256 static void I2C_Reset_EnterBootloader(void) {
257 I2C_SetResetStatus(0, 1, 1);
259 I2C_SetResetStatus(1, 1, 1);
263 // Wait max 1800ms or until SCL goes LOW.
264 // It timeout reading response from card
265 // Which ever comes first
266 bool WaitSCL_L_timeout(void){
267 volatile uint16_t delay
= 1800;
278 static bool I2C_WaitForSim() {
279 // wait for data from card
280 if (!WaitSCL_L_timeout())
283 // 8051 speaks with smart card.
284 // 1000*50*3.07 = 153.5ms
285 // 1byte transfer == 1ms with max frame being 256bytes
286 if (!WaitSCL_H_delay(10 * 1000 * 50))
293 static void I2C_Ack(void) {
294 SCL_L
; I2C_DELAY_2CLK
;
295 SDA_L
; I2C_DELAY_2CLK
;
296 SCL_H
; I2C_DELAY_2CLK
;
297 if (!WaitSCL_H()) return;
298 SCL_L
; I2C_DELAY_2CLK
;
302 static void I2C_NoAck(void) {
303 SCL_L
; I2C_DELAY_2CLK
;
304 SDA_H
; I2C_DELAY_2CLK
;
305 SCL_H
; I2C_DELAY_2CLK
;
306 if (!WaitSCL_H()) return;
307 SCL_L
; I2C_DELAY_2CLK
;
310 static int16_t I2C_ReadByte(void) {
311 uint8_t bits
= 8, b
= 0;
317 if (!WaitSCL_L()) return -2;
322 if (!WaitSCL_H()) return -1;
332 // Sends one byte ( command to be written, SlaveDevice address)
333 static bool I2C_WriteCmd(uint8_t device_cmd
, uint8_t device_address
) {
339 I2C_SendByte(device_address
& 0xFE);
343 I2C_SendByte(device_cmd
);
352 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
358 // Sends 1 byte data (Data to be written, command to be written , SlaveDevice address ).
359 static bool I2C_WriteByte(uint8_t data
, uint8_t device_cmd
, uint8_t device_address
) {
365 I2C_SendByte(device_address
& 0xFE);
369 I2C_SendByte(device_cmd
);
382 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
388 //Sends a string of data (Array, length, command to be written , SlaveDevice address ).
389 // len = uint8 (max buffer to write 256bytes)
390 static bool I2C_BufferWrite(uint8_t *data
, uint8_t len
, uint8_t device_cmd
, uint8_t device_address
) {
396 I2C_SendByte(device_address
& 0xFE);
400 I2C_SendByte(device_cmd
);
420 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
426 // read 1 strings of data (Data array, Readout length, command to be written , SlaveDevice address ).
427 // len = uint8 (max buffer to read 256bytes)
428 static int16_t I2C_BufferRead(uint8_t *data
, uint8_t len
, uint8_t device_cmd
, uint8_t device_address
) {
430 if ( !data
|| len
== 0 )
433 // extra wait 500us (514us measured)
434 // 200us (xx measured)
437 uint16_t readcount
= 0;
443 // 0xB0 / 0xC0 == i2c write
444 I2C_SendByte(device_address
& 0xFE);
448 I2C_SendByte(device_cmd
);
452 // 0xB1 / 0xC1 == i2c read
454 I2C_SendByte(device_address
| 1);
463 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
469 int16_t tmp
= I2C_ReadByte();
473 *data
= (uint8_t)tmp
& 0xFF;
477 // ¶ÁÈ¡µÄµÚÒ»¸ö×Ö½ÚΪºóÐø³¤¶È
478 // The first byte in response is the message length
479 if (!readcount
&& (len
> *data
)) {
486 // acknowledgements. After last byte send NACK.
495 // return bytecount - first byte (which is length byte)
499 static int16_t I2C_ReadFW(uint8_t *data
, uint8_t len
, uint8_t msb
, uint8_t lsb
, uint8_t device_address
) {
500 //START, 0xB0, 0x00, 0x00, START, 0xB1, xx, yy, zz, ......, STOP
502 uint8_t readcount
= 0;
509 // 0xB0 / 0xC0 i2c write
510 I2C_SendByte(device_address
& 0xFE);
522 // 0xB1 / 0xC1 i2c read
524 I2C_SendByte(device_address
| 1);
533 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
540 int16_t tmp
= I2C_ReadByte();
544 *data
= (uint8_t)tmp
& 0xFF;
550 // acknowledgements. After last byte send NACK.
561 static bool I2C_WriteFW(uint8_t *data
, uint8_t len
, uint8_t msb
, uint8_t lsb
, uint8_t device_address
) {
562 //START, 0xB0, 0x00, 0x00, xx, yy, zz, ......, STOP
570 I2C_SendByte(device_address
& 0xFE);
597 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
603 void I2C_print_status(void) {
604 DbpString("Smart card module (ISO 7816)");
605 uint8_t resp
[] = {0,0,0,0};
606 I2C_Reset_EnterMainProgram();
607 uint8_t len
= I2C_BufferRead(resp
, sizeof(resp
), I2C_DEVICE_CMD_GETVERSION
, I2C_DEVICE_ADDRESS_MAIN
);
609 Dbprintf(" version.................v%x.%02x", resp
[0], resp
[1]);
611 DbpString(" version.................FAILED");
614 // Will read response from smart card module, retries 3 times to get the data.
615 static bool sc_rx_bytes(uint8_t* dest
, uint8_t *destlen
) {
622 len
= I2C_BufferRead(dest
, *destlen
, I2C_DEVICE_CMD_READ
, I2C_DEVICE_ADDRESS_MAIN
);
626 } else if ( len
== 1 ) {
628 } else if ( len
<= 0 ) {
636 *destlen
= (uint8_t)len
& 0xFF;
640 static bool GetATR(smart_card_atr_t
*card_ptr
) {
646 card_ptr
->atr_len
= 0;
647 memset(card_ptr
->atr
, 0, sizeof(card_ptr
->atr
));
650 // start [C0 01] stop start C1 len aa bb cc stop]
651 I2C_WriteCmd(I2C_DEVICE_CMD_GENERATE_ATR
, I2C_DEVICE_ADDRESS_MAIN
);
653 // wait for sim card to answer.
654 // 1byte = 1ms, max frame 256bytes. Should wait 256ms at least just in case.
655 if (!I2C_WaitForSim())
658 // read bytes from module
659 uint8_t len
= sizeof(card_ptr
->atr
);
660 if ( !sc_rx_bytes(card_ptr
->atr
, &len
) )
663 card_ptr
->atr_len
= len
;
664 LogTrace(card_ptr
->atr
, card_ptr
->atr_len
, 0, 0, NULL
, false);
669 void SmartCardAtr(void) {
670 smart_card_atr_t card
;
674 I2C_Reset_EnterMainProgram();
675 bool isOK
= GetATR( &card
);
676 cmd_send(CMD_ACK
, isOK
, sizeof(smart_card_atr_t
), 0, &card
, sizeof(smart_card_atr_t
));
681 void SmartCardRaw( uint64_t arg0
, uint64_t arg1
, uint8_t *data
) {
686 uint8_t *resp
= BigBuf_malloc(ISO7618_MAX_FRAME
);
687 smartcard_command_t flags
= arg0
;
689 if ((flags
& SC_CONNECT
))
694 if ((flags
& SC_CONNECT
)) {
696 I2C_Reset_EnterMainProgram();
698 if ((flags
& SC_SELECT
)) {
699 smart_card_atr_t card
;
700 bool gotATR
= GetATR( &card
);
701 //cmd_send(CMD_ACK, gotATR, sizeof(smart_card_atr_t), 0, &card, sizeof(smart_card_atr_t));
707 if ((flags
& SC_RAW
) || (flags
& SC_RAW_T0
)) {
709 LogTrace(data
, arg1
, 0, 0, NULL
, true);
712 // asBytes = A0 A4 00 00 02
714 bool res
= I2C_BufferWrite(data
, arg1
, ((flags
& SC_RAW_T0
) ? I2C_DEVICE_CMD_SEND_T0
: I2C_DEVICE_CMD_SEND
), I2C_DEVICE_ADDRESS_MAIN
);
715 if ( !res
&& MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
717 // read bytes from module
718 len
= ISO7618_MAX_FRAME
;
719 res
= sc_rx_bytes(resp
, &len
);
721 LogTrace(resp
, len
, 0, 0, NULL
, false);
727 cmd_send(CMD_ACK
, len
, 0, 0, resp
, len
);
733 void SmartCardUpgrade(uint64_t arg0
) {
737 #define I2C_BLOCK_SIZE 128
738 // write. Sector0, with 11,22,33,44
739 // erase is 128bytes, and takes 50ms to execute
741 I2C_Reset_EnterBootloader();
745 uint16_t length
= arg0
;
747 uint8_t *fwdata
= BigBuf_get_addr();
748 uint8_t *verfiydata
= BigBuf_malloc(I2C_BLOCK_SIZE
);
752 uint8_t msb
= (pos
>> 8) & 0xFF;
753 uint8_t lsb
= pos
& 0xFF;
755 Dbprintf("FW %02X%02X", msb
, lsb
);
757 size_t size
= MIN(I2C_BLOCK_SIZE
, length
);
760 res
= I2C_WriteFW(fwdata
+pos
, size
, msb
, lsb
, I2C_DEVICE_ADDRESS_BOOT
);
762 DbpString("Writing failed");
767 // writing takes time.
771 res
= I2C_ReadFW(verfiydata
, size
, msb
, lsb
, I2C_DEVICE_ADDRESS_BOOT
);
773 DbpString("Reading back failed");
779 if ( 0 != memcmp(fwdata
+pos
, verfiydata
, size
)) {
780 DbpString("not equal data");
788 cmd_send(CMD_ACK
, isOK
, pos
, 0, 0, 0);
793 // unfinished (or not needed?)
794 //void SmartCardSetBaud(uint64_t arg0) {
797 void SmartCardSetClock(uint64_t arg0
) {
800 I2C_Reset_EnterMainProgram();
803 // start [C0 05 xx] stop
804 I2C_WriteByte(arg0
, I2C_DEVICE_CMD_SIM_CLC
, I2C_DEVICE_ADDRESS_MAIN
);
806 cmd_send(CMD_ACK
, 1, 0, 0, 0, 0);