Overview

Python library

This library provide the abstractions needed to represent the side channel-attack pipeline.

It allows to code your own scripts without using the high-level API. This can be useful especially if you want to have a behavior during acquisition or processing that is not provided by the API.

The library allows to do the following tasks programmatically :

  • Acquire side-channel data

  • Acquire channel data

  • Parse the data

  • Export and import data

  • Apply basic filtering

  • Compute attack models

  • Compute correlation

  • Compute guess and related stats

lib.aes module

Numpy based AES module for side-channel attacks

This module is designed to allow easily build power consumption models.

It separately provides all the round operations used in the AES algorithm. It also features a handler class used to encapsulate key-expansion and ease encryption and decryption.

Examples

>>> from lib import aes
>>> import numpy as np
>>> key = np.ones((4,4), dtype=np.uint8)
>>> plain = np.eye(4, dtype=np.uint8)
>>> ark = aes.add_round_key(plain, key)
>>> handler = aes.Handler(key)
>>> cipher = handler.encrypt(plain)

Unlike the usual AES implementation, this one keeps a full trace of the intermediate operations during encryption.

More precisely, this module stores the value of the message block at each round and for each round operation.

Examples

>>> from lib import aes
>>> import numpy as np
>>> key = np.ones((4,4), dtype=np.uint8)
>>> plain = np.eye(4, dtype=np.uint8)
>>> handler = aes.Handler(key)
>>> cipher = handler.encrypt(plain)
>>> ark = handler.blocks[1, aes.Stages.ADD_ROUND_KEY]
src.lib.aes.word_to_col(w)

Splits a hexadecimal string to a bytes column.

Parameters

w (str) – Hexadecimal 32-bit word.

Returns

4 bytes column containing integers representing the input string.

Return type

list

src.lib.aes.col_to_word(c)

Formats a bytes column as a hexadecimal string.

Parameters

c (np.ndarray) – 4 bytes column to format

Returns

Hexadecimal 32 bits words representing the input column

Return type

str

Raises

ValueError – If the column has a length different from 4

src.lib.aes.words_to_block(words)

Transforms hexadecimal message string into an AES block matrix.

Parameters

words (str) – 4 32-bits words as strings representing block’s columns

Returns

4x4 matrix column major message block’s matrix.

Return type

np.ndarray

Raises

ValueError – If the count of words provided differs from 4.

See also

word_to_col

Column conversion from word.

src.lib.aes.block_to_words(block)

Formats a state block into an hexadecimal string.

Parameters

block (np.ndarray) – 4x4 row major block matrix.

Returns

4 32-bit words string representing the column major block.

Return type

str

Raises

ValueError – If count of rows in block provided differs from 4.

See also

col_to_word

column conversion to hexadecimal string.

src.lib.aes.add_round_key(block, key)

Performs a bitwise XOR between a state block and the key.

Parameters
  • block (np.ndarray) – 4x4 column major block matrix.

  • key (np.ndarray) – 4x4 column major block matrix.

Returns

4x4 result block matrix

Return type

np.ndarray

src.lib.aes.sub_bytes(block)

Applies sbox to a state block.

Parameters

block (np.ndarray) – 4x4 column major block matrix.

Returns

4x4 result block matrix

Return type

np.ndarray

src.lib.aes.inv_sub_bytes(block)

Applies inverse sbox to a state block.

Parameters

block (np.ndarray) – 4x4 column major block matrix.

Returns

4x4 result block matrix.

Return type

np.ndarray

src.lib.aes.shift_rows(block)

Shifts rows of a state block.

Parameters

block (np.ndarray) – 4x4 column major block matrix.

Returns

4x4 result block matrix.

Return type

np.ndarray

src.lib.aes.inv_shift_rows(block)

Reverses shift rows of a state block.

Parameters

block (np.ndarray) – 4x4 column major block matrix.

Returns

4x4 result block matrix.

Return type

np.ndarray

src.lib.aes.mix_columns(block)

Mix columns of a state block.

Parameters

block (np.ndarray) – 4x4 column major block matrix.

Returns

4x4 result block matrix.

Return type

np.ndarray

src.lib.aes.inv_mix_columns(block)

Reverses mix columns of a state block.

Parameters

block (np.ndarray) – 4x4 column major block matrix.

Returns

4x4 result block matrix.

Return type

np.ndarray

src.lib.aes.sub_word(col)

Applies SBOX to a key column.

Parameters

col (np.ndarray) – 4 bytes array.

Returns

Result column.

Return type

np.ndarray

src.lib.aes.rot_word(col)

Rotates a 4 key column.

Parameters

col (np.ndarray) – 4 bytes array.

