Source Code Documentation

Findus is a Python library to perform fault-injection attacks on embedded devices. It was developed for the Pico Glitcher, however, the ChipWhisperer Pro and the ChipWhisperer Husky is also supported.

This is the documentation of the findus module and all its classes.

Database

Database class managing access to the SQLite databases to store results from a glitching campaign. The parameter points stored in these databases are used to render an overview of the scanned parameter point via a web application. The web application and data analyzer can be run separately from the glitcher scripts by the following command:

analyzer --directory databases

Example usage:

# import Database from findus
from findus import Database
...
database = Database(argv=argv)
...
database.insert(experiment_id, delay, length, color, response)

Example usage for multi-dimensional parameter space:

# import Database from findus
from findus import Database
...
database = Database(argv=argv, column_names=["delay", "length", "t1"])
...
database.insert(experiment_id, delay, length, t1, color, response)

If you want to plot the (length, t1)-slice, you can call the analyzer script as follows:

analyzer --directory databases -x length -y t1

If dbname is not provided, a name will automatically generated based on argv.

Methods:

Name Description
__init__

Default constructor.

insert

Method to insert datapoints into the SQLite database.

get_parameters_of_experiment_rel

Get the parameters of a dataset by experiment_id relative to the base row count.

get_parameters_of_experiment

Get the parameters of a dataset by experiment_id.

remove_conditional

Remove a parameter point from the database by a condition.

remove_rel

Remove a parameter point from the database by experiment_id relative to the base row count.

remove

Remove a parameter point from the database by experiment_id.

cleanup

Remove all parameter points with a given color.

get_number_of_experiments

Get the total number of performed experiments (number of datasets in the database).

get_latest_experiment_id

Get the latest experiment_id.

get_base_experiments_count

[Deprecated] Get the total number of performed experiments (number of datasets in the database).

close

Close the connection to the database.

__init__(argv, dbname=None, resume=False, nostore=False, column_names=None, dirname='databases')

Default constructor of the Database class.

Parameters:
  • argv (list[str]) –

    Arguments that were supplied to the main-script. These arguments are stored as metadata when the database is instantiated.

  • dbname (str, default: None ) –

    Name of the database to be generated.

  • resume (bool, default: False ) –

    Resume a previous run and write the results into the previously generated database

  • nostore (bool, default: False ) –

    Do not store the results in a database (can be used for debugging).

  • column_names (list[str], default: None ) –

    Specify the parameter names of the experiments.

  • dirname (str, default: 'databases' ) –

    Directory name to store the databases. If dirname is None, dbname can be an absolut path.

change_color_of_experiment(experiment_id, color)

Change the color of a dataset by experiment_id.

Parameters:
  • experiment_id (int) –

    ID of the experiment

change_color_of_experiment_rel(experiment_id, color)

Change the color of a dataset by experiment_id relative to the base row count.

Parameters:
  • experiment_id (int) –

    ID of the experiment r1elative to the base row count

cleanup(color)

Remove all parameter points with a given color.

close()

Close the connection to the database.

get_base_experiments_count()

[Deprecated] Get the total number of performed experiments (number of datasets in the database).

Returns:
  • int

    Number of experiments performed so far in the current database.

get_latest_experiment_id()

Get the latest experiment_id.

Returns:
  • int

    Experiment ID.

get_number_of_experiments()

Get the total number of performed experiments (number of datasets in the database).

Returns:
  • int

    Number of experiments performed so far in the current database.

get_parameters_of_experiment(experiment_id)

Get the parameters of a dataset by experiment_id.

Parameters:
  • experiment_id (int) –

    ID of the experiment

Returns:
  • list

    List of parameters.

get_parameters_of_experiment_rel(experiment_id)

Get the parameters of a dataset by experiment_id relative to the base row count.

Parameters:
  • experiment_id (int) –

    ID of the experiment relative to the base row count.

Returns:
  • list

    List of parameters.

insert(*dataset)

Method to insert datapoints into the SQLite database.

Parameters:
  • dataset

    Dataset consisting of experiment_id, delay, length, [additional parameters, ...], color and response. - experiment_id: ID of the experiment to insert into the database. - delay: Time from trigger until the glitch is set (in nano seconds). - length: Length of glitch (in nano seconds). - color: Color with which the parameter point (delay, length) is to be displayed in the graph. - response: Byte string of target response.

remove(experiment_id)

Remove a parameter point from the database by experiment_id.

Parameters:
  • experiment_id (int) –

    ID of the experiment to insert into the database.

remove_conditional(condition)

Remove a parameter point from the database by a condition.

Parameters:
  • condition (str) –

    Condition to apply. For example, id = 1000, id > 1000, color = \"C\" or delay < 6000.

remove_rel(experiment_id)

Remove a parameter point from the database by experiment_id relative to the base row count.

Parameters:
  • experiment_id (int) –

    ID of the experiment to insert into the database.

ErrorHandling

check(experiment_id, response, expected=b'expected', keep=None, user_action=None, recolor='O')

Check for consecutive errors and act accordingly.

Parameters:
  • experiment_id (int) –

    The current experiment id.

  • response (bytes) –

    Response of the current experiment id.

  • expected (bytes, default: b'expected' ) –

    The expected response. Everything else is considered erroneous.

  • keep (list[bytes], default: None ) –

    List of characterization to keep. For example keep = [b'ok', b'success'].

  • user_action

    Function to execute in the case of consecutive errors. Could be a function to reprogram the target, for example.

Returns:
  • Returns the response. If a consecutive error is detected, b'error: successive error occurred' is returned.

Glitcher

Glitcher template class. This class defines a common anchestor from which other glitcher modules should inherit from.

Methods:

Name Description
__init__

Default constructor. Does nothing in this case.

classify

Template method to classify an output state.

colorize

Returns a colored string depending on a color identifier (G, Y, R, M, C, B).

get_speed

Calculate and return the average speed of the glitching campaign (glitches per second).

__init__()

Default constructor. Does nothing in this case.

classify(state) staticmethod

Template method to classify an output state. Overload this class if you want to customize the targets response classification. Alternatively, use the built-in class GlitchState to characterize the targets responses. Remember to define certain response states depending on the possible responses. See class STM32Bootloader for an example.

from findus import PicoGlitcher
from findus.STM32Bootloader import STM32Bootloader
glitcher = PicoGlitcher()
...
programmer = STM8Programmer(port=self.args.target, baud=115200)
...
state = programmer.bootloader_enter()
...
glitcher.classify(state)

colorize(s, color) staticmethod

Returns a colorized string depending on a color identifier (G, Y, R, M, C, B, O, Z).

Parameters:
  • s (str) –

    The string you want to colorize.

  • color (str) –

    Color identifier, one of 'G', 'Y', 'R', 'M', 'C', 'B', 'O', 'Z' (black).

Returns: Returns the colorized string.

get_speed(start_time, number_of_experiments) staticmethod

Calculate and return the average speed of the glitching campaign (glitches per second).

Parameters:
  • start_time (int) –

    Start time of the glitching campaign in seconds.

  • number_of_experiments (int) –

    Number of experiments carried out so far.

Returns: Returns the average number of experiments per second.

Helper

Helper class that provides useful functions. Example usage:

from findus import Helper as helper
filename = f"{helper.timestamp()}_memory_dump.bin"

Methods:

Name Description
timestamp

Provides the current timestamp in a file-friendly format.

arange(start, stop=None, step=1.0) staticmethod

Return evenly spaced values within a given interval. Equivalent to numpy's arange function.

Parameters:
  • start

    Start of interval. The interval includes this value. The default start value is 0.

  • stop

    End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.

  • step

    Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given.

Returns:
  • list

    List of integer or real numbers.

linspace(start, stop, num, endpoint=True) staticmethod

Generate equidistant points from a start to a stop point. Equivalent to numpy's linspace function.

Parameters:
  • start

    Start point of the interval.

  • stop

    End point of the interval.

  • num

    Number of points to divide the interval into.

  • endpoint

    Whether the stop point should be part of the interval.

Returns:
  • list

    List of integer or real numbers.

timestamp() staticmethod

Provides the current timestamp in a file-friendly format.

Returns:
  • str

    Returns the current timestamp in the format %Y-%m-%d_%H-%M-%S.

PicoGlitcher

Bases: Glitcher

Class giving access to the functions of the Pico Glitcher. Derived from Glitcher class. For an example, connect the Pico Glitcher as follows:

  • Remove any capacitors on your target device that could infere with the glitch.
  • Set the desired output voltage VTARGET with the micro switch.
  • Connect VTARGET with the voltage input of your target (VCC).
  • Connect the GLITCH output (either the SMA connector or the pin header) to an appropriate target pin, for example VCC.
  • Connect the RESET output with the target's reset input.
  • Connect the RESET line with the TRIGGER input.

