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
23 #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 function
53 #define I2C_DELAY_1CLK I2CSpinDelayClk(1)
54 #define I2C_DELAY_2CLK I2CSpinDelayClk(2)
55 #define I2C_DELAY_XCLK(x) I2CSpinDelayClk((x))
58 #define ISO7618_MAX_FRAME 255
60 static void I2C_init(void) {
61 // Configure reset pin
62 AT91C_BASE_PIOA
->PIO_PPUDR
= GPIO_RST
; // disable pull up resistor
63 AT91C_BASE_PIOA
->PIO_MDDR
= GPIO_RST
; // push-pull output (multidriver disabled)
65 // Configure SCL and SDA pins
66 AT91C_BASE_PIOA
->PIO_PPUER
|= (GPIO_SCL
| GPIO_SDA
); // enable pull up resistor
67 AT91C_BASE_PIOA
->PIO_MDER
|= (GPIO_SCL
| GPIO_SDA
); // open drain output (multidriver enabled) - requires external pull up resistor
69 // set all three outputs to high
70 AT91C_BASE_PIOA
->PIO_SODR
|= (GPIO_SCL
| GPIO_SDA
| GPIO_RST
);
72 // configure all three pins as output, controlled by PIOA
73 AT91C_BASE_PIOA
->PIO_OER
|= (GPIO_SCL
| GPIO_SDA
| GPIO_RST
);
74 AT91C_BASE_PIOA
->PIO_PER
|= (GPIO_SCL
| GPIO_SDA
| GPIO_RST
);
79 // set the reset state
80 static void I2C_SetResetStatus(uint8_t LineRST
, uint8_t LineSCK
, uint8_t LineSDA
) {
98 // Reset the SIM_Adapter, then enter the main program
99 // Note: the SIM_Adapter will not enter the main program after power up. Please run this function before use SIM_Adapter.
100 static void I2C_Reset_EnterMainProgram(void) {
101 I2C_SetResetStatus(0, 0, 0); // ÀµÍ¸´Î»Ïß
103 I2C_SetResetStatus(1, 0, 0); // ½â³ý¸´Î»
105 I2C_SetResetStatus(1, 1, 1); // À¸ßÊý¾ÝÏß
110 // Wait for the clock to go High.
111 static bool WaitSCL_H_delay(uint32_t delay
) {
121 // 15000 * 3.07us = 46050us. 46.05ms
122 static bool WaitSCL_H(void) {
123 return WaitSCL_H_delay(15000);
126 bool WaitSCL_L_delay(uint32_t delay
) {
136 bool WaitSCL_L(void) {
137 return WaitSCL_L_delay(15000);
140 static bool I2C_Start(void) {
143 SDA_H
; I2C_DELAY_1CLK
;
145 if (!WaitSCL_H()) return false;
149 if (!SCL_read
) return false;
150 if (!SDA_read
) return false;
152 SDA_L
; I2C_DELAY_2CLK
;
157 static void I2C_Stop(void) {
158 SCL_L
; I2C_DELAY_2CLK
;
159 SDA_L
; I2C_DELAY_2CLK
;
160 SCL_H
; I2C_DELAY_2CLK
;
161 if (!WaitSCL_H()) return;
166 static bool I2C_WaitAck(void) {
167 SCL_L
; I2C_DELAY_1CLK
;
168 SDA_H
; I2C_DELAY_1CLK
;
183 static void I2C_SendByte(uint8_t data
) {
187 SCL_L
; I2C_DELAY_1CLK
;
207 bool I2C_is_available(void) {
209 I2C_Reset_EnterMainProgram();
210 if (!I2C_Start()) // some other device is active on the bus
212 I2C_SendByte(I2C_DEVICE_ADDRESS_MAIN
& 0xFE);
213 if (!I2C_WaitAck()) { // no response from smartcard reader
221 #ifdef WITH_SMARTCARD
223 // Reset the SIM_Adapter, then enter the bootloader program
224 // Reserve£ºFor firmware update.
225 static void I2C_Reset_EnterBootloader(void) {
226 I2C_SetResetStatus(0, 1, 1); // ÀµÍ¸´Î»Ïß
228 I2C_SetResetStatus(1, 1, 1); // ½â³ý¸´Î»
232 // Wait max 300ms or until SCL goes LOW.
233 // Which ever comes first
234 static bool WaitSCL_L_300ms(void) {
235 volatile uint16_t delay
= 310;
246 static bool I2C_WaitForSim() {
247 // variable delay here.
248 if (!WaitSCL_L_300ms())
251 // 8051 speaks with smart card.
252 // 1000*50*3.07 = 153.5ms
253 // 1byte transfer == 1ms with max frame being 256bytes
254 if (!WaitSCL_H_delay(10 * 1000 * 50))
261 static void I2C_Ack(void) {
262 SCL_L
; I2C_DELAY_2CLK
;
263 SDA_L
; I2C_DELAY_2CLK
;
264 SCL_H
; I2C_DELAY_2CLK
;
265 if (!WaitSCL_H()) return;
266 SCL_L
; I2C_DELAY_2CLK
;
270 static void I2C_NoAck(void) {
271 SCL_L
; I2C_DELAY_2CLK
;
272 SDA_H
; I2C_DELAY_2CLK
;
273 SCL_H
; I2C_DELAY_2CLK
;
274 if (!WaitSCL_H()) return;
275 SCL_L
; I2C_DELAY_2CLK
;
278 static int16_t I2C_ReadByte(void) {
279 uint8_t bits
= 8, b
= 0;
285 if (!WaitSCL_L()) return -2;
290 if (!WaitSCL_H()) return -1;
300 // Sends one byte ( command to be written, SlaveDevice address)
301 static bool I2C_WriteCmd(uint8_t device_cmd
, uint8_t device_address
) {
307 I2C_SendByte(device_address
& 0xFE);
311 I2C_SendByte(device_cmd
);
320 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
326 // дÈë1×Ö½ÚÊý¾Ý £¨´ýдÈëÊý¾Ý£¬´ýдÈëµØÖ·£¬Æ÷¼þÀàÐÍ£©
327 // Sends 1 byte data (Data to be written, command to be written , SlaveDevice address ).
328 static bool I2C_WriteByte(uint8_t data
, uint8_t device_cmd
, uint8_t device_address
) {
334 I2C_SendByte(device_address
& 0xFE);
338 I2C_SendByte(device_cmd
);
351 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
357 // дÈë1´®Êý¾Ý£¨´ýдÈëÊý×éµØÖ·£¬´ýдÈ볤¶È£¬´ýдÈëµØÖ·£¬Æ÷¼þÀàÐÍ£©
358 //Sends a string of data (Array, length, command to be written , SlaveDevice address ).
359 // len = uint8 (max buffer to write 256bytes)
360 static bool I2C_BufferWrite(uint8_t *data
, uint8_t len
, uint8_t device_cmd
, uint8_t device_address
) {
366 I2C_SendByte(device_address
& 0xFE);
370 I2C_SendByte(device_cmd
);
390 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
396 // ¶Á³ö1´®Êý¾Ý£¨´æ·Å¶Á³öÊý¾Ý£¬´ý¶Á³ö³¤¶È£¬´ø¶Á³öµØÖ·£¬Æ÷¼þÀàÐÍ£©
397 // read 1 strings of data (Data array, Readout length, command to be written , SlaveDevice address ).
398 // len = uint8 (max buffer to read 256bytes)
399 static int16_t I2C_BufferRead(uint8_t *data
, uint8_t len
, uint8_t device_cmd
, uint8_t device_address
) {
401 if ( !data
|| len
== 0 )
404 // extra wait 500us (514us measured)
405 // 200us (xx measured)
408 uint16_t readcount
= 0;
414 // 0xB0 / 0xC0 == i2c write
415 I2C_SendByte(device_address
& 0xFE);
419 I2C_SendByte(device_cmd
);
423 // 0xB1 / 0xC1 == i2c read
425 I2C_SendByte(device_address
| 1);
434 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
440 int16_t tmp
= I2C_ReadByte();
444 *data
= (uint8_t)tmp
& 0xFF;
448 // ¶ÁÈ¡µÄµÚÒ»¸ö×Ö½ÚΪºóÐø³¤¶È
449 // The first byte in response is the message length
450 if (!readcount
&& (len
> *data
)) {
457 // acknowledgements. After last byte send NACK.
465 // return bytecount - first byte (which is length byte)
469 static int16_t I2C_ReadFW(uint8_t *data
, uint8_t len
, uint8_t msb
, uint8_t lsb
, uint8_t device_address
) {
470 //START, 0xB0, 0x00, 0x00, START, 0xB1, xx, yy, zz, ......, STOP
472 uint8_t readcount
= 0;
479 // 0xB0 / 0xC0 i2c write
480 I2C_SendByte(device_address
& 0xFE);
494 // 0xB1 / 0xC1 i2c read
496 I2C_SendByte(device_address
| 1);
505 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
512 int16_t tmp
= I2C_ReadByte();
516 *data
= (uint8_t)tmp
& 0xFF;
522 // acknowledgements. After last byte send NACK.
533 static bool I2C_WriteFW(uint8_t *data
, uint8_t len
, uint8_t msb
, uint8_t lsb
, uint8_t device_address
) {
534 //START, 0xB0, 0x00, 0x00, xx, yy, zz, ......, STOP
542 I2C_SendByte(device_address
& 0xFE);
571 if ( MF_DBGLEVEL
> 3 ) DbpString(I2C_ERROR
);
577 void I2C_print_status(void) {
578 DbpString("Smart card module (ISO 7816)");
579 uint8_t resp
[] = {0,0,0,0};
581 I2C_Reset_EnterMainProgram();
582 uint8_t len
= I2C_BufferRead(resp
, sizeof(resp
), I2C_DEVICE_CMD_GETVERSION
, I2C_DEVICE_ADDRESS_MAIN
);
584 Dbprintf(" version.................v%x.%02x", resp
[0], resp
[1]);
586 DbpString(" version.................FAILED");
589 // Will read response from smart card module, retries 3 times to get the data.
590 static bool sc_rx_bytes(uint8_t* dest
, uint8_t *destlen
) {
597 len
= I2C_BufferRead(dest
, *destlen
, I2C_DEVICE_CMD_READ
, I2C_DEVICE_ADDRESS_MAIN
);
601 } else if ( len
== 1 ) {
603 } else if ( len
<= 0 ) {
611 *destlen
= (uint8_t)len
& 0xFF;
615 static bool GetATR(smart_card_atr_t
*card_ptr
) {
621 card_ptr
->atr_len
= 0;
622 memset(card_ptr
->atr
, 0, sizeof(card_ptr
->atr
));
625 // start [C0 01] stop start C1 len aa bb cc stop]
626 I2C_WriteCmd(I2C_DEVICE_CMD_GENERATE_ATR
, I2C_DEVICE_ADDRESS_MAIN
);
627 uint8_t cmd
[1] = {1};
628 LogTrace(cmd
, 1, 0, 0, NULL
, true);
630 // wait for sim card to answer.
631 // 1byte = 1ms, max frame 256bytes. Should wait 256ms at least just in case.
632 if (!I2C_WaitForSim())
635 // read bytes from module
636 uint8_t len
= sizeof(card_ptr
->atr
);
637 if ( !sc_rx_bytes(card_ptr
->atr
, &len
) )
641 if ( (card_ptr
->atr
[1] & 0x10) == 0x10) pos_td
++;
642 if ( (card_ptr
->atr
[1] & 0x20) == 0x20) pos_td
++;
643 if ( (card_ptr
->atr
[1] & 0x40) == 0x40) pos_td
++;
645 // T0 indicate presence T=0 vs T=1. T=1 has checksum TCK
646 if ( (card_ptr
->atr
[1] & 0x80) == 0x80) {
650 // 1 == T1 , presence of checksum TCK
651 if ( (card_ptr
->atr
[pos_td
] & 0x01) == 0x01) {
653 // xor property. will be zero when xored with chksum.
654 for (uint8_t i
= 1; i
< len
; ++i
)
655 chksum
^= card_ptr
->atr
[i
];
657 if ( MF_DBGLEVEL
> 2) DbpString("Wrong ATR checksum");
662 // for some reason we only get first byte of atr, if that is so, send dummy command to retrieve the rest of the atr
665 uint8_t data
[1] = {0};
666 I2C_BufferWrite(data
, len
, I2C_DEVICE_CMD_SEND
, I2C_DEVICE_ADDRESS_MAIN
);
668 if ( !I2C_WaitForSim() )
671 uint8_t len2
= I2C_BufferRead(card_ptr
->atr
+ len
, sizeof(card_ptr
->atr
) - len
, I2C_DEVICE_CMD_READ
, I2C_DEVICE_ADDRESS_MAIN
);
675 card_ptr
->atr_len
= len
;
676 LogTrace(card_ptr
->atr
, card_ptr
->atr_len
, 0, 0, NULL
, false);
681 void SmartCardAtr(void) {
682 smart_card_atr_t card
;
687 I2C_Reset_EnterMainProgram();
688 bool isOK
= GetATR( &card
);
689 cmd_send(CMD_ACK
, isOK
, sizeof(smart_card_atr_t
), 0, &card
, sizeof(smart_card_atr_t
));
694 void SmartCardRaw( uint64_t arg0
, uint64_t arg1
, uint8_t *data
) {
699 uint8_t *resp
= BigBuf_malloc(ISO7618_MAX_FRAME
);
700 smartcard_command_t flags
= arg0
;
702 if ((flags
& SC_CONNECT
))
707 if ((flags
& SC_CONNECT
)) {
710 I2C_Reset_EnterMainProgram();
712 if ( !(flags
& SC_NO_SELECT
) ) {
713 smart_card_atr_t card
;
714 bool gotATR
= GetATR( &card
);
715 //cmd_send(CMD_ACK, gotATR, sizeof(smart_card_atr_t), 0, &card, sizeof(smart_card_atr_t));
721 if ((flags
& SC_RAW
)) {
723 LogTrace(data
, arg1
, 0, 0, NULL
, true);
726 // asBytes = A0 A4 00 00 02
728 I2C_BufferWrite(data
, arg1
, I2C_DEVICE_CMD_SEND
, I2C_DEVICE_ADDRESS_MAIN
);
730 if ( !I2C_WaitForSim() )
733 // read bytes from module
734 len
= ISO7618_MAX_FRAME
;
735 sc_rx_bytes(resp
, &len
);
736 LogTrace(resp
, len
, 0, 0, NULL
, false);
739 cmd_send(CMD_ACK
, len
, 0, 0, resp
, len
);
744 void SmartCardUpgrade(uint64_t arg0
) {
748 #define I2C_BLOCK_SIZE 128
749 // write. Sector0, with 11,22,33,44
750 // erase is 128bytes, and takes 50ms to execute
753 I2C_Reset_EnterBootloader();
757 uint16_t length
= arg0
;
759 uint8_t *fwdata
= BigBuf_get_addr();
760 uint8_t *verfiydata
= BigBuf_malloc(I2C_BLOCK_SIZE
);
764 uint8_t msb
= (pos
>> 8) & 0xFF;
765 uint8_t lsb
= pos
& 0xFF;
767 Dbprintf("FW %02X%02X", msb
, lsb
);
769 size_t size
= MIN(I2C_BLOCK_SIZE
, length
);
772 res
= I2C_WriteFW(fwdata
+pos
, size
, msb
, lsb
, I2C_DEVICE_ADDRESS_BOOT
);
774 DbpString("Writing failed");
779 // writing takes time.
783 res
= I2C_ReadFW(verfiydata
, size
, msb
, lsb
, I2C_DEVICE_ADDRESS_BOOT
);
785 DbpString("Reading back failed");
791 if ( 0 != memcmp(fwdata
+pos
, verfiydata
, size
)) {
792 DbpString("not equal data");
800 cmd_send(CMD_ACK
, isOK
, pos
, 0, 0, 0);
804 // unfinished (or not needed?)
805 //void SmartCardSetBaud(uint64_t arg0) {
808 void SmartCardSetClock(uint64_t arg0
) {
812 I2C_Reset_EnterMainProgram();
815 // start [C0 05 xx] stop
816 I2C_WriteByte(arg0
, I2C_DEVICE_CMD_SIM_CLC
, I2C_DEVICE_ADDRESS_MAIN
);
818 cmd_send(CMD_ACK
, 1, 0, 0, 0, 0);