Hackaday USSSSSBTalkingUSBFromPython OFlynn PDF
Hackaday USSSSSBTalkingUSBFromPython OFlynn PDF
https://hackaday.io/project/956-chipwhisperer-security-research/log/10108-aes-256-is-not-enough-breaking-a-bootloader
https://eprint.iacr.org/2014/899.pdf
AWESOME: Live Workshop
• Atmel has donated a number of SAM D21 Xplained Pro Boards
– I’m going to use them to give you the hands-on experience.
– Note I don’t have a connection to Atmel. Am just familiar with their
products and have used them previously.
– 90% of what I’ll take you through is portable across other devices and
families or USB stacks.
Software Setup While I Talk
• Download and install Atmel
Studio (6.2 latest as of these http://oflynn.com/?p=669
slides, use 7.x if possible)
All links available from here
• Download and install
WinPython-2.7 (latest version)
http://xkcd.com/927/
Finding USB Resources
Get the original docs at http://www.usb.org/developers/docs/ - the USB specs are very
well written for “regular users”
• Be sure to get the USB 2.0 docs, not latest 3.x!
• Original spec is updated with ECN
USB 3.0 effectively adds a separate channel for 3.x traffic… the cable still has the 2.0
signals. But honestly let’s start with slower 2.0 for now…
Part #2: USB Solutions
USB-Serial
• Can use DMA to dump data from USB to memory-mapped FPGA registers
Part #4: Python Intro
http://xkcd.com/353/
because it’s so easy
– Very easy to write bad code
– Example: Despite not needing
semicolons, Python will ignore
them if added at the end of
lines. This looks terrible but
Python knows what you want
so just ignores it…
Basics of Python (The Shortcut)
• Python is whitespace-sensitive:
if a < 4:
print("That is wrong you jerk")
b++
d++
Basics of Python (The Shortcut)
#Strings
myname = "Colin"
Basics of Python (The Shortcut)
1. Switch back USB to Debug port (if not using two USB cables)
2. Select Device Programming
Overwrite the coarse variable at this point… start with HEX value read from fuses
(so don’t forget 0x), and go up a few numbers… here 0x26 works for me
Work-Around for SAMD11
• Re-build and re-program
• Switch USB cable from DEBUG to TARGET (or if have two USB
cables, just hit RESET button)
Run Spyder
Checking for Python Console
Example – NOT a Python Console
Open a Python Console (if not running)
Testing Basic USB Connectivity
https://github.com/walac/pyusb/blob/master/docs/tutorial.rst
Need to Insert Filter Driver!
VID = 03EB
PID = 2402
Install Successful
NOTE: Remove to restore
• If other driver/program needed this device, be sure to remove
the filter driver to restore original operation once you are
done tinkering!
• In our case just leave it in…
Re-Trying Test from Python
Simple Test File
import usb.core
dev = usb.core.find(idVendor=0x03eb, idProduct=0x2402)
print dev
print data
Problems with Control Endpoint
• Limited endpoint size
• Should try to avoid using for real data transfer!
Input and Output Reports
• INPUT reports are sent TO the computer
• OUTPUT reports are sent FROM the computer
src\ASF\common\services\usb\class\hid\device\generic\udi_hid_generic.c
Input Report
dev.read(0x81, 8, timeout=500)
Getting Input Report
print test
Running This Demo
Prints 10 state
changes… press
button to generate
state changes.
Want the full source code for copy/paste? See http://oflynn.com/?p=669
Making a Simple GUI
• No longer doing this inside Spyder… instead open actual
editor
• Use IDLE that ships with Python
Making a Simple GUI
class USBForm(QDialog):
def __init__(self, parent=None):
super(USBForm, self).__init__(parent)
self.setWindowTitle(“Hackaday 2015 Demo")
if __name__ == "__main__":
app = QApplication(sys.argv)
form = USBForm()
form.show()
sys.exit(app.exec_())
layout = QVBoxLayout()
self.setLayout(layout)
self.pbConnect = QPushButton("Connect")
self.pbConnect.clicked.connect(self.con)
self.isConnected = False
layout.addWidget(self.pbConnect)
layout.addWidget(self.pbLED)
Buttons do
nothing yet…
#Sync changeLED
self.changeLED()
self.isConnected = True
…rest of code from before…
self.swStatus = QLineEdit()
self.swStatus.setReadOnly(True)
layout.addWidget(self.swStatus)
self.butTimer = QTimer(self)
self.butTimer.timeout.connect(self.pollButton)
Adding Button Reading…
def con(self):
if self.isConnected == False:
… original stuff still here…
#Sync changeLED
self.changeLED()
self.butTimer.start(100)
self.isConnected = True
self.pbConnect.setText("Disconnect")
self.pbLED.setEnabled(True)
else:
self.butTimer.stop()
self.isConnected = False
…again rest of code stil here…
Adding Button Reading…
def pollButton(self):
try:
data = self.dev.read(0x81, 8, timeout=50)
if data[0]:
self.swStatus.setText("Button Pressed")
else:
self.swStatus.setText("Button Released")
except usb.core.USBError, e:
if str(e).find("timeout") >= 0:
pass
else:
raise IOError("USB Error: %s"%str(e))
Testing
Congratulations!
You did it! USB Communication and a Windows GUI all without
any terribly bad hacks!
Part #6: Vendor-Specific Bulk Transfer
From HID to Bulk Transfer
• You probably just want to shovel bytes across interface
• Possible with HID, but limited speed
• Instead let’s use vendor-specific Bulk Transfer
– Just send a packet to the IN or OUT bulk endpoint
– Will require a simple driver
ASF Demos
• ASF has vendor-specific demo as example project
– Same idea of using dev.write() and dev.read()
• Also what is used in my ChipWhisperer-Lite project
– Lots of examples there, also uses USB high-speed mode (not
supported in SAMD21 chips)
ASF Demos
Making a Driver
• Wireshark!
Using a Virtual Machine
USB Driver/App
VM
Your PC
USB Device
http://vusb-analyzer.sourceforge.net/tutorial.html
Hardware Protocol Analyzers
• If doing USB where your time has value, these will pay for
themselves VERY quickly
– Example from these slides: Finding that bug in my SAMD11 dev-kit,
using USB Hardware Analyzer I could easily see corrupt packets going
across the wire
• Suggests something very wrong at lower layers
• First thing to check: clock reliability Problem Solved in ~30 mins.
• w/o Hardware analyzer might have wasted time thinking it was SW issue
causing device to not enter correct mode
Hardware Protocol Analyzer
Breakpoint Here
Debugging Firmware
• If just checking a single packet is OK, since don’t care about
lost connection
• But harder when checking more complex protocols…
Debugging Firmware
• Use hardware I/O lines in protocol analyzer (Beagle USB 480
supports this feature, others probably do too)
– #1: Toggle lines when certain areas of software are run
– #2: Trigger interrupts when specific errors occur
Debugging Firmware Example #1
Debugging Firmware Example #1
6.770.979
Setup
Packet
(6.770.952)
Debugging Firmware Example #1
• Use IO Pins to get real time ability to link USB packets to
Events
• This is a very useful ability – highly recommend purchasing a
USB analyzer with trigger(s) input
Debugging Firmware Example #2
– Interrupt pin, and set breakpoint inside ISR… step out of ISR to see
what the firmware was doing
Debugging Firmware Example #2
Part #8: Distributing Drivers
Without Signed Drivers…
With Signed Drivers…
How to Sign Windows Drivers
• There is cheaper/free ways, but I’m showing you the “least
painful / most useful”
• This is the greatest resource I’ve found:
http://www.davidegrayson.com/signing/
• Supplement my notes by reading the above!
Step 1: Give Someone $$$
• Require code signing certificate… several options, i.e.:
– https://www.globalsign.com/en/code-signing-certificate/
– Will require verification as part of this process
• Following steps assume you’ve installed certificate on system
– NB: If doing that, don’t install on laptop you could easily lose…
Step 2: Install 10GB of Crap
• You require ‘signtool’ and ‘inf2cat’ programs
– Need to install Windows SDK + WDK (which also uses Visual Studio
2013)
– Then you can just copy those files out…
Step 3: Fancy Batch File
NOTE: Have choice of SHA1 or SHA2… SHA1 will be obsolete in 2016 so now just use
SHA2
NOTE2: Possible to sign with both, as older systems didn’t always work with SHA2
Step 4: Signing a Driver
Sadface.
USB Suspend Current
Uses differential probe from NewAE Technology Inc. (NB: requires mode for DC-accurate
levels, see http://newae.com/sidechannel/cwdocs/naecw501_hwdiffprobe.html
USB Inrush Testing
Free tool from USB-IF Compliance
Program website to analyzer
captures
Serial Numbers
• If your device DOES NOT have a serial number, drivers are
reinstalled when device is plugged into a different port
• Easy solution: many micros have unique ID nowadays, just use
that to generate a serial number
– Doesn’t require you to manage anything
– Better for user, since Windows doesn’t keep reinstalling drivers
USB Inrush Testing
• USB Specs require minimum of ~1uF for device detection
• Upper limit is ~10uF
• Official testing done with current probe (somewhat expensive
for one-off test)
That’s All Folks!
• USB Interfaces aren’t too difficult! Need to get your feet wet.
• Having a hardware debugger is a useful investment.
• Can communicate from something like Python even.
Thanks for Sticking Around!
My Contact:
Email: coflynn@newae.com
Twitter: @colinoflynn