pad dumps to 4k for correct key loading
[perl-Mifare-MAD.git] / nfc-card-dumper.pl
index 5403ada..143ac04 100755 (executable)
@@ -9,9 +9,10 @@ use Digest::MD5 qw(md5_hex);
 
 use Data::Dump qw(dump);
 
+my $debug = $ENV{DEBUG} || 0;
 my $keyfile = shift @ARGV;
 
-my $r = RFID::Libnfc::Reader->new(debug => 1);
+my $r = RFID::Libnfc::Reader->new(debug => $debug);
 if ($r->init()) {
     printf ("Reader: %s\n", $r->name);
     my $tag = $r->connect(IM_ISO14443A_106);
@@ -49,6 +50,16 @@ if ($r->init()) {
             $i += 3 if ($tag->type eq "ULTRA");
                        $card .= $data;
                        print STDERR "$i ";
+               } elsif ( $tag->error =~ m/auth/ ) {
+                       warn $tag->error,"\n";
+
+                       # disconnect from reader so we can run mfoc
+                       RFID::Libnfc::nfc_disconnect($r->{_pdi});
+
+                       my $file = "cards/$uid.key";
+                       unlink $file;
+                       warn "# finding keys for card $uid with: mfoc -O $file\n";
+                       exec "mfoc -O $file" || die $!;
         } else {
             die $tag->error."\n";
         }
@@ -68,11 +79,15 @@ if ($r->init()) {
                warn "sector $i keys re-inserted at $o\n";
        }
 
+       if ( my $padding = 4096 - length($card) ) {
+               warn "add $padding bytes up to 4k dump (needed for keys loading)\n";
+               $card .= "\x00" x $padding;
+       }
+
        my $md5 = md5_hex($card);
-       if ( glob "cards/$uid.md5.*" ) {
+       if ( glob "cards/$uid.$md5.*" ) {
                warn "SKIPPING, same dump allready exits\n";
        } else {
-
                my $out_file = "cards/$uid.$md5";
                write_file $out_file, $card;
                print "$out_file ", -s $out_file, " bytes\n";
@@ -80,7 +95,7 @@ if ($r->init()) {
                        symlink $out_file, "cards/$uid.key" || die "cards/$uid.key: $!";
                        warn "using keys as default for card $uid\n";
                }
-               system "./mifare-mad.pl $out_file | vi -R -";
+               $ENV{MAD} && system "./mifare-mad.pl $out_file | vi -R -";
        }
 
 }