def resetDevice(self): # Reset the target by reading its signature target = self.findParam('target').getValue() if target == 'xmega (PDI)': CWCoreAPI.getInstance().getScope().scopetype.dev.getCwliteXMEGA().readSignature() else: CWCoreAPI.getInstance().getScope().scopetype.dev.getCwliteAVR().readSignature()
class gui(object): def __init__(self): Parameter.usePyQtGraph = True self.api = CWCoreAPI() def register_scope(self, obj): self.api.setScope(obj, addToList=True, blockSignal=True) def register_target(self, obj): self.api.setTarget(obj, addToList=True, blockSignal=True) def register(self, obj): #Figure out what we're registering here if isinstance(obj, ScopeTemplate): self.register_scope(obj) elif isinstance(obj, TargetTemplate): self.register_target(obj) else: raise ValueError("Unknown object type %s" % str(obj)) def capture(self): self.app = cwc.makeApplication("Capture") self.window = cwc.CWCaptureGUI(self.api) self.window.show() # Run the main Qt loop self.app.exec_()
def trigger(self, _=None): print "AUXIO: Trigger pin %d" % self.pin self.checkMode() CWCoreAPI.getInstance().getScope().advancedSettings.cwEXTRA.setGPIOState(state=(not self.standby), IONumber=self.pin) self.nonblockingSleep(self.triglength) CWCoreAPI.getInstance().getScope().advancedSettings.cwEXTRA.setGPIOState(state=self.standby, IONumber=self.pin) self.nonblockingSleep(self.postdelay)
def setPin(self, state, pin=None): if pin is None: pin = self.pin if state != True and state != False and state != None: raise ValueError("Invalid State %s" % str(state)) if pin < 4: CWCoreAPI.getInstance().getScope( ).advancedSettings.cwEXTRA.setGPIOState(state=state, IONumber=pin) elif pin == 100 or pin == 101 or pin == 102: if state == True: strstate = "High" elif state == False: strstate = "Low" else: strstate = "Disabled" if pin == 100: pinname = 'nRST' elif pin == 101: pinname = 'PDID' elif pin == 102: pinname = 'PDIC' CWCoreAPI.getInstance().setParameter([ 'CW Extra Settings', 'Target IOn GPIO Mode', '%s: GPIO' % pinname, strstate ]) else: raise ValueError("Invalid Pin %d" % pin)
def captureInit(self): self.checkMode() CWCoreAPI.getInstance().getScope( ).advancedSettings.cwEXTRA.setGPIOState(state=self.standby, IONumber=self.pin) if self.triglocation == 0: self.trigger()
def test_connectNone(self): t = CWCoreAPI() self.assertEqual(t.connectTarget, True) self.assertEqual(t.getTarget(), None) self.assertEqual(t.getScope(), None) self.assertEqual(t.capture1(), True) self.assertEqual(t.captureM(), True) sys.exit(self.app.exec_())
def savePOI(self): poiDict = { "poi": self.poiArray, "partitiontype": self.parent.partObject.partMethod.__class__.__name__ } CWCoreAPI.getInstance().project().addDataConfig( poiDict, "Template Data", "Points of Interest")
def trigger(self, _=None): logging.info('AUXIO: Trigger pin %d' % self.pin) self.checkMode() CWCoreAPI.getInstance().getScope( ).advancedSettings.cwEXTRA.setGPIOState(state=(not self.standby), IONumber=self.pin) self.nonblockingSleep(self.triglength) CWCoreAPI.getInstance().getScope( ).advancedSettings.cwEXTRA.setGPIOState(state=self.standby, IONumber=self.pin) self.nonblockingSleep(self.postdelay)
def processTraces(self, _=None): tstart = self.findParam('tracerng').getValue()[0] tend = self.findParam('tracerng').getValue()[1] pstart = self.findParam('pointrng').getValue()[0] pend = self.findParam('pointrng').getValue()[1] trace = CWCoreAPI.getInstance().getNewTrace(self.findParam('tracefmt').getValue()) trace.config.setAttr("notes", "Recorded from \"%s\" output: Traces (%s,%s). Points (%s,%s)" % (self.findParam('Input').getValueKey(), tstart, tend, pstart, pend)) for tnum in range(tstart, tend+1): trace.addTrace(self.getTraceSource().getTrace(tnum)[pstart:pend+1], self.getTraceSource().getTextin(tnum), self.getTraceSource().getTextout(tnum), self.getTraceSource().getKnownKey(tnum)) trace.closeAll() CWCoreAPI.getInstance().project().traceManager().appendSegment(trace, enabled=False)
def wrapper(*args, **kwargs): gui_warning = "This api function is for use inside GUI Python Console" try: api = CWCoreAPI.getInstance() if api is None: raise Exception except: raise UserWarning(gui_warning) return func(api, *args, **kwargs)
def main(): # Create the Qt Application app = makeApplication("Capture") Parameter.usePyQtGraph = True # Create and show the GUI window = CWCaptureGUI(CWCoreAPI()) window.show() # Run the main Qt loop app.exec_()
def main(): # Create the Qt Application app = makeApplication("Analyzer") # Create and show the GUI Parameter.usePyQtGraph = True window = CWAnalyzerGUI(CWCoreAPI()) window.show() # Run the main Qt loop app.exec_()
def checkMode(self): cwa = CWCoreAPI.getInstance().getScope().advancedSettings.cwEXTRA if self.pin != self.lastPin: # Turn off last used pin if self.lastPin: cwa.setTargetIOMode(IONumber=self.lastPin, setting=0) # Setup new pin cwa.setTargetIOMode(IONumber=self.pin, setting=cwa.IOROUTE_GPIOE) # Don't do this again self.lastPin = self.pin
def __init__(self, name=None): PassiveTraceObserver.__init__(self) self.getParams().addChildren([ {'name':'Trace Format', 'key':'tracefmt', 'type':'list', 'values':CWCoreAPI.getInstance().valid_traces, 'value':None}, {'name':'Trace Range', 'key':'tracerng', 'type':'range', 'limits':(0, 0), 'value':(0, 0)}, {'name':'Point Range', 'key':'pointrng', 'type':'rangegraph', 'limits':(0, 0), 'value':(0, 0), 'graphwidget':ResultsBase.registeredObjects["Trace Output Plot"]}, {'name':'Save', 'type':'action', 'action':self.processTraces}, ]) self.findParam('input').setValue(TraceSource.registeredObjects["Trace Management"]) TraceSource.sigRegisteredObjectsChanged.connect(self.traceSourcesChanged) TraceSource.sigRegisteredObjectsChanged.connect(self.resetTraceLimits)
def processTraces(self, _=None): tstart = self.findParam('tracerng').getValue()[0] tend = self.findParam('tracerng').getValue()[1] pstart = self.findParam('pointrng').getValue()[0] pend = self.findParam('pointrng').getValue()[1] trace = CWCoreAPI.getInstance().getNewTrace( self.findParam('tracefmt').getValue()) trace.config.setAttr("scopeSampleRate", self._traceSource.getSampleRate()) trace.config.setAttr( "notes", "Recorded from \"%s\" output: Traces (%s,%s). Points (%s,%s)" % (self.findParam('Input').getValueKey(), tstart, tend, pstart, pend)) for tnum in range(tstart, tend + 1): trace.addTrace( self.getTraceSource().getTrace(tnum)[pstart:pend + 1], self.getTraceSource().getTextin(tnum), self.getTraceSource().getTextout(tnum), self.getTraceSource().getKnownKey(tnum)) trace.closeAll() CWCoreAPI.getInstance().project().traceManager().appendSegment( trace, enabled=False)
def __init__(self, parent): AutoScript.__init__(self) self._autoscript_init = False self.parent = parent self.poi = POI(self) self.poiDock = CWMainGUI.getInstance().addDock(self.poi, "Partition Comparison POI Table", area=Qt.TopDockWidgetArea) self.poiDock.hide() self.defineName() self._traces = None self.api = CWCoreAPI.getInstance() self.graph = GraphWidget() self.bselection = QToolBar() self.graph.addWidget(self.bselection) self.graphDock = CWMainGUI.getInstance().addDock(self.graph, "Partition Comparison Graph", area=Qt.TopDockWidgetArea) self.graphDock.hide()
def __init__(self, parent): AutoScript.__init__(self) self._autoscript_init = False self.parent = parent self.poi = POI(self) self.poiDock = CWMainGUI.getInstance().addDock( self.poi, "Partition Comparison POI Table", area=Qt.TopDockWidgetArea) self.poiDock.hide() self.defineName() self._traces = None self.api = CWCoreAPI.getInstance() self.graph = GraphWidget() self.bselection = QToolBar() self.graph.addWidget(self.bselection) self.graphDock = CWMainGUI.getInstance().addDock( self.graph, "Partition Comparison Graph", area=Qt.TopDockWidgetArea) self.graphDock.hide()
def __init__(self): self._cwusb = NAEUSB() # Connect required modules up here self.fpga = FPGA(self._cwusb) self.xmega = XMEGAPDI(self._cwusb) self.avr = AVRISP(self._cwusb) self.usart = USART(self._cwusb) self.serialstm32f = STM32FSerial(cwserial=self.usart, cwapi=CWCoreAPI.getInstance()) self.getParams().addChildren([{ 'name': "CW-Lite XMEGA Programmer", 'tip': "Open XMEGA Programmer (ChipWhisperer-Lite Only)", 'type': "menu", "action": lambda _: self.getCwliteXMEGA().show() }, { 'name': "CW-Lite AVR Programmer", 'tip': "Open AVR Programmer (ChipWhisperer-Lite Only)", 'type': "menu", "action": lambda _: self.getCwliteAVR().show() }, { 'name': 'Serial STM32F Programmer', 'tip': "Open STM32F Programmer (Serial/ChipWhisperer)", 'type': "menu", "action": lambda _: self.getSerialSTM32F().show() }])
def __init__(self, name=None): PassiveTraceObserver.__init__(self) self.getParams().addChildren([ { 'name': 'Trace Format', 'key': 'tracefmt', 'type': 'list', 'values': CWCoreAPI.getInstance().valid_traces, 'value': None }, { 'name': 'Trace Range', 'key': 'tracerng', 'type': 'range', 'limits': (0, 0), 'value': (0, 0) }, { 'name': 'Point Range', 'key': 'pointrng', 'type': 'rangegraph', 'limits': (0, 0), 'value': (0, 0), 'graphwidget': ResultsBase.registeredObjects["Trace Output Plot"] }, { 'name': 'Save', 'type': 'action', 'action': self.processTraces }, ]) self.findParam('input').setValue( TraceSource.registeredObjects["Trace Management"]) TraceSource.sigRegisteredObjectsChanged.connect( self.traceSourcesChanged) TraceSource.sigRegisteredObjectsChanged.connect(self.resetTraceLimits)
def captureN(scope=None, target=None, project=None, aux_list=None, ktp=None, N=1, seg_size=None): """Capture a number of traces, saving power traces and input/output text and keys to disk along the way. Args: scope: A connected scope object. If None, no power trace will be recorded - possibly helpful for testing target setups target: A connected target object. If None, no target commmands will be sent - assumed that aux commands or external boards are controlling target project: A ChipWhisperer project object. If None, no data will be saved - helpful when testing scope settings without saving aux_list: An AuxList object with auxiliary functions registered. If None, no auxiliary functions are run ktp: A key/text input object. Produces pairs of encryption key/input text for each capture. Can't be None as these values are required N: The number of traces to capture. seg_size: The number of traces to record in each segment. The data is saved to disk in a number of segments to avoid making one enormous data file. If None, a sane default is used. To emulate GUI capture: >>> cw.captureN(self.scope, self.target, self.project, self.aux_list, self.ktp, 50) """ api = CWCoreAPI.getInstance() api.captureM(scope=scope, target=target, project=project, aux_list=aux_list, ktp=ktp, N=N, seg_size=seg_size)
def __init__(self): Parameter.usePyQtGraph = True self.api = CWCoreAPI()
def captureInit(self): self.checkMode() CWCoreAPI.getInstance().getScope().advancedSettings.cwEXTRA.setGPIOState(state=self.standby, IONumber=self.pin) if self.triglocation == 0: self.trigger()
def __init__(self, oldprojectname, newprojectname): cwapi_new = CWCoreAPI() cwapi_old = CWCoreAPI() cwapi_old.openProject(oldprojectname) cwapi_new.newProject() cwapi_new.saveProject(newprojectname) tm = cwapi_old.project().traceManager() ntraces = tm.numTraces() segs = tm.getSegmentList() numtraces = 0 for offset, seg_idx in enumerate(segs['offsetList']): seg_len = segs['lengthList'][seg_idx] seg = tm.getSegment(seg_idx) tc = TraceContainerNative() tc.clear() # Copy all aux data over # seg.config._configfile tc.config.config = seg.config.config prefix = tc.config.config['Trace Config']['prefix'] tc.config.setConfigFilename(cwapi_new.project().datadirectory + "traces/config_" + prefix + ".cfg") tc.setDirty(True) tc.config.syncFile() for tnum in range(offset, seg_len + offset): trace = tm.getTrace(tnum) textin = tm.getTextin(tnum) textout = tm.getTextout(tnum) key = tm.getKnownKey(tnum) try: textin, textout, trace, key = self.trace_callback( textin, textout, trace, key) except StopIteration: continue numtraces += 1 tc.addTrace(trace, textin, textout, key) tc.closeAll() cwapi_new.project().traceManager().appendSegment(tc) cwapi_new.saveProject()
# (at your option) any later version. # # chipwhisperer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU General Public License # along with chipwhisperer. If not, see <http://www.gnu.org/licenses/>. #================================================= from chipwhisperer.common.api.CWCoreAPI import CWCoreAPI from matplotlib.pylab import * import numpy as np cwapi = CWCoreAPI() #You may need to specify the full path for this to work cwapi.openProject(r'rsa_test_2bytes.cwp') tm = cwapi.project().traceManager() ntraces = tm.numTraces() #Reference trace trace_ref = tm.getTrace(0) #plot(trace_ref) #The target trace we will attack #If following tutorial: #0/1 = 80 00 #2/3 = 81 40
def main(): app = makeApplication("Test") CWMainGUI(CWCoreAPI(), app.applicationName()) app.exec_()
self.attack.setPointRange((0, 3000)) def initReporting(self): # Configures the attack observers (usually a set of GUI widgets) self.api.getResults("Attack Settings").setAnalysisSource(self.attack) self.api.getResults("Correlation vs Traces in Attack").setAnalysisSource(self.attack) self.api.getResults("Output vs Point Plot").setAnalysisSource(self.attack) self.api.getResults("PGE vs Trace Plot").setAnalysisSource(self.attack) self.api.getResults("Results Table").setAnalysisSource(self.attack) self.api.getResults("Save to Files").setAnalysisSource(self.attack) self.api.getResults("Trace Output Plot").setTraceSource(self.traces) self.api.getResults("Trace Recorder").setTraceSource(self.traces) def run(self): self.attack.processTraces() if __name__ == "__main__": import sys from chipwhisperer.common.api.CWCoreAPI import CWCoreAPI import chipwhisperer.analyzer.ui.CWAnalyzerGUI as cwa from chipwhisperer.common.utils.parameter import Parameter app = cwa.makeApplication() # Comment if you don't need the GUI Parameter.usePyQtGraph = True # Comment if you don't need the GUI api = CWCoreAPI() # Instantiate the API gui = cwa.CWAnalyzerGUI(api) # Comment if you don't need the GUI api.runScriptClass(UserScript) # Run UserScript through the API sys.exit(app.exec_()) # Comment if you don't need the GUI
def __init__(self): AuxiliaryTemplate.__init__(self) self.api = CWCoreAPI.getInstance()
def savePOI(self): poiDict = {"poi":self.poiArray, "partitiontype":self.parent.partObject.partMethod.__class__.__name__} CWCoreAPI.getInstance().project().addDataConfig(poiDict, "Template Data", "Points of Interest")
import chipwhisperer from chipwhisperer.common.api.CWCoreAPI import CWCoreAPI from matplotlib.pylab import * cwapi = CWCoreAPI() #cwapi.openProject(r'c:\users\colin\chipwhisperer_projects\tmp\mpc5748g_password_group0_100k.cwp') #knownkey = "0000000000000000FFFFFFFFFFFFFFFF00000000FFFFFFFF0000000000000000" cwapi.openProject( r'c:\users\colin\chipwhisperer_projects\tmp\mpc5748g_password_group3_100k.cwp' ) knownkey = "5c3c3dc267b1d8f792f633c51389356c104100f0b52f1aa7f85c2c786d376cf8" #knownkey = "6d376cf8f85c2c78b52f1aa7104100f01389356c92f633c567b1d8f75c3c3dc2" knownkey = [int(knownkey[i:(i + 2)], 16) for i in range(0, 64, 2)] #HD Tests knownkey[4:] = [knownkey[i + 0] ^ knownkey[i + 4] for i in range(0, 32 - 4)] tm = cwapi.project().traceManager() #ppMod0 = chipwhisperer.analyzer.preprocessing.resync_sad.ResyncSAD(cwapi.project().traceManager(), connectTracePlot=False) #ppMod0.setEnabled(True) ##ppMod0.setReference(rtraceno=0, refpoints=(12,211), inputwindow=(0,487)) #ppMod0.setReference(rtraceno=0, refpoints=(513,657), inputwindow=(326,713)) #ppMod0.init() # #ppMod4 = chipwhisperer.analyzer.preprocessing.cache_traces.CacheTraces(ppMod0) #ppMod4.setEnabled(False) #ppMod4.init()
# Record traces api.newProject() api.saveProject(cwp_fname) api.captureM() api.saveProject(cwp_fname) if __name__ == "__main__": # Record timestamp for labelling output run_timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") # Get ChipWhisperer API ready import chipwhisperer.capture.ui.CWCaptureGUI as cwc app = cwc.makeApplication("Capture") api = CWCoreAPI() # Set up the ChipWhisperer setup_chipwhisperer(api) for i in range(len(fw_fnames)): fw_fname = fw_fnames[i] proj_title = proj_titles[i] print "Testing firmware file %s..." % fw_fname # Run capture script print "Capturing power traces..." base_fname = "%s-%s" % (run_timestamp, fw_fname) fw_fname_full = os.path.join(fw_path, fw_fname) cwp_fname = os.path.join(cwp_path, "%s.cwp" % base_fname)
def addTraces(self, tracedata, tracerange, progressBar=None, pointRange=None): keyround=self.keyround modeltype=self.modeltype brange=self.brange foundkey = [] self.all_diffs = range(0,16) tdiff = self.findParam('reportinterval').getValue() numtraces = tracerange[1] - tracerange[0] if progressBar: progressBar.setMinimum(0) progressBar.setMaximum(len(brange) * 256 * (numtraces/tdiff + 1)) #r = Parallel(n_jobs=4)(delayed(traceOneSubkey)(bnum, pointRange, traces_all, numtraces, plaintexts, ciphertexts, keyround, modeltype, progressBar, self.model, pbcnt) for bnum in brange) #self.all_diffs, pb = zip(*r) cpa = [None]*(max(brange)+1) for bnum in brange: cpa[bnum] = CPAProgressiveOneSubkey() # cpa[bnum] = MinDistOneSubkey() # cpa[bnum] = TemplateOneSubkey() brangeMap = [None]*(max(brange)+1) i = 1 for bnum in brange: brangeMap[bnum] = i i += 1 skipPGE = self.findParam('checkpge').getValue() bf = self.findParam('itmode').getValue() == 'bf' #bf specifies a 'breadth-first' search. bf means we search across each #subkey by only the amount of traces specified. Depth-First means we #search each subkey completely, then move onto the next. if bf: brange_df = [0] brange_bf = brange else: brange_bf = [0] brange_df = brange #H = np.load('channelinfo-masked.npy') #H = np.load('csi-masked-newkey.npy') #H = np.load('channelinfo.npy') #mio = sio.loadmat('equalizer.mat') #H = mio['equaltotal'] # H = np.load('equalization.npy') # self.project() ? project = CWCoreAPI.getInstance().project() section = project.getDataConfig("Template Data", "Equalization Matrix") # section = project.getDataConfig("Template Data", "AOF Matrix") fname = project.convertDataFilepathAbs(section[0]["filename"]) H = np.load(fname) #for j in range(0, 16): #4 = 500-800 #test = H.copy() #for i in range(0, 5): # threshold = max(abs(test[j])) # test[j, abs(test[j,:]) >= threshold ] = 0 #print "%f %d"%(threshold, (abs(H[j,:]) > threshold).sum()) #H[j, abs(H[j,:]) < threshold] = 0 for bnum_df in brange_df: #CPAMemoryOneSubkey #CPASimpleOneSubkey #(self.all_diffs[bnum], pbcnt) = sCPAMemoryOneSubkey(bnum, pointRange, traces_all, numtraces, plaintexts, ciphertexts, keyround, modeltype, progressBar, self.model, pbcnt) tstart = 0 tend = tdiff while tstart < numtraces: pbcnt = 0 if tend > numtraces: tend = numtraces if tstart > numtraces: tstart = numtraces data = [] textins = [] textouts = [] knownkeys = [] for i in range(tstart, tend): # Handle Offset tnum = i + tracerange[0] d = tracedata.getTrace(tnum) if d is None: continue data.append(d) textins.append(tracedata.getTextin(tnum)) textouts.append(tracedata.getTextout(tnum)) knownkeys.append(tracedata.getKnownKey(tnum)) traces = np.array(data) textins = np.array(textins) textouts = np.array(textouts) for bnum_bf in brange_bf: if bf: bnum = bnum_bf else: bnum = bnum_df traces_fixed = np.dot(traces - traces.mean(axis=0), H[bnum]) + 4 skip = False if (self.stats.simplePGE(bnum) != 0) or (skipPGE == False): (data, pbcnt) = cpa[bnum].oneSubkey(bnum, pointRange, traces_fixed, tend - tstart, textins, textouts, keyround, modeltype, progressBar, self.model, pbcnt) self.stats.updateSubkey(bnum, data, tnum=tend) else: skip = True if skip: pbcnt = brangeMap[bnum] * 256 * (numtraces/tdiff + 1) if bf is False: tstart = numtraces tend += tdiff tstart += tdiff if self.sr is not None: self.sr()
['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], ] #Download all hardware setup parameters for cmd in lstexample: self.api.setParameter(cmd) #Let's only do a few traces self.api.setParameter(['Generic Settings', 'Acquisition Settings', 'Number of Traces', 50]) #Throw away first few self.api.capture1() self.api.capture1() #Capture a set of traces and save the project # self.api.captureM() # self.api.saveProject("../../../projects/test.cwp") if __name__ == '__main__': app = cwc.makeApplication() # Comment this line if you don't want to use the GUI Parameter.usePyQtGraph = True # Comment this line if you don't want to use the GUI api = CWCoreAPI() # Instantiate the API # app.setApplicationName("Capture Scripted") # If you DO NOT want to overwrite settings from the GUI gui = cwc.CWCaptureGUI(api) # Comment this line if you don't want to use the GUI gui.show() # Comment this line if you don't want to use the GUI api.runScriptClass(UserScript) # Run the User Script sys.exit(app.exec_()) # Comment this line if you don't want to use the GUI
def cwconnect(offset=1250, totalsamples=3000): api = CWCoreAPI() # Instantiate the API api.setParameter( ['Generic Settings', 'Scope Module', 'ChipWhisperer/OpenADC']) api.setParameter(['Generic Settings', 'Target Module', 'Simple Serial']) #No actual need for saving data so we ignore this? #api.setParameter(['Generic Settings', 'Trace Format', 'ChipWhisperer/Native']) api.setParameter( ['Simple Serial', 'Connection', 'NewAE USB (CWLite/CW1200)']) api.setParameter( ['ChipWhisperer/OpenADC', 'Connection', 'NewAE USB (CWLite/CW1200)']) api.connect() # Example of using a list to set parameters. Slightly easier to copy/paste in this format lstexample = [ [ 'CW Extra Settings', 'Trigger Pins', 'Target IO4 (Trigger Line)', True ], ['CW Extra Settings', 'Target IOn Pins', 'Target IO1', 'Serial RXD'], ['CW Extra Settings', 'Target IOn Pins', 'Target IO2', 'Serial TXD'], [ 'OpenADC', 'Clock Setup', 'CLKGEN Settings', 'Desired Frequency', 7370000.0 ], ['CW Extra Settings', 'Target HS IO-Out', 'CLKGEN'], ['OpenADC', 'Clock Setup', 'ADC Clock', 'Source', 'CLKGEN x4 via DCM'], ['OpenADC', 'Trigger Setup', 'Total Samples', int(totalsamples)], ['OpenADC', 'Trigger Setup', 'Offset', int(offset)], ['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], ] # Download all hardware setup parameters for cmd in lstexample: api.setParameter(cmd) return api
partDiffs = ted.generatePartitionDiffs(DifferenceModeSAD, statsInfo={"partclass":PartitionHWIntermediate, "stats":partStats}, saveFile=True, loadFile=False, progressBar=progressBar) ted.displayPartitions(differences={"partclass":PartitionHWIntermediate, "diffs":partDiffs}) ted.poi.setDifferences(partDiffs) def TraceExplorerDialog_PartitionDisplay_findPOI(self): self.cwagui = CWAnalyzerGUI.getInstance() ted = self.cwagui.attackScriptGen.utilList[0].exampleScripts[0] return ted.poi.calcPOI(numMax=3, pointRange=(0, 3000), minSpace=5)['poi'] def generateTemplates(self): self.TraceExplorerDialog_PartitionDisplay_displayPartitionStats() tRange = (0, 1499) poiList = self.TraceExplorerDialog_PartitionDisplay_findPOI() partMethod = PartitionHWIntermediate() templatedata = self.attack.attack.profiling.generate(tRange, poiList, partMethod) tfname = self.attack.attack.saveTemplatesToProject(tRange, templatedata) if __name__ == '__main__': import sys from chipwhisperer.common.api.CWCoreAPI import CWCoreAPI import chipwhisperer.analyzer.ui.CWAnalyzerGUI as cwa from chipwhisperer.common.utils.parameter import Parameter app = cwa.makeApplication() # Comment if you don't need the GUI Parameter.usePyQtGraph = True # Comment if you don't need the GUI api = CWCoreAPI() # Instantiate the API api.runScriptClass(Capture) gui = cwa.CWAnalyzerGUI(api) # Comment if you don't need the GUI gui.show() # Comment if you don't need the GUI api.runScriptClass(Attack) sys.exit(app.exec_()) # Comment if you don't need the GUI
import chipwhisperer from chipwhisperer.common.api.CWCoreAPI import CWCoreAPI from matplotlib.pylab import * cwapi = CWCoreAPI() #cwapi.openProject(r'c:\users\colin\chipwhisperer_projects\tmp\mpc5748g_password_group0_100k.cwp') #knownkey = "0000000000000000FFFFFFFFFFFFFFFF00000000FFFFFFFF0000000000000000" #cwapi.openProject(r'c:\users\colin\chipwhisperer_projects\tmp\mpc5748g_password_group3_100k.cwp') cwapi.openProject(r'e:\mpcfiles\mpc5748g_pw_1core_200k_randtext_group3.cwp') #Knownkey for group 3 as sent knownkey = "5c3c3dc267b1d8f792f633c51389356c104100f0b52f1aa7f85c2c786d376cf8" #Knownkey for group 3 as written in FLASH (which is bakcwards to how comparison actually ahppens) #knownkey = "6d376cf8f85c2c78b52f1aa7104100f01389356c92f633c567b1d8f75c3c3dc2" knownkey = [int(knownkey[i:(i + 2)], 16) for i in range(0, 64, 2)] #HD Tests knownkey[4:] = [knownkey[i - 4] ^ knownkey[i] for i in range(0, 32 - 4)] tm = cwapi.project().traceManager() #ppMod0 = chipwhisperer.analyzer.preprocessing.resync_sad.ResyncSAD(cwapi.project().traceManager(), connectTracePlot=False) #ppMod0.setEnabled(True) ##ppMod0.setReference(rtraceno=0, refpoints=(12,211), inputwindow=(0,487)) #ppMod0.setReference(rtraceno=0, refpoints=(513,657), inputwindow=(326,713)) #ppMod0.init() #ppMod4 = chipwhisperer.analyzer.preprocessing.cache_traces.CacheTraces(ppMod0) #pMod4.setEnabled(True)
# Download all hardware setup parameters for cmd in lstexample: self.api.setParameter(cmd) # Let's only do a few traces self.api.setParameter(['Simple Serial', 'Key Length (Bytes)', 8]) self.api.setParameter(['Simple Serial', 'Input Length (Bytes)', 8]) self.api.setParameter(['Simple Serial', 'Output Length (Bytes)', 8]) self.api.setParameter(['Generic Settings', 'Basic', 'Key', 'Fixed']) self.api.setParameter(['Generic Settings', 'Basic', 'Fixed Encryption Key', u'2B 7E 15 16 28 AE D2 A6']) self.api.setParameter(['Generic Settings', 'Acquisition Settings', 'Number of Traces', 50]) # Throw away first few self.api.capture1() self.api.capture1() # Capture a set of traces and save the project # self.api.captureM() # self.api.saveProject("../../../projects/test.cwp") if __name__ == '__main__': import chipwhisperer.capture.ui.CWCaptureGUI as cwc # Import the ChipWhispererCapture GUI from chipwhisperer.common.utils.parameter import Parameter # Comment this line if you don't want to use the GUI Parameter.usePyQtGraph = True # Comment this line if you don't want to use the GUI api = CWCoreAPI() # Instantiate the API app = cwc.makeApplication("Capture") # Change the name if you want a different settings scope gui = cwc.CWCaptureGUI(api) # Comment this line if you don't want to use the GUI api.runScriptClass(UserScript) # Run the User Script (executes "run()" by default) app.exec_() # Comment this line if you don't want to use the GUI
ted.displayPartitions(differences={"partclass":PartitionHWIntermediate, "diffs":partDiffs}) ted.poi.setDifferences(partDiffs) def TraceExplorerDialog_PartitionDisplay_findPOI(self): # Calculate the POIs self.cwagui = CWAnalyzerGUI.getInstance() ted = self.cwagui.attackScriptGen.utilList[0].exampleScripts[0] return ted.poi.calcPOI(numMax=3, pointRange=(0, 3000), minSpace=5)['poi'] def generateTemplates(self): # Generate the templates and save to the project self.TraceExplorerDialog_PartitionDisplay_displayPartitionStats() tRange = (0, 1499) poiList = self.TraceExplorerDialog_PartitionDisplay_findPOI() partMethod = PartitionHWIntermediate() templatedata = chipwhisperer.analyzer.attacks.profiling_algorithms.template.TemplateUsingMVS.generate(self.attack.getTraceSource(), tRange, poiList, partMethod) tfname = self.attack.attack.saveTemplatesToProject(tRange, templatedata) if __name__ == '__main__': import sys from chipwhisperer.common.api.CWCoreAPI import CWCoreAPI import chipwhisperer.analyzer.ui.CWAnalyzerGUI as cwa from chipwhisperer.common.utils.parameter import Parameter app = cwa.makeApplication() Parameter.usePyQtGraph = True api = CWCoreAPI() # Instantiate the API api.runScriptClass(Capture) gui = cwa.CWAnalyzerGUI(api) # Instantiate the Analyzer GUI api.runScriptClass(Attack) # Run the script (default is the "run" method) sys.exit(app.exec_())
self.attack.setTargetSubkeys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) self.attack.setTraceSource(self.traces) self.attack.setPointRange((0,3000)) def initReporting(self): # Configures the attack observers (usually a set of GUI widgets) self.api.getResults("Attack Settings").setAnalysisSource(self.attack) self.api.getResults("Correlation vs Traces in Attack").setAnalysisSource(self.attack) self.api.getResults("Output vs Point Plot").setAnalysisSource(self.attack) self.api.getResults("PGE vs Trace Plot").setAnalysisSource(self.attack) self.api.getResults("Results Table").setAnalysisSource(self.attack) self.api.getResults("Save to Files").setAnalysisSource(self.attack) self.api.getResults("Trace Output Plot").setTraceSource(self.traces) self.api.getResults("Trace Recorder").setTraceSource(self.traces) def run(self): self.attack.processTraces() if __name__ == '__main__': import sys from chipwhisperer.common.api.CWCoreAPI import CWCoreAPI import chipwhisperer.analyzer.ui.CWAnalyzerGUI as cwa from chipwhisperer.common.utils.parameter import Parameter app = cwa.makeApplication() # Comment if you don't need the GUI Parameter.usePyQtGraph = True # Comment if you don't need the GUI api = CWCoreAPI() # Instantiate the API gui = cwa.CWAnalyzerGUI(api) # Comment if you don't need the GUI api.runScriptClass(UserScript) # Run UserScript through the API sys.exit(app.exec_()) # Comment if you don't need the GUI
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().datapoints # 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 if __name__ == '__main__': import chipwhisperer.capture.ui.CWCaptureGUI as cwc # Import the ChipWhispererCapture GUI from chipwhisperer.common.utils.parameter import Parameter # Comment this line if you don't want to use the GUI Parameter.usePyQtGraph = True # Comment this line if you don't want to use the GUI api = CWCoreAPI() # Instantiate the API app = cwc.makeApplication("Capture") # Change the name if you want a different settings scope gui = cwc.CWCaptureGUI(api) # Comment this line if you don't want to use the GUI gui.show() # Comment this line if you don't want to use the GUI api.runScriptClass(UserScript) # Run the User Script (executes "run()" by default) app.exec_() # Comment this line if you don't want to use the GUI
['Glitch Explorer', 'Tuning Parameter 1', 'Step', 0.5], ['Glitch Explorer', 'Tuning Parameter 1', 'Repeat', 1], ['Glitch Explorer', 'Tuning Parameter 0', 'Range', (-8, 3)], ['Glitch Explorer', 'Tuning Parameter 0', 'Value', -8], ['Glitch Module', 'Repeat', 1], ['Generic Settings', 'Acquisition Settings', 'Number of Traces', 345], ] for cmd in lstexample: self.api.setParameter(cmd) self.api.captureM() print "Using the Glitch Explorer - Fine-tune those values" self.api.setParameter(['Glitch Module', 'Glitch Offset (as % of period)',-3.5]) self.api.setParameter(['Glitch Module', 'Glitch Width (as % of period)',7.5]) self.api.capture1() self.api.capture1() self.api.capture1() self.api.setParameter(['Glitch Module', 'Glitch Offset (fine adjust)', 44]) self.api.capture1() self.api.capture1() self.api.capture1() if __name__ == '__main__': app = cwc.makeApplication() # Comment this line if you don't want to use the GUI Parameter.usePyQtGraph = True # Comment this line if you don't want to use the GUI api = CWCoreAPI() # Instantiate the API gui = cwc.CWCaptureGUI(api) # Comment this line if you don't want to use the GUI gui.glitchMonitor.show() gui.serialTerminal.show() api.runScriptClass(UserScript) # Run the User Script app.exec_()
# This is what the API will execute self.api.openProject("projects/tut_descpa.cwp") self.initPreprocessing() # Setup the analysis, widgets, and do the attack self.initAnalysis() self.initReporting() self.attack.processTraces() # Delete all pending scripts executions (that are observing the api be available again), # otherwise the current setup would be overridden self.api.executingScripts.disconnectAll() if __name__ == '__main__': from chipwhisperer.common.api.CWCoreAPI import CWCoreAPI import chipwhisperer.capture.ui.CWCaptureGUI as cwc import chipwhisperer.analyzer.ui.CWAnalyzerGUI as cwa from chipwhisperer.common.utils.parameter import Parameter app = cwc.makeApplication(doDeleteLater=False) Parameter.usePyQtGraph = True api = CWCoreAPI() # Instantiate the API gui = cwc.CWCaptureGUI(api) # Instantiate the Capture GUI api.runScriptClass(Capture) gui.deleteLater() gui.reset() gui = cwa.CWAnalyzerGUI(api) # Instantiate the Analyzer GUI api.runScriptClass(Attack) # Run the script (default is the "run" method) app.exec_()
def addTraces(self, traceSource, tracerange, progressBar=None, pointRange=None): keyround = self.keyround modeltype = self.modeltype brange = self.brange tdiff = self.findParam('reportinterval').getValue() numtraces = tracerange[1] - tracerange[0] if progressBar: progressBar.setMinimum(0) progressBar.setMaximum(len(brange) * 256 * (numtraces / tdiff + 1)) #r = Parallel(n_jobs=4)(delayed(traceOneSubkey)(bnum, pointRange, traces_all, numtraces, plaintexts, ciphertexts, keyround, modeltype, progressBar, self.model, pbcnt) for bnum in brange) #self.all_diffs, pb = zip(*r) cpa = [None] * (max(brange) + 1) for bnum in brange: cpa[bnum] = CPAProgressiveOneSubkey() # cpa[bnum] = MinDistOneSubkey() # cpa[bnum] = TemplateOneSubkey() brangeMap = [None] * (max(brange) + 1) i = 1 for bnum in brange: brangeMap[bnum] = i i += 1 skipPGE = self.findParam('checkpge').getValue() bf = self.findParam('itmode').getValue() == 'bf' #bf specifies a 'breadth-first' search. bf means we search across each #subkey by only the amount of traces specified. Depth-First means we #search each subkey completely, then move onto the next. if bf: brange_df = [0] brange_bf = brange else: brange_bf = [0] brange_df = brange #H = np.load('channelinfo-masked.npy') #H = np.load('csi-masked-newkey.npy') #H = np.load('channelinfo.npy') #mio = sio.loadmat('equalizer.mat') #H = mio['equaltotal'] # H = np.load('equalization.npy') # self.project() ? project = CWCoreAPI.getInstance().project() section = project.getDataConfig("Template Data", "Equalization Matrix") # section = project.getDataConfig("Template Data", "AOF Matrix") fname = project.convertDataFilepathAbs(section[0]["filename"]) H = np.load(fname) #for j in range(0, 16): #4 = 500-800 #test = H.copy() #for i in range(0, 5): # threshold = max(abs(test[j])) # test[j, abs(test[j,:]) >= threshold ] = 0 #print "%f %d"%(threshold, (abs(H[j,:]) > threshold).sum()) #H[j, abs(H[j,:]) < threshold] = 0 for bnum_df in brange_df: #CPAMemoryOneSubkey #CPASimpleOneSubkey #(self.all_diffs[bnum], pbcnt) = sCPAMemoryOneSubkey(bnum, pointRange, traces_all, numtraces, plaintexts, ciphertexts, keyround, modeltype, progressBar, self.model, pbcnt) tstart = 0 tend = tdiff while tstart < numtraces: pbcnt = 0 if tend > numtraces: tend = numtraces if tstart > numtraces: tstart = numtraces data = [] textins = [] textouts = [] knownkeys = [] for i in range(tstart, tend): # Handle Offset tnum = i + tracerange[0] d = traceSource.getTrace(tnum) if d is None: continue data.append(d) textins.append(traceSource.getTextin(tnum)) textouts.append(traceSource.getTextout(tnum)) knownkeys.append(traceSource.getKnownKey(tnum)) traces = np.array(data) textins = np.array(textins) textouts = np.array(textouts) for bnum_bf in brange_bf: if bf: bnum = bnum_bf else: bnum = bnum_df traces_fixed = np.dot(traces - traces.mean(axis=0), H[bnum]) + 4 skip = False if (self.stats.simplePGE(bnum) != 0) or (skipPGE == False): (data, pbcnt) = cpa[bnum].oneSubkey( bnum, pointRange, traces_fixed, tend - tstart, textins, textouts, keyround, modeltype, progressBar, self.model, pbcnt) self.stats.updateSubkey(bnum, data, tnum=tend) else: skip = True if skip: pbcnt = brangeMap[bnum] * 256 * (numtraces / tdiff + 1) if bf is False: tstart = numtraces tend += tdiff tstart += tdiff if self.sr is not None: self.sr()