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 A5 Breaking AES-256 Bootloader

2,832 bytes removed, 17:35, 21 June 2016
Appendix A: Target Code: Added new code
= Appendix A: Target Code =
 The following: <pre>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013-20142016, NewAE Technology Inc
# All rights reserved.
#
# Authors: Colin O'Flynn, Greg d'Eon
#
# Find this and more at newae.com - this file is part of the chipwhisperer
#
# You should have received a copy of the GNU General Public License
# along with chipwhisperer. If not, see &lt;<http://www.gnu.org/licenses/&gt;>.
#=================================================
#
#
#
# This example captures data using the ChipWhisperer Rev2 capture hardware.
# The target is a SimpleSerial board attached to the ChipWhisperer.
#
# Data is saved into both a project file and a MATLAB array
#
#Setup path
import sys
 
import time
 #Import the ChipWhispererCapture moduleimport chipwhisperer.capture.ChipWhispererCapture ui.CWCaptureGUI as cwcfrom chipwhisperer.capturecommon.targetsapi.TargetTemplate CWCoreAPI import TargetTemplateCWCoreAPIfrom chipwhisperer.capture.targets.SimpleSerial import SimpleSerial_ChipWhispererSimpleSerial #Check for PySidetry: from PySidechipwhisperer.common.scripts.QtCore base import *UserScriptBase from PySidechipwhisperer.QtGui capture.targets._base import *TargetTemplateexcept ImportError: print &quot;ERROR: PySide is required for this program&quot; sysfrom chipwhisperer.exit() common.utils import threadpluginmanager import scipyfrom chipwhisperer.io as siocapture.targets.simpleserial_readers.cwlite import SimpleSerial_ChipWhispererLite exitWhenDone=False def pe(): QCoreApplicationfrom chipwhisperer.processEvents()common.utils.parameter import setupSetParam
