nfc-mfultralight.c 8.52 KB
Newer Older
1
/*-
2
 * Free/Libre Near Field Communication (NFC) library
3
 *
4 5 6 7 8 9
 * Libnfc historical contributors:
 * Copyright (C) 2009      Roel Verdult
 * Copyright (C) 2009-2013 Romuald Conty
 * Copyright (C) 2010-2012 Romain Tartière
 * Copyright (C) 2010-2013 Philippe Teuwen
 * 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 15 16
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *  1) Redistributions of source code must retain the above copyright notice,
17
 *  this list of conditions and the following disclaimer.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
 *  2 )Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 * Note that this license only applies on the examples, NFC library itself is under LGPL
35
 *
36 37 38
 */

/**
39
 * @file nfc-mfultralight.c
40
 * @brief MIFARE Ultralight dump/restore tool
41
 */
Romuald Conty's avatar
Romuald Conty committed
42

43
#ifdef HAVE_CONFIG_H
44
#  include "config.h"
45 46
#endif // HAVE_CONFIG_H

Romuald Conty's avatar
Romuald Conty committed
47 48 49 50 51 52 53 54 55
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>

#include <string.h>
#include <ctype.h>

56
#include <nfc/nfc.h>
57

58
#include "nfc-utils.h"
59
#include "mifare.h"
Romuald Conty's avatar
Romuald Conty committed
60

61 62
static nfc_device *pnd;
static nfc_target nt;
Romuald Conty's avatar
Romuald Conty committed
63 64
static mifare_param mp;
static mifareul_tag mtDump;
65 66
static uint32_t uiBlocks = 0xF;

67
static const nfc_modulation nmMifare = {
68 69 70 71
  .nmt = NMT_ISO14443A,
  .nbr = NBR_106,
};

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
}
Romuald Conty's avatar
Romuald Conty committed
79

80
static  bool
81
read_card(void)
Romuald Conty's avatar
Romuald Conty committed
82
{
83
  uint32_t page;
84
  bool    bFailure = false;
85
  uint32_t uiReadedPages = 0;
86

87
  printf("Reading %d pages |", uiBlocks + 1);
88

89 90
  for (page = 0; page <= uiBlocks; page += 4) {
    // Try to read out the data block
91 92
    if (nfc_initiator_mifare_cmd(pnd, MC_READ, page, &mp)) {
      memcpy(mtDump.amb[page / 4].mbd.abtData, mp.mpd.abtData, 16);
93 94 95 96 97
    } else {
      bFailure = true;
      break;
    }

98 99 100 101
    print_success_or_failure(bFailure, &uiReadedPages);
    print_success_or_failure(bFailure, &uiReadedPages);
    print_success_or_failure(bFailure, &uiReadedPages);
    print_success_or_failure(bFailure, &uiReadedPages);
Romuald Conty's avatar
Romuald Conty committed
102
  }
103 104 105
  printf("|\n");
  printf("Done, %d of %d pages readed.\n", uiReadedPages, uiBlocks + 1);
  fflush(stdout);
106 107

  return (!bFailure);
Romuald Conty's avatar
Romuald Conty committed
108 109
}

110
static  bool
111
write_card(void)
Romuald Conty's avatar
Romuald Conty committed
112 113
{
  uint32_t uiBlock = 0;
114
  bool    bFailure = false;
115
  uint32_t uiWritenPages = 0;
116
  uint32_t uiSkippedPages = 0;
Romuald Conty's avatar
Romuald Conty committed
117

118 119
  char    buffer[BUFSIZ];
  bool    write_otp;
120
  bool    write_lock;
121
  bool    write_uid;
122

123 124 125
  printf("Write OTP bytes ? [yN] ");
  if (!fgets(buffer, BUFSIZ, stdin)) {
    ERR("Unable to read standard input.");
126
  }
127
  write_otp = ((buffer[0] == 'y') || (buffer[0] == 'Y'));
128 129 130
  printf("Write Lock bytes ? [yN] ");
  if (!fgets(buffer, BUFSIZ, stdin)) {
    ERR("Unable to read standard input.");
131
  }
132
  write_lock = ((buffer[0] == 'y') || (buffer[0] == 'Y'));
133 134 135 136 137
  printf("Write UID bytes (only for special writeable UID cards) ? [yN] ");
  if (!fgets(buffer, BUFSIZ, stdin)) {
    ERR("Unable to read standard input.");
  }
  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. */
Philippe Teuwen's avatar
Philippe Teuwen committed
141
  if (!write_uid) {
142 143 144
    printf("ss");
    uiSkippedPages = 2;
  }
145

146
  for (int page = uiSkippedPages; page <= 0xF; page++) {
147
    if ((page == 0x2) && (!write_lock)) {
148
      printf("s");
149 150 151
      uiSkippedPages++;
      continue;
    }
152
    if ((page == 0x3) && (!write_otp)) {
153
      printf("s");
154 155 156
      uiSkippedPages++;
      continue;
    }
157 158 159
    // Show if the readout went well
    if (bFailure) {
      // 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;
Romuald Conty's avatar
Romuald Conty committed
163
      }
164 165
      bFailure = false;
    }
166
    // For the Mifare Ultralight, this write command can be used
167
    // in compatibility mode, which only actually writes the first
168 169 170
    // page (4 bytes). The Ultralight-specific Write command only
    // writes one page at a time.
    uiBlock = page / 4;
171 172
    memcpy(mp.mpd.abtData, mtDump.amb[uiBlock].mbd.abtData + ((page % 4) * 4), 16);
    if (!nfc_initiator_mifare_cmd(pnd, MC_WRITE, page, &mp))
173
      bFailure = true;
174

175
    print_success_or_failure(bFailure, &uiWritenPages);
Romuald Conty's avatar
Romuald Conty committed
176
  }
