As of August 2020 the site you are on (wiki.newae.com) is deprecated, and content is now at rtfm.newae.com.

Changes

Jump to: navigation, search

Tutorial B3-1 Timing Analysis with Power for Password Bypass

1,033 bytes removed, 19:18, 10 October 2018
Reset via Auxiliary Module
|capture hardware = CW-Lite, CW-Lite 2-Part, CW-Pro
|Target Device =
|Target Architecture = XMEGA/Arm
|Hardware Crypto = No
|Purchase Hardware =
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 target firmware we'll be using for this tutorial 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{{CollapsibleSection|intro =</code> command. You should end up === Building for CWLite with something like this being printed:XMEGA Target ===|content= Building for XMEGA}}
<pre>Creating Symbol Table: basic-passwdcheck.sym{{CollapsibleSectionavr-nm -n basic-passwdcheck.elf &gt; basic-passwdcheck.sym|intro = === Building for CWLite with Arm Target ===|content= Building for Arm}}
Size after:{{CollapsibleSectionAVR Memory Usage|intro = === Building for Other Targets ===----------------Device: atxmega128d3|content= Building for Other Targets}}
Program: 5400 bytes (3.9% Full)== Hardware Setup =={{CollapsibleSection|intro = === CW1173 (.text + .data + .bootloaderLite)Hardware Setup ===|content= CWLite HW Setup}}
Data: 524 bytes {{CollapsibleSection|intro = === CW1200 (6.4% FullPro)Hardware Setup ===(.data + .bss + .noinit)|content= CW1200 HW Setup}}
{{CollapsibleSection
|intro = === CW308 (UFO) Hardware Setup ===
|content= CW308 HW Setup}}
Built for platform CW-Lite == Programming the Target =={{CollapsibleSection|intro = === Programming the XMEGATarget ===|content= Programming XMEGA}}
-------- end --------</pre>{{CollapsibleSection|intro = === Programming the STM32F3 (CW303 Arm) Target ===|content= Programming Arm}}
{{CollapsibleSection|intro = Manual Communications with the Target === Programming Other Targets ===|content= Programming Other}}
At this point, you should be able to configure == Manual Communications with 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.Target ==
<ol style="list-style-type: decimal;"><li>Connect your target hardware (ChipWhisperer-Lite/Pro or Assuming you have ChipWhisperer-Capture Rev 2 with setup when you programmed the target board).</li><li>Start ChipWhisperer-Capture</li><li>Under the ''Python Console'' tab(if not, find the run ''connect_cwlite_simpleserial.py'' script and double-click.</li><li>Check there are no errors on the connection.</li><li>Under the ''Python Console'' tab, find the ''setup_cwlite_xmegasetup_*.py'' script and double-click.</li><li>Both the Target &amp; Scope should switch relevant to ''CON'' and be green circles.</li><li>Using the programming tool (such as XMEGA programming dialogyour target), 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 can continue by selecting ''Tools --> Terminal'', and press pressing ''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. 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><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 &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.</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>&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></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.
<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.
== Reset via Spare IO Lines ==BOTH of these methods use the "Auxilary Modules". See the page [[Auxiliary modules]] for more details.
TODO - see 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 via programming interface for nowthe target chip before arming the measurement so that we don't have to manually reset the device.
=== Reset via Auxiliary Module Spare IO Lines ===
TODO - see reset via programming interface for now === Reset via 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.Module ===
<ol style="list-style-type: decimal;">
<li> Scroll down the list of scripts, and you'll find one labeled "aux_reset_cw1173.py". This script has a simple function of attempting to reset If you're not using the XMEGA device using target, you'll need to edit the programmerscript to use the ''nrst'' pin instead of <u>''pdic''</u>:
<br>
[[File:auxreset_test1.png|600px]]
# Reset XMEGA device
Resetter = ResetCW1173(xmegapin=True'pdic', delay_ms=delay_ms)# Reset STM32Fx device#Resetter = ResetCW1173(pin='nrst', delay_ms=delay_ms)
# Reset AVR
#Resetter = ResetCW1173(xmegapin=False'nrst', delay_ms=delay_ms)
# Reset before arming - more stable# 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.
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.
</li>
<li><p>Finally, we We will need to set the passwordguess 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 capturecw.captureN(self.scope, self.target, None, self.aux_list, self.ktp, 1)trace = scope.getLastTrace()</syntaxhighlight>
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:
<presyntaxhighlight lang=python>#Put this at beginning of scriptimport chipwhisperer as cw #Put this later on after setup happenscw.captureN(self.apiscope, self.capture1()data = target, None, self.apiaux_list, self.getScope(ktp, 1)trace = scope.channels[0].getTracegetLastTrace()print datatrace</presyntaxhighlight> Run your script. The ChipWhisperer should automatically capture one trace and print out the several thousand some 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 (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 avr-gcc 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></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
* Repeats for all characters we want to try
An example of this loop is:
 <presyntaxhighlight lang=python>
trylist = 'abcdefghijklmnopqrstuvwxyz0123456789'
for c in trylist:
# Test this password and record Get a power traceusing our next attempt selfnextPass = password + '{}'.api.setParameterformat(['Simple Serial', 'Go Command', c ) + '"\n'])" target.go_cmd = nextPass cw.captureN(self.apiscope, self.capture1(target, None, self.aux_list, self.ktp, 1) # Get Grab the data trace and check data[153] data nextTrace = selfscope.api.getScope().channels[0].getTracegetLastTrace() if datanextTrace[153] > -0.2:
print "Success: " + c
</presyntaxhighlight>
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
An example of this loop is:
<presyntaxhighlight lang=python># Crack the first letter
password = ''
trylist = 'abcdefghijklmnopqrstuvwxyz0123456789'
for c in trylist:
# Get a power trace using our next attempt
nextPass = password + '{}'.format(c)+ "\n" selftarget.apigo_cmd = nextPass cw.setParametercaptureN(['Simple Serial'self.scope, 'Go Command'self.target, '{}\n'None, self.format(nextPass)]) aux_list, self.api.capture1(ktp, 1)
# Grab the trace
nextTrace = selfscope.api.getScope().channels[0].getTracegetLastTrace()
# Check location 153, 225, etc. If it's too low, we've failed
print '{} characters: {}'.format(i+1, password)
break
</presyntaxhighlight>
After some time, this prints <code>5 characters: h0px3</code> -- it automatically finds the correct 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 complete tutorial might look something like the followingthis:<presyntaxhighlight 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 cwfrom chipwhisperer.capture.auxiliary.ResetCW1173Read import ResetCW1173 # GUI compatibilitytry: def runscope = self.scope target = self.target aux_list = self.aux_listexcept NameError: pass # Set up scopescope.gain.gain = 45scope.adc.samples = 2000scope.adc.offset = 0scope.adc.basic_mode = "rising_edge"scope.clock.clkgen_freq = 7370000scope.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 targettarget.key_cmd = ""target.go_cmd = "h0px3\n"target.output_cmd = "" # Set up aux module to reset target before captureresetter = ResetCW1173(xmega=True, delay_ms=1200)aux_list.register(resetter.resetThenDelay, "before_trace") # Test one capturecw.captureN(self.scope, self.target, None, self.aux_list, self.ktp, 1)trace = scope.getLastTrace()print trace # Crack the first letterpassword = ''trylist = 'abcdefghijklmnopqrstuvwxyz0123456789' for i in range(5): for c in trylist: # This is the function that gets called when Get a power trace using our script startsnext attempt nextPass = password + '{}'.format(c) + "\n" target.go_cmd = nextPass cw.captureN(self.scope, self.target, None, self.aux_list, self.ktp, 1)
# First: set up Grab the basics and connect to the CW-Litetrace 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.apinextTrace = scope.connectgetLastTrace()
# 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</presyntaxhighlight== Links ==
{{Template:Tutorials}}
[[Category:Tutorials]]
Approved_users, administrator
366
edits

Navigation menu