Code snippet:

from findus import PicoGlitcher
glitcher = PicoGlitcher()
glitcher.init(port="/dev/ttyACM0", ext_power="/dev/ttyACM1", ext_power_voltage=3.3)
# set up database, define delay and length
...
# one shot glitching
glitcher.arm(delay, length)
# reset target for 0.01 seconds (the rising edge on reset line triggers the glitch)
glitcher.reset_target(0.01)
# read the response from the device (for example UART, SWD, etc.)
response = ...
# classify the response and put into database
color = glitcher.classify(response)
database.insert(experiment_id, delay, length, color, response)

Methods:

Name Description
__init__

Default constructor. Does nothing in this case.

init

Default initialization procedure.

arm

Arm the Pico Glitcher and wait for trigger condition.

block

Block the main script until trigger condition is met. Times out.

reset

Reset the target via the Pico Glitcher's RESET output.

release_reset

Release the reset to the target via the Pico Glitcher's RESET output.

power_cycle_target

Power cycle the target via the Pico Glitcher VTARGET output or optionally via the multiplexing stage.

power_cycle_reset

Power cycle and reset the target via the Pico Glitcher RESET and VTARGET output.

reset_and_eat_it_all

Reset the target and flush the serial buffers.

reset_wait

Reset the target and read from serial.

set_lpglitch

Enable low-power MOSFET for glitch generation.

set_hpglitch

Enable high-power MOSFET for glitch generation.

rising_edge_trigger

Configure the Pico Glitcher to trigger on a rising edge on the TRIGGER line.

uart_trigger

Configure the Pico Glitcher to trigger when a specific byte pattern is observed on the TRIGGER line.

set_cpu_frequency

Set the CPU frequency of the Raspberry Pi Pico.

get_cpu_frequency

Get the current CPU frequency of the Raspberry Pi Pico.

__del__

Default deconstructor. Disconnects Pico Glitcher.

__init__()

Default constructor. Does nothing in this case.

apply_calibration(vhigh, vlow, store=True)

Calculate and store the offset and gain parameters that were determined by the calibration routine. These values are stored in config.json and must be re-calculated if the config is overwritten.

Parameters:
  • vhigh (float) –

    The maximum voltage of the calibration voltage trace.

  • vlow (float) –

    The minimum voltage of the calibration voltage trace.

  • store (bool, default: True ) –

    wether to store the offset and gain factor in the Pico Glitcher configuration.

arm(delay, length, number_of_pulses=1, delay_between=0)

Arm the Pico Glitcher and wait for the trigger condition. The trigger condition can either be when the reset on the target is released or when a certain pattern is observed in the serial communication.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • length (int) –

    Length of the glitch in nano seconds. Expect a resolution of about 5 nano seconds.

  • number_of_pulses (int, default: 1 ) –

    The number of pulses to emit. This can be used to emit bursts of crowbar glitches.

  • delay_between (int, default: 0 ) –

    The delay between each pulse.

arm_adc()

Arm the ADC on pin 26 and capture ADC samples if the trigger condition is met. On Pico Glitcher hardware version 1, the separate SMA connector labeled Analog can be used to measure analog voltage traces. On revision 2, the analog input is directly connected to the GLITCH line.

arm_double(delay1, length1, delay2, length2)

Arm the Pico Glitcher and wait for the trigger condition. The trigger condition can either be when the reset on the target is released or when a certain pattern is observed in the serial communication. This functions emits two glitches after a given time, each measured separately from the trigger condition. Be sure that delay2 > delay1 + length1.

Parameters:
  • delay1 (int) –

    First glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • length1 (int) –

    Length of the frist glitch in nano seconds. Expect a resolution of about 5 nano seconds.

  • delay2 (int) –

    Second glitch is emitted after this time measured from the trigger condition.

  • length2 (int) –

    Length of the second glitch in nano seconds.

arm_multiplexing(delay, mul_config, vinit='config')

Arm the Pico Glitcher and wait for the trigger condition. The trigger condition can either be when the reset on the target is released or when a certain pattern is observed in the serial communication. Only available for hardware revision 2 and later.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • mul_config (dict) –

    The dictionary for the multiplexing profile with pairs of identifiers and values. For example, this could be {"t1": 10, "v1": "GND", "t2": 20, "v2": "1.8", "t3": 30, "v3": "GND", "t4": 40, "v4": "1.8"}. Meaning that when triggered, a GND-voltage pulse with duration of 10ns is emitted, followed by a +1.8V step with duration of 20ns and so on.

  • vinit (str, default: 'config' ) –

    The initial value of the multiplexer. If 'config' is chosen, the initial value is read from the configuration file. Additionally, the user can choose between 'VI1' or 'VI2'.

arm_pulseshaping_from_config(delay, ps_config)

Arm the Pico Glitcher and wait for the trigger condition. The trigger condition can either be when the reset on the target is released or when a certain pattern is observed in the serial communication. Only available for hardware revision 2 and later. Additionally, the Pulse Shaping Expansion board is needed.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • ps_config (list[list[int]]) –

    The pulse configuration given as a list of time deltas and voltage values.

Example:

ps_config = [[4*length, 1.8], [4*length, 0.95], [length, 0.0]]
glitcher.arm_pulseshaping_from_config(delay, ps_config)

arm_pulseshaping_from_lambda(delay, ps_lambda, pulse_number_of_points)

Arm the Pico Glitcher and wait for the trigger condition. Generate the pulse from a lambda function depending on the time.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • ps_lambda (str) –

    A lambda function that defines the glitch at certain times. Must be given as string which is processed by the Pico Glitcher at runtime.

  • pulse_number_of_points (int) –

    The approximate length of the pulse. This is needed to constrain the pulse and to save computing time.

Example:

ps_lambda = f"lambda t:-1.0/({2*length})*t+3.0 if t<{2*length} else 2.0 if t<{4*length} else 0.0 if t<{5*length} else 3.0"
glitcher.arm_pulseshaping_from_lambda(delay, ps_lambda, 6*length)

arm_pulseshaping_from_list(delay, pulse)

Arm the Pico Glitcher and wait for the trigger condition. Genereate the pulse from a raw array of values.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • pulse (list[int]) –

    A raw list of points that define the pulse. No calibration and no constraints are applied to the list. The list is forwarded directly to the DAC.

Example:

pulse = [-0x1fff] * 50 + [-0x0fff] * 50 + [-0x07ff] * 50 + [0x0000] * 50
glitcher.arm_pulseshaping_from_list(delay, pulse)

arm_pulseshaping_from_spline(delay, xpoints, ypoints)

Arm the Pico Glitcher and wait for the trigger condition. The pulse definition is given by time and voltage points. Intermediate values are interpolated.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • xpoints (list[int]) –

    A list of time points (in nanoseconds) where voltage changes occur.

  • ypoints (list[float]) –

    The corresponding voltage levels at each time point.

Example:

xpoints = [0,   100, 200, 300, 400, 500, 515, 520]
ypoints = [3.0, 2.1, 2.0, 2.0, 1.7, 0.0, 2.0, 3.0]
glitcher.arm_pulseshaping_from_spline(delay, xpoints, ypoints)

block(timeout=1.0)

Block until trigger condition is met. Raises an exception if times out.

Parameters:
  • timeout (float, default: 1.0 ) –

    Time after the block is released.

change_config_and_apply(key, value)

Change the content of the configuration file config.json. Note that the value to be changed must already exist. Apply the values afterwards without reset by calling glitcher.switch_pio(1). This will re-initialize the internal statemachines and apply the configuration.

Parameters:
  • key (str) –

    Key of value to be replaced.

  • value (int | float | str) –

    Value to be set.

change_config_and_reset(key, value)

Change the content of the configuration file config.json. Note that the value to be changed must already exist. After calling this function, the Pico Glitcher must be re-initialized (call glitcher.init(port=args.rpico, ext_power=args.power, ext_power_voltage=3.3) again).

Parameters:
  • key (str) –

    Key of value to be replaced.

  • value (int | float | str) –

    Value to be set.

check_glitch()

Check if the glitch was emitted.

Returns:
  • bool

    Returns True if statemachine 1, that is used for glitch generation, was triggered.

clean_init()

Re-initialize the Pico Glitcher on the fly. Can be used to make changes to the configuration on the fly.

cleanup_pio()

Remove all programs from the internal statemachines. Could be necessary before a program is added to the statemachine but it is out of memory. Some weird behavior was observed when removing and adding programs to the statemachines. Use with caution.

configure_adc(number_of_samples=1024, sampling_freq=500000)