# Class Crc
#############################################################
# These CRC routines are copy-pasted from pycrc, which are:
# Copyright (c) 2006-2013 Thomas Pircher &lt;<tehpeh@gmx.net&gt;>
#
class Crc(object):
&quot;&quot;&quot;"""
A base class for CRC routines.
&quot;&quot;&quot;"""
def __init__(self, width, poly):
&quot;&quot;&quot;"""The Crc constructor.
The parameters are as follows:
reflect_out
xor_out
&quot;&quot;&quot;"""
self.Width = width
self.Poly = poly
self.MSB_Mask = 0x1 &lt;&lt; << (self.Width - 1) self.Mask = ((self.MSB_Mask - 1) &lt;&lt; << 1) | 1
self.XorIn = 0x0000
self.DirectInit = self.XorIn
self.NonDirectInit = self.__get_nondirect_init(self.XorIn)
if self.Width &lt; < 8:
self.CrcShift = 8 - self.Width
else:
def __get_nondirect_init(self, init):
&quot;&quot;&quot;"""
return the non-direct init if the direct algorithm has been selected.
&quot;&quot;&quot;"""
crc = init
for i in range(self.Width):
bit = crc &amp; 0x01
if bit:
crc ^= self.Poly
crc &gt;&gt;>>= 1
if bit:
crc |= self.MSB_Mask
return crc &amp; self.Mask
def bit_by_bit(self, in_data):
&quot;&quot;&quot;"""
Classic simple and slow CRC implementation. This function iterates bit
by bit over the augmented input message and returns the calculated CRC
value at the end.
&quot;&quot;&quot;"""
# If the input data is a string, convert to bytes.
if isinstance(in_data, str):
for octet in in_data:
for i in range(8):
topbit = register &amp; self.MSB_Mask register = ((register &lt;&lt; << 1) &amp; self.Mask) | ((octet &gt;&gt; >> (7 - i)) &amp; 0x01)
if topbit:
register ^= self.Poly
for i in range(self.Width):
topbit = register &amp; self.MSB_Mask register = ((register &lt;&lt; << 1) &amp; self.Mask)
if topbit:
register ^= self.Poly
return register ^ self.XorOut
class BootloaderTarget(TargetTemplate):
paramListUpdated _name = Signal'AES Bootloader'  def __init__(listself, parentParam=None): TargetTemplate.__init__(self, parentParam)  ser_cons = pluginmanager.getPluginsInDictFromPackage("chipwhisperer.capture.targets.simpleserial_readers", True, False, self) self.ser = ser_cons[SimpleSerial_ChipWhispererLite._name]
def setupParameters(self):
self.ser = SimpleSerial_ChipWhisperer()
self.keylength = 16
self.input = &quot;&quot;""
self.crc = Crc(width=16, poly=0x1021)
  def setOpenADC(self, oadc): try: self.setConnection(self.ser.setOpenADC(oadc) except: pass
def setKeyLen(self, klen):
&quot;&quot;&quot; """ Set key length in BITS &quot;&quot;&quot;""" self.keylength = klen / 8
def keyLen(self):
&quot;&quot;&quot; """ Return key length in BYTES &quot;&quot;&quot;"""
return self.keylength
def getConnection(self):
return self.ser
 
def setConnection(self, con):
self.ser = con
self.params.append(self.ser.getParams())
self.ser.connectStatus.connect(self.connectStatus.emit)
self.ser.selectionChanged()
def paramListcon(self, scope=None): return []if not scope or not hasattr(scope, "qtadc"): Warning( "You need a scope with OpenADC connected to use this Target")
def self.ser.con(selfscope): # 'x' flushes everything & sets system back to idle self.ser.conwrite("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
self.ser.flush()
  def dis(self): self.closeconnectStatus.setValue(True)
def close(self):
if self.ser != None:
self.ser.close()
self.ser = None
return
def setModeDecrypt(self):
return
 
def convertVarToString(self, var):
if isinstance(var, str):
return var
 
sep = ""
s = sep.join(["%c" % b for b in var])
return s
def loadEncryptionKey(self, key):
def loadInput(self, inputtext):
self.input = inputtext
 
def readOutput(self):
# No actual output
return [0] * 16
def isDone(self):
return True
def readOutputcheckEncryptionKey(self, kin): #No actual output return [0] * 16kin
def go(self):
crcdata = self.crc.bit_by_bit(self.input)
message.append(crcdata &gt;&gt; >> 8) message.append(crcdata &amp; 0xff)
# Write message
message = self.convertVarToString(message)
for i in range(0, 5):
self.ser.flush()
data = self.ser.read(1)
if len(data) &gt; > 0:
resp = ord(data[0])
if resp != 0xA1:
raise IOError(&quot;"Bad Response %x&quot; " % resp)
if len(data) &gt; > 0:
if resp != 0xA4:
raise IOError(&quot;"Failed to communicate, last response: %x&quot; " % resp)
else:
raise IOError(&quot;"Failed to communicate, no response&quot;" def checkEncryptionKey(self, kin): return kin class userScript(QObject):  def __init__(self, capture): super(userScript, self).__init__() self.capture = capture   def run(self): cap = self.capture  #User commands here print &quot;***** Starting User Script *****&quot;  tbootloader = BootloaderTarget()  cap.setParameter(['Generic Settings', 'Scope Module', 'ChipWhisperer/OpenADC']) cap.setParameter(['Generic Settings', 'Trace Format', 'ChipWhisperer/Native'])  cap.target.setDriver(tbootloader)  #Load FW (must be configured in GUI first) cap.FWLoaderGo()  #NOTE: You MUST add this call to pe() to process events. This is done automatically #for setParameter() calls, but everything else REQUIRES this pe()  cap.doConDis()  pe()  #Example of using a list to set parameters. Slightly easier to copy/paste in this format lstexample = [['CW Extra', 'CW Extra Settings', 'Trigger Pins', 'Front Panel A', False], ['CW Extra', 'CW Extra Settings', 'Trigger Pins', 'Target IO4 (Trigger Line)', True], ['CW Extra', 'CW Extra Settings', 'Clock Source', 'Target IO-IN'], ['OpenADC', 'Clock Setup', 'ADC Clock', 'Source', 'EXTCLK x4 via DCM'], ['OpenADC', 'Trigger Setup', 'Total Samples', 11000], ['OpenADC', 'Trigger Setup', 'Offset', 0], ['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],  ['Generic Settings', 'Auxilary Module', 'Toggle FPGA-GPIO Pins'], ['GPIO Toggle', 'Standby State', 'High'], ['GPIO Toggle', 'Post-Toggle Delay', 150], ['GPIO Toggle', 'Toggle Length', 100], ]  # For IV: offset = 70000  #Download all hardware setup parameters for cmd in lstexample: cap.setParameter(cmd)  #Let's only do a few traces cap.setParameter(['Generic Settings', 'Acquisition Settings', 'Number of Traces', 50])  #Throw away first few cap.capture1() pe() cap.capture1() pe()  print &quot;***** Ending User Script *****&quot;  if __name__ == '__main__': #Make the application app = cwc.makeApplication()  #If you DO NOT want to overwrite/use settings from the GUI version including #the recent files list, uncomment the following: #app.setApplicationName(&quot;Capture V2 Scripted&quot;)  #Get main module capture = cwc.ChipWhispererCapture()  #Show window - even if not used capture.show()  #NB: Must call processEvents since we aren't using proper event loop pe() # Call user-specific commands usercommands = userScript(capture)  usercommands.run()  app.exec_()  sys.exit()</pre> 
= Appendix B: Capture Script =
Approved_users
510
edits

Navigation menu