Returns

Result column.

Return type

np.ndarray

src.lib.aes.key_expansion(key)

Performs key expansion.

Parameters

key (np.ndarray) – 4x4 input block key matrix.

Returns

4x4 input block key matrices for each round.

Return type

np.ndarray

class src.lib.aes.Stages

Bases: object

AES round stages enumeration.

The index of the stage correspond to its order into the round.

START = 0
SUB_BYTES = 1
SHIFT_ROWS = 2
MIX_COLUMNS = 3
ADD_ROUND_KEY = 4
INV_SHIFT_ROWS = 1
INV_SUB_BYTES = 2
INV_ADD_ROUND_KEY = 3
INV_MIX_COLUMNS = 4
class src.lib.aes.Handler(key)

Bases: object

AES computations handler interface.

blocks

4x4 block state matrix for each round and each operation.

Type

np.ndarray

keys

4x4 block key matrix for each round.

Type

np.ndarray

encrypt(block)

Performs AES cipher algorithm.

Parameters

block (np.ndarray) – Plain 4x4 column major block matrix.

Returns

Cipher 4x4 column major block matrix.

Return type

np.ndarray

decrypt(block)

Performs AES inverse cipher algorithm.

Parameters

block (np.ndarray) – Cipher 4x4 column major block matrix.

Returns

Plain 4x4 column major block matrix.

Return type

np.ndarray

lib.cpa module

Numpy based module for CPA side-channel attacks.

This module is provides abstractions to handle side channel attacks via power consumption acquisition.

It features a trace accumulator to avoid storing all the traces in memory. It also implements a fast Pearson correlation algorithm to retrieve attack results in a reasonable amount of time.

class src.lib.cpa.Statistics(handler=None)

Bases: object

update(handler)
clear()
div_idxs(n=0.2)
classmethod graph(data)
classmethod guess_stats(cor, key)

Computes the best guess key from correlation data.

Parameters
  • cor (np.ndarray) – Temporal correlation per block byte and hypothesis.

  • key (np.ndarray) –

Returns

  • guess (np.ndarray) – Guessed key block.

  • maxs (np.ndarray) – Maximums of temporal correlation per hypothesis.

  • exact (np.ndarray) – True if the guess is exact for each byte position.

  • rank (np.ndarray) – Rank of the true key in terms of correlation.

See also

correlations

Compute temporal correlation.

classmethod guess_envelope(cor, guess)

Computes the envelope of correlation.

The envelope consists on two curves representing respectively the max and min of temporal correlation at each instant.

This feature is mainly useful to plot temporal correlations curve.

Parameters
  • cor (np.ndarray) – Temporal correlation per block position and hypothesis.

  • guess (np.ndarray) – Guessed block matrix.

Returns

  • cor_max (np.ndarray) – Maximum correlation at each instant.

  • cor_min (np.ndarray) – Minimum correlation at each instant.

See also

correlations

Compute temporal correlation.

class src.lib.cpa.Handler(model=None, channel=None, traces=None, samples=None)

Bases: object

CPA correlation handler interface.

blocks

Encrypted data blocks for each trace.

Type

np.ndarray

key

Key data block for all the traces.

Type

np.ndarray

hypothesis

Value of power consumption for each hypothesis and class.

Type

np.ndarray

lens

Count of traces per class.

Type

np.ndarray

sums

Average trace per class.

Type

np.ndarray

sums2

Standard deviation trace per class.

Type

np.ndarray

sum

Average trace for all classes.

Type

np.ndarray

sum2

Standard deviation trace for all classes.

Type

np.ndarray

class Models(value)

Bases: enum.Enum

CPA power consumption models.

SBOX_R0 = 0
INV_SBOX_R10 = 1
clear(samples=0)
accumulate(traces)

Sorts traces by class and compute means and deviation.

Parameters

traces (np.ndarray) – Traces matrix.

Returns

Reference to self.

Return type

sca-automation.lib.cpa.Handler

set_key(channel)
set_blocks(channel)
set_model(model)

Initializes power consumption model.

Parameters

model (Handler.Models) – Model value.

Returns

Reference to self.

Return type

sca-automation.lib.cpa.Handler

correlations()

Computes Pearson’s correlation coefficients on current data.

Returns

Temporal correlation per byte and hypothesis.

Return type

np.ndarray

lib.log module

Python-agnostic SCA data parsing, logging and reporting module.

This module is designed as a class library providing entity classes to represent the side channel data acquired from SoC.

It provides binary data parsing in order to read acquisition data from a serial sources or a binary file and retrieve it in the entity classes.