Configure the onboard ADC of the Pico Glitcher.

Parameters:
  • number_of_samples (int, default: 1024 ) –

    The number of samples to capture after triggering.

  • sampling_freq (int, default: 500000 ) –

    The sampling frequency of the ADC. 500 kSPS is the maximum for the Pico Glitcher.

configure_gpio_out(pin_number)

Configure the GPIO pin pin_number as an output.

Parameters:
  • pin_number (int) –

    GPIO pin number (for example 4, 5, 6).

disable_vtarget()

Disable the Pico Glitcher's VTARGET output.

do_calibration(vhigh)

Emit a calibration pulse with the Pico Glitcher Pulse Shaping expansion board to determine vhigh and vlow. These parameters are used to calculate the offset and gain parameters of the DAC.

Parameters:
  • vhigh (float) –

    The initial voltage to perform the calibration with. Default is 1V.

edge_count_trigger(pin_trigger='default', number_of_edges=2, edge_type='rising')

Configure the Pico Glitcher to trigger after a certain number of eddges on the TRIGGER line.

Parameters:
  • pin_trigger (str, default: 'default' ) –

    The trigger pin to use. Can either be 'default' (default TRIGGER input) or 'alt' (alternative trigger input TRIGGER1). For hardware version 2 options 'ext1' or 'ext2' are also available.

  • number_of_edges (int, default: 2 ) –

    The number of edges after which the Pico Glitcher triggers.

  • edge_type (str, default: 'rising' ) –

    Trigger on a 'rising' (default) or 'falling' edge.

enable_vtarget()

Enable the Pico Glitcher's VTARGET output.

falling_edge_trigger(pin_trigger='default', dead_time=0, pin_condition='default', condition='rising')

Configure the Pico Glitcher to trigger on a falling edge on the TRIGGER line with optional trigger suppression (dead time).

Parameters:
  • pin_trigger (str, default: 'default' ) –

    The trigger pin to use. Can either be 'default' (default TRIGGER input) or 'alt' (alternative trigger input TRIGGER1). For hardware version 2 options 'ext1' or 'ext2' are also available.

  • dead_time (float, default: 0 ) –

    Set a dead time that prohibits triggering within a certain time (trigger rejection). This is intended to exclude false trigger conditions. Can also be set to 0 to disable this feature.

  • pin_condition (str, default: 'default' ) –

    The rejection time is generated internally by measuring the state of the the given pin of the Pico Glitcher. If you want to trigger on the reset condition, set pin_condition = 'reset', else if you want to trigger on the target power set pin_condition = 'power'. pin_condition can either be 'default', 'power', 'reset' or a GPIO pin number (for example "4", "5" or "6"). If dead_time is set to zero and pin_condition = 'default', this parameter is ignored.

  • condition (str, default: 'rising' ) –

    Can either be 'falling' or 'rising'. The dead_time is measured on the pin pin_condition after the specified condition (falling- or rising-edge). For example, a good choice is 'rising' for the 'default' configuration and 'falling' for the 'reset' configuration. However, this could depend on the specific use case.

get_adc_samples(timeout=1.0)

Read back the captured ADC samples.

get_cpu_frequency()

Get the current CPU frequency of the Raspberry Pi Pico.

Returns:
  • int

    Returns the CPU frequency.

get_power_supply()

To control the external power supply in a script, the power_supply object is necessary.

Returns:
  • Returns the power_supply object if the external power supply is used.

hard_reset()

Perform a hard reset of the Pico Glitcher (Raspberry Pi Pico).

init(port, ext_power=None, ext_power_voltage=3.3, enable_vtarget=True)

Default initialization procedure of the Pico Glitcher. Default configuration is:

  • Set the trigger input to rising-edge trigger on TRIGGER input and assume triggering when the reset is released.
  • Set a dead time that prohibits triggering within a certain time (trigger rejection). This is intended to exclude false trigger conditions.
  • Use the low-power crowbar MOSFET as default.
Parameters:
  • port (str) –

    Port identifier of the Pico Glitcher.

  • ext_power (str, default: None ) –

    Port identifier of the external power supply (RD6006). If None, target is assumed to be supplied by VTARGET of the Pico Glitcher.

  • ext_power_voltage (float, default: 3.3 ) –

    Supply voltage of the external power supply. Must be used in combination with ext_power. You can not control the supply voltage VTARGET of the Pico Glitcher with this parameter.

initiate_reset()

Initiate the reset of the target via the Pico Glitcher's RESET output.

power_cycle_reset(power_cycle_time=0.2)

Power cycle and reset the target via the Pico Glitcher VTARGET and RESET output. Optionally the multiplexing stage can be used to power-cycle the target. Can also be used to define sharper trigger conditions via the RESET line. Depending on the glitch configuration (crowbar, multiplexing, pulse-shaping), the power-cycle is performed with either the crowbar, multiplexing or pulse-shaping stage.

Parameters:
  • power_cycle_time (float, default: 0.2 ) –

    Time how long the power supply is cut. If ext_power is defined, the external power supply is cycled.

power_cycle_target(power_cycle_time=0.2)

Power cycle the target via the Pico Glitcher VTARGET output or optionally via the multiplexing stage. Depending on the glitch configuration (crowbar, multiplexing, pulse-shaping), the power-cycle is performed with either the crowbar, multiplexing or pulse-shaping stage. If available, target is power-cycled by the external power supply RD6006.

Parameters:
  • power_cycle_time (float, default: 0.2 ) –

    Time how long the power supply is cut. If ext_power is defined, the external power supply (RD6006) is cycled.

release_reset()

Release the reset of the target via the Pico Glitcher's RESET output.

reset(reset_time=0.2)

Reset the target via the Pico Glitcher's RESET output. This function is the same as reset_target. Left in for downward compatibility.

Parameters:
  • reset_time (float, default: 0.2 ) –

    Time how long the target is held in reset.

reset_and_eat_it_all(target, target_timeout=0.3)

Reset the target via the Pico Glitcher's RESET output and flush the serial buffers.

Parameters:
  • target (Serial) –

    Serial communication object (usually defined as target = serial.Serial(...)).

  • target_timeout (float, default: 0.3 ) –

    Time-out of the serial communication. After this time, reading from the serial connection is canceled and it is assumed that there is no more garbage on the line.

reset_target(reset_time=0.2)

Reset the target via the Pico Glitcher's RESET output.

Parameters:
  • reset_time (float, default: 0.2 ) –

    Time how long the target is held in reset.

reset_wait(target, token, reset_time=0.2, debug=False)

Reset the target via the Pico Glitchers's RESET output and wait until the target responds (read from serial).

Parameters:
  • target (Serial) –

    Serial communication object (usually defined as target = serial.Serial(...)).

  • token (bytes) –

    Expected response from target. Read from serial multiple times until target responds.

  • reset_time (float, default: 0.2 ) –

    Time how long the target is held under reset.

  • debug (bool, default: False ) –

    If true, more output is given.

Returns:
  • bytes

    Returns the target's response.

rising_edge_trigger(pin_trigger='default', dead_time=0, pin_condition='default', condition='rising')

Configure the Pico Glitcher to trigger on a rising edge on the TRIGGER line with optional trigger suppression (dead time).

Parameters:
  • pin_trigger (str, default: 'default' ) –

    The trigger pin to use. Can either be 'default' (default TRIGGER input) or 'alt' (alternative trigger input TRIGGER1). For hardware version 2 options 'ext1' or 'ext2' are also available.

  • dead_time (float, default: 0 ) –

    Set a dead time that prohibits triggering within a certain time (trigger rejection). This is intended to exclude false trigger conditions. Can also be set to 0 to disable this feature.

  • pin_condition (str, default: 'default' ) –

    The rejection time is generated internally by measuring the state of the the given pin of the Pico Glitcher. If you want to trigger on the reset condition, set pin_condition = 'reset', else if you want to trigger on the target power set pin_condition = 'power'. pin_condition can either be 'default', 'power', 'reset' or a GPIO pin number (for example "4", "5" or "6"). If dead_time is set to zero and pin_condition = 'default', this parameter is ignored.

  • condition (str, default: 'rising' ) –

    Can either be 'falling' or 'rising'. The dead_time is measured on the pin pin_condition after the specified condition (falling- or rising-edge). For example, a good choice is 'rising' for the 'default' configuration and 'falling' for the 'reset' configuration. However, this could depend on the specific use case.

set_cpu_frequency(frequency=200000000)

Set the CPU frequency of the Raspberry Pi Pico.

Parameters:
  • frequency (int, default: 200000000 ) –

    the CPU frequency.

set_ext_mosfet(*pin)

