libnfc  1.7.0-rc7
nfc-mfultralight.c
Go to the documentation of this file.
1 /*-
2  * Free/Libre Near Field Communication (NFC) library
3  *
4  * Libnfc historical contributors:
5  * Copyright (C) 2009 Roel Verdult
6  * Copyright (C) 2009-2013 Romuald Conty
7  * Copyright (C) 2010-2012 Romain Tartière
8  * Copyright (C) 2010-2013 Philippe Teuwen
9  * Copyright (C) 2012-2013 Ludovic Rousseau
10  * Additional contributors of this file:
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions are met:
14  * 1) Redistributions of source code must retain the above copyright notice,
15  * this list of conditions and the following disclaimer.
16  * 2 )Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in the
18  * documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  *
32  * Note that this license only applies on the examples, NFC library itself is under LGPL
33  *
34  */
35 
41 #ifdef HAVE_CONFIG_H
42 # include "config.h"
43 #endif // HAVE_CONFIG_H
44 
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <stdint.h>
48 #include <stddef.h>
49 #include <stdbool.h>
50 
51 #include <string.h>
52 #include <ctype.h>
53 
54 #include <nfc/nfc.h>
55 
56 #include "nfc-utils.h"
57 #include "mifare.h"
58 
59 static nfc_device *pnd;
60 static nfc_target nt;
61 static mifare_param mp;
62 static mifareul_tag mtDump;
63 static uint32_t uiBlocks = 0xF;
64 
65 static const nfc_modulation nmMifare = {
66  .nmt = NMT_ISO14443A,
67  .nbr = NBR_106,
68 };
69 
70 static void
71 print_success_or_failure(bool bFailure, uint32_t *uiCounter)
72 {
73  printf("%c", (bFailure) ? 'x' : '.');
74  if (uiCounter)
75  *uiCounter += (bFailure) ? 0 : 1;
76 }
77 
78 static bool
79 read_card(void)
80 {
81  uint32_t page;
82  bool bFailure = false;
83  uint32_t uiReadedPages = 0;
84 
85  printf("Reading %d pages |", uiBlocks + 1);
86 
87  for (page = 0; page <= uiBlocks; page += 4) {
88  // Try to read out the data block
89  if (nfc_initiator_mifare_cmd(pnd, MC_READ, page, &mp)) {
90  memcpy(mtDump.amb[page / 4].mbd.abtData, mp.mpd.abtData, 16);
91  } else {
92  bFailure = true;
93  break;
94  }
95 
96  print_success_or_failure(bFailure, &uiReadedPages);
97  print_success_or_failure(bFailure, &uiReadedPages);
98  print_success_or_failure(bFailure, &uiReadedPages);
99  print_success_or_failure(bFailure, &uiReadedPages);
100  }
101  printf("|\n");
102  printf("Done, %d of %d pages readed.\n", uiReadedPages, uiBlocks + 1);
103  fflush(stdout);
104 
105  return (!bFailure);
106 }
107 
108 static bool
109 write_card(void)
110 {
111  uint32_t uiBlock = 0;
112  bool bFailure = false;
113  uint32_t uiWritenPages = 0;
114  uint32_t uiSkippedPages;
115 
116  char buffer[BUFSIZ];
117  bool write_otp;
118  bool write_lock;
119 
120  printf("Write OTP bytes ? [yN] ");
121  if (!fgets(buffer, BUFSIZ, stdin)) {
122  ERR("Unable to read standard input.");
123  }
124  write_otp = ((buffer[0] == 'y') || (buffer[0] == 'Y'));
125  printf("Write Lock bytes ? [yN] ");
126  if (!fgets(buffer, BUFSIZ, stdin)) {
127  ERR("Unable to read standard input.");
128  }
129  write_lock = ((buffer[0] == 'y') || (buffer[0] == 'Y'));
130 
131  printf("Writing %d pages |", uiBlocks + 1);
132  /* We need to skip 2 first pages. */
133  printf("ss");
134  uiSkippedPages = 2;
135 
136  for (int page = 0x2; page <= 0xF; page++) {
137  if ((page == 0x2) && (!write_lock)) {
138  printf("s");
139  uiSkippedPages++;
140  continue;
141  }
142  if ((page == 0x3) && (!write_otp)) {
143  printf("s");
144  uiSkippedPages++;
145  continue;
146  }
147  // Show if the readout went well
148  if (bFailure) {
149  // When a failure occured we need to redo the anti-collision
150  if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) {
151  ERR("tag was removed");
152  return false;
153  }
154  bFailure = false;
155  }
156  // For the Mifare Ultralight, this write command can be used
157  // in compatibility mode, which only actually writes the first
158  // page (4 bytes). The Ultralight-specific Write command only
159  // writes one page at a time.
160  uiBlock = page / 4;
161  memcpy(mp.mpd.abtData, mtDump.amb[uiBlock].mbd.abtData + ((page % 4) * 4), 16);
162  if (!nfc_initiator_mifare_cmd(pnd, MC_WRITE, page, &mp))
163  bFailure = true;
164 
165  print_success_or_failure(bFailure, &uiWritenPages);
166  }
167  printf("|\n");
168  printf("Done, %d of %d pages written (%d pages skipped).\n", uiWritenPages, uiBlocks + 1, uiSkippedPages);
169 
170  return true;
171 }
172 
173 int
174 main(int argc, const char *argv[])
175 {
176  bool bReadAction;
177  FILE *pfDump;
178 
179  if (argc < 3) {
180  printf("\n");
181  printf("%s r|w <dump.mfd>\n", argv[0]);
182  printf("\n");
183  printf("r|w - Perform read from or write to card\n");
184  printf("<dump.mfd> - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)\n");
185  printf("\n");
186  exit(EXIT_FAILURE);
187  }
188 
189  DBG("\nChecking arguments and settings\n");
190 
191  bReadAction = tolower((int)((unsigned char) * (argv[1])) == 'r');
192 
193  if (bReadAction) {
194  memset(&mtDump, 0x00, sizeof(mtDump));
195  } else {
196  pfDump = fopen(argv[2], "rb");
197 
198  if (pfDump == NULL) {
199  ERR("Could not open dump file: %s\n", argv[2]);
200  exit(EXIT_FAILURE);
201  }
202 
203  if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
204  ERR("Could not read from dump file: %s\n", argv[2]);
205  fclose(pfDump);
206  exit(EXIT_FAILURE);
207  }
208  fclose(pfDump);
209  }
210  DBG("Successfully opened the dump file\n");
211 
212  nfc_context *context;
213  nfc_init(&context);
214  if (context == NULL) {
215  ERR("Unable to init libnfc (malloc)");
216  exit(EXIT_FAILURE);
217  }
218 
219  // Try to open the NFC device
220  pnd = nfc_open(context, NULL);
221  if (pnd == NULL) {
222  ERR("Error opening NFC device");
223  nfc_exit(context);
224  exit(EXIT_FAILURE);
225  }
226 
227  if (nfc_initiator_init(pnd) < 0) {
228  nfc_perror(pnd, "nfc_initiator_init");
229  nfc_close(pnd);
230  nfc_exit(context);
231  exit(EXIT_FAILURE);
232  }
233 
234  // Let the device only try once to find a tag
235  if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) {
236  nfc_perror(pnd, "nfc_device_set_property_bool");
237  nfc_close(pnd);
238  nfc_exit(context);
239  exit(EXIT_FAILURE);
240  }
241 
242  printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
243 
244  // Try to find a MIFARE Ultralight tag
245  if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) {
246  ERR("no tag was found\n");
247  nfc_close(pnd);
248  nfc_exit(context);
249  exit(EXIT_FAILURE);
250  }
251  // Test if we are dealing with a MIFARE compatible tag
252 
253  if (nt.nti.nai.abtAtqa[1] != 0x44) {
254  ERR("tag is not a MIFARE Ultralight card\n");
255  nfc_close(pnd);
256  nfc_exit(context);
257  exit(EXIT_FAILURE);
258  }
259  // Get the info from the current tag
260  printf("Found MIFARE Ultralight card with UID: ");
261  size_t szPos;
262  for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) {
263  printf("%02x", nt.nti.nai.abtUid[szPos]);
264  }
265  printf("\n");
266 
267  if (bReadAction) {
268  if (read_card()) {
269  printf("Writing data to file: %s ... ", argv[2]);
270  fflush(stdout);
271  pfDump = fopen(argv[2], "wb");
272  if (pfDump == NULL) {
273  printf("Could not open file: %s\n", argv[2]);
274  nfc_close(pnd);
275  nfc_exit(context);
276  exit(EXIT_FAILURE);
277  }
278  if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
279  printf("Could not write to file: %s\n", argv[2]);
280  fclose(pfDump);
281  nfc_close(pnd);
282  nfc_exit(context);
283  exit(EXIT_FAILURE);
284  }
285  fclose(pfDump);
286  printf("Done.\n");
287  }
288  } else {
289  write_card();
290  }
291 
292  nfc_close(pnd);
293  nfc_exit(context);
294  exit(EXIT_SUCCESS);
295 }