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
24 #include "smartcard.h"
28 #define GPIO_RST AT91C_PIO_PA1
29 #define GPIO_SCL AT91C_PIO_PA5
30 #define GPIO_SDA AT91C_PIO_PA7
32 #define SCL_H HIGH(GPIO_SCL)
33 #define SCL_L LOW(GPIO_SCL)
34 #define SDA_H HIGH(GPIO_SDA)
35 #define SDA_L LOW(GPIO_SDA)
37 #define SCL_read (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SCL)
38 #define SDA_read (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SDA)
40 #define I2C_ERROR "I2C_WaitAck Error"
42 static volatile unsigned long c
;
44 // Ö±½ÓʹÓÃÑ»·À´ÑÓʱ£¬Ò»¸öÑ»· 6 ÌõÖ¸Á48M£¬ Delay=1 ´ó¸ÅΪ 200kbps
46 // I2CSpinDelayClk(4) = 12.31us
47 // I2CSpinDelayClk(1) = 3.07us
48 static void __attribute__((optimize("O0"))) I2CSpinDelayClk(uint16_t delay
) {
49 for (c
= delay
* 2; c
; c
--) {};
52 // communication delay functions
53 #define I2C_DELAY_1CLK I2CSpinDelayClk(1)
54 #define I2C_DELAY_2CLK I2CSpinDelayClk(2)
55 #define I2C_DELAY_XCLK(x) I2CSpinDelayClk((x))
57 #define ISO7618_MAX_FRAME 255
59 // try i2c bus recovery at 100kHz = 5uS high, 5uS low
60 static void I2C_recovery(void) {
62 DbpString("Performing i2c bus recovery");
67 //9nth cycle acts as NACK
68 for (int i
= 0; i
< 10; i
++) {
73 //a STOP signal (SDA from low to high while CLK is high)
78 bool isok
= (SCL_read
&& SDA_read
);
80 DbpString("I2C bus recovery error: SDA still LOW");
82 DbpString("I2C bus recovery error: SCL still LOW");
84 DbpString("I2C bus recovery complete");
87 static void I2C_init(void) {
88 // Configure reset pin
89 AT91C_BASE_PIOA
->PIO_PPUDR
= GPIO_RST
; // disable pull up resistor
90 AT91C_BASE_PIOA
->PIO_MDDR
= GPIO_RST
; // push-pull output (multidriver disabled)
92 // Configure SCL and SDA pins
93 AT91C_BASE_PIOA
->PIO_PPUER
|= (GPIO_SCL
| GPIO_SDA
); // enable pull up resistor
94 AT91C_BASE_PIOA
->PIO_MDER
|= (GPIO_SCL
| GPIO_SDA
); // open drain output (multidriver enabled) - requires external pull up resistor
96 // set all three outputs to high
97 AT91C_BASE_PIOA
->PIO_SODR
|= (GPIO_SCL
| GPIO_SDA
| GPIO_RST
);
99 // configure all three pins as output, controlled by PIOA
100 AT91C_BASE_PIOA
->PIO_OER
|= (GPIO_SCL
| GPIO_SDA
| GPIO_RST
);
101 AT91C_BASE_PIOA
->PIO_PER
|= (GPIO_SCL
| GPIO_SDA
| GPIO_RST
);
103 bool isok
= (SCL_read
&& SDA_read
);
109 // set the reset state
110 static void I2C_SetResetStatus(uint8_t LineRST
, uint8_t LineSCK
, uint8_t LineSDA
) {
127 // Reset the SIM_Adapter, then enter the main program
128 // Note: the SIM_Adapter will not enter the main program after power up. Please run this function before use SIM_Adapter.
129 static void I2C_Reset_EnterMainProgram(void) {
132 I2C_SetResetStatus(0, 0, 0);
134 I2C_SetResetStatus(1, 0, 0);
136 I2C_SetResetStatus(1, 1, 1);
140 // Wait for the clock to go High.
141 static bool WaitSCL_H_delay(uint32_t delay
) {
151 // 15000 * 3.07us = 46050us. 46.05ms
152 static bool WaitSCL_H(void) {
153 return WaitSCL_H_delay(15000);
156 bool WaitSCL_L_delay(uint32_t delay
) {
166 bool WaitSCL_L(void) {
167 return WaitSCL_L_delay(15000);
170 static bool I2C_Start(void) {
173 SDA_H
; I2C_DELAY_1CLK
;
175 if (!WaitSCL_H()) return false;
179 if (!SCL_read
) return false;
180 if (!SDA_read
) return false;
182 SDA_L
; I2C_DELAY_2CLK
;
187 static void I2C_Stop(void) {
188 SCL_L
; I2C_DELAY_2CLK
;
189 SDA_L
; I2C_DELAY_2CLK
;
190 SCL_H
; I2C_DELAY_2CLK
;
191 if (!WaitSCL_H()) return;
196 static bool I2C_WaitAck(void) {
197 SCL_L
; I2C_DELAY_1CLK
;
198 SDA_H
; I2C_DELAY_1CLK
;
213 static void I2C_SendByte(uint8_t data
) {
238 bool I2C_is_available(void) {
239 I2C_Reset_EnterMainProgram();
240 if (!I2C_Start()) // some other device is active on the bus
242 I2C_SendByte(I2C_DEVICE_ADDRESS_MAIN
& 0xFE);
243 if (!I2C_WaitAck()) { // no response from smartcard reader
251 #ifdef WITH_SMARTCARD
252 // Reset the SIM_Adapter, then enter the bootloader program
253 // Reserve£ºFor firmware update.
254 static void I2C_Reset_EnterBootloader(void) {
255 I2C_SetResetStatus(0, 1, 1);
257 I2C_SetResetStatus(1, 1, 1);
261 // Wait max 1800ms or until SCL goes LOW.
262 // It timeout reading response from card
263 // Which ever comes first
264 bool WaitSCL_L_timeout(void){
265 volatile uint16_t delay
= 1800;
276 static bool I2C_WaitForSim() {
277 // wait for data from card
278 if (!WaitSCL_L_timeout())
281 // 8051 speaks with smart card.
282 // 1000*50*3.07 = 153.5ms
283 // 1byte transfer == 1ms with max frame being 256bytes
284 if (!WaitSCL_H_delay(10 * 1000 * 50))
291 static void I2C_Ack(void) {
292 SCL_L
; I2C_DELAY_2CLK
;
293 SDA_L
; I2C_DELAY_2CLK
;
294 SCL_H
; I2C_DELAY_2CLK
;
295 if (!WaitSCL_H()) return;
296 SCL_L
; I2C_DELAY_2CLK
;
300 static void I2C_NoAck(void) {
301 SCL_L
; I2C_DELAY_2CLK
;
302 SDA_H
; I2C_DELAY_2CLK
;
303 SCL_H
; I2C_DELAY_2CLK
;
304 if (!WaitSCL_H()) return;
305 SCL_L
; I2C_DELAY_2CLK
;
308 static int16_t I2C_ReadByte(void) {
309 uint8_t bits
= 8, b
= 0;
315 if (!WaitSCL_L()) return -2;
320 if (!WaitSCL_H()) return -1;
330 // Sends one byte ( command to be written, SlaveDevice address)
331 static bool I2C_WriteCmd(uint8_t device_cmd
, uint8_t device_address
) {
337 I2C_SendByte(device_address
& 0xFE);
341 I2C_SendByte(device_cmd
);
350 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
356 // Sends 1 byte data (Data to be written, command to be written , SlaveDevice address ).
357 static bool I2C_WriteByte(uint8_t data
, uint8_t device_cmd
, uint8_t device_address
) {
363 I2C_SendByte(device_address
& 0xFE);
367 I2C_SendByte(device_cmd
);
380 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
386 //Sends a string of data (Array, length, command to be written , SlaveDevice address ).
387 // len = uint8 (max buffer to write 256bytes)
388 static bool I2C_BufferWrite(uint8_t *data
, uint8_t len
, uint8_t device_cmd
, uint8_t device_address
) {
394 I2C_SendByte(device_address
& 0xFE);
398 I2C_SendByte(device_cmd
);
418 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
424 // read 1 strings of data (Data array, Readout length, command to be written , SlaveDevice address ).
425 // len = uint8 (max buffer to read 256bytes)
426 static int16_t I2C_BufferRead(uint8_t *data
, uint8_t len
, uint8_t device_cmd
, uint8_t device_address
) {
428 if ( !data
|| len
== 0 )
431 // extra wait 500us (514us measured)
432 // 200us (xx measured)
435 uint16_t readcount
= 0;
441 // 0xB0 / 0xC0 == i2c write
442 I2C_SendByte(device_address
& 0xFE);
446 I2C_SendByte(device_cmd
);
450 // 0xB1 / 0xC1 == i2c read
452 I2C_SendByte(device_address
| 1);
461 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
467 int16_t tmp
= I2C_ReadByte();
471 *data
= (uint8_t)tmp
& 0xFF;
475 // ¶ÁÈ¡µÄµÚÒ»¸ö×Ö½ÚΪºóÐø³¤¶È
476 // The first byte in response is the message length
477 if (!readcount
&& (len
> *data
)) {
484 // acknowledgements. After last byte send NACK.
493 // return bytecount - first byte (which is length byte)
497 static int16_t I2C_ReadFW(uint8_t *data
, uint8_t len
, uint8_t msb
, uint8_t lsb
, uint8_t device_address
) {
498 //START, 0xB0, 0x00, 0x00, START, 0xB1, xx, yy, zz, ......, STOP
500 uint8_t readcount
= 0;
507 // 0xB0 / 0xC0 i2c write
508 I2C_SendByte(device_address
& 0xFE);
520 // 0xB1 / 0xC1 i2c read
522 I2C_SendByte(device_address
| 1);
531 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
538 int16_t tmp
= I2C_ReadByte();
542 *data
= (uint8_t)tmp
& 0xFF;
548 // acknowledgements. After last byte send NACK.
559 static bool I2C_WriteFW(uint8_t *data
, uint8_t len
, uint8_t msb
, uint8_t lsb
, uint8_t device_address
) {
560 //START, 0xB0, 0x00, 0x00, xx, yy, zz, ......, STOP
568 I2C_SendByte(device_address
& 0xFE);
595 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
601 void I2C_print_status(void) {
602 DbpString("Smart card module (ISO 7816)");
603 uint8_t resp
[] = {0,0,0,0};
604 I2C_Reset_EnterMainProgram();
605 uint8_t len
= I2C_BufferRead(resp
, sizeof(resp
), I2C_DEVICE_CMD_GETVERSION
, I2C_DEVICE_ADDRESS_MAIN
);
607 Dbprintf(" version.................v%x.%02x", resp
[0], resp
[1]);
609 DbpString(" version.................FAILED");
612 // Will read response from smart card module, retries 3 times to get the data.
613 static bool sc_rx_bytes(uint8_t* dest
, uint8_t *destlen
) {
620 len
= I2C_BufferRead(dest
, *destlen
, I2C_DEVICE_CMD_READ
, I2C_DEVICE_ADDRESS_MAIN
);
624 } else if ( len
== 1 ) {
626 } else if ( len
<= 0 ) {
634 *destlen
= (uint8_t)len
& 0xFF;
638 static bool GetATR(smart_card_atr_t
*card_ptr
) {
644 card_ptr
->atr_len
= 0;
645 memset(card_ptr
->atr
, 0, sizeof(card_ptr
->atr
));
648 // start [C0 01] stop start C1 len aa bb cc stop]
649 I2C_WriteCmd(I2C_DEVICE_CMD_GENERATE_ATR
, I2C_DEVICE_ADDRESS_MAIN
);
651 // wait for sim card to answer.
652 // 1byte = 1ms, max frame 256bytes. Should wait 256ms at least just in case.
653 if (!I2C_WaitForSim())
656 // read bytes from module
657 uint8_t len
= sizeof(card_ptr
->atr
);
658 if ( !sc_rx_bytes(card_ptr
->atr
, &len
) )
661 card_ptr
->atr_len
= len
;
662 LogTrace(card_ptr
->atr
, card_ptr
->atr_len
, 0, 0, NULL
, false);
667 void SmartCardAtr(void) {
668 smart_card_atr_t card
;
672 I2C_Reset_EnterMainProgram();
673 bool isOK
= GetATR( &card
);
674 cmd_send(CMD_ACK
, isOK
, sizeof(smart_card_atr_t
), 0, &card
, sizeof(smart_card_atr_t
));
679 void SmartCardRaw( uint64_t arg0
, uint64_t arg1
, uint8_t *data
) {
684 uint8_t *resp
= BigBuf_malloc(ISO7618_MAX_FRAME
);
685 smartcard_command_t flags
= arg0
;
687 if ((flags
& SC_CONNECT
))
692 if ((flags
& SC_CONNECT
)) {
694 I2C_Reset_EnterMainProgram();
696 if ((flags
& SC_SELECT
)) {
697 smart_card_atr_t card
;
698 bool gotATR
= GetATR( &card
);
699 //cmd_send(CMD_ACK, gotATR, sizeof(smart_card_atr_t), 0, &card, sizeof(smart_card_atr_t));
705 if ((flags
& SC_RAW
) || (flags
& SC_RAW_T0
)) {
707 LogTrace(data
, arg1
, 0, 0, NULL
, true);
710 // asBytes = A0 A4 00 00 02
712 bool res
= I2C_BufferWrite(data
, arg1
, ((flags
& SC_RAW_T0
) ? I2C_DEVICE_CMD_SEND_T0
: I2C_DEVICE_CMD_SEND
), I2C_DEVICE_ADDRESS_MAIN
);
713 if ( !res
&& MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
715 // read bytes from module
716 len
= ISO7618_MAX_FRAME
;
717 res
= sc_rx_bytes(resp
, &len
);
719 LogTrace(resp
, len
, 0, 0, NULL
, false);
725 cmd_send(CMD_ACK
, len
, 0, 0, resp
, len
);
731 void SmartCardUpgrade(uint64_t arg0
) {
735 #define I2C_BLOCK_SIZE 128
736 // write. Sector0, with 11,22,33,44
737 // erase is 128bytes, and takes 50ms to execute
739 I2C_Reset_EnterBootloader();
743 uint16_t length
= arg0
;
745 uint8_t *fwdata
= BigBuf_get_addr();
746 uint8_t *verfiydata
= BigBuf_malloc(I2C_BLOCK_SIZE
);
750 uint8_t msb
= (pos
>> 8) & 0xFF;
751 uint8_t lsb
= pos
& 0xFF;
753 Dbprintf("FW %02X%02X", msb
, lsb
);
755 size_t size
= MIN(I2C_BLOCK_SIZE
, length
);
758 res
= I2C_WriteFW(fwdata
+pos
, size
, msb
, lsb
, I2C_DEVICE_ADDRESS_BOOT
);
760 DbpString("Writing failed");
765 // writing takes time.
769 res
= I2C_ReadFW(verfiydata
, size
, msb
, lsb
, I2C_DEVICE_ADDRESS_BOOT
);
771 DbpString("Reading back failed");
777 if ( 0 != memcmp(fwdata
+pos
, verfiydata
, size
)) {
778 DbpString("not equal data");
786 cmd_send(CMD_ACK
, isOK
, pos
, 0, 0, 0);
791 // unfinished (or not needed?)
792 //void SmartCardSetBaud(uint64_t arg0) {
795 void SmartCardSetClock(uint64_t arg0
) {
798 I2C_Reset_EnterMainProgram();
801 // start [C0 05 xx] stop
802 I2C_WriteByte(arg0
, I2C_DEVICE_CMD_SIM_CLC
, I2C_DEVICE_ADDRESS_MAIN
);
804 cmd_send(CMD_ACK
, 1, 0, 0, 0, 0);