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