自从家里换了指纹锁,出门就再也没带过钥匙,然而小区门禁卡还是要带,为了彻底实现 key free,我在万能的淘宝上买到了可以贴在手机背面的只有线圈和芯片的 UID 卡,只要能把门禁卡信息复制到芯片中,从此出门就只用带手机了。

硬件准备

  • PN532 读卡器模块
  • Raspberry Pi,预装 Raspbian 系统
  • 0扇区可读写的 UID 卡

在 Raspberry Pi 上启用串口

淘宝上买到的 PN532 模块可以支持 UART/SPI/I2C 三种连接方式,并且可以通过板子上的开关来进行切换。而由于我的 Raspberry Pi 上的 SPI/I2C 端口都已经接了别的设备,这里我选择 UART 连接方式连接 PN532 模块,因此需要在 Raspberry Pi 上启用串口。

为了把 Raspberry Pi 的串口打开,需要在 Raspberry Pi 上运行:

sudo raspi-config

然后在设置界面中选择 Interfacing Options -> Serial 。

Would you like a login shell to be accessible over serial?

选 No 以关闭串口的 shell 登录,否则会干扰串口设备的正常工作。

Would you like the serial port hardware to be enabled?

选 Yes 以打开串口。

连接 PN532 模块到 Raspberry Pi

对照 Raspberry Pi Pinout ,将 PN532 模块的对应接口连接到 Raspberry Pi 上:

  • PN532 VCC <-> Raspberry Pi 5V
  • PN532 GND <-> Raspberry Pi GND
  • PN532 TXD <-> Raspberry Pi RXD
  • PN532 RXD <-> Raspberry Pi TXD

安装 libnfc

libnfc 是 Raspberry Pi 上控制 PN532 模块读写卡片所必需的库,在 Raspberry Pi 上安装 libnfc:

sudo apt install libnfc-bin libnfc-dev libnfc-examples

编辑 libnfc 的配置文件:

sudo vim /etc/nfc/libnfc.conf

打开 autoscan 和 intrusive scan:

allow_autoscan = true
allow_intrusive_scan = true

测试 PN532 模块

将门禁卡放到 PN532 模块上,然后运行:

sudo nfc-list

如果能够正确读取到卡片信息,说明 PN532 模块和 libnfc 都能正常工作。

安装 mfoc

为了破解并 dump 卡片中的数据,需要用到 mfoc 这一工具。

由于 mfoc 并不在 Raspbian 的软件仓库中,因此需要手动去编译。

安装编译所 mfoc 需要的依赖包:

sudo apt install build-essential
sudo apt install autoconf automake libtool

获取 mfoc 代码:

git clone https://github.com/nfc-tools/mfoc.git

编译并安装 mfoc:

cd mfoc
autoreconf -is
./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var
make
sudo make install

Dump门禁卡数据

有了 mfoc,就可以开始破解并 dump 门禁卡的数据了。将门禁卡放到 PN532 模块上,然后执行:

sudo mfoc -O orig.mfd

mfoc 会自动选用自带的默认 key 去解锁并读取卡片中的所有16个扇区的数据,如果部分扇区采用了非默认的 key 进行加密,mfoc 则会尝试去破解。

如果所有扇区的 key 都能够被破解出来,mfoc 会将 dump 出的数据导出到 orig.mfd 文件中。

写入门禁卡数据

拿到原始的门禁卡数据后,就可以拿去写入新的卡片了。按理说,标准的 Mifare Classic 卡片的0扇区应该是出厂后无法再次写入的,但是万能的淘宝可以买到0扇区可写入的卡片,将卡片放在 PN532 模块上,然后执行写入命令:

sudo nfc-mfclassic W a orig.mfd orig.mfd f

如果一切正常的话,我们就可以得到两张完全一样的卡片,把新复制的卡片贴到手机后盖,就可以拿去刷门禁了!