All the entity classes of the module provide CSV support to allow processing acquisition data without parsing. It also provides formatting data in a more human-readable format.

class src.lib.data.Serializable

Bases: object

write_csv(path: str, append: bool)None
class src.lib.data.Deserializable

Bases: object

read_csv(path: str, count: int, start: int)None
class src.lib.data.Channel(path=None, count=None, start=0)

Bases: collections.abc.MutableSequence, collections.abc.Reversible, collections.abc.Sized, src.lib.data.Serializable, src.lib.data.Deserializable

Encryption channel data.

This class is designed to represent AES 128 encryption data for each trace acquired.

data are represented as 32-bit hexadecimal strings in order to accelerate IO operations on the encrypted block.

plains

Hexadecimal plain data of each trace.

Type

list[str]

ciphers

Hexadecimal cipher data of each trace.

Type

list[str]

keys

Hexadecimal key data of each trace.

Type

list[str]

Raises

ValueError – If the three list attributes does not have the same length.

STR_MAX_LINES = 32
clear()

Clears all the attributes.

append(item)

S.append(value) – append value to the end of the sequence

pop([index])item remove and return item at index (default last).

Raise IndexError if list is empty or index is out of range.

insert(index: int, item)

S.insert(index, value) – insert value before index

write_csv(path, append=False)

Exports encryption data to a CSV file.

Parameters
  • path (str) – Path to the CSV file to write.

  • append (bool, optional) – True to append the data to an existing file.

read_csv(path=None, count=None, start=0)
class src.lib.data.Leak(path=None, count=None, start=0)

Bases: collections.abc.MutableSequence, collections.abc.Reversible, collections.abc.Sized, src.lib.data.Serializable, src.lib.data.Deserializable

Side-channel leakage data.

This class represents the power consumption traces acquired during encryption in order to process these.

samples

Count of samples for each traces.

Type

list[int]

traces

Power consumption leakage signal for each acquisition.

Type

list[list[int]]

STR_MAX_LINES = 32
clear()None remove all items from S
append(item)

S.append(value) – append value to the end of the sequence

pop([index])item remove and return item at index (default last).

Raise IndexError if list is empty or index is out of range.

insert(index, item)

S.insert(index, value) – insert value before index

write_csv(path, append=False)

Exports leakage data to CSV.

Parameters
  • path (str) – Path to the CSV file to write.

  • append (bool, optional) – True to append the data to an existing file.

read_csv(path, count=None, start=0)
class src.lib.data.Meta(path=None, count=None, start=0)

Bases: src.lib.data.Serializable, src.lib.data.Deserializable

Meta-data of acquisition.

This class is designed to represent additional infos about the current side-channel acquisition run.

modestr

Encryption mode.

directionstr

Encryption direction, either encrypt or decrypt.

targetint

Sensors calibration target value.

sensorsint

Count of sensors.

iterationsint

Requested count of traces.

offsetint

If the traces are ASCII encoded, code offset

clear()

Resets meta-data.

write_csv(path, append=False)

Exports meta-data to a CSV file.

Parameters
  • path (str) – Path to the CSV file to write.

  • append (bool, optional) –

read_csv(path, count=None, start=0)
class src.lib.data.Request(args=None)

Bases: object

Data processing request.

This class provides a simple abstraction to wrap file naming arguments during acquisition, import or export.

The these arguments combined together form a data request specifying all the characteristics of the target data-set.

target

Serial port id or file prefix according to the source mode.

Type

str

iterations

Requested count of traces.

Type

int

mode

Encryption mode.

Type

str

direction

Encrypt direction.

Type

str

source

Source mode.

Type

str

verbose

True to perform verbose acquisition.

Type

True

chunks

Count of chunks to acquire or None if not performing chunk acquisition

Type

int, optional

ACQ_CMD_NAME = 'sca'
class Algos(value)

Bases: enum.Enum

An enumeration.

AES = 'aes'
PRESENT = 'present'
KLEIN = 'klein'
CRYPTON = 'crypton'
class Modes(value)

Bases: enum.Enum

An enumeration.

HARDWARE = 'hw'
TINY = 'tiny'
OPENSSL = 'ssl'
DHUERTAS = 'dhuertas'
PRESENT = 'present'
KLEIN = 'klein'
CRYPTON = 'crypton'
class Directions(value)

Bases: enum.Enum

An enumeration.

ENCRYPT = 'enc'
DECRYPT = 'dec'
filename(prefix=None, suffix='')

Creates a filename based on the request.

This method allows to consistently name the files according to request’s characteristics.

Parameters
  • prefix (str) – Prefix of the filename.

  • suffix (str, optional) – Suffix of the filename.

Returns

The complete filename.

