db71536b9fafd6fe9adebfab9c403532d47c6d41
[profile/ivi/neard.git] / plugins / mifare.c
1 /*
2  *
3  *  neard - Near Field Communication manager
4  *
5  *  Copyright (C) 2012  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdint.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <sys/socket.h>
30
31 #include <linux/socket.h>
32 #include <linux/nfc.h>
33
34 #include <near/plugin.h>
35 #include <near/log.h>
36 #include <near/types.h>
37 #include <near/adapter.h>
38 #include <near/tag.h>
39 #include <near/ndef.h>
40 #include <near/tlv.h>
41
42 /* NXP Application Notes:
43  * AN1304, AN1305, ...
44  * http://www.nxp.com/technical-support-portal/53420/71108/application-notes
45  * */
46
47 /* Prototype */
48 int mifare_read(uint32_t adapter_idx, uint32_t target_idx,
49                 near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype);
50
51 /* MIFARE command set */
52 #define MF_CMD_WRITE            0xA2
53 #define MF_CMD_READ             0x30
54 #define MF_CMD_AUTH_KEY_A       0x60
55
56 #define NFC_AID_TAG             0xE103
57
58 /* Define boundaries for 1K / 2K / 4K
59  * 1K:   sector 0 to 15 (3 blocks each + trailer block )
60  * 2K:   sector 0 to 31 (3 blocks each + trailer block )
61  * 4K:   sector 0 to 31 (3 blocks each + trailer block )
62  *      and sector 32 to 39 (15 blocks each + trailer block )
63  * */
64 #define DEFAULT_BLOCK_SIZE      16      /* MF_CMD_READ */
65
66 #define STD_BLK_SECT_TRAILER    4       /* bl per sect with trailer 1K/2K */
67 #define EXT_BLK_SECT_TRAILER    16      /* bl per sect with trailer 4K */
68
69 #define STD_BLK_PER_SECT        3       /* 1 sect == 3blocks */
70 #define EXT_BLK_PER_SECT        15      /* for 4K tags */
71
72 /* Usual sector size, including trailer */
73 #define STD_SECTOR_SIZE         (4 * DEFAULT_BLOCK_SIZE)        /* 00-31 */
74 #define EXT_SECTOR_SIZE         (16 * DEFAULT_BLOCK_SIZE)       /* 32-39 */
75
76 /* Usual sector size, without trailer */
77 #define SECTOR_SIZE             (3 * DEFAULT_BLOCK_SIZE)
78 #define BIG_SECTOR_SIZE         (15 * DEFAULT_BLOCK_SIZE)
79
80 #define T4K_BOUNDARY            32
81 #define T4K_BLK_OFF             0x80    /* blocks count before sector 32 */
82
83 #define NO_TRAILER      0
84 #define WITH_TRAILER    1
85 #define SECT_IS_NFC     1
86
87 /* Default MAD keys. Key length = 6 bytes */
88 #define MAD_KEY_LEN     6
89 static uint8_t MAD_public_key[] = {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5};
90 static uint8_t MAD_NFC_key[] = {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7};
91
92 #define MAD1_SECTOR             0x00    /* Sector 0 is for MAD1 */
93 #define MAD1_1ST_BLOCK          0x00    /* 1st block of sector 0 */
94 #define MAD2_GPB_BITS           0x02    /* MAD v2 flag */
95
96 #define MAD2_SECTOR             0x10    /* Sector 0 is for MAD2 */
97 #define MAD2_1ST_BLOCK          0x40    /* 1st block of MAD2 */
98
99 #define MAD_V1_AIDS_LEN         15      /* 1 to 0x0F */
100 #define MAD_V2_AIDS_LEN         23      /*0x11 to 0x27 */
101
102 /* MAD1 sector structure. Start at block 0x00 */
103 struct MAD_1 {
104         uint8_t man_info[16];
105         uint16_t crc_dir;
106         uint16_t aids[MAD_V1_AIDS_LEN];
107         /* Trailer */
108         uint8_t key_A[MAD_KEY_LEN];
109         uint8_t access_cond[3];
110         uint8_t GPB;
111         uint8_t key_B[MAD_KEY_LEN];
112 } __attribute__((packed));
113
114 /* MAD2 sector structure. Start at block 0x40 */
115 struct MAD_2 {
116         uint16_t crc_dir;
117         uint16_t aids[MAD_V2_AIDS_LEN];
118         /* Trailer */
119         uint8_t key_A[MAD_KEY_LEN];
120         uint8_t access_cond[3];
121         uint8_t GPB;
122         uint8_t key_B[MAD_KEY_LEN];
123 } __attribute__((packed));
124
125 struct mifare_cookie {
126         uint32_t adapter_idx;
127         uint32_t target_idx;
128         uint8_t *nfcid1;
129         uint8_t nfcid1_len;
130
131         struct near_tag *tag;
132         near_tag_io_cb cb;
133         near_recv next_far_func;
134
135         /* For MAD access */
136         struct MAD_1 *mad_1;
137         struct MAD_2 *mad_2;
138         GSList *g_sect_list;            /* Global sectors list */
139
140         /* For read functions */
141         near_recv rs_next_fct;          /* next function */
142         int rs_block_start;             /* first block */
143         int rs_block_end;               /* last block */
144         int rs_completed;               /* read blocks */
145         int rs_length;                  /* read length */
146         uint8_t *rs_pmem;               /* Stored read sector */
147         int rs_max_length;              /* available size */
148         uint8_t *nfc_data;
149         size_t nfc_data_length;
150 };
151
152 struct type2_cmd {
153         uint8_t cmd;
154         uint8_t block;
155         uint8_t data[];
156 } __attribute__((packed));
157
158 struct mifare_cmd {
159         uint8_t cmd;
160         uint8_t block;
161         uint8_t key[MAD_KEY_LEN];
162         uint8_t nfcid[NFC_NFCID1_MAXSIZE];
163 } __attribute__((packed));
164
165 /* Common free func */
166 static int mifare_release(int err, struct mifare_cookie *cookie)
167 {
168         DBG("%p", cookie);
169
170         if (cookie == NULL)
171                 return err;
172
173         if (err < 0 && cookie->cb) {
174                 cookie->cb(cookie->adapter_idx, cookie->target_idx, err);
175                 near_adapter_disconnect(cookie->adapter_idx);
176         }
177
178         /* Now free allocs */
179         g_free(cookie->nfcid1);
180         g_slist_free(cookie->g_sect_list);
181         g_free(cookie->mad_1);
182         g_free(cookie->mad_2);
183         g_free(cookie);
184         cookie = NULL;
185
186         return err;
187 }
188
189 /* Mifare_generic MAD unlock block function
190  * This function send unlock code to the tag, and so, allow access
191  * to the complete related sector.
192  */
193 static int mifare_unlock_sector(int block_id,
194                                 near_recv next_far_fct,
195                                 void *data)
196 {
197         struct mifare_cmd cmd;
198         struct mifare_cookie *cookie = data;
199         uint8_t *key_ref;
200
201         /* For MADs sectors we use public key A (a0a1a2a3a4a5) but
202          * for NFC sectors we use NFC_KEY_A (d3f7d3f7d3f7)
203          *  */
204         if ((block_id == MAD1_1ST_BLOCK) || (block_id == MAD2_1ST_BLOCK))
205                 key_ref = MAD_public_key;
206         else
207                 key_ref = MAD_NFC_key;
208
209          /* CMD AUTHENTICATION */
210         cmd.cmd = MF_CMD_AUTH_KEY_A;
211
212         /* We want to authenticate the 1st bloc of the sector */
213         cmd.block = block_id;
214
215         /* Store the AUTH KEY */
216         memcpy(&cmd.key, key_ref, MAD_KEY_LEN);
217
218         /* add the UID */
219         memcpy(&cmd.nfcid, cookie->nfcid1, cookie->nfcid1_len);
220
221         return near_adapter_send(cookie->adapter_idx, (uint8_t *)&cmd,
222                 sizeof(cmd) - NFC_NFCID1_MAXSIZE + cookie->nfcid1_len,
223                 next_far_fct,
224                 cookie);
225 }
226
227 /* Common MIFARE Bloc read:
228  * Each call will read 16 bytes from tag... so to read 1 sector,
229  * we must call it 4 times or 16 times (minus 1 or not for the trailer block)
230  *
231  * data: mifare_cookie *mf_ck
232  * mf_ck->read_block: block number to read
233  * */
234 static int mifare_read_block(uint8_t block_id,
235                                 void *data,
236                                 near_recv far_func)
237 {
238         struct type2_cmd cmd;
239         struct mifare_cookie *mf_ck = data;
240
241         cmd.cmd = MF_CMD_READ; /* MIFARE READ */
242         cmd.block = block_id;
243
244         return near_adapter_send(mf_ck->adapter_idx,
245                         (uint8_t *) &cmd, 2,
246                         far_func, data);
247 }
248
249 static int mifare_read_sector_cb(uint8_t *resp, int length, void *data)
250 {
251         struct mifare_cookie *mf_ck = data;
252         int err = -1;
253
254         if (length < 0) {
255                 err = length;
256                 goto out_err;
257         }
258
259         /* Save the data */
260         length = length - 1; /* ignore first byte - Reader byte */
261
262         /* save the length: */
263         mf_ck->rs_length = mf_ck->rs_length + length;
264
265         memcpy(mf_ck->rs_pmem + mf_ck->rs_completed * DEFAULT_BLOCK_SIZE,
266                         resp + 1,/* ignore reader byte */
267                         length);
268
269         /* Next block */
270         mf_ck->rs_completed = mf_ck->rs_completed + 1;
271
272         if ((mf_ck->rs_block_start + mf_ck->rs_completed) < mf_ck->rs_block_end)
273                 err = mifare_read_block(
274                                 (mf_ck->rs_block_start + mf_ck->rs_completed),
275                                 data,
276                                 mifare_read_sector_cb);
277         else {
278                 /* Now Process the callback ! */
279                 err = (*mf_ck->rs_next_fct)(mf_ck->rs_pmem,
280                                                 mf_ck->rs_length, data);
281         }
282
283         if (err < 0)
284                 goto out_err;
285         return err;
286
287 out_err:
288         return mifare_release(err, mf_ck);
289 }
290
291 static int mifare_read_sector_unlocked(uint8_t *resp, int length, void *data)
292 {
293         struct mifare_cookie *mf_ck = data;
294         int err;
295
296         if (length < 0) {
297                 err = length;
298                 return err;
299         }
300         /* And run the read process on the first block of the sector */
301         err = mifare_read_block(mf_ck->rs_block_start, data,
302                                 mifare_read_sector_cb);
303
304         if (err < 0)
305                 goto out_err;
306         return err;
307
308 out_err:
309         return err;
310 }
311
312 /* This function reads a complete sector, using block per block function.
313  * sector sizes can be:
314  * Sectors 0 to 31:
315  *      48 bytes: 3*16 no trailer
316  *      64 bytes: 4*16 with trailer
317  * Sectors 32 to 39:
318  *      240 bytes: 15*16 no trailer
319  *      256 bytes: 16*16 with trailer
320  *
321  * Unlock is done at the beginning of first sector.
322  */
323 static int mifare_read_sector(void *cookie,
324                         uint8_t *pmem,          /* memory to fill */
325                         uint16_t memsize,       /* remaining free size */
326                         uint8_t sector_id,      /* sector to read */
327                         near_bool_t trailer,    /* Add trailer or not */
328                         near_recv next_func)
329 {
330         struct mifare_cookie *mf_ck = cookie;
331         int err;
332         int blocks_count;
333
334         DBG("");
335
336         /* Prepare call values */
337         mf_ck->rs_pmem = pmem;                  /* where to store */
338         mf_ck->rs_max_length = memsize;         /* max size to store */
339         mf_ck->rs_length = 0;                   /* no bytes yet */
340         mf_ck->rs_completed = 0;                /* blocks read */
341
342         /* According to tag size, compute the correct block offset */
343         if (sector_id < T4K_BOUNDARY)
344                 mf_ck->rs_block_start = sector_id * 4;  /* 1st block to read */
345         else
346                 mf_ck->rs_block_start =
347                                 (sector_id - T4K_BOUNDARY) * 16 + T4K_BLK_OFF;
348
349         /* Find blocks_per_sect, according to position and trailer or not */
350         if (sector_id < T4K_BOUNDARY)
351                 blocks_count = (STD_BLK_PER_SECT + trailer);
352         else
353                 blocks_count = (EXT_BLK_PER_SECT + trailer);
354
355         mf_ck->rs_block_end = mf_ck->rs_block_start + blocks_count;
356
357         mf_ck->rs_next_fct = next_func;         /* leaving function */
358
359         /* As we are on the first block of a sector, we unlock it */
360         err = mifare_unlock_sector(mf_ck->rs_block_start,
361                         mifare_read_sector_unlocked, mf_ck);
362
363         return err;
364 }
365
366 static int mifare_read_NFC_loop(uint8_t *resp, int length, void *data)
367 {
368         struct mifare_cookie *mf_ck = data;
369         int err = 0;
370
371         DBG("");
372
373         if (length < 0) {
374                 err = length;
375                 return err;
376         }
377
378         /* ptr to the next read ptr */
379         mf_ck->nfc_data = mf_ck->nfc_data + length;
380
381         /* remaining free mem */
382         mf_ck->nfc_data_length = mf_ck->nfc_data_length - length;
383
384
385         /* Additional sectors to read ? */;
386         if (mf_ck->g_sect_list->next != NULL) {
387
388                 err = mifare_read_sector(data,  /* cookie */
389                         mf_ck->nfc_data,                /* where to store */
390                         (int) mf_ck->nfc_data_length,   /* global length */
391                         GPOINTER_TO_INT(mf_ck->g_sect_list->data), /* id */
392                         NO_TRAILER,                     /* Trailer ? */
393                         mifare_read_NFC_loop);          /* next function */
394
395                 mf_ck->g_sect_list = g_slist_remove(mf_ck->g_sect_list,
396                                                 mf_ck->g_sect_list->data);
397
398                 if (err < 0)
399                         goto out_err;
400                 return err;
401         } else {
402                 GList *records;
403                 uint8_t *nfc_data;
404                 size_t nfc_data_length;
405
406                 DBG("READ DONE");
407
408                 nfc_data = near_tag_get_data(mf_ck->tag, &nfc_data_length);
409                 if (nfc_data == NULL) {
410                         err = -ENOMEM;
411                         goto out_err;
412                 }
413
414                 records = near_tlv_parse(nfc_data, nfc_data_length);
415                 near_tag_add_records(mf_ck->tag, records, mf_ck->cb, 0);
416
417                 err = 0;
418         }
419
420 out_err:
421         return mifare_release(err, mf_ck);
422 }
423
424 /* Prepare read NFC loop
425  */
426 static int mifare_read_NFC(void *data)
427 {
428         struct mifare_cookie *mf_ck = data;
429         int err;
430
431         /* save tag memory pointer to data_block */
432         mf_ck->nfc_data = near_tag_get_data(mf_ck->tag,
433                                         &mf_ck->nfc_data_length);
434
435         /* First read here: */
436         err = mifare_read_sector(data,          /* cookie */
437                 mf_ck->nfc_data,                /* where to store */
438                 mf_ck->nfc_data_length,         /* global length */
439                 GPOINTER_TO_INT(mf_ck->g_sect_list->data), /* sector id */
440                 NO_TRAILER,                     /* Don't want Trailer */
441                 mifare_read_NFC_loop);          /* next function */
442
443         mf_ck->g_sect_list = g_slist_remove(mf_ck->g_sect_list,
444                                                 mf_ck->g_sect_list->data);
445         if (err < 0)
446                 goto out_err;
447         return err;
448
449 out_err:
450         return mifare_release(err, mf_ck);
451 }
452
453 static int mifare_process_MADs(void *data)
454 {
455         struct mifare_cookie *mf_ck = data;
456         int err;
457         int i;
458         int global_tag_size = 0;
459         int ioffset;
460
461         DBG("");
462
463         /* Parse MAD entries to get the global size and fill the array */
464         if (mf_ck->mad_1 == NULL) {
465                 err = -EINVAL;
466                 goto out_err;
467         }
468
469         for (i = 0; i < MAD_V1_AIDS_LEN; i++) {
470                 if (mf_ck->mad_1->aids[i] != NFC_AID_TAG)
471                         continue;
472
473                 /* Save in the global list */
474                 mf_ck->g_sect_list = g_slist_append(mf_ck->g_sect_list,
475                                                 GINT_TO_POINTER(i + 1));
476                 global_tag_size += SECTOR_SIZE;
477         }
478
479         /* Now MAD 2 */
480         ioffset = MAD_V1_AIDS_LEN + 1 + 1; /* skip 0x10 */
481         if (mf_ck->mad_2 == NULL)
482                 goto done_mad;
483
484         for (i = 0; i < MAD_V2_AIDS_LEN; i++) {
485                 if (mf_ck->mad_2->aids[i] != NFC_AID_TAG)
486                         continue;
487
488                 mf_ck->g_sect_list = g_slist_append( mf_ck->g_sect_list,
489                                                 GINT_TO_POINTER(ioffset + i));
490                 if (i < EXT_BLK_PER_SECT)
491                         global_tag_size += SECTOR_SIZE;
492                 else
493                         global_tag_size += BIG_SECTOR_SIZE;
494         }
495
496 done_mad:
497         /* n sectors, each sector is 3 blocks, each block is 16 bytes */
498         DBG("TAG Global size: [%d]", global_tag_size);
499
500         err = near_tag_add_data(mf_ck->adapter_idx,
501                                                 mf_ck->target_idx,
502                                                 NULL, /* Empty */
503                                                 global_tag_size);
504         if (err < 0)
505                 goto out_err;
506
507         mf_ck->tag = near_tag_get_tag(mf_ck->adapter_idx, mf_ck->target_idx);
508         if (mf_ck->tag == NULL) {
509                 err = -ENOMEM;
510                 goto out_err;
511         }
512
513         /* Time to read the NFC data */
514         err = mifare_read_NFC(mf_ck);
515
516         return err;
517
518 out_err:
519         return mifare_release(err, mf_ck);
520 }
521
522 /* Transitional function - async
523  */
524 static int read_MAD2_complete(uint8_t *empty, int iempty, void *data)
525 {
526         return mifare_process_MADs(data);
527 }
528
529 /* This function reads the MAD2 sector
530  */
531 static int mifare_read_MAD2(void *data)
532 {
533         struct mifare_cookie *mf_ck = data;
534         int err = 0;
535
536         DBG("");
537
538         /* As auth is ok, we allocate Mifare Access Directory v1 */
539         mf_ck->mad_2 = g_try_malloc0(STD_SECTOR_SIZE);
540         if (mf_ck->mad_2 == NULL) {
541                 near_error("Memory allocation failed (MAD2)");
542                 err = -ENOMEM;
543                 goto out_err;
544         }
545
546         err = mifare_read_sector(data,
547                         (uint8_t *) mf_ck->mad_2,
548                         (int) STD_SECTOR_SIZE,
549                         MAD2_SECTOR,                    /* sector 0x10 */
550                         WITH_TRAILER,                   /* Want Trailer */
551                         read_MAD2_complete);
552
553         if (err < 0)
554                 goto out_err;
555         return err;
556
557 out_err:
558         return mifare_release(err, mf_ck);
559 }
560
561 /* This function checks, in MAD1, if there's a MAD2 directory
562  * available. This is is the case for 2K and 4K tag
563  * If MAD2 exists, we want to read it, elsewhere we process the
564  * current MAD
565  */
566 static int read_MAD1_complete(uint8_t *empty, int iempty, void *data)
567 {
568         struct mifare_cookie *mf_ck = data;
569         int err;
570
571         DBG("");
572
573         /* Check if we need to get MAD2 sector (bits 0..1)*/
574         if ((mf_ck->mad_1->GPB & 0x03) == MAD2_GPB_BITS)
575                 err = mifare_read_MAD2(mf_ck);
576         else
577                 err = mifare_process_MADs(data);
578
579         return err;
580 }
581
582 /* Function called to read the first MAD sector
583  * MAD is mandatory
584  */
585 static int mifare_read_MAD1(uint8_t *resp, int length, void *data)
586 {
587         struct mifare_cookie *mf_ck = data;
588         int err = 0;
589
590         DBG("%p %d", data, length);
591
592         if (length < 0) {
593                 err = length;
594                 return err;
595         }
596
597         /* As auth is ok, we allocate Mifare Access Directory v1
598          * allocated size is also STD_SECTOR_SIZE */
599         mf_ck->mad_1 = g_try_malloc0(STD_SECTOR_SIZE);
600         if (mf_ck->mad_1 == NULL) {
601                 near_error("Memory allocation failed (MAD1)");
602                 err = -ENOMEM;
603                 goto out_err;
604         }
605
606         /* Call to mifare_read_sector */
607         err = mifare_read_sector(data,
608                         (uint8_t *)mf_ck->mad_1,        /* where to store */
609                         (int) STD_SECTOR_SIZE,          /* allocated size */
610                         MAD1_SECTOR,                    /* sector 0 */
611                         WITH_TRAILER,                   /* Want Trailer */
612                         read_MAD1_complete);
613
614         if (err < 0)
615                 goto out_err;
616         return err;
617
618 out_err:
619         return mifare_release(err, mf_ck);
620 }
621
622 /* MIFARE: entry point:
623  * Read all the MAD sectors (0x00, 0x10) to get the Application Directory
624  * entries.
625  * On sector 0x00, App. directory is on block 0x01 & block 0x02
626  * On sector 0x10, App. directory is on block 0x40, 0x41 & 0x42
627  * On reading, we ignore the CRC.
628  */
629 int mifare_read(uint32_t adapter_idx, uint32_t target_idx,
630                 near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype)
631 {
632         struct mifare_cookie *cookie;
633         int err;
634
635         DBG("");
636
637         /*Check supported and tested Mifare type */
638         switch (tgt_subtype) {
639         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_1K:
640         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_4K:
641                 break;
642         default:
643                 near_error("Mifare tag type [%d] not supported.", tgt_subtype);
644                 return -1;
645         }
646
647         /* Alloc global cookie */
648         cookie = g_try_malloc0(sizeof(struct mifare_cookie));
649         if (cookie == NULL)
650                 return -ENOMEM;
651
652         /* Get the nfcid1 */
653         cookie->nfcid1 = near_tag_get_nfcid(adapter_idx, target_idx,
654                                 &cookie->nfcid1_len);
655         cookie->adapter_idx = adapter_idx;
656         cookie->target_idx = target_idx;
657         cookie->cb = cb;
658
659         /* Need to unlock before reading
660          * This will check if public keys are allowed (and, so, NDEF could
661          * be "readable"...
662          * */
663         err = mifare_unlock_sector(MAD1_1ST_BLOCK,      /* related block */
664                                 mifare_read_MAD1,       /* callback function */
665                                 cookie);                /* target data */
666         if (err < 0)
667                 return mifare_release(err, cookie);
668
669         return 0;
670 }