Enable glitch generation on a given GPIO output. Could be used generate glitches by an external MOSFET.

Parameters:
  • pin (int, default: () ) –

    Optional GPIO pin to use. Default pin is 19 which is an unbuffered GPIO (recommended for glitch generation). Other options are GPIO pin 16, 17 or 18.

set_gpio(pin_number, value)

Set the GPIO pin pin_number to a specific output value (0 or 1).

Parameters:
  • pin_number (int) –

    GPIO pin number (for example 4, 5, 6).

  • value (int) –

    Output value of the GPIO pin (0 or 1).

set_hpglitch()

Enable the high-power crowbar MOSFET for glitch generation.

The glitch output is an SMA-connected output line that is normally connected to a target's power rails. If this setting is enabled, a high-powered MOSFET shorts the power-rail to ground when the glitch module's output is active.

set_lpglitch()

Enable the low-power crowbar MOSFET for glitch generation.

The glitch output is an SMA-connected output line that is normally connected to a target's power rails. If this setting is enabled, a low-powered MOSFET shorts the power-rail to ground when the glitch module's output is active.

set_multiplexing()

Enables the multiplexing mode of the Pico Glitcher version 2 to quickly switch between different voltage levels.

set_mux_voltage(voltage)

TODO

set_pulseshaping(vinit=1.8)

Enables the pulse-shaping mode of the Pico Glitcher version 2 to apply a voltage profile to the target's supply voltage.

Parameters:
  • vinit (float, default: 1.8 ) –

    The initial voltage (voltage offset) to base the calculations on. This does not change the output voltage of the pulse shaping expansion board. However, this parameter is used to calculate the correct offsets and scaling of the pulse.

switch_pio(pio_base)

In some rare cases, it might be necessary to switch to the other internal statemachine. For example, if a change in the glitch configuration is necessary but the statemachine is out of memory. Instead of removing the programs from the statemachine (cleanup_pio), one can simply switch to the other statemachine and setup the Pico Glitcher to use the configuration on the second statemachine.

Parameters:
  • pio_base (int) –

    Base number of the statemachine. Can either be 0 or 1. Other values are ignored.

tio_trigger(pin_trigger='default', edge_type='rising')

Configure the Pico Glitcher to trigger on a rising or falling edge on the TRIGGER line.

Parameters:
  • pin_trigger (str, default: 'default' ) –

    The trigger pin to use. Can either be 'default' (default TRIGGER input) or 'alt' (alternative trigger input TRIGGER1). For hardware version 2 options 'ext1' or 'ext2' are also available.

  • edge_type (str, default: 'rising' ) –

    Trigger on a 'rising' (default) or 'falling' edge.

uart_trigger(pattern, baudrate=115200, number_of_bits=8, pin_trigger='default')

Configure the Pico Glitcher to trigger when a specific byte pattern is observed on the TRIGGER line.

Parameters:
  • pattern (int) –

    Byte pattern that is transmitted on the serial lines to trigger on. For example 0x11.

  • baudrate (int, default: 115200 ) –

    The baudrate of the serial communication.

  • number_of_bits (int, default: 8 ) –

    The number of bits of the UART payload.

  • pin_trigger (str, default: 'default' ) –

    The trigger pin to use. Can be either 'default' or 'alt'. For hardware version 2 options 'ext1' or 'ext2' can also be chosen.

waveform_generator(frequency, gain, waveid)

The Pulse Shaping expansion board of the Pico Glitcher v2 can be used to generate arbitrary and continous waveforms as well.

Parameters:
  • frequency (int) –

    The frequency of the signal.

  • gain (float) –

    The gain (overall amplitude) of the signal.

  • waveid (int) –

    This determines the signal type, that is, what signal should be generated.

  • sine wave: waveid = 0
  • cosine wave: waveid = 1
  • triangle: waveid = 2
  • positive sawtooth: waveid = 3
  • negative sawtooth: waveid = 4

Serial

Class to manage serial connections more easily. Example usage:

# import Serial from findus
from findus import Serial
ser = Serial(port="/dev/ttyUSB0")
ser.write(b'\x7f')
...
result = ser.read(3)

Methods:

Name Description
__init__

Default constructor.

write

Write data out via the serial interface.

read

Read data from the serial interface.

reset

Reset target via DTR pin and flush data lines.

flush

Flush data buffers.

flush_v2

Flush serial data buffers with timeout.

close

Close serial connection.

__init__(port='/dev/ttyUSB0', baudrate=115200, timeout=0.1, bytesize=8, parity='N', stopbits=1)

init: Default constructor.

Parameters:
  • port (str, default: '/dev/ttyUSB0' ) –

    Port identifier of the serial connection.

  • baudrate (int, default: 115200 ) –

    Baudrate of the serial connection.

  • timeout (float, default: 0.1 ) –

    Timeout after the serial connection stops listening.

  • bytesize (int, default: 8 ) –

    Number of bytes per payload.

  • parity (str, default: 'N' ) –

    Even ('E') or Odd ('O') parity.

  • stopbits (int, default: 1 ) –

    Number of stop bits.

close()

Close serial connection.

flush()

Flush serial data buffers.

flush_v2(timeout=0.01)

Flush serial data buffers with timeout.

Parameters:
  • timeout (float, default: 0.01 ) –

    Timeout after the serial connection stops listening. Can be tweaked to make sure all data is flushed.

init()

Initializes the serial connection. Can be called again, if the connection was closed previously.

read(length)

Read length bytes from the serial port. If a timeout is set it may return fewer characters than requested. With no timeout it will block until the requested number of bytes is read.

Parameters:
  • length (int) –

    Number of bytes to read.

Returns: Bytes read from the port.

read_until(expected='\n', size=None)

Read until an expected sequence is found (\n by default), the size is exceeded or until timeout occurs. If a timeout is set it may return fewer characters than requested. With no timeout it will block until the requested number of bytes is read.

Parameters:
  • expected (bytes, default: '\n' ) –

    The byte string to search for.

  • size (int, default: None ) –

    Number of bytes to read

Returns:
  • bytes

    The line received from the target.

readline()

Read up to one line, including the \n at the end.

Returns:
  • bytes

    The line received from the target.

reset(debug=False)

Reset target via DTR pin and flush data lines. Can be used alternatively to the reset lines of the Pico Glitcher (or ChipWhisperer Husky, or ChipWhisperer Pro) to reset the target. This function is the same as reset_target. Left in for downward compatibility.

Parameters:
  • debug (bool, default: False ) –

    If set to true, garbage on the serial interface is plotted to tty.

reset_target(debug=False)

Reset target via DTR pin and flush data lines. Can be used alternatively to the reset lines of the Pico Glitcher (or ChipWhisperer Husky, or ChipWhisperer Pro) to reset the target.

Parameters:
  • debug (bool, default: False ) –

    If set to true, garbage on the serial interface is plotted to tty.

write(message)

Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g. 'hello'.encode('utf-8').

Parameters:
  • message (bytes) –

    Data to send

Returns: Number of bytes written.

This is the documentation of the PicoGlitcher module and all its classes.

Upload this module onto your Pico Glitcher. The classes and methods will become available through the pyboard interface.

PicoGlitcher

Class that contains the code to access the hardware of the Pico Glitcher.

__change_config(key, value)

Change the content of the configuration file config.json. Note that the value to be changed must already exist.

Parameters:
  • key (str) –

    Key of value to be replaced.

  • value (int | float | str) –

    Value to be set.

__init__()

Default constructor. Initializes the Pico Glitcher with the default configuration. - Disables VTARGET - Enables the low-power MOSFET for glitching - Configures the Pico Glitcher to use the rising-edge triggger condition.

apply_calibration(vhigh, vlow, store=True)

Calculate and store the offset and gain parameters that were determined by the calibration routine. These values are stored in config.json and must be re-calculated if the config is overwritten.

Parameters:
  • vhigh (float) –

    The maximum voltage of the calibration voltage trace.

  • vlow (float) –

    The minimum voltage of the calibration voltage trace.

  • store (bool, default: True ) –

    wether to store the offset and gain factor in the Pico Glitcher configuration.

arm(delay, length, number_of_pulses=1, delay_between=0)

Arm the Pico Glitcher and wait for the trigger condition. The trigger condition can either be when the reset on the target is released or when a certain pattern is observed in the serial communication.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • length (int) –

    Length of the glitch in nano seconds. Expect a resolution of about 5 nano seconds.

  • number_of_pulses (int, default: 1 ) –

    The number of pulses to emit. This can be used to emit bursts of crowbar glitches.

  • delay_between (int, default: 0 ) –

    The delay between each pulse.

arm_adc()