177 178
  printf("|\n");
  printf("Done, %d of %d pages written (%d pages skipped).\n", uiWritenPages, uiBlocks + 1, uiSkippedPages);
179

Romuald Conty's avatar
Romuald Conty committed
180 181 182
  return true;
}

183
int
184
main(int argc, const char *argv[])
185
{
186 187
  bool    bReadAction;
  FILE   *pfDump;
188 189

  if (argc < 3) {
190 191 192 193 194 195
    printf("\n");
    printf("%s r|w <dump.mfd>\n", argv[0]);
    printf("\n");
    printf("r|w         - Perform read from or write to card\n");
    printf("<dump.mfd>  - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)\n");
    printf("\n");
196
    exit(EXIT_FAILURE);
Romuald Conty's avatar
Romuald Conty committed
197 198
  }

199
  DBG("\nChecking arguments and settings\n");
Romuald Conty's avatar
Romuald Conty committed
200

201
  bReadAction = tolower((int)((unsigned char) * (argv[1])) == 'r');
Romuald Conty's avatar
Romuald Conty committed
202

203
  if (bReadAction) {
204
    memset(&mtDump, 0x00, sizeof(mtDump));
Romuald Conty's avatar
Romuald Conty committed
205
  } else {
206
    pfDump = fopen(argv[2], "rb");
Romuald Conty's avatar
Romuald Conty committed
207

208
    if (pfDump == NULL) {
209
      ERR("Could not open dump file: %s\n", argv[2]);
210
      exit(EXIT_FAILURE);
Romuald Conty's avatar
Romuald Conty committed
211 212
    }

213 214 215
    if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
      ERR("Could not read from dump file: %s\n", argv[2]);
      fclose(pfDump);
216
      exit(EXIT_FAILURE);
Romuald Conty's avatar
Romuald Conty committed
217
    }
218
    fclose(pfDump);
Romuald Conty's avatar
Romuald Conty committed
219
  }
220
  DBG("Successfully opened the dump file\n");
Romuald Conty's avatar
Romuald Conty committed
221

222 223
  nfc_context *context;
  nfc_init(&context);
224 225 226 227
  if (context == NULL) {
    ERR("Unable to init libnfc (malloc)");
    exit(EXIT_FAILURE);
  }
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 234
    nfc_exit(context);
    exit(EXIT_FAILURE);
Romuald Conty's avatar
Romuald Conty committed
235 236
  }

237 238
  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
239 240
    nfc_close(pnd);
    nfc_exit(context);
241
    exit(EXIT_FAILURE);
242
  }
Romuald Conty's avatar
Romuald Conty committed
243

244
  // Let the device only try once to find a tag
245 246
  if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) {
    nfc_perror(pnd, "nfc_device_set_property_bool");
247 248
    nfc_close(pnd);
    nfc_exit(context);
249
    exit(EXIT_FAILURE);
250
  }
Romuald Conty's avatar
Romuald Conty committed
251

252
  printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
Romuald Conty's avatar
Romuald Conty committed
253 254

  // Try to find a MIFARE Ultralight tag
255
  if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) {
256 257
    ERR("no tag was found\n");
    nfc_close(pnd);
258
    nfc_exit(context);
259
    exit(EXIT_FAILURE);
Romuald Conty's avatar
Romuald Conty committed
260 261 262
  }
  // Test if we are dealing with a MIFARE compatible tag

263
  if (nt.nti.nai.abtAtqa[1] != 0x44) {
264 265
    ERR("tag is not a MIFARE Ultralight card\n");
    nfc_close(pnd);
266
    nfc_exit(context);
267
    exit(EXIT_FAILURE);
Romuald Conty's avatar
Romuald Conty committed
268
  }
269
  // Get the info from the current tag
270
  printf("Found MIFARE Ultralight card with UID: ");
271 272
  size_t  szPos;
  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 279 280 281
    if (read_card()) {
      printf("Writing data to file: %s ... ", argv[2]);
      fflush(stdout);
      pfDump = fopen(argv[2], "wb");
282
      if (pfDump == NULL) {
283
        printf("Could not open file: %s\n", argv[2]);
284 285 286
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
Romuald Conty's avatar
Romuald Conty committed
287
      }
288 289
      if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
        printf("Could not write to file: %s\n", argv[2]);
290
        fclose(pfDump);
291 292 293
        nfc_close(pnd);
        nfc_exit(context);
        exit(EXIT_FAILURE);
Romuald Conty's avatar
Romuald Conty committed
294
      }
295 296
      fclose(pfDump);
      printf("Done.\n");
Romuald Conty's avatar
Romuald Conty committed
297 298
    }
  } else {
299
    write_card();
Romuald Conty's avatar
Romuald Conty committed
300 301
  }

302
  nfc_close(pnd);
303
  nfc_exit(context);
304
  exit(EXIT_SUCCESS);
Romuald Conty's avatar
Romuald Conty committed
305
}