Exemplo n.º 1
0
    def run(self):
        # Deletes previous saved data
        if os.path.isfile("projects/tut_randkey_randplain.cwp"): os.remove("projects/tut_randkey_randplain.cwp")
        shutil.rmtree("projects/tut_randkey_randplain_data", ignore_errors=True)
        if os.path.isfile("projects/tut_fixedkey_randplain.cwp"): os.remove("projects/tut_fixedkey_randplain.cwp")
        shutil.rmtree("projects/tut_fixedkey_randplain_data", ignore_errors=True)

        # Setup the capture hardware
        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', 'NewAE USB (CWLite/CW1200)'])
        self.api.setParameter(['ChipWhisperer/OpenADC', 'Connection', 'NewAE USB (CWLite/CW1200)'])

        # Conect both: scope and target
        self.api.connect()

        # Flash the firmware
        xmega = XMEGAProgrammer()
        xmega.setUSBInterface(self.api.getScope().scopetype.dev.xmega)
        xmega._logging = None
        xmega.find()
        xmega.erase()
        xmega.program(r"simpleserial-aes-xmega.hex", memtype="flash", verify=True)
        xmega.close()

        # Setup the capture parameters
        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', 3000],
                      ['OpenADC', 'Trigger Setup', 'Offset', 1250],
                      ['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],
                      ]
        for cmd in lstexample: self.api.setParameter(cmd)

        # Capture a set of traces with random key and save the project
        self.api.setParameter(['Generic Settings', 'Basic', 'Key', 'Random'])
        self.api.setParameter(['Generic Settings', 'Acquisition Settings', 'Number of Traces', 1500])
        self.api.saveProject("projects/tut_randkey_randplain.cwp")
        self.api.captureM()
        self.api.saveProject()

        # Capture a set of traces with fixed key and save the project
        self.api.newProject()
        self.api.saveProject("projects/tut_fixedkey_randplain.cwp")
        self.api.setParameter(['Generic Settings', 'Basic', 'Key', 'Fixed'])
        self.api.setParameter(['Generic Settings', 'Acquisition Settings', 'Number of Traces', 20])
        self.api.captureM()
        self.api.saveProject()
    def run(self):
        # Deletes previous saved data
        if os.path.isfile("projects/tut_descpa.cwp"):
            os.remove("projects/tut_descpa.cwp")
        shutil.rmtree("projects/tut_descpa_data", ignore_errors=True)

        # Setup the capture hardware
        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', 'NewAE USB (CWLite/CW1200)'])
        self.api.setParameter([
            'ChipWhisperer/OpenADC', 'Connection', 'NewAE USB (CWLite/CW1200)'
        ])

        # Conect both: scope and target
        self.api.connect()

        # Flash the firmware
        xmega = XMEGAProgrammer()
        xmega.setUSBInterface(self.api.getScope().scopetype.dev.xmega)
        xmega._logging = None
        xmega.find()
        xmega.erase()
        xmega.program(r"simpleserial-des-xmega.hex",
                      memtype="flash",
                      verify=True)
        xmega.close()

        # Setup the capture parameters
        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', 3500],
            ['OpenADC', 'Trigger Setup', 'Offset', 15500],
            ['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],
        ]
        for cmd in lstexample:
            self.api.setParameter(cmd)

        # Capture a set of traces with fixed key and save the project
        self.api.newProject()
        self.api.saveProject("projects/tut_descpa.cwp")
        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', 100
        ])
        time.sleep(1)
        self.api.captureM()
        self.api.saveProject()