Arm the ADC on pin 26 and capture ADC samples if the trigger condition is met. On Pico Glitcher hardware version 1, the separate SMA connector labeled Analog can be used to measure analog voltage traces. On revision 2, the analog input is directly connected to the GLITCH line.

arm_double(delay1, length1, delay2, length2)

Arm the Pico Glitcher and wait for the trigger condition. The trigger condition can either be when the reset on the target is released or when a certain pattern is observed in the serial communication. This functions emits two glitches after a given time, each measured separately from the trigger condition. Be sure that delay2 > delay1 + length1.

Parameters:
  • delay1 (int) –

    First glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • length1 (int) –

    Length of the frist glitch in nano seconds. Expect a resolution of about 5 nano seconds.

  • delay2 (int) –

    Second glitch is emitted after this time measured from the trigger condition.

  • length2 (int) –

    Length of the second glitch in nano seconds.

arm_multiplexing(delay, mul_config, vinit='config')

Arm the Pico Glitcher in multiplexing mode and wait for the trigger condition.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • mul_config (dict) –

    The dictionary for the multiplexing profile with pairs of identifiers and values. For example, this could be {"t1": 10, "v1": "GND", "t2": 20, "v2": "1.8", "t3": 30, "v3": "GND", "t4": 40, "v4": "1.8"}. Meaning that when triggered, a GND-voltage pulse with duration of 10ns is emitted, followed by a +1.8V step with duration of 20ns and so on.

  • vinit (str, default: 'config' ) –

    The initial value of the multiplexer. If "config" is chosen, the initial value is read from the configuration file. Additionally, the user can choose between "VI1" or "VI2".

arm_pulseshaping_from_config(delay, ps_config)

Arm the Pico Glitcher and wait for the trigger condition. The pulse is defined via a configuration similar to multiplexing (without interpolation):

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • ps_config (list[list[float]]) –

    The pulse configuration given as a list of time deltas and voltage values.

arm_pulseshaping_from_lambda(delay, ps_lambda, pulse_number_of_points)

Arm the Pico Glitcher and wait for the trigger condition. Generate the pulse from a lambda function depending on the time.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • ps_lambda

    A lambda function that defines the glitch at certain times. Must be given as string which is processed by the Pico Glitcher at runtime.

  • pulse_number_of_points (int) –

    The approximate length of the pulse. This is needed to constrain the pulse and to save computing time.

arm_pulseshaping_from_list(delay, pulse)

Arm the Pico Glitcher and wait for the trigger condition. Genereate the pulse from a raw array of values.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • pulse (list[int]) –

    A raw list of points that define the pulse. No calibration and no constraints are applied to the list. The list is forwarded directly to the DAC.

arm_pulseshaping_from_spline(delay, xpoints, ypoints)

Arm the Pico Glitcher and wait for the trigger condition. The pulse definition is given by time and voltage points. Intermediate values are interpolated.

Parameters:
  • delay (int) –

    Glitch is emitted after this time. Given in nano seconds. Expect a resolution of about 5 nano seconds.

  • xpoints (list[int]) –

    A list of time points (in nanoseconds) where voltage changes occur.

  • ypoints (list[float]) –

    The corresponding voltage levels at each time point.

block(timeout)

Block until trigger condition is met. Raises an exception if times out.

Parameters:
  • timeout (float) –

    Time after the block is released.

change_config_and_apply(key, value)

Change the content of the configuration file config.json. Note that the value to be changed must already exist. Apply the values afterwards.

Parameters:
  • key (str) –

    Key of value to be replaced.

  • value (int | float | str) –

    Value to be set.

change_config_and_reset(key, value)

Change the content of the configuration file config.json. Note that the value to be changed must already exist. Reset the Pico Glitcher.

Parameters:
  • key (str) –

    Key of value to be replaced.

  • value (int | float | str) –

    Value to be set.

check_glitch()

Check if the glitch was emitted.

Returns:
  • bool

    Returns True if statemachine 0, that is used for glitch generation, was triggered.

configure_adc(number_of_samples=1024, sampling_freq=500000)

Configure the onboard ADC of the Pico Glitcher.

Parameters:
  • number_of_samples (int, default: 1024 ) –

    The number of samples to capture after triggering.

  • sampling_freq (int, default: 500000 ) –

    The sampling frequency of the ADC. 500 kSPS is the maximum.

disable_vtarget()

Disables VTARGET output. Disables the Pico Glitcher's power supply for the target.

do_calibration(vhigh)

Emit a calibration pulse with that can be used to determine vhigh and vlow. These parameters are used to calculate the offset and gain parameters of the DAC.

Parameters:
  • vhigh (float) –

    The initial voltage to perform the calibration with. Default is 1V.

enable_vtarget()

Enable VTARGET output. Activates the Pico Glitcher's power supply for the target.

get_adc_samples(timeout=1.0)

Read back the captured ADC samples.

get_firmware_version()

Get the current firmware version. Can be used to check if the current version is compatible with findus.

Returns:
  • list[int]

    Returns the current firmware version.

get_frequency()

Get the current CPU frequency of the Raspberry Pi Pico.

Returns:
  • int

    Returns the CPU frequency.

hard_reset()

Perform a hard reset of the Pico Glitcher (Raspberry Pi Pico).

initiate_reset()

Reset the target via the Pico Glitcher's RESET output.

power_cycle_reset(power_cycle_time=0.2)

Power cycle and reset the target via the Pico Glitcher VTARGET and RESET output. Optionally the multiplexing stage can be used to power-cycle the target. Can also be used to define sharper trigger conditions via the RESET line.

Parameters:
  • power_cycle_time (float, default: 0.2 ) –

    Time how long the power supply is cut. If ext_power is defined, the external power supply is cycled.

power_cycle_target(power_cycle_time=0.2)

Power cycle the target via the Pico Glitcher VTARGET output.

Parameters:
  • power_cycle_time (float, default: 0.2 ) –

    Time how long the power supply is cut.

release_reset()

Release the reset on the target via the Pico Glitcher's RESET output.

reset_target(reset_time=0.01)

Reset the target via the Pico Glitcher's RESET output, release the reset on the target after a certain time.

Parameters:
  • reset_time (float, default: 0.01 ) –

    Time how long the target is held in reset.

set_baudrate(baud=115200)

Set the baudrate of the UART communication in UART-trigger mode.

Parameters:
  • baud (int, default: 115200 ) –

    The baudrate to use.

set_dead_zone(dead_time=0, pin_condition='default', condition='rising')

Set a dead time that prohibits triggering within a certain time (trigger rejection). This is intended to exclude false trigger conditions. Can also be set to 0 to disable this feature.

Parameters:
  • dead_time (float, default: 0 ) –

    Rejection time during triggering is disabled.

  • pin_condition (str, default: 'default' ) –

    Can either be "default", "power", "reset" or a GPIO pin number (for example "4", "5" or "6"). In "power" mode, the TRIGGER input is connected to the target's power and the rejection time is measured after power down. In "reset" mode, the TRIGGER input is connected to the RESET line and the rejection time is measured after the device is reset. These modes imply different internal conditions to configure the dead time. If "default" is chosen, effectively no dead time is active.

  • condition (str, default: 'rising' ) –

    Can either be "falling" or "rising". The dead_time is measured on the pin pin_condition after the specified condition (falling- or rising-edge). For example, a good choice is "rising" for the "default" configuration and "falling" for the "reset" configuration. However, this could depend on the specific use case.

set_ext_mosfet(pin=Globals.EXT_GLITCH)

Enable the external mosfet triggering on GPIO19

set_frequency(frequency=200000000)

Set the CPU frequency of the Raspberry Pi Pico.

Parameters:
  • frequency (int, default: 200000000 ) –

    the CPU frequency.

set_hpglitch()

Enable the high-power crowbar MOSFET for glitch generation.

The glitch output is an SMA-connected output line that is normally connected to a target's power rails. If this setting is enabled, a low-powered MOSFET shorts the power-rail to ground when the glitch module's output is active.

set_lpglitch()

Enable the low-power crowbar MOSFET for glitch generation.

The glitch output is an SMA-connected output line that is normally connected to a target's power rails. If this setting is enabled, a low-powered MOSFET shorts the power-rail to ground when the glitch module's output is active.

set_multiplexing()

Enables the multiplexing mode of the Pico Glitcher version 2 to switch between different voltage levels.

set_number_of_bits(number_of_bits=8)

Set the number of bits of the UART communication in UART-trigger mode.

Parameters:
  • number_of_bits (int, default: 8 ) –

    The number of bits of the UART payload to use.

set_number_of_edges(number_of_edges=2)

Set the number of edges after which the Pico Glitcher triggers in edge-counting trigger mode.