Return type

str

command(name)
property total
requested(chunk=None)
class src.lib.data.Keywords(meta=False, inv=False, verbose=False, noise=False)

Bases: object

Iterates over the binary log keywords.

This iterator allows to represent the keywords and the order in which they appear in the binary log consistently.

This feature is useful when parsing log lines in order to avoid inserting a sequence that came in the wrong order.

At each iteration the next expected keyword is returned.

meta attribute allows to avoid expect again meta keywords when an error occurs and the iterator must be reset.

idx

Current keyword index.

Type

int

meta

True if the meta-data keyword have already been browsed.

Type

bool

inv

True if the keywords follow the inverse encryption sequence.

Type

bool

metawords

Keywords displayed once at the beginning of acquisition.

Type

str

datawords

Keywords displayed recurrently during each trace acquisition.

Type

str

value

Value of the current keyword.

Type

str

MODE = 'mode'
DIRECTION = 'direction'
SENSORS = 'sensors'
TARGET = 'target'
KEY = 'keys'
PLAIN = 'plains'
CIPHER = 'ciphers'
SAMPLES = 'samples'
CODE = 'code'
WEIGHTS = 'weights'
OFFSET = 'offset'
ITERATIONS = 'iterations'
DELIMITER = b':'
START_RAW_TAG = b'\xfd\xfd\xfd\xfd'
START_TRACE_TAG = b'\xfe\xfe\xfe\xfe'
END_ACQ_TAG = b'\xff\xff\xff\xff'
END_LINE_TAG = b';;\n'
reset(meta=None)
all()
class src.lib.data.Parser(s=b'', direction=<Directions.ENCRYPT: 'enc'>, noise=False, verbose=False)

Bases: object

Binary data parser.

This class is designed to parse binary acquisition data and store parsed data in the entity classes in order to later import and export it.

leak

Leakage data.

Type

Leak

channel

Encryption data.

Type

Channel

meta

Meta-data.

Type

Meta

See also

Keywords

iterator representing the keyword sequence

pop()

Pops acquired value until data lengths matches.

This method allows to guarantee that the data contained in the parser will always have the same length which is the number of traces parsed.

Returns

Reference to self.

Return type

Parser

clear()

Clears all the parser data.

parse(s, direction=<Directions.ENCRYPT: 'enc'>, noise=False, verbose=False, warns=False)

Parses the given bytes to retrieve acquisition data.

If inv`` is not specified the parser will infer the encryption direction from s.

Parameters
  • s (bytes) – Binary data.

  • noise (bool) – True if noise traces must be acquired before crypto-traces.

  • direction (str) – Encryption direction.

Returns

Reference to self.

Return type

Parser

lib.traces module

Perform signal processing on power consumption traces.

This module is designed to provide fast signal processing function for power consumption signals.

class src.lib.traces.Statistics(leak=None, filters=None, noise=None)

Bases: object

update(leak, filters=None, noise=None)
clear()
src.lib.traces.crop(traces, end=None)

Crops all the traces signals to have the same duration.

If end parameter is not provided the traces are cropped to have the same duration as the shortest given trace.

Parameters
  • traces (list[list[int]]) – 2D list of numbers representing the trace signal.

  • end (int, optional) – Index after which the traces are truncated. Must be inferior to the length of the shortest trace.

Returns

Cropped traces.

Return type

list[list[int]]

src.lib.traces.pad(traces, fill=0, end=None)

Pads all the traces signals have the same duration.

If end parameter is not provided the traces are padded to have the same duration as the longest given trace.

Parameters
  • traces (list[list[int]]) – 2D list of numbers representing the trace signal.

  • fill (int, optional) – Padding value to insert after the end of traces.

  • end (int, optional) – New count of samples of the traces. Must be greater than the length of the longest trace.

Returns

Padded traces.

Return type

list[list[int]]

src.lib.traces.adjust(traces, n=None, fill=0)
src.lib.traces.sync(traces, step=1, stop=None)

Synchronize trace signals by correlating them

WARNING: this method may cause segfault when the memory adjacent to traces cannot be used

This function implements an algorithm based on Pearson’s correlation to synchronize signals peaks.

More precisely, it compares the traces to a reference trace by rolling theses forward or backward. The algorithm search for the roll value that maximizes pearson correlation.

Parameters
  • traces (np.ndarray) – 2D numbers array representing cropped or padded traces data.

  • step (int, optional) – Rolling step, if equals n, the trace will be rolled n times in both directions at each rolling iteration.

  • stop (int, optional) – Rolling stop, maximum roll to perform.

Returns

2D array representing synchronized traces.

Return type

np.ndarray