rusTkey ("rusty key")
A library for developing bare-bones applications for the tillitis TKey in rust.
warning this library is still in development. There may be API-breaking changes in the future.
The crate provides:
- basic set-up for a new rust-based TKey application,
- functions to interact with the TKey device (encapsulating
unsafeoperations),
This library and the proposed set-up is chosen to keep things simple. The set-up itself requires no external dependencies and the linker-script and initial assembly-code are almost exactly as provided by tillitis.
note a few points of attention:
random(out, seed)is not yet sufficiently mature. It is based on a persistent buffer of random bytes and 4-byte input from TRNG. Until new entropy is available, currently sampled entropy is used to derive new unpredictable bits. There is undoubtedly room for improvement.rusTkeywill panic in case of improper use: there is no point in obscuring or working around incorrect uses. There is more risk in making things seem okay. Instead, assertions and panics will signal improper use (or a bug in rusTkey).
Changes
0.5.0
Backwards-incompatible
- BLAKE2s (
rustkey::blake2s) as stand-alone implementation. (Sourced from RustCrypto/hashes.) Use of this implementation saves about 3.5 KiB (~50%, 3536 bytes vs 7376 bytes) compared to use of a dependency. An upcoming version of Tillitis TKey will drop access toblake2sin firmware. Consequently, programs will need to provide their own implementation for these newer models. - Feature
blake2-firmwareredirects functionrustkey::blake2s(..)to firmware instead of standalone implementation. - Feature
blake2-standaloneenables/exposes the BLAKE2s stand-alone modulerustkey::blake2s. - Defaults
blake2-standaloneis enabled by default. Forblake2sin firmware, also enableblake2-firmware. This is not enabled by default to ensure output binaries work on all models. Fine-tuning the configuration later would result in nett benefit. - rusTkey library will prefer BLAKE2s from firmware if
blake2-firmwareis enabled, but will defer to standalone-implementation otherwise. - Test-binary
testblake2fw.bin(seesrc/testblake2fw.rs) compares BLAKE2s digests from firmware and stand-alone implementation. (Will only work on device models that makeblake2sin firmware available.) - note the function signature for
rustkey::blake2s(..)has changed to accomodate for swapping BLAKE2s implementations and because parametric types do not allow for dynamically (non-const) specifying digest output size.
0.4.3
- Linker-script: move
.eh_framefrom.textto/DISCARD/section.
This solves, by override, the problem that even though rust is instructed to abort on panic, the build-toolchain still demands presence of.eh_frame. Dropping.eh_framefurther reduces program-binary size. (Inspired by TKey-support contributions to TinyGo.) - Fix: incorrect end address for firmware ROM.
0.4.2
- Change license to 2-Clause BSD License, from GPL-2.0 only. This follows the recent license change by Tillitis.
hash_firmware_rom(key)for calculating a hash of the TKey device's firmware-ROM. It computes a hash over the complete available ROM-space. (Experimental)
0.4.1
cpumonitor::monitor_application_memory: fix address of "last" in monitoring range.
0.4.0
- Module
io:- Added functions for controlled reading:
read_available,read_into_checked,read_into_timed,read_into_limited,read_checked,read_timed. - Change
available()to returnusize, which is the more appropriate data-type for what it represents. - Added
configuration(),configure(bitrate, data_bits, stop_bits)for configuring UART I/O operation. See documentation for parameter specifics.bitrateis expressed in the representation used by the device.
- Added functions for controlled reading:
rustkey::Error: added variantsUnderrunandTimeoutused by controlled-read functions.timer::PRESCALE_MILLISECONDS, also used for timed-read functions.rustkey::TK1_CPU_FREQUENCYas the CPU frequency of the TKey1.
0.3.1
rustkey::random: proper unsafe access to buffer without using&mut(static_mut_refs)
0.3.0
rustkey::random: remix existing TRNG entropy if TRNG is not yet ready. Given TRNG's rate of approx. 66.6 times per second, this improves performance.- Renamed
benchfrombench_trng, as it tests a few more aspects of TKey. - Moved changelog into
README.mdfromCHANGELOG.md, to make it available wherever the README is readable.
0.2.0
- Module
cpumonitor:monitor_rangeallowfirstandlastto be same address. - Module
timer:- provide
PRESCALE_SECONDSprescaler constant. - provide
sleepfor timer-based blocking sleep in seconds.
- provide
- Module
touch: tweak, improverequest. - Module
trng:- comment on production-rate of entropy
- add
read_next, renameread_next_bytestoread_bytes_next.
- Module
frameprovidesLENGTH_MAXfor maximum length of frame according to the protocol. ErrorderivesDebugtrait.README.md: comments documenting some configuration options, ref for minimizing rust binaries, clean-up.bench_trng: application used to perform repeated sampling of TRNG entropy for purpose of testing performance. Seems to be stable at approximately 66.6 samples per second.
0.1.0
Initial release.
Open issues
These are known open issues.
cargo buildwarns of an unstable feature. Maybe we should file an issue for this.cargo build --release --bins warning: unknown and unstable feature specified for `-Ctarget-feature`: `zmmul` | = note: it is still passed through to the codegen backend, but use of this feature might be unsound and the behavior of this feature can change in the future = help: consider filing a feature request
Apart from items listed here, I leave TODO comments for things that need to be considered, even if they turn out to be irrelevant.
Decisions
- No heap/dynamic memory allocation (for now).
- use crate 'heapless' for some data structures implementation on stack.
- Not thread-safe (not needed until
stdor customized threading). - No use of dependencies w.r.t. bootstrapping the execution (such as rust-embedded/riscv):
- adds a layer of intransparency, non-straightforward logic.
- more comprehensive initialization which addresses features that are not supported, performing initialization that is not needed.
- instead, when initializing in global assembly, execution from entry-point (linker-script) to initialization to
mainis obvious.
- Incorrect use of the functions may result in panic.
- Implementations (in rare cases) may change.
For example, ifrandomcan be improved within reasonable constraints.
Getting started
The following describes the application set-up needed to build app binaries for loading onto the TKey.
The following steps are required:
- Configure the build for
riscv32i-unknown-none-elf, with additional CPU features 'c' (compressed instructions) and 'Zmmul' (multiplication instructions only, i.e. not division). Other build-options contribute to a smaller binary such that it fits in 128 KiB of memory. - Apply a suitable linker-script.
- Create an entry-point that performs basic initialization of the TKey device for the application.
- Use
llvm-objcopyto create the raw bare-bones application binary for the tillitis TKey. - The application:
src/main.rsis an example that uses this set-up and demonstrates a working TKey-app.
Configure the build
The build target riscv32i-unknown-none-elf must be available in the rust ecosystem.
The following build configuration enables the necessary features and options.
.cargo/config.toml:
[]
= "riscv32i-unknown-none-elf"
[]
= "abort"
[]
= 1 # No parallelism, may increase ability to optimize.
= false # Do not produce a debug-build.
= false # Drop debug-assertions.
= 3 # Perform a high level of optimization, also 'z' to specifically target size.
= false
= true # Currently translates to 'strip = "symbols"', i.e. strip all excess information.
= true # Perform link-time optimization, to further optimize and reduce binary size.
= "abort"
[]
= [
"-Ctarget-feature=+c,+zmmul",
"-Ccode-model=medium",
"-Cpanic=abort",
"-Crelocation-model=pic",
"-Clink-arg=-Tapp.lds",
]
This configuration applies to --release builds.
Note: the panic settings should obviate the need for .eh_frame section in the linker-script, but this is not currently the case.
Linker-script
The following linker-script defines the memory region for the TKey.
Changes to the original linker-script:
- defining
_stack_startsymbol such that this address can be modified outside of assembly-code. _stack_startis assigned a different value: 'ORIGIN(RAM)+LENGTH(RAM)' from the original value '0x4001fff0'. The original value is slightly lower, which I suspect is unnecessary given that the stack-pointer is manipulated before use. (issue)- added
*(.eh_frame)in a region/DISCARD/.
This should not be necessary, becausepanic=abortshould obviate the need for.eh_framesection according to many references. Adding.eh_framein region/DISCARD/instructs the linker to discard.eh_framesection.
If a strategy other thanpanic=abortis used,.eh_framemay need to move to section.text.
/*
* SPDX-FileCopyrightText: 2022 Tillitis AB <tillitis.se>
* SPDX-License-Identifier: BSD-2-Clause
*
* Modified for rusTkey. (See README.md for details.)
*/
OUTPUT_ARCH( "riscv" )
ENTRY(_start)
MEMORY
{
RAM (rwx) : ORIGIN = 0x40000000, LENGTH = 0x20000 /* 128 KB */
}
SECTIONS
{
.text.init :
{
*(.text.init)
} >RAM
.text :
{
. = ALIGN(4);
*(.text) /* .text sections (code) */
*(.text*) /* .text* sections (code) */
*(.rodata) /* .rodata sections (constants, strings, etc.) */
*(.rodata*) /* .rodata* sections (constants, strings, etc.) */
*(.srodata) /* .rodata sections (constants, strings, etc.) */
*(.srodata*) /* .rodata* sections (constants, strings, etc.) */
. = ALIGN(4);
_etext = .;
_sidata = _etext;
} >RAM
.data : AT (_etext)
{
. = ALIGN(4);
_sdata = .;
. = ALIGN(4);
*(.data) /* .data sections */
*(.data*) /* .data* sections */
*(.sdata) /* .sdata sections */
*(.sdata*) /* .sdata* sections */
. = ALIGN(4);
_edata = .;
} >RAM
/* Uninitialized data section */
.bss :
{
. = ALIGN(4);
_sbss = .;
*(.bss)
*(.bss*)
*(.sbss)
*(.sbss*)
*(COMMON)
. = ALIGN(4);
_ebss = .;
} >RAM
/* `panic=abort` does not require `.eh_frame`. */
/DISCARD/ :
{
*(.eh_frame)
}
}
_stack_start = ORIGIN(RAM) + LENGTH(RAM);
Create an entry-point
The following (global) assembly-code create the entry-point _start at which the device is initialized for the loaded application, after which function main is called.
The response of the device on returning from 'main' seems to deviate based on the optimization-level of the application binary. It is best to define main as '#[no_mangle] extern "C" fn main() -> !', i.e. non-returning as to avoid running into this situation.
Changes to the original assembly-code:
- to expect symbol
_stack_startto be defined in the linker-script for initialization of the stack-pointer.
// Note: this assembly provides the initialization procedure that clears memory and finally calls
// `main` to start execution of the app-binary.
global_asm!;
Create the raw application-binary
Use 'llvm-objcopy --input-target=elf32-littleriscv --output-target=binary target/riscv32i-unknown-none-elf/release/example example.bin' to produce the raw binary data for loading onto the TKey.
The application
At this point, the set-up is done up to entering the application at function main.
There are a few recommendations:
- '
#![no_std]' to prevent standard library from being included. This also means thatstd::*is unavailable, although most primitive functions can also be found atcore::*. - '
#![no_main]' to indicate that we provide our own entry-point into the application - '
#[no_mangle] extern "C" fn main() -> !' as our definition for main, such that:maincan be found after initialization,#[no_mangle] extern "C"to ensure availability under the expected, unchanged function-name,- non-returning, to avoid running into undefined behavior and/or making the device unavailable.
- need to define a
#[panic_handler], given that the run-time is minimized. - heapless provides static-friendly data-structures that do not require dynamic memory allocation.
An basic example src/main.rs can be found in this code-base.
Alternative
An alternative approach, is to use a #![feature(start)] macro with #[start] annotated fn main(). This is currently only possible if Rust nightly features are activated. This, together with appropriate build configuration to ensure that main as a function is available in unmangled form, is sufficient get the application to run. Unfortunately, this does not resolve the issue with .eh_frame described above.
For now, this crate will keep using the global_asm! macro in an application. This creates a straight-forward path from linker-script (app.lds) to global assembly (_start) to calling main(). This also leaves open possibilities for a call to a set-up of stack-protector and other security-features that need early initialization, with everything concentrated within the application.
LICENSE
Copyright 2024 D. van Heumen
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
See LICENSE for the full license.
References
- Minimizing Rust Binary Size
- Note to self: Last evaluated: 66a1fd90eead93d9e0472a3a1a88e185ae8c1761
- Some references discussing dynamic memory allocation. (Not currently in use.)
- Embedded RiscV (riscv, riscv-rt, etc.) code-base
- Heap Allocation