b30156a9a0e61b7bc91bcb13e5867439aa680b5b
[hackover2013-badge-firmware.git] / drivers / sensors / pn532 / helpers / pn532_mifare_classic.c
1 /**************************************************************************/
2 /*!
3 @file pn532_mifare_classic.c
4 */
5 /**************************************************************************/
6
7 /* MIFARE CLASSIC DESCRIPTION
8 ==========================
9
10 MIFARE Classic cards come in 1K and 4K varieties. While several
11 varieties of chips exist, the two main chipsets used are described
12 in the following publicly accessible documents:
13
14 MF1S503x Mifare Classic 1K data sheet:
15 http://www.nxp.com/documents/data_sheet/MF1S503x.pdf
16
17 MF1S70yyX MIFARE Classic 4K data sheet:
18 http://www.nxp.com/documents/data_sheet/MF1S70YYX.pdf
19
20 Mifare Classic cards typically have a a 4-byte NUID, though you may
21 find cards with 7 byte IDs as well
22
23 EEPROM MEMORY
24 =============
25 Mifare Classic cards have either 1K or 4K of EEPROM memory. Each
26 memory block can be configured with different access conditions,
27 with two seperate authentication keys present in each block.
28
29 The two main Mifare Classic card types are organised as follows:
30
31 1K Cards: 16 sectors of 4 blocks (0..15)
32 4K Cards: 32 sectors of 4 blocks (0..31) and
33 8 sectors of 16 blocks (32..39)
34
35 4 block sectors
36 ===============
37 Sector Block Bytes Description
38 ------ ----- ----- -----------
39 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
40
41 1 3 [-------KEY A-------] [Access Bits] [-------KEY A-------] Sector Trailer 1
42 2 [ Data ] Data
43 1 [ Data ] Data
44 0 [ Data ] Data
45
46 0 3 [-------KEY A-------] [Access Bits] [-------KEY A-------] Sector Trailer 1
47 2 [ Data ] Data
48 1 [ Data ] Data
49 0 [ Manufacturer Data ] Manufacturer Block
50
51 Sector Trailer (Block 3)
52 ------------------------
53 The sector trailer block contains the two secret keys (Key A and Key B), as well
54 as the access conditions for the four blocks. It has the following structure:
55
56 Sector Trailer Bytes
57 --------------------------------------------------------------
58 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
59 [ Key A ] [Access Bits] [ Key B ]
60
61 For more information in using Keys to access the clock contents, see
62 Accessing Data Blocks further below.
63
64 Data Blocks (Blocks 0..2)
65 -------------------------
66 Data blocks are 16 bytes wide and, depending on the permissions set in the
67 access bits, can be read from and written to. You are free to use the 16 data
68 bytes in any way you wish. You can easily store text input, store four 32-bit
69 integer values, a 16 character uri, etc.
70
71 Data Blocks as "Value Blocks"
72 -----------------------------
73 An alternative to storing random data in the 16 byte-wide blocks is to
74 configure them as "Value Blocks". Value blocks allow performing electronic
75 purse functions (valid commands are: read, write, increment, decrement,
76 restore, transfer).
77
78 Each Value block contains a single signed 32-bit value, and this value is
79 stored 3 times for data integrity and security reasons. It is stored twice
80 non-inverted, and once inverted. The last 4 bytes are used for a 1-byte
81 address, which is stored 4 times (twice non-inverted, and twice inverted).
82
83 Data blocks configured as "Value Blocks" have the following structure:
84
85 Value Block Bytes
86 --------------------------------------------------------------
87 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
88 [ Value ] [ ~Value ] [ Value ] [A ~A A ~A]
89
90 Manufacturer Block (Sector 0, Block 0)
91 --------------------------------------
92 Sector 0 is special since it contains the Manufacturer Block. This block
93 contains the manufacturer data, and is read-only. It should be avoided
94 unless you know what you are doing.
95
96 16 block sectors
97 ================
98 16 block sectors are identical to 4 block sectors, but with more data blocks. The same
99 structure described in the 4 block sectors above applies.
100
101 Sector Block Bytes Description
102 ------ ----- ----- ----------
103 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
104
105 32 15 [-------KEY A-------] [Access Bits] [-------KEY B-------] Sector Trailer 32
106 14 [ Data ] Data
107 13 [ Data ] Data
108 ...
109 2 [ Data ] Data
110 1 [ Data ] Data
111 0 [ Data ] Data
112
113 ACCESSING DATA BLOCKS
114 =====================
115
116 Before you can access the cards, you must following two steps:
117
118 1.) You must retrieve the 7 byte UID or the 4-byte NUID of the card.
119 This can be done using pn532_mifareclassic_WaitForPassiveTarget()
120 below, which will return the appropriate ID.
121
122 2.) You must authenticate the sector you wish to access according to the
123 access rules defined in the Sector Trailer block for that sector.
124 This can be done using pn532_mifareclassic_AuthenticateBlock(),
125 passing in the appropriate key value.
126
127 Most new cards have a default Key A of 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF,
128 but some common values worth trying are:
129
130 0XFF 0XFF 0XFF 0XFF 0XFF 0XFF
131 0XD3 0XF7 0XD3 0XF7 0XD3 0XF7
132 0XA0 0XA1 0XA2 0XA3 0XA4 0XA5
133 0XB0 0XB1 0XB2 0XB3 0XB4 0XB5
134 0X4D 0X3A 0X99 0XC3 0X51 0XDD
135 0X1A 0X98 0X2C 0X7E 0X45 0X9A
136 0XAA 0XBB 0XCC 0XDD 0XEE 0XFF
137 0X00 0X00 0X00 0X00 0X00 0X00
138 0XAB 0XCD 0XEF 0X12 0X34 0X56
139
140 3.) Once authenication has succeeded, and depending on the sector
141 permissions, you can then read/write/increment/decrement the
142 contents of the specific block, using one of the helper functions
143 included in this module.
144
145 */
146
147 #include <string.h>
148
149 #include "../pn532.h"
150 #include "../pn532_bus.h"
151 #include "pn532_mifare.h"
152 #include "pn532_mifare_classic.h"
153
154 #include "core/systick/systick.h"
155
156 /**************************************************************************/
157 /*!
158 Indicates whether the specified block number is the first block
159 in the sector (block 0 relative to the current sector)
160 */
161 /**************************************************************************/
162 bool is_first_block (uint32_t uiBlock)
163 {
164 // Test if we are in the small or big sectors
165 if (uiBlock < 128)
166 return ((uiBlock) % 4 == 0);
167 else
168 return ((uiBlock) % 16 == 0);
169 }
170
171 /**************************************************************************/
172 /*!
173 Indicates whether the specified block number is the sector trailer
174 */
175 /**************************************************************************/
176 bool is_trailer_block (uint32_t uiBlock)
177 {
178 // Test if we are in the small or big sectors
179 if (uiBlock < 128)
180 return ((uiBlock + 1) % 4 == 0);
181 else
182 return ((uiBlock + 1) % 16 == 0);
183 }
184
185 /**************************************************************************/
186 /*!
187 Tries to detect MIFARE targets in passive mode. This needs to be done
188 before anything useful can be accomplished with a tag since you need
189 the tag's unique UID to communicate with it.
190
191 @param pbtCUID Pointer to the byte array where the card's UID
192 will be stored once a card is detected
193 @param pszUIDLen Pointer to the size of the card UID in bytes
194
195 Response for a valid ISO14443A 106KBPS (Mifare Classic, etc.)
196 should be in the following format. See UM0701-02 section
197 7.3.5 for more information
198
199 byte Description
200 ------------- ------------------------------------------
201 b0..6 Frame header and preamble
202 b7 Tags Found
203 b8 Tag Number (only one used in this example)
204 b9..10 SENS_RES
205 b11 SEL_RES
206 b12 NFCID Length
207 b13..NFCIDLen NFCID
208
209 SENS_RES SEL_RES Manufacturer/Card Type NFCID Len
210 -------- ------- ----------------------- ---------
211 00 04 08 NXP Mifare Classic 1K 4 bytes
212 00 02 18 NXP Mifare Classic 4K 4 bytes
213
214 @note Possible error messages are:
215
216 - PN532_ERROR_WRONGCARDTYPE
217 */
218 /**************************************************************************/
219 pn532_error_t pn532_mifareclassic_WaitForPassiveTarget (byte_t * pbtCUID, size_t * szCUIDLen)
220 {
221 byte_t abtResponse[PN532_RESPONSELEN_INLISTPASSIVETARGET];
222 pn532_error_t error;
223 size_t szLen;
224
225 #ifdef PN532_DEBUGMODE
226 PN532_DEBUG("Waiting for an ISO14443A Card%s", CFG_PRINTF_NEWLINE);
227 #endif
228
229 /* Try to initialise a single ISO14443A tag at 106KBPS */
230 /* Note: To wait for a card with a known UID, append the four byte */
231 /* UID to the end of the command. */
232 byte_t abtCommand[] = { PN532_COMMAND_INLISTPASSIVETARGET, 0x01, PN532_MODULATION_ISO14443A_106KBPS};
233 error = pn532Write(abtCommand, sizeof(abtCommand));
234 if (error)
235 return error;
236
237 /* Wait until we get a valid response or a timeout */
238 do
239 {
240 systickDelay(25);
241 error = pn532Read(abtResponse, &szLen);
242 } while (error == PN532_ERROR_RESPONSEBUFFEREMPTY);
243 if (error)
244 return error;
245
246 /* Check SENSE_RES to make sure this is a Mifare Classic card */
247 /* Classic 1K = 00 04 */
248 /* Classic 4K = 00 02 */
249 /* Classic Emulated = 00 08 */
250 if ((abtResponse[10] == 0x02) ||
251 (abtResponse[10] == 0x04) ||
252 (abtResponse[10] == 0x08))
253 {
254 /* Card appears to be Mifare Classic */
255 *szCUIDLen = abtResponse[12];
256 for (uint8_t i=0; i < *szCUIDLen; i++)
257 {
258 pbtCUID[i] = abtResponse[13+i];
259 }
260 #ifdef PN532_DEBUGMODE
261 PN532_DEBUG("Card Found: %s", CFG_PRINTF_NEWLINE);
262 PN532_DEBUG(" ATQA: ");
263 pn532PrintHex(abtResponse+9, 2);
264 PN532_DEBUG(" SAK: %02x%s", abtResponse[11], CFG_PRINTF_NEWLINE);
265 PN532_DEBUG(" UID: ");
266 pn532PrintHex(pbtCUID, *szCUIDLen);
267 #endif
268 }
269 else
270 {
271 /* Card is ISO14443A but doesn't appear to be Mifare Classic */
272 /* Mifare Ultralight = 0x0044 */
273 /* Mifare DESFire = 0x0344 */
274 /* Innovision Jewel = 0x0C00 */
275 #ifdef PN532_DEBUGMODE
276 PN532_DEBUG("Wrong Card Type (Expected ATQA 00 02, 00 04 or 00 08) %s%s", CFG_PRINTF_NEWLINE, CFG_PRINTF_NEWLINE);
277 PN532_DEBUG(" ATQA : ");
278 pn532PrintHex(abtResponse+9, 2);
279 PN532_DEBUG(" SAK : %02x%s", abtResponse[11], CFG_PRINTF_NEWLINE);
280 PN532_DEBUG(" UID Length : %d%s", abtResponse[12], CFG_PRINTF_NEWLINE);
281 PN532_DEBUG(" UID : ");
282 size_t pos;
283 for (pos=0; pos < abtResponse[12]; pos++)
284 {
285 printf("%02x ", abtResponse[13 + pos]);
286 }
287 printf("%s%s", CFG_PRINTF_NEWLINE, CFG_PRINTF_NEWLINE);
288 #endif
289 return PN532_ERROR_WRONGCARDTYPE;
290 }
291
292 return PN532_ERROR_NONE;
293 }
294
295
296 /**************************************************************************/
297 /*!
298 Tries to authenticate a block of memory on a MIFARE card using the
299 INDATAEXCHANGE command. See section 7.3.8 of the PN532 User Manual
300 for more information on sending MIFARE and other commands.
301
302 @param pbtCUID Pointer to a byte array containing the card UID
303 @param szCUIDLen The length (in bytes) of the card's UID (Should
304 be 4 for MIFARE Classic)
305 @param uiBlockNumber The block number to authenticate. (0..63 for
306 1KB cards, and 0..255 for 4KB cards).
307 @param uiKeyType Which key type to use during authentication
308 (PN532_MIFARE_CMD_AUTH_A or PN532_MIFARE_CMD_AUTH_B)
309 @param pbtKeys Pointer to a byte array containing the 6 byte
310 key value
311 */
312 /**************************************************************************/
313 pn532_error_t pn532_mifareclassic_AuthenticateBlock (byte_t * pbtCUID, size_t szCUIDLen, uint32_t uiBlockNumber, uint8_t uiKeyType, byte_t * pbtKeys)
314 {
315 pn532_error_t error;
316 byte_t abtCommand[17];
317 byte_t abtResponse[PN532_RESPONSELEN_INDATAEXCHANGE];
318 size_t szLen;
319
320 #ifdef PN532_DEBUGMODE
321 PN532_DEBUG("Trying to authenticate card ");
322 pn532PrintHex(pbtCUID, szCUIDLen);
323 #endif
324
325 /* Prepare the authentication command */
326 abtCommand[0] = PN532_COMMAND_INDATAEXCHANGE; /* Data Exchange Header */
327 abtCommand[1] = 1; /* Max card numbers */
328 abtCommand[2] = (uiKeyType) ? PN532_MIFARE_CMD_AUTH_A : PN532_MIFARE_CMD_AUTH_B;
329 abtCommand[3] = uiBlockNumber; /* Block Number (1K = 0..63, 4K = 0..255 */
330 memcpy (abtCommand+4, pbtKeys, 6);
331 uint8_t i;
332 for (i = 0; i < szCUIDLen; i++)
333 {
334 abtCommand[10+i] = pbtCUID[i]; /* 4 byte card ID */
335 }
336
337 /* Send the command */
338 error = pn532Write(abtCommand, 10+szCUIDLen);
339 if (error)
340 {
341 /* Problem with the serial bus, etc. */
342 #ifdef PN532_DEBUGMODE
343 PN532_DEBUG("Authentification failed%s", CFG_PRINTF_NEWLINE);
344 #endif
345 return error;
346 }
347
348 /* Read the authentification response */
349 memset(abtResponse, 0, PN532_RESPONSELEN_INDATAEXCHANGE);
350 do
351 {
352 systickDelay(25);
353 error = pn532Read(abtResponse, &szLen);
354 }
355 while (error == PN532_ERROR_RESPONSEBUFFEREMPTY);
356 if (error)
357 {
358 #ifdef PN532_DEBUGMODE
359 PN532_DEBUG("Authentification failed%s", CFG_PRINTF_NEWLINE);
360 #endif
361 return error;
362 }
363
364 // ToDo: How to check if authentification really worked (bad key, etc.)?
365
366 /* Output the authentification data */
367 #ifdef PN532_DEBUGMODE
368 PN532_DEBUG("Authenticated block %d %s", uiBlockNumber, CFG_PRINTF_NEWLINE);
369 #endif
370
371 // Return OK signal
372 return PN532_ERROR_NONE;
373 }
374
375 /**************************************************************************/
376 /*!
377 Tries to read an entire 16-byte data block at the specified block
378 address.
379
380 @param uiBlockNumber The block number to authenticate. (0..63 for
381 1KB cards, and 0..255 for 4KB cards).
382 @param pbtData Pointer to the byte array that will hold the
383 retrieved data (if any)
384
385 @note Possible error messages are:
386
387 - PN532_ERROR_BLOCKREADFAILED
388 */
389 /**************************************************************************/
390 pn532_error_t pn532_mifareclassic_ReadDataBlock (uint8_t uiBlockNumber, byte_t * pbtData)
391 {
392 pn532_error_t error;
393 byte_t abtCommand[4];
394 byte_t abtResponse[PN532_RESPONSELEN_INDATAEXCHANGE];
395 size_t szLen;
396
397 #ifdef PN532_DEBUGMODE
398 PN532_DEBUG("Reading 16 bytes at block %03d%s", uiBlockNumber, CFG_PRINTF_NEWLINE);
399 #endif
400
401 /* Prepare the command */
402 abtCommand[0] = PN532_COMMAND_INDATAEXCHANGE;
403 abtCommand[1] = 1; /* Card number */
404 abtCommand[2] = PN532_MIFARE_CMD_READ; /* Mifare Read command = 0x30 */
405 abtCommand[3] = uiBlockNumber; /* Block Number (0..63 for 1K, 0..255 for 4K) */
406
407 /* Send the commands */
408 error = pn532Write(abtCommand, sizeof(abtCommand));
409 if (error)
410 {
411 /* Bus error, etc. */
412 #ifdef PN532_DEBUGMODE
413 PN532_DEBUG("Read failed%s", CFG_PRINTF_NEWLINE);
414 #endif
415 return error;
416 }
417
418 /* Read the response */
419 memset(abtResponse, 0, PN532_RESPONSELEN_INDATAEXCHANGE);
420 do
421 {
422 systickDelay(50);
423 error = pn532Read(abtResponse, &szLen);
424 }
425 while (error == PN532_ERROR_RESPONSEBUFFEREMPTY);
426 if (error)
427 {
428 #ifdef PN532_DEBUGMODE
429 PN532_DEBUG("Read failed%s", CFG_PRINTF_NEWLINE);
430 #endif
431 return error;
432 }
433
434 /* Make sure we have a valid response (should be 26 bytes long) */
435 if (szLen == 26)
436 {
437 /* Copy the 16 data bytes to the output buffer */
438 /* Block content starts at byte 8 of a valid response */
439 memcpy (pbtData, abtResponse+7, 16);
440 }
441 else
442 {
443 #ifdef PN532_DEBUGMODE
444 PN532_DEBUG("Unexpected response reading block %d. Bad key?%s", uiBlockNumber, CFG_PRINTF_NEWLINE);
445 #endif
446 return PN532_ERROR_BLOCKREADFAILED;
447 }
448
449 /* Display data for debug if requested */
450 #ifdef PN532_DEBUGMODE
451 PN532_DEBUG("Block %03d: ", uiBlockNumber, CFG_PRINTF_NEWLINE);
452 pn532PrintHexVerbose(pbtData, 16);
453 #endif
454
455 // Return OK signal
456 return PN532_ERROR_NONE;
457 }
This page took 0.066386 seconds and 3 git commands to generate.