Parameters:
  • number_of_edges (int, default: 2 ) –

    The number of edges after which the Pico Glitcher triggers.

set_pattern_match(pattern)

Configure the Pico Glitcher to trigger when a specific byte pattern is observed on the RX line (TRIGGER pin).

Parameters:
  • pattern (int) –

    Byte pattern that is transmitted on the serial lines to trigger on. For example 0x11.

set_pulseshaping(vinit=1.8)

Enables the pulse-shaping mode of the Pico Glitcher version 2 to emit a pre-defined voltage pulse on the Pulse Shaping expansion board.

set_trigger(mode='tio', pin_trigger='default', edge_type='rising')

Configures the Pico Glitcher which triggger mode to use. In "tio"-mode, the Pico Glitcher triggers on a rising edge on the TRIGGER pin. If "uart"-mode is chosen, the Pico Glitcher listens on the TRIGGER pin and triggers if a specific byte pattern in the serial communication is observed. In "edge"-mode, the Pico Glitcher counts the number of edges and triggers if a certain number of edges were observed. The parameter edge_type should be ignored if "uart"-mode is selected.

Parameters:
  • mode (str, default: 'tio' ) –

    The trigger mode to use. Either "tio" or "uart".

  • pin_trigger (str, default: 'default' ) –

    The trigger pin to use. Can be either "default" or "alt". For hardware version 2 options "ext1" or "ext2" can also be chosen.

  • edge_type (str, default: 'rising' ) –

    Trigger on the "rising" (default) or "falling" edge.

GeneticAlgorithm

This module includes all classes and functions that are necessary to search for optimal parameters in a multidimenstional parameter space.

GeneticAlgorithm

Class representing a Genetic Algorithm for optimizing a given problem.

__init__(parameterspace, population, health_malus_factor=1)

Initializes the Genetic Algorithm with a parameterspace, population, and an optional health malus factor.

Parameters:
  • parameterspace (Parameterspace) –

    The space of parameters over which the algorithm operates.

  • population (Population) –

    The initial population of candidate solutions.

  • health_malus_factor (float, default: 1 ) –

    A factor that penalizes solutions based on their healthiness.

get_bins_from_genom(parameters)

Converts a list of parameters into a list of bins based on the parameterspace.

Parameters:
  • parameters (list[int]) –

    A list of parameters.

Returns:
  • list[int]

    A list of bins corresponding to the parameters.

get_max_health()

Calculate the maximum health possible for an individual based on the population's genom length and the weights in the parameter space.

Returns:
  • int

    Maximum health value.

get_parameterspace()

Returns the parameterspace.

Returns:

get_population()

Returns the population.

Returns:

health_function(parameters)

Calculates the health of an individual:

health = Sum(weight_i) - factor * malus * Sum(weight_i)
health = (1 - factor * malus) * Sum(weight_i)
Parameters:
  • parameters (list[int]) –

    The parameters to set.

run(threshold)

Runs the simulation until an individual's health meets or exceeds a certain threshold.

Parameters:
  • threshold (float) –

    The threshold as a fraction of the maximum health value.

Returns:
  • list[int]

    A list of bins derived from the genom of the individual with the highest health.

step()

Perform one step of the simulation by updating the population, performing breeding, mutation, replacing weak individuals, and killing old individuals.

Returns:
  • list[Individual]

    List of updated individuals in the population.

Individual

This class represents an individual with parameters, health, maximum age, and current age.

Attributes:
  • parameters

    A list of parameters associated with the individual.

  • health

    The current health status of the individual.

  • max_age

    The maximum age that the individual can reach.

  • age

    The current age of the individual.

get_age()

Get the current age of the entity.

Returns:
  • int( int ) –

    The current age of the entity.

get_genom()

Get the parameters (genom) of the entity.

Returns:
  • list( list[int] ) –

    The parameters (genom) of the entity.

get_health()

Get the health of the entity.

Returns:
  • int( int ) –

    The health of the entity.

get_max_age()

Get the maximum age of the entity.

Returns:
  • int( int ) –

    The maximum age of the entity.

increase_age()

Increase the age of the entity by one.

set_genom(parameters)

Set the parameters (genom) for the entity.

Parameters:
  • parameters (list[int]) –

    The parameters to set.

set_health(health)

Set the health of the entity.

Parameters:
  • health (int) –

    The health value to set.

OptimizationController

Wrapper class for initializing parameter space binning and using the genetic algorithm to search for optimal paramters.

Methods:

Name Description
__init__

Constructor of the OptimizationController. Parameter boundaries and parameter divisions must be provided. Parameters for the genetic algorithm are optional.

print_best_performing_bins

Output the best performing parameter space bins. In these bins a successful glitch is assumed.

step

Perform the next step of the genetic algorithm; should be called before every experiment.

add_experiment

Add the parameters and the outcome (weights) to the parameter space.

__init__(parameter_boundaries, parameter_divisions, number_of_individuals=10, length_of_genom=20, malus_factor_for_equal_bins=1)

Constructor of the OptimizationController. Parameter boundaries and parameter divisions must be provided. Parameters for the genetic algorithm are optional.

Parameters:
  • parameter_boundaries (list[tuple[int, int]]) –

    Boundaries of all parameters to look into, for example [(s_delay, e_delay), (s_t1, e_t1), (s_length, e_length)].

  • parameter_divisions (list[int]) –

    Number of how many bins the individual parameter ranges should be divided into, for example [10, 10, 5]. Bigger values mean division into smaller bins which increases accuracy at the expense of performance (longer glitching campaign duration).

  • number_of_individuals (int, default: 10 ) –

    Number of individuals used simultaneously in the genetic algorithm. Increasing this number improves accuracy at the expense of performance (longer glitching campaign duration).

  • length_of_genom (int, default: 20 ) –

    Number of bins to track per individual. The larger the parameter space, the higher this number should be.

  • malus_factor_for_equal_bins (float, default: 1 ) –

    Can be used to punish individuals that look into the same bin multiple times. Must be in range [0, 1]. A bigger value means a greater penalty.

add_experiment(weight, *parameter)

Method to add the parameters and the outcome (weights) to the parameter space. Can be used similarly to the method Database.insert().

Parameters:
  • weight (int) –

    Weight of the outcome of the experiment. Higher values mean a better performing bin and a better health of the individuals that track that bin.

  • parameter (int, default: () ) –

    list of parameters that were used for the experiment.

print_best_performing_bins()

Method that prints an overview of the best performing bins of the parameterspace. Can be called from time to time to obtain an overview of the optimization process.

step()

Perform the next step in the optimization process. Should be called before the next experiment.

Returns:
  • list[int]

    A list of the parameters for the next experiment.

Parameterspace

__init__(parameter_boundaries, parameter_divisions)

Initializes the class with the given parameter boundaries and divisions.

Parameters:
  • parameter_boundaries (list[tuple[float, float]]) –

    A list of tuples representing the lower and upper bounds for each parameter.

  • parameter_divisions (list[int]) –

    A list of integers representing the number of divisions for each parameter.

Raises:
  • Exception

    If the lengths of parameter_boundaries and parameter_divisions are different.

  • Exception

    If any upper bound is lower than the corresponding lower bound.

add_experiment(weight, *parameter)

Add experiment data to the dataset. This function adds an experiment to the dataset with the given weight and parameters. It checks if each parameter is within the specified boundaries. If any parameter is out of bounds, it prints an error message and returns without adding the experiment. Otherwise, it assigns the experiment to a bin and updates the weight for that bin.

Parameters:
  • weight (int) –

    The weight to assign to the experiment.

  • *parameter (float, default: () ) –

    The parameters for the experiment, must be within the specified boundaries.

Returns:
  • None

get_bin_assignment(*parameter)

This function assigns a bin to each parameter based on its value.

Parameters:
  • *parameter (float, default: () ) –

    A list of float values representing the parameters to be assigned to bins.

Returns:
  • list( list[int] ) –

    A list of integers representing the bin numbers for each parameter.

get_bin_numbers_sorted_by_weights()

Returns a list of bin numbers sorted by their corresponding weights.

Returns:
  • list( list[int] ) –

    A list of bin numbers sorted by increasing weights.

get_boundaries(bin_assignment)

Returns the boundaries for a given bin assignment.

Parameters:
  • bin_assignment (int) –

    The bin assignment for which to get the boundaries.

Returns:
  • list( list[tuple[float, float]] ) –

    A list of tuples representing the boundaries.

get_boundaries_from_coordinates(coordinates)

This function calculates the boundaries for each parameter based on the given coordinates.

Parameters:
  • coordinates (list[float]) –

    A list of coordinates.

Returns:
  • list( list[tuple[float, float]] ) –

    A list of tuples representing the boundaries for each parameter.