Exemplo n.º 3
0
class XMEGAProgrammerDialog(QtFixes.QDialog):
    def __init__(self):
        super(XMEGAProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.xmega = XMEGAProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite XMEGA Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("xmega-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.xmega.newTextLog.connect(self.append)
        layout.addWidget(self.statusLine)

        # Set dialog layout
        self.setLayout(layout)

    def append(self, text):
        self.statusLine.appendPlainText(text)

    def findFlash(self):
        fname, _ = QFileDialog.getOpenFileName(
            self, 'Find FLASH File',
            QSettings().value("xmega-flash-location"), '*.hex')
        if fname:
            self.flashLocation.setText(fname)
            QSettings().setValue("xmega-flash-location", fname)

    def readSignature(self, close=True):
        self.xmega.find()
        if close:
            self.xmega.close()

    def verifyFlash(self):
        pass

    def writeFlash(self, erase=True, verify=True):
        self.xmega.autoProgram(self.flashLocation.text(), erase, verify,
                               self.statusLine.appendPlainText,
                               QCoreApplication.processEvents)

    def setUSBInterface(self, iface):
        self.xmega.setUSBInterface(iface)
Exemplo n.º 4
0
print("Erase target...")

# program the XMEGA with the built hex file
# programmer = AVRProgrammer()
programmer = XMEGAProgrammer()
programmer.scope = scope
programmer._logging = None
programmer.find()
programmer.erase()

print("Programming...")

# programmer.program("~/software/chipwhisperer/hardware/victims/firmware/glitch-simple/glitchsimple-CW304.hex", memtype="flash")
programmer.program("glitchsimple.hex", memtype="flash", verify=False)
programmer.close()

scope.glitch.trigger_src = 'ext_single'

traces = []
outputs = []
widths = []
offsets = []

Range = namedtuple('Range', ['min', 'max', 'step'])

gc = support.GlitchCore()
gc.setRepeat(1)
gc.setWidth(38.5)
gc.setOffsetRange(29.0, 32.0, 0.5)
gc.setExtOffsetRange(15, 30, 1)
Exemplo n.º 5
0
    def test_TutorialB5(self):
        self.aes_firmware_dir = os.path.join(FIRMWARE_DIR, "simpleserial-aes")

        # Build firmware
        logging.info('Building firmware from make file')
        call = ["make", "--directory", self.aes_firmware_dir, "PLATFORM=CW303"]
        logging.info(call)
        exit_code = subprocess.check_call(call)
        if exit_code == 0:
            logging.info('Finished building firmware')
        else:
            logging.error('Build Failed with exit code {}'.format(exit_code))

        # create capture gui
        self.auto_ui = test_tools.FakeUI()
        self.auto_ui.create_capture()
        capture_gui = self.auto_ui.capture.gui

        # TODO use the created project (currently cause PyQtGraph error)

        # connect scope and target
        logging.info('Executing "connect_cwlite_simpleserial.py"')
        connect_cwlite_simpleserial = os.path.join(
            CAPTURE_SCRIPTS_DIR, "connect_cwlite_simpleserial.py")
        capture_gui.execute(script_path=connect_cwlite_simpleserial)
        self.auto_ui.updateUI()
        logging.info('Finished executing "connect_cwlite_simpleserial.py"')

        # program the target with the built firmware
        programmer = XMEGAProgrammer()
        programmer.scope = capture_gui.scope
        programmer._logging = None
        programmer.find()
        programmer.erase()
        aes_hex = os.path.join(self.aes_firmware_dir,
                               r"simpleserial-aes-CW303.hex")
        programmer.program(aes_hex, memtype="flash", verify=True)
        programmer.close()

        # Execute the setup script for simple serial aes
        logging.info('Executing "setup_cwlite_xmega_aes.py"')
        setup_cwlite_xmega_aes = os.path.join(CAPTURE_SCRIPTS_DIR,
                                              "setup_cwlite_xmega_aes.py")
        capture_gui.execute(script_path=setup_cwlite_xmega_aes)
        self.auto_ui.updateUI()
        logging.info('Finished executing "setup_cwlite_xmega.py"')

        # Create a basic key text pattern
        logging.info('Creating key text pattern')
        ktp = AcqKeyTextPattern_Basic()
        logging.info('Finished creating key text pattern')

        # Capture traces
        logging.info('Capturing traces')
        capture_gui.execute(string='self.api.setNumTraces(60)')
        capture_gui.doCapture(capture_gui.captureM)
        self.auto_ui.updateUI()
        logging.info('Finished capturing traces')

        # Close the capture gui and open the analyzer gui
        logging.info('Closing capture and opening analyzer')
        self.auto_ui.close_capture()
        self.auto_ui.create_analyzer()
        analyzer_gui = self.auto_ui.analyzer.gui
        logging.info('Finished closing capture and opening analyzer')

        # TODO Open the project in the analyzer gui
        #logging.info('Opening project')
        #analyzer_gui.project = self.project
        #logging.info('Finished opening project')

        # Perform the attack
        attack_cpa_script = os.path.join(ANALYZER_SCRIPTS_DIR, "attack_cpa.py")
        logging.info('Executing attack script {}'.format(attack_cpa_script))
        analyzer_gui.execute(script_path=attack_cpa_script)
        self.auto_ui.updateUI()
        logging.info('Finished executing attack script')

        # check if the key is the expected key
        result_subkeys = self.auto_ui.analyzer.gui.results_table.sub_key_row(1)
        result_key = u' '.join(result_subkeys)
        actual_key = ktp.initkey

        logging.info('Actual Key: {}'.format(actual_key))
        logging.info('Result Key: {}'.format(result_key))

        if result_key == actual_key:
            logging.info('Sucess, keys match')
        else:
            logging.error('Keys do not match')
        self.assertEqual(result_key, actual_key)

        # close the analayzer
        self.auto_ui.close_analyzer()
    def run(self):
        # Delete previous project files
        if os.path.isfile("projects/glitchtest.cwp"): os.remove("projects/glitchtest.cwp")
        shutil.rmtree("projects/glitchtest_data", ignore_errors=True)

        # Save current open project (default) to a new place
        self.api.saveProject("projects/glitchtest.cwp")

        print "Software Setup - 1. Connect to the ChipWhisperer device:"
        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', 'None'])
        self.api.setParameter(['Simple Serial', 'Connection', 'NewAE USB (CWLite/CW1200)'])
        self.api.setParameter(['ChipWhisperer/OpenADC', 'Connection', 'NewAE USB (CWLite/CW1200)'])
        # Connect to both: scope and target
        self.api.connect()

        print "Software Setup - 2. Setup the CLKGEN Module to Generate a 7.37 MHz clock and route it through the Glitch Generator"
        lstexample = [
            ['OpenADC', 'Clock Setup', 'Freq Counter Src', 'CLKGEN Output'],
            ['OpenADC', 'Clock Setup', 'CLKGEN Settings', 'Desired Frequency', 7370000.0],
            ['OpenADC', 'Clock Setup', 'ADC Clock', 'Reset ADC DCM', None],
            ['Glitch Module', 'Clock Source', 'CLKGEN'],
            ['CW Extra Settings', 'Target HS IO-Out', 'Glitch Module'],
        ]
        for cmd in lstexample: self.api.setParameter(cmd)

        print "Software Setup - 3. Connect the Serial Port"
        lstexample = [
            ['CW Extra Settings', 'Target IOn Pins', 'Target IO1', 'Serial RXD'],
            ['CW Extra Settings', 'Target IOn Pins', 'Target IO2', 'Serial TXD']
        ]
        for cmd in lstexample: self.api.setParameter(cmd)

        print "Software Setup - 3.4. Flashing test firmware"
        xmega = XMEGAProgrammer()
        xmega.setUSBInterface(self.api.getScope().scopetype.dev.xmega)
        xmega._logging = None
        xmega.find()
        xmega.erase()
        xmega.program(r"glitchsimple.hex", memtype="flash", verify=True)
        xmega.close()

        print "Manual Glitch Trigger"
        lstexample = [
            ['Glitch Module', 'Glitch Width (as % of period)', 10],
            ['Glitch Module', 'Glitch Offset (as % of period)', 26.6],
            ['Glitch Module', 'Repeat', 105],
            ['Glitch Module', 'Glitch Trigger', 'Manual'],
            ['Glitch Module', 'Manual Trigger / Single-Shot Arm', None],  # Push the button
        ]
        for cmd in lstexample: self.api.setParameter(cmd)

        print "Automatically Resetting Target"
        lstexample = [
            ['Generic Settings', 'Auxiliary Module', 'Reset AVR/XMEGA via CW-Lite'],
            ['Aux Settings', 'Reset AVR/XMEGA via CW-Lite', 'Interface', 'xmega (PDI)'],
            ['Aux Settings', 'Reset AVR/XMEGA via CW-Lite', 'Test Reset', None],  # Push the button
            ['Simple Serial', 'Load Key Command', u''],
            ['Simple Serial', 'Go Command', u''],
            ['Simple Serial', 'Output Format', u''],
        ]
        for cmd in lstexample: self.api.setParameter(cmd)
        self.api.capture1()
        self.api.capture1()
        self.api.capture1()

        print "Automatically Triggering Glitch - Enable the power analysis capture"
        lstexample = [
            ['OpenADC', 'Clock Setup', 'ADC Clock', 'Source', 'CLKGEN x4 via DCM'],
            ['OpenADC', 'Clock Setup', 'ADC Clock', 'Reset ADC DCM', None],  # Push the button
            ['OpenADC', 'Trigger Setup', 'Mode', 'rising edge'],
            ['OpenADC', 'Trigger Setup', 'Total Samples', 1000],
            ['OpenADC', 'Gain Setting', 'Setting', 40],
        ]
        for cmd in lstexample: self.api.setParameter(cmd)
        self.api.capture1()
        self.api.capture1()
        self.api.capture1()

        print "Automatically Triggering Glitch - Enable the trigger of the glitch to occur based on this external trigger pin"
        self.api.setParameter(['Glitch Module', 'Glitch Trigger', 'Ext Trigger:Single-Shot'])
        self.api.capture1()
        self.api.capture1()
        self.api.capture1()

        print "Using the Glitch Explorer"
        self.api.setParameter(['Simple Serial', 'Output Format', u'$GLITCH$'])
        self.api.capture1()
        self.api.capture1()
        self.api.capture1()
        lstexample = [
            ['Glitch Explorer', 'Normal Response', u"s == '\\x00hello\\nA'"],
            ['Glitch Explorer', 'Successful Response', u"s.endswith('1234')"],
        ]
        for cmd in lstexample: self.api.setParameter(cmd)
        self.api.capture1()
        self.api.capture1()
        self.api.capture1()

        print "Using the Glitch Explorer -  Tune the glitch offset to attempt to get a successful clock glitch"
        self.api.setParameter(['Glitch Explorer', 'Plot Widget', None])  # Push the button
        lstexample = [
            ['Glitch Explorer', 'Tuning Parameters', 1],
            ['Glitch Explorer', 'Tuning Parameter 0', 'Name', u'Offset'],
            ['Glitch Explorer', 'Tuning Parameter 0', 'Parameter Path', u"['Glitch Module', 'Glitch Offset (as % of period)']"],
            ['Glitch Explorer', 'Tuning Parameter 0', 'Data Format', 'Float'],
            ['Glitch Explorer', 'Tuning Parameter 0', 'Range', (-30, 30)],
            ['Glitch Explorer', 'Tuning Parameter 0', 'Value', -30.0],
            ['Glitch Explorer', 'Tuning Parameter 0', 'Step', 0.5],
            ['Glitch Explorer', 'Tuning Parameter 0', 'Repeat', 1],
            ['Glitch Module', 'Repeat', 10],
            ['Glitch Module', 'Glitch Width (as % of period)', 8.0],
            ['Generic Settings', 'Acquisition Settings', 'Number of Traces', 121]
        ]
        for cmd in lstexample: self.api.setParameter(cmd)
        self.api.captureM()

        print "Using the Glitch Explorer - Tune the Glitch Width"
        lstexample = [
            ['Glitch Explorer', 'Tuning Parameters', 2],
            ['Glitch Explorer', 'Tuning Parameter 1', 'Name', u'Width'],
            ['Glitch Explorer', 'Tuning Parameter 1', 'Parameter Path', u"['Glitch Module', 'Glitch Width (as % of period)']"],
            ['Glitch Explorer', 'Tuning Parameter 1', 'Data Format', 'Float'],
            ['Glitch Explorer', 'Tuning Parameter 1', 'Range', (4, 11)],
            ['Glitch Explorer', 'Tuning Parameter 1', 'Value', 4],
            ['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()
Exemplo n.º 7
0
class XMEGAProgrammerDialog(QtFixes.QDialog):
    def __init__(self):
        super(XMEGAProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.xmega = XMEGAProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite XMEGA Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("xmega-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.statusLine.append = self.statusLine.appendPlainText
        layout.addWidget(self.statusLine)

        self.xmega._logging = self.statusLine.append

        # Set dialog layout
        self.setLayout(layout)

    def findFlash(self):
        fname, _ = QFileDialog.getOpenFileName(self, 'Find FLASH File', QSettings().value("xmega-flash-location"), '*.hex')
        if fname:
            self.flashLocation.setText(fname)
            QSettings().setValue("xmega-flash-location", fname)

    def readSignature(self, close=True):
        self.xmega.find()
        if close:
            self.xmega.close()

    def verifyFlash(self):
        pass

    def writeFlash(self, erase=True, verify=True):

        status = "FAILED"

        fname = self.flashLocation.text()
        self.statusLine.append("***Starting FLASH program process at %s***" % datetime.now().strftime('%H:%M:%S'))
        if (os.path.isfile(fname)):
            self.statusLine.append("File %s last changed on %s" % (fname, time.ctime(os.path.getmtime(fname))))
            QCoreApplication.processEvents()

            try:
                self.statusLine.append("Entering Programming Mode")
                QCoreApplication.processEvents()
                self.readSignature(close=False)

                if erase:
                    try:
                        self.statusLine.append("Erasing Chip")
                        QCoreApplication.processEvents()
                        self.xmega.erase()
                    except IOError:
                        self.statusLine.append("**chip-erase timeout, erasing application only**")
                        QCoreApplication.processEvents()
                        self.xmega.xmega.enablePDI(False)
                        self.xmega.xmega.enablePDI(True)
                        self.xmega.erase("app")

                QCoreApplication.processEvents()
                self.xmega.program(self.flashLocation.text(), memtype="flash", verify=verify)
                QCoreApplication.processEvents()
                self.statusLine.append("Exiting programming mode")
                self.xmega.close()
                QCoreApplication.processEvents()

                status = "SUCCEEDED"

            except IOError, e:
                self.statusLine.append("FAILED: %s" % str(e))
                try:
                    self.xmega.close()
                except IOError:
                    pass

        else:
    def test_tutorial_B6(self):
        scope = self.scope
        target = self.target

        programmer = XMEGAProgrammer()
        programmer.scope = scope
        programmer._logging = None
        programmer.find()
        programmer.erase()
        aes_firmware_dir = os.path.join(FIRMWARE_DIR, 'simpleserial-aes')
        aes_hex = os.path.join(aes_firmware_dir, r"simpleserial-aes-CW303.hex")
        programmer.program(aes_hex, memtype="flash", verify=True)
        programmer.close()

        # setup scope parameters
        scope.gain.gain = 45
        scope.adc.samples = 3000
        scope.adc.offset = 1250
        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"

        ktp = AcqKeyTextPattern_Basic(target=target)

        traces = []
        textin = []
        N = 100 # Number of traces
        print('Capturing traces...')
        target.init()
        for i in tqdm(range(N)):
            key, text = ktp.newPair() # manual creation of a key, text pair can be substituted here
            textin.append(text)

            target.reinit()

            target.setModeEncrypt() # only does something for targets that support it
            target.loadEncryptionKey(key)
            target.loadInput(text)

            # run aux stuff that should run before the scope arms here

            scope.arm()

            # run aux stuff that should run after the scope arms here

            target.go()
            timeout=50
            # wait for target to finish
            while target.isDone() is False and timeout:
                timeout -= 1
                time.sleep(0.01)

            try:
                ret = scope.capture()
                if ret:
                    logging.warning('Timeout happened during acquisition')
            except IOError as e:
                logging.error('IOError: %s' % str(e))

            # run aux stuff that should happen after trace here
            _ = target.readOutput() # for keep the v1.1 protocol working
            traces.append(scope.getLastTrace())

        knownkey = key
        pt = np.asarray(textin)
        traces = np.asarray(traces)
        numtraces = np.shape(traces)[0]
        numpoint = np.shape(traces)[1]

        bestguess = [0] * 16
        pge = [256] * 16
        print("Attacking subkeys...")
        for bnum in tqdm(range(0, 16)):
            cpaoutput = [0] * 256
            maxcpa = [0] * 256
            for kguess in range(0, 256):
                #print("Subkey %2d, hyp = %02x: " % (bnum, kguess), end='')

                # Initialize arrays & variables to zero
                sumnum = np.zeros(numpoint)
                sumden1 = np.zeros(numpoint)
                sumden2 = np.zeros(numpoint)

                hyp = np.zeros(numtraces)
                for tnum in range(0, numtraces):
                    hyp[tnum] = self.HW[self.intermediate(pt[tnum][bnum], kguess)]

                # Mean of hypothesis
                meanh = np.mean(hyp, dtype=np.float64)

                # Mean of all points in trace
                meant = np.mean(traces, axis=0, dtype=np.float64)

                # For each trace, do the following
                for tnum in range(0, numtraces):
                    hdiff = (hyp[tnum] - meanh)
                    tdiff = traces[tnum, :] - meant

                    sumnum = sumnum + (hdiff * tdiff)
                    sumden1 = sumden1 + hdiff * hdiff
                    sumden2 = sumden2 + tdiff * tdiff

                cpaoutput[kguess] = sumnum / np.sqrt(sumden1 * sumden2)
                maxcpa[kguess] = max(abs(cpaoutput[kguess]))

                #print(maxcpa[kguess])

            bestguess[bnum] = np.argmax(maxcpa)

            cparefs = np.argsort(maxcpa)[::-1]

            # Find PGE
            pge[bnum] = list(cparefs).index(knownkey[bnum])

        print("Best Key Guess: ", end="")
        for b in bestguess: print("%02x " % b, end="")

        print("")
        print("PGE: ", end="")
        for b in pge: print("%02d " % b, end="")
        self.assertLess(sum(pge), 5)
    def test_tutorial_A2(self):
        # build the firmware
        self.glitch_simple_firmware_dir = os.path.join(FIRMWARE_DIR, "glitch-simple")

        # Build firmware
        logging.info('Building firmware from make file')
        call = ["make", "--directory", self.glitch_simple_firmware_dir, "PLATFORM=CW303"]
        logging.info(call)
        exit_code = subprocess.check_call(call)
        if exit_code == 0:
            logging.info('Finished building firmware')
        else:
            logging.error('Build Failed with exit code {}'.format(exit_code))

        # connect the scope and target
        scope = self.scope
        target = self.target

        # program the XMEGA with the built hex file
        programmer = XMEGAProgrammer()
        programmer.scope = scope
        programmer._logging = None
        programmer.find()
        programmer.erase()
        glitch_simple_hex = os.path.join(self.glitch_simple_firmware_dir, r"glitchsimple-CW303.hex")
        programmer.program(glitch_simple_hex, memtype="flash", verify=True)
        programmer.close()

        # setup parameters needed for glitch the XMEGA
        scope.glitch.clk_src = 'clkgen'

        scope.gain.gain = 45
        scope.adc.samples = 3000
        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 = "glitch"

        target.go_cmd = ""
        target.key_cmd = ""

        # set glitch parameters
        # trigger glitches with external trigger
        scope.glitch.trigger_src = 'ext_single'
        scope.glitch.repeat = 105

        traces = []
        outputs = []

        # named tuples to make it easier to change the scope of the test
        Range = namedtuple('Range', ['min', 'max', 'step'])
        width_range = Range(-10, 10, 1.7)
        offset_range = Range(-10, 10, 1.7)

        # glitch cycle
        scope.glitch.width = width_range.min
        success = False
        target.init()
        while scope.glitch.width < width_range.max and not success:
            scope.glitch.offset = offset_range.min
            while scope.glitch.offset < offset_range.max and not success:
                # call before trace things here
                # flush the garbage from the computer's target read buffer
                target.ser.flush()

                # target enters reset mode
                scope.io.pdic = 'low'

                # run aux stuff that should run before the scope arms here

                scope.arm()

                # run aux stuff that should run after the scope arms here

                # target exits reset mode
                scope.io.pdic = 'high'

                timeout = 50
                # wait for target to finish
                while target.isDone() is False and timeout:
                    timeout -= 1
                    time.sleep(0.01)

                try:
                    ret = scope.capture()
                    if ret:
                        logging.warning('Timeout happened during acquisition')
                except IOError as e:
                    logging.error('IOError: %s' % str(e))

                #textout = target.readOutput() # raises invalid literal for int base 16

                # get the results
                trace = scope.getLastTrace()
                output = target.ser.read(target.output_len * 2, timeout=10)
                traces.append(trace)
                outputs.append(output)
                if '1234' in repr(output):
                    success = True

                # run aux stuff that should happen after trace here
                scope.glitch.offset += offset_range.step
            scope.glitch.width += width_range.step
        self.assertTrue(success, 'There is no "1234" in the outputs, maybe glitch1() in c file is not active')
Exemplo n.º 10
0
    def run(self):
        for cmd in [
            ['Generic Settings', 'Scope Module', 'ChipWhisperer/OpenADC'],
            ['Generic Settings', 'Target Module', 'Simple Serial'],
            ['Generic Settings', 'Trace Format', 'ChipWhisperer/Native'],
            ['Simple Serial', 'Connection', 'NewAE USB (CWLite/CW1200)'],
            ['ChipWhisperer/OpenADC', 'Connection', 'NewAE USB (CWLite/CW1200)'],
            ]:
            self.api.setParameter(cmd)

        self.api.connect()

        # Flash the firmware
        xmega = XMEGAProgrammer()
        xmega.setUSBInterface(self.api.getScope().scopetype.dev.xmega)
        xmega.find()
        xmega.erase()
        xmega.program(getFirmwarePath('usb-descriptor-simple'), memtype='flash', verify=True)
        xmega.close()

        # Capture parameters
        for cmd in [
            ['Simple Serial', 'Load Key Command', u''],
            ['Simple Serial', 'Go Command', u'\n'],
            ['Simple Serial', 'Output Format', u'$GLITCH$8000'],
            ['Simple Serial', 'NewAE USB (CWLite/CW1200)', 'baud', 115200],

            ['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'],
            ['CW Extra Settings', 'Target HS IO-Out', 'CLKGEN'],

            ['OpenADC', 'Clock Setup', 'CLKGEN Settings', 'Desired Frequency', 12e6],
            ['OpenADC', 'Clock Setup', 'ADC Clock', 'Source', 'CLKGEN x4 via DCM'],
            ['OpenADC', 'Trigger Setup', 'Total Samples', 24400],
            ['OpenADC', 'Trigger Setup', 'Pre-Trigger Samples', 0],
            ['OpenADC', 'Trigger Setup', 'Offset', 14100],
            ['OpenADC', 'Gain Setting', 'Setting', 38],
            ['OpenADC', 'Trigger Setup', 'Mode', 'rising edge'],
            ['OpenADC', 'Clock Setup', 'ADC Clock', 'Reset ADC DCM', None],

            ['Generic Settings', 'Acquisition Settings', 'Number of Traces', 500],

            ['CW Extra Settings', 'HS-Glitch Out Enable (Low Power)', True],
            ['CW Extra Settings', 'HS-Glitch Out Enable (High Power)', True],
            ['Glitch Module', 'Clock Source', 'CLKGEN'],
            ['Glitch Module', 'Single-Shot Arm', 'Before Scope Arm'],
            ['Glitch Module', 'Glitch Trigger', 'Ext Trigger:Single-Shot'],
            ['Glitch Module', 'Output Mode', 'Glitch Only'],

            ['Glitch Module', 'Glitch Width (as % of period)', 44.4],
            ['Glitch Module', 'Glitch Offset (as % of period)', 5.3],
            ['Glitch Module', 'Repeat', 2],
            ['Glitch Module', 'Ext Trigger Offset', 7218],

            # Fixme: these are specific to the target device I'm experimenting on
            ['Glitch Explorer', 'Normal Response', u's.find("rcode 5 total 34") >= 0'],
            ['Glitch Explorer', 'Successful Response', u"(lambda n: n.isdigit() and int(n))((s+' x').split('total ')[-1].split()[0]) > 34"],
            ]:
            self.api.setParameter(cmd)

        self.api.capture1()
        self.api.capture1()
Exemplo n.º 11
0
class XMEGAProgrammerDialog(QtFixes.QDialog):
    def __init__(self):
        super(XMEGAProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.xmega = XMEGAProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite XMEGA Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("xmega-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.xmega.newTextLog.connect(self.append)
        layout.addWidget(self.statusLine)

        # Set dialog layout
        self.setLayout(layout)

    def append(self, text):
        self.statusLine.appendPlainText(text)

    def findFlash(self):
        fname, _ = QFileDialog.getOpenFileName(
            self, 'Find FLASH File',
            QSettings().value("xmega-flash-location"), '*.hex')
        if fname:
            self.flashLocation.setText(fname)
            QSettings().setValue("xmega-flash-location", fname)

    def readSignature(self, close=True):
        self.xmega.find()
        if close:
            self.xmega.close()

    def verifyFlash(self):
        pass

    def writeFlash(self, erase=True, verify=True):
        status = "FAILED"

        fname = self.flashLocation.text()
        self.statusLine.appendPlainText(
            "***Starting FLASH program process at %s***" %
            datetime.now().strftime('%H:%M:%S'))
        if (os.path.isfile(fname)):
            self.statusLine.appendPlainText(
                "File %s last changed on %s" %
                (fname, time.ctime(os.path.getmtime(fname))))
            QCoreApplication.processEvents()

            try:
                self.statusLine.appendPlainText("Entering Programming Mode")
                QCoreApplication.processEvents()
                self.readSignature(close=False)

                if erase:
                    try:
                        self.xmega.erase()
                    except IOError:
                        self.statusLine.appendPlainText(
                            "**chip-erase timeout, erasing application only**")
                        QCoreApplication.processEvents()
                        self.xmega.xmega.enablePDI(False)
                        self.xmega.xmega.enablePDI(True)
                        self.xmega.erase("app")

                QCoreApplication.processEvents()
                self.xmega.program(self.flashLocation.text(),
                                   memtype="flash",
                                   verify=verify)
                QCoreApplication.processEvents()
                self.statusLine.appendPlainText("Exiting programming mode")
                self.xmega.close()
                QCoreApplication.processEvents()

                status = "SUCCEEDED"

            except IOError, e:
                self.statusLine.appendPlainText("FAILED: %s" % str(e))
                try:
                    self.xmega.close()
                except IOError:
                    pass

        else: