libnfc  1.7.1
nfc-mfultralight.c
Go to the documentation of this file.
00001 /*-
00002  * Free/Libre Near Field Communication (NFC) library
00003  *
00004  * Libnfc historical contributors:
00005  * Copyright (C) 2009      Roel Verdult
00006  * Copyright (C) 2009-2013 Romuald Conty
00007  * Copyright (C) 2010-2012 Romain Tartière
00008  * Copyright (C) 2010-2013 Philippe Teuwen
00009  * Copyright (C) 2012-2013 Ludovic Rousseau
00010  * See AUTHORS file for a more comprehensive list of contributors.
00011  * Additional contributors of this file:
00012  * Copyright (C) 2013      Adam Laurie
00013  *
00014  * Redistribution and use in source and binary forms, with or without
00015  * modification, are permitted provided that the following conditions are met:
00016  *  1) Redistributions of source code must retain the above copyright notice,
00017  *  this list of conditions and the following disclaimer.
00018  *  2 )Redistributions in binary form must reproduce the above copyright
00019  *  notice, this list of conditions and the following disclaimer in the
00020  *  documentation and/or other materials provided with the distribution.
00021  *
00022  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
00023  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00024  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00025  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
00026  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
00027  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
00028  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
00029  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
00030  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
00031  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
00032  * POSSIBILITY OF SUCH DAMAGE.
00033  *
00034  * Note that this license only applies on the examples, NFC library itself is under LGPL
00035  *
00036  */
00037 
00043 #ifdef HAVE_CONFIG_H
00044 #  include "config.h"
00045 #endif // HAVE_CONFIG_H
00046 
00047 #include <stdio.h>
00048 #include <stdlib.h>
00049 #include <stdint.h>
00050 #include <stddef.h>
00051 #include <stdbool.h>
00052 
00053 #include <string.h>
00054 #include <ctype.h>
00055 
00056 #include <nfc/nfc.h>
00057 
00058 #include "nfc-utils.h"
00059 #include "mifare.h"
00060 
00061 static nfc_device *pnd;
00062 static nfc_target nt;
00063 static mifare_param mp;
00064 static mifareul_tag mtDump;
00065 static uint32_t uiBlocks = 0xF;
00066 
00067 static const nfc_modulation nmMifare = {
00068   .nmt = NMT_ISO14443A,
00069   .nbr = NBR_106,
00070 };
00071 
00072 static void
00073 print_success_or_failure(bool bFailure, uint32_t *uiCounter)
00074 {
00075   printf("%c", (bFailure) ? 'x' : '.');
00076   if (uiCounter)
00077     *uiCounter += (bFailure) ? 0 : 1;
00078 }
00079 
00080 static  bool
00081 read_card(void)
00082 {
00083   uint32_t page;
00084   bool    bFailure = false;
00085   uint32_t uiReadedPages = 0;
00086 
00087   printf("Reading %d pages |", uiBlocks + 1);
00088 
00089   for (page = 0; page <= uiBlocks; page += 4) {
00090     // Try to read out the data block
00091     if (nfc_initiator_mifare_cmd(pnd, MC_READ, page, &mp)) {
00092       memcpy(mtDump.amb[page / 4].mbd.abtData, mp.mpd.abtData, 16);
00093     } else {
00094       bFailure = true;
00095       break;
00096     }
00097 
00098     print_success_or_failure(bFailure, &uiReadedPages);
00099     print_success_or_failure(bFailure, &uiReadedPages);
00100     print_success_or_failure(bFailure, &uiReadedPages);
00101     print_success_or_failure(bFailure, &uiReadedPages);
00102   }
00103   printf("|\n");
00104   printf("Done, %d of %d pages readed.\n", uiReadedPages, uiBlocks + 1);
00105   fflush(stdout);
00106 
00107   return (!bFailure);
00108 }
00109 
00110 static  bool
00111 write_card(void)
00112 {
00113   uint32_t uiBlock = 0;
00114   bool    bFailure = false;
00115   uint32_t uiWritenPages = 0;
00116   uint32_t uiSkippedPages = 0;
00117 
00118   char    buffer[BUFSIZ];
00119   bool    write_otp;
00120   bool    write_lock;
00121   bool    write_uid;
00122 
00123   printf("Write OTP bytes ? [yN] ");
00124   if (!fgets(buffer, BUFSIZ, stdin)) {
00125     ERR("Unable to read standard input.");
00126   }
00127   write_otp = ((buffer[0] == 'y') || (buffer[0] == 'Y'));
00128   printf("Write Lock bytes ? [yN] ");
00129   if (!fgets(buffer, BUFSIZ, stdin)) {
00130     ERR("Unable to read standard input.");
00131   }
00132   write_lock = ((buffer[0] == 'y') || (buffer[0] == 'Y'));
00133   printf("Write UID bytes (only for special writeable UID cards) ? [yN] ");
00134   if (!fgets(buffer, BUFSIZ, stdin)) {
00135     ERR("Unable to read standard input.");
00136   }
00137   write_uid = ((buffer[0] == 'y') || (buffer[0] == 'Y'));
00138 
00139   printf("Writing %d pages |", uiBlocks + 1);
00140   /* We may need to skip 2 first pages. */
00141   if (!write_uid) {
00142     printf("ss");
00143     uiSkippedPages = 2;
00144   }
00145 
00146   for (int page = uiSkippedPages; page <= 0xF; page++) {
00147     if ((page == 0x2) && (!write_lock)) {
00148       printf("s");
00149       uiSkippedPages++;
00150       continue;
00151     }
00152     if ((page == 0x3) && (!write_otp)) {
00153       printf("s");
00154       uiSkippedPages++;
00155       continue;
00156     }
00157     // Show if the readout went well
00158     if (bFailure) {
00159       // When a failure occured we need to redo the anti-collision
00160       if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) {
00161         ERR("tag was removed");
00162         return false;
00163       }
00164       bFailure = false;
00165     }
00166     // For the Mifare Ultralight, this write command can be used
00167     // in compatibility mode, which only actually writes the first
00168     // page (4 bytes). The Ultralight-specific Write command only
00169     // writes one page at a time.
00170     uiBlock = page / 4;
00171     memcpy(mp.mpd.abtData, mtDump.amb[uiBlock].mbd.abtData + ((page % 4) * 4), 16);
00172     if (!nfc_initiator_mifare_cmd(pnd, MC_WRITE, page, &mp))
00173       bFailure = true;
00174 
00175     print_success_or_failure(bFailure, &uiWritenPages);
00176   }
00177   printf("|\n");
00178   printf("Done, %d of %d pages written (%d pages skipped).\n", uiWritenPages, uiBlocks + 1, uiSkippedPages);
00179 
00180   return true;
00181 }
00182 
00183 int
00184 main(int argc, const char *argv[])
00185 {
00186   bool    bReadAction;
00187   FILE   *pfDump;
00188 
00189   if (argc < 3) {
00190     printf("\n");
00191     printf("%s r|w <dump.mfd>\n", argv[0]);
00192     printf("\n");
00193     printf("r|w         - Perform read from or write to card\n");
00194     printf("<dump.mfd>  - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)\n");
00195     printf("\n");
00196     exit(EXIT_FAILURE);
00197   }
00198 
00199   DBG("\nChecking arguments and settings\n");
00200 
00201   bReadAction = tolower((int)((unsigned char) * (argv[1])) == 'r');
00202 
00203   if (bReadAction) {
00204     memset(&mtDump, 0x00, sizeof(mtDump));
00205   } else {
00206     pfDump = fopen(argv[2], "rb");
00207 
00208     if (pfDump == NULL) {
00209       ERR("Could not open dump file: %s\n", argv[2]);
00210       exit(EXIT_FAILURE);
00211     }
00212 
00213     if (fread(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
00214       ERR("Could not read from dump file: %s\n", argv[2]);
00215       fclose(pfDump);
00216       exit(EXIT_FAILURE);
00217     }
00218     fclose(pfDump);
00219   }
00220   DBG("Successfully opened the dump file\n");
00221 
00222   nfc_context *context;
00223   nfc_init(&context);
00224   if (context == NULL) {
00225     ERR("Unable to init libnfc (malloc)");
00226     exit(EXIT_FAILURE);
00227   }
00228 
00229   // Try to open the NFC device
00230   pnd = nfc_open(context, NULL);
00231   if (pnd == NULL) {
00232     ERR("Error opening NFC device");
00233     nfc_exit(context);
00234     exit(EXIT_FAILURE);
00235   }
00236 
00237   if (nfc_initiator_init(pnd) < 0) {
00238     nfc_perror(pnd, "nfc_initiator_init");
00239     nfc_close(pnd);
00240     nfc_exit(context);
00241     exit(EXIT_FAILURE);
00242   }
00243 
00244   // Let the device only try once to find a tag
00245   if (nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false) < 0) {
00246     nfc_perror(pnd, "nfc_device_set_property_bool");
00247     nfc_close(pnd);
00248     nfc_exit(context);
00249     exit(EXIT_FAILURE);
00250   }
00251 
00252   printf("NFC device: %s opened\n", nfc_device_get_name(pnd));
00253 
00254   // Try to find a MIFARE Ultralight tag
00255   if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) <= 0) {
00256     ERR("no tag was found\n");
00257     nfc_close(pnd);
00258     nfc_exit(context);
00259     exit(EXIT_FAILURE);
00260   }
00261   // Test if we are dealing with a MIFARE compatible tag
00262 
00263   if (nt.nti.nai.abtAtqa[1] != 0x44) {
00264     ERR("tag is not a MIFARE Ultralight card\n");
00265     nfc_close(pnd);
00266     nfc_exit(context);
00267     exit(EXIT_FAILURE);
00268   }
00269   // Get the info from the current tag
00270   printf("Found MIFARE Ultralight card with UID: ");
00271   size_t  szPos;
00272   for (szPos = 0; szPos < nt.nti.nai.szUidLen; szPos++) {
00273     printf("%02x", nt.nti.nai.abtUid[szPos]);
00274   }
00275   printf("\n");
00276 
00277   if (bReadAction) {
00278     if (read_card()) {
00279       printf("Writing data to file: %s ... ", argv[2]);
00280       fflush(stdout);
00281       pfDump = fopen(argv[2], "wb");
00282       if (pfDump == NULL) {
00283         printf("Could not open file: %s\n", argv[2]);
00284         nfc_close(pnd);
00285         nfc_exit(context);
00286         exit(EXIT_FAILURE);
00287       }
00288       if (fwrite(&mtDump, 1, sizeof(mtDump), pfDump) != sizeof(mtDump)) {
00289         printf("Could not write to file: %s\n", argv[2]);
00290         fclose(pfDump);
00291         nfc_close(pnd);
00292         nfc_exit(context);
00293         exit(EXIT_FAILURE);
00294       }
00295       fclose(pfDump);
00296       printf("Done.\n");
00297     }
00298   } else {
00299     write_card();
00300   }
00301 
00302   nfc_close(pnd);
00303   nfc_exit(context);
00304   exit(EXIT_SUCCESS);
00305 }