get_cardinality()

Returns the cardinality of the set.

get_coordinates(bin_assignment)

This function calculates the coordinates of a given bin assignment in a multi-dimensional binning system.

Parameters:
  • bin_assignment (int) –

    The bin assignment for which to calculate the coordinates.

Returns:
  • list( list[int] ) –

    A list of coordinates corresponding to the bin assignment.

Raises:
  • Exception

    If the bin assignment exceeds the total number of bins.

get_weights()

Returns the list of weights per bin.

Returns:
  • list( list[int] ) –

    A list of weights corresponding to each bin.

Population

A class to represent a population of individuals.

__init__(number_of_individuals, length_of_genom)

Initializes a new population with a given number of individuals and genom length.

Parameters:
  • number_of_individuals (int) –

    The number of individuals in the population.

  • length_of_genom (int) –

    The length of the genom for each individual.

breed(i, j)

Breeds two individuals and returns a new individual with a genom that is a combination of the two parents.

Parameters:
  • i (int) –

    The index of the first parent individual.

  • j (int) –

    The index of the second parent individual.

Returns:
  • Individual

    A new individual that is a result of breeding the two parents.

generate_random_individual()

Generates a random individual with a genom of length 'length_of_genom'.

Returns:

get_individuals()

Returns a list of all individuals in the population.

Returns:

get_length_of_genom()

Returns the length of the genom for each individual.

Returns:
  • int

    The length of the genom.

get_number_of_individuals()

Returns the number of individuals in the population.

Returns:
  • int

    The number of individuals.

increase_age_of_population()

Increases the age of each individual in the population.

kill_and_replace()

Removes individuals from the population that have exceeded their maximum age and replaces them with random individuals.

mutate(i)

Mutates the genom of the individual at the given index.

Parameters:
  • i (int) –

    The index of the individual to mutate.

Returns:

replace(i, individual)

Replaces the individual at the given index with the given individual.

Parameters:
  • i (int) –

    The index of the individual to replace.

  • individual (Individual) –

    The individual to replace the old individual with.

replace_with_random(i)

Replaces the individual at the given index with a random individual.

Parameters:
  • i (int) –

    The index of the individual to replace.

set_individuals(individuals)

Sets the population to the given list of individuals.

Parameters:
  • individuals (list[Individual]) –

    A list of individuals to set as the population.

sort_by_health()

Sorts the population by the health of each individual.

update_health(health_function)

Updates the health of each individual in the population using the given health function.

Parameters:
  • health_function

    A function that takes a genom and returns a health value.

DebugInterface

Class to interact with the target device using OpenOCD and GDB.

__del__()

Destructor method called when the object is about to be garbage collected. Detaches the debugger by printing a message and invoking the detach method.

__init__(interface='stlink', interface_config=None, target='stm32l0', target_config=None, transport='hla_swd', gdb_exec='arm-none-eabi-gdb', adapter_serial=None, gdb_port=3333, telnet_port=4444, tcl_port=6666)

Initializes the OpenOCD configuration with default values or custom values provided.

Parameters:
  • interface (str, default: 'stlink' ) –

    The interface type, e.g., 'stlink' or 'j-link'. Defaults to 'stlink'.

  • interface_config (str, default: None ) –

    Path to a custom interface configuration file. If None, uses the default configuration for the specified interface.

  • target (str, default: 'stm32l0' ) –

    The target microcontroller, e.g., 'stm32l0'. Defaults to 'stm32l0'.

  • target_config (str, default: None ) –

    Path to a custom target configuration file. If None, uses the default configuration for the specified target.

  • transport (str, default: 'hla_swd' ) –

    The transport protocol, e.g., 'hla_swd'. Defaults to 'hla_swd'.

  • gdb_exec (str, default: 'arm-none-eabi-gdb' ) –

    The path to the GDB executable. Defaults to 'arm-none-eabi-gdb'.

  • adapter_serial (str, default: None ) –

    The serial number of the adapter. If None, no specific serial is used.

  • gdb_port

    The port number for GDB communication. Defaults to 3333.

  • telnet_port

    The port number for Telnet communication. Defaults to 4444.

  • tcl_port

    The port number for TCL communication. Defaults to 6666.

__parse_register_string(input_string)

Parses a custom formatted string into a dictionary containing a list of register values.

The input string follows the pattern: ^done,register-values=[{number="0",value="0x0"}, ...]

Parameters:
  • input_string (str) –

    The raw input string containing register data.

Returns:
  • dict( dict[str, any] ) –

    A dictionary with a 'register_values' key containing a list of parsed registers. Each item in the list has 'number' (int) and 'value' (str or int). Example: {"r0": "0x00", "r1": "0x01"}

attach(delay=0.1)

Attaches to the OpenOCD server.

Parameters:
  • delay

    Delay in seconds before checking if OpenOCD is running.

characterize(response, mem)

Characterizes the response based on the memory content.

Parameters:
  • response (str) –

    The response string to characterize.

  • mem (int) –

    The memory content to check.

Returns:
  • bytes( bytes ) –

    A byte string representing the characterization.

detach()

Detaches from the current debugging session by terminating and closing the necessary processes and socket.

extract_memory_content(response, address=0)

Extracts memory content from the response.

Parameters:
  • response (str) –

    The response string to extract memory content from.

  • address (int, default: 0 ) –

    The memory address to search for. Defaults to 0x00.

Returns:
  • int | None

    The extracted memory content if found, otherwise None.

format_bytes(value) staticmethod

Wandelt einen String-Wert so um, dass er nach dem '0x'-Präfix mindestens 4 Hex-Ziffern lang ist.

gdb_init(timeout=1.0, verbose=False)

Init the gdb debug session.

Parameters:
  • timeout

    Timeout for GDB operations.

  • verbose

    Whether to print verbose output.

gdb_interrupt_disconnect(timeout=0.3, halt_target=True, verbose=False)

Disconnects the GDB target and exits the GDB process.

Parameters:
  • timeout

    The maximum time to wait for GDB operations to complete.

  • halt_target

    Whether to halt the target before disconnecting.

  • verbose

    Whether to print verbose output.

gdb_load_exec(elf_image='program.elf', timeout=0.3, verbose=False)

Load and execute an ELF image using GDB.

Parameters:
  • elf_image (str, default: 'program.elf' ) –

    Path to the ELF image to be loaded and executed.

  • timeout

    Timeout for GDB operations.

  • verbose

    Whether to print verbose output.

gdb_read_register_names()

Connects to the microcontroller over openocd and gdb and extracts the available registers.

Returns:
  • list[str]

    A list of register names.

gdb_read_registers(timeout=1.0, verbose=False)

Read the current register values.

Parameters:
  • timeout

    Timeout for GDB operations.

  • verbose

    Whether to print verbose output.

kill_process(port, verbose=False)

Kill the process that is using the specified port.

Parameters:
  • port (int) –

    The port number to check for a process.

  • verbose

    If True, print detailed output.

load_exec(elf_image='program.elf', sp=536879104, pc=536874916, verbose=False)

Load image to RAM and execute. Attention: Program must also be compiled to be compatible to run in RAM.

Parameters:
  • elf_image (str, default: 'program.elf' ) –

    The path to the ELF image file to be loaded. Default is "program.elf".

  • sp (int, default: 536879104 ) –

    The initial stack pointer value. Default is 0x20002000.

  • pc (int, default: 536874916 ) –

    The initial program counter value. Default is 0x20000fa4.

  • verbose (bool, default: False ) –

    If True, print the output and error from openocd. Default is False.

lock_target(verbose=False, overwrite_target_name='')

Locks the target (activates RDP).

mi(cmd, verbose=False)

Sends a GDB command through the GDB process.

Parameters:
  • cmd

    The GDB command to send.

  • verbose

    If True, prints the command before sending it. Defaults to False.

mi_wait_done(timeout=1.0, ok_prefixes=('^done', '^running', '^connected'), verbose=False)

Wait for a GDB MI command to complete with a timeout.

Parameters:
  • timeout

    Maximum time to wait for the command to complete (default: 1.0 seconds)

  • ok_prefixes

    Prefixes indicating a successful completion (default: ("^done", "^running", "^connected"))

  • verbose

    Whether to print each line received (default: False)

Raises:
  • TimeoutError

    If the command times out

  • RuntimeError

    If the GDB process exits unexpectedly or encounters an error

program_target(glitcher=None, elf_image='program.elf', unlock=True, rdp_level=0, power_cycle_time=0.1, overwrite_target_name='', verbose=False)

Main function to program the target. Optionally unlocks the target, writes the ELF image, and adjusts the RDP level.

Parameters:
  • glitcher (PicoGlitcher, default: None ) –

    An instance of the Glitcher class used for glitching operations.

  • elf_image (str, default: 'program.elf' ) –

    The path to the ELF image file to be written to the target. Default is "program.elf".

  • unlock (bool, default: True ) –

    Whether to unlock the target before programming. Default is True.

  • rdp_level (int, default: 0 ) –

    The desired RDP level (0 or 1). Default is 0.

  • power_cycle_time (float, default: 0.1 ) –

    The time to wait between power cycles. Default is 0.1 seconds.

  • verbose (bool, default: False ) –

    Whether to print verbose output. Default is False.

read_address(address)

Read memory content from a specific address using OpenOCD.

Parameters:
  • address

    The memory address to read from.

Returns:
  • A tuple containing the extracted memory content and the raw response.

read_image(bin_image='memory_dump.bin', start_addr=134217728, length=1024, verbose=False)

Reads an image from the target device's memory and saves it to a binary file.

Parameters:
  • bin_image (str, default: 'memory_dump.bin' ) –

    The path to the binary file where the image will be saved.

  • start_addr (int, default: 134217728 ) –

    The starting address in memory to read from.

  • length (int, default: 1024 ) –

    The number of bytes to read from memory.

  • verbose (bool, default: False ) –

    If True, print the output and error messages.

read_option_bytes()

Reads the option bytes from the memory address 0x4002201c for stm32l0, or 0x1FFF7800 for stm32g0 microcontrollers.

Returns:
  • int

    A tuple containing the memory value and the response from the read operation.

  • str

    If the memory value is None, returns (0x00, response).

read_pcrop()

Reads the PCROP (Programmable Code Protection Region) value from the option bytes.

Returns:
  • int

    The PCROP value.

read_rdp()

Reads the RDP (Read Protection) value from the option bytes.

Returns:
  • int( int ) –

    The RDP value.

read_rdp_and_pcrop(verbose=False)

Reads both RDP and PCROP values from the option bytes.

Parameters:
  • verbose (bool, default: False ) –

    If True, prints the response from the read operation. Defaults to False.

Returns:
  • tuple[int, int]

    A tuple containing the RDP and PCROP values.

telnet_init()

Establishes a connection to the OpenOCD telnet server and receives initial messages.

telnet_interact(command, read=True, delay_before_read=0.01, verbose=False)

Sends a command via Telnet and receives the response.

Parameters:
  • command (str) –

    The command to send.

  • delay_before_read (float, default: 0.01 ) –

    Time to wait between sending the command and receiving the response. Defaults to 0.01.

  • read (bool, default: True ) –

    Whether to read the telnet response or not.

  • verbose (bool, default: False ) –

    Whether to print the response. Defaults to False.

Returns:
  • str

    The response received from the Telnet server.

telnet_interrupt_disconnect(halt_target=True, shutdown_openocd=True, verbose=False)

Disconnects from the target and exits the telnet process.

Parameters:
  • timeout

    The maximum time to wait for GDB operations to complete.

  • halt_target (bool, default: True ) –

    Whether to halt the target before disconnecting.

  • shutdown_openocd (bool, default: True ) –

    Whether to send the signal to openocd to shutdown.

  • verbose (bool, default: False ) –

    Whether to print verbose output.

telnet_parse_registers(input_data)

Parses a string of register names and their hexadecimal values into a dictionary.

Parameters:
  • input_data (str) –

    A multi-line string where each line contains a register name followed by its hex value (e.g., "r0 0x00000033").

Returns:
  • dict[str, str]

    A dictionary with register names as keys and their values.

telnet_read_address(address)

Reads the memory content at a specified address using Telnet.

Parameters:
  • address (int) –

    The memory address to read.

Returns:
  • tuple

    A tuple containing the memory content and the response from the Telnet command.

telnet_read_image(bin_image='memory_dump.bin', start_addr=134217728, length=1024, verbose=False)

Reads an image from a specified memory address using a telnet connection.

Parameters:
  • bin_image (str, default: 'memory_dump.bin' ) –

    The filename where the dumped image will be saved.

  • start_addr (int, default: 134217728 ) –

    The starting memory address to read from.

  • length (int, default: 1024 ) –

    The length of the data to read.

  • verbose (bool, default: False ) –

    If True, prints the response from the telnet server.

telnet_read_memory(start_address, width=32, count=256, halt=True, delay_before_read=0.1, verbose=False)

Read the current register values.

Parameters:
  • reg_name_list

    List of register names to read from the target

  • halt (bool, default: True ) –

    Whether to halt the target before reading.

  • delay_before_read (float, default: 0.1 ) –

    Time before reading the telnet response.

  • verbose (bool, default: False ) –

    Whether to print verbose output.

telnet_read_register_names()

Connects to the microcontroller over an open openocd connection via telnet and extracts the available registers.

Returns:
  • list[str]

    A list of register names.

telnet_read_registers(reg_name_list, halt=True, delay_before_read=0.1, verbose=False)

Read the current register values.

Parameters:
  • reg_name_list (list[str]) –

    List of register names to read from the target

  • halt (bool, default: True ) –

    Whether to halt the target before reading.

  • delay_before_read (float, default: 0.1 ) –

    Time before reading the telnet response.

  • verbose (bool, default: False ) –

    Whether to print verbose output.

test_connection()

Tests the connection to the target device by resetting it.

unlock_target(verbose=False, overwrite_target_name='')

Unlocks the target and removes any read-out protection. Attention: This will erase the targets flash!

write_image(elf_image='program.elf', verbose=False)

Writes an ELF image to the target using OpenOCD.

Parameters:
  • elf_image (str, default: 'program.elf' ) –

    The path to the ELF image to be written. Defaults to "program.elf".

  • verbose (bool, default: False ) –

    Whether to print verbose output. Defaults to False.

AnalogPlot

Class to easily plot captured voltage traces with the ADC.

Example usage:

from findus.AnalogPlot import AnalogPlot
...
glitcher.configure_adc(number_of_samples=1024, sampling_freq=450_000)
plotter = AnalogPlot(number_of_samples=1024, sampling_freq=450_000)
...
glitcher.arm_adc()
...
samples = glitcher.get_adc_samples()
plotter.update_curve(samples)

__init__(number_of_samples, vref=3.3, sampling_freq=500000, dynamic_range=4096)

Initialize the AnalogPlot object.

Parameters:
  • number_of_samples (int) –

    Number of samples to plot.

  • vref (float, default: 3.3 ) –

    Reference voltage. Defaults to 3.3.

  • sampling_freq

    Sampling frequency in Hz. Defaults to 500,000.

  • dynamic_range (int, default: 4096 ) –

    Dynamic range of the ADC. Defaults to 4096.

show()

Show the plot without blocking the program.

update_curve(y)

Update the curve with new data.

Parameters:
  • y (list) –

    List of new y-values.

ExternalPowerSupply

Wrapper class for the RD6006 voltage supply to align function names with the rest of the library. Example usage:

from findus import ExternalPowerSupply
power_supply = ExternalPowerSupply(port="/dev/ttyACM0")
power_supply.set_voltage(ext_power_voltage)
print(power_supply.status())
power_supply.power_cycle_target(power_cycle_time)

Methods:

Name Description
__init__

Default constructor.

status

Get the status of the voltage supply.

set_voltage

Set the voltage.

enable_vtarget

Enable voltage output.

disable_vtarget

Disable voltage output

power_cycle_target

Power cycle the target (disables output, waits a certain time, enables voltage output again).

__init__(port)

Default constructor.

Parameters:
  • port (str) –

    Port identifier of the voltage supply.

disable_vtarget()

Disable voltage output.

enable_vtarget()

Enable voltage output.

power_cycle_target(power_cycle_time=0.2)

Power cycle the target (disables output, waits a certain time, enables voltage output again).

Parameters:
  • power_cycle_time (float, default: 0.2 ) –

    Time to wait between disabling and enabling the voltage output again.

set_voltage(voltage)

Set the voltage of the power supply.

Parameters:
  • voltage (float) –

    Desired output voltage.

status()

Get the status of the voltage supply.

Returns:
  • str

    Status message of the voltage supply.

GlitchState

Class that combines subclasses for different states. Can be used to classify different responses.

  • Error: Enum class for error states.
  • Warning: Enum class for warning states.
  • OK: Enum class for ok states (no errors).
  • Expected: Enum class for expected states.
  • Success: Enum class for success states (glitching was successful).

Example usage:

from findus.GlitchState import GlitchState, OKType

def return_ok():
    return GlitchState.OK.ack

def main():
    response = return_ok()
    if issubclass(type(response), OKType):
        print("Response was OK.")