Merge branch 'trezor-storage-integration'

pull/25/head
Pavol Rusnak 5 years ago
commit 6d817a813d
No known key found for this signature in database
GPG Key ID: 91F3B339B9A02A3D

3
.gitmodules vendored

@ -13,3 +13,6 @@
[submodule "vendor/nanopb"]
path = vendor/nanopb
url = https://github.com/nanopb/nanopb.git
[submodule "vendor/trezor-storage"]
path = vendor/trezor-storage
url = https://github.com/trezor/trezor-storage.git

@ -175,6 +175,12 @@ flash_combine: $(PRODTEST_BUILD_DIR)/combined.bin ## flash combined using OpenOC
flash_erase: ## erase all sectors in flash bank 0
$(OPENOCD) -c "init; reset halt; flash info 0; flash erase_sector 0 0 last; flash erase_check 0; exit"
flash_read_storage: ## read storage sectors from flash
$(OPENOCD) -c "init; flash read_bank 0 storage1.data 0x10000 65536; flash read_bank 0 storage2.data 0x110000 65536; exit"
flash_erase_storage: ## erase storage sectors from flash
$(OPENOCD) -c "init; flash erase_sector 0 4 4; flash erase_sector 0 16 16; exit"
## openocd debug commands:
openocd: ## start openocd which connects to the device

@ -10,10 +10,14 @@ SOURCE_MOD = []
PYOPT = '1'
# modtrezorconfig
CPPPATH_MOD += [
'embed/extmod/modtrezorconfig',
'vendor/trezor-storage',
]
SOURCE_MOD += [
'embed/extmod/modtrezorconfig/modtrezorconfig.c',
'embed/extmod/modtrezorconfig/norcow.c',
'embed/extmod/modtrezorconfig/storage.c',
'vendor/trezor-storage/norcow.c',
'vendor/trezor-storage/storage.c',
]
# modtrezorcrypto

@ -9,10 +9,14 @@ SOURCE_MOD = []
LIBS_MOD = []
# modtrezorconfig
CPPPATH_MOD += [
'embed/extmod/modtrezorconfig',
'vendor/trezor-storage',
]
SOURCE_MOD += [
'embed/extmod/modtrezorconfig/modtrezorconfig.c',
'embed/extmod/modtrezorconfig/norcow.c',
'embed/extmod/modtrezorconfig/storage.c',
'vendor/trezor-storage/norcow.c',
'vendor/trezor-storage/storage.c',
]
# modtrezorcrypto

@ -133,7 +133,7 @@ static secbool copy_sdcard(void)
}
display_printf(" done\n\n");
ensure(flash_unlock(), NULL);
ensure(flash_unlock_write(), NULL);
// copy bootloader from SD card to Flash
display_printf("copying new bootloader from SD card\n\n");
@ -149,7 +149,7 @@ static secbool copy_sdcard(void)
}
sdcard_power_off();
ensure(flash_lock(), NULL);
ensure(flash_lock_write(), NULL);
display_printf("\ndone\n\n");
display_printf("Unplug the device and remove the SD card\n");

@ -517,14 +517,14 @@ int process_msg_FirmwareUpload(uint8_t iface_num, uint32_t msg_size, uint8_t *bu
return -6;
}
ensure(flash_unlock(), NULL);
ensure(flash_unlock_write(), NULL);
const uint32_t * const src = (const uint32_t * const)chunk_buffer;
for (int i = 0; i < chunk_size / sizeof(uint32_t); i++) {
ensure(flash_write_word(firmware_sectors[firmware_block], i * sizeof(uint32_t), src[i]), NULL);
}
ensure(flash_lock(), NULL);
ensure(flash_lock_write(), NULL);
firmware_remaining -= chunk_requested;
firmware_block++;

@ -26,13 +26,18 @@
#include "embed/extmod/trezorobj.h"
#include "storage.h"
#include "common.h"
#include "memzero.h"
STATIC mp_obj_t ui_wait_callback = mp_const_none;
STATIC void wrapped_ui_wait_callback(uint32_t wait, uint32_t progress) {
STATIC secbool wrapped_ui_wait_callback(uint32_t wait, uint32_t progress) {
if (mp_obj_is_callable(ui_wait_callback)) {
mp_call_function_2(ui_wait_callback, mp_obj_new_int(wait), mp_obj_new_int(progress));
if (mp_call_function_2(ui_wait_callback, mp_obj_new_int(wait), mp_obj_new_int(progress)) == mp_const_true) {
return sectrue;
}
}
return secfalse;
}
/// def init(ui_wait_callback: (int, int -> None)=None) -> None:
@ -43,10 +48,11 @@ STATIC void wrapped_ui_wait_callback(uint32_t wait, uint32_t progress) {
STATIC mp_obj_t mod_trezorconfig_init(size_t n_args, const mp_obj_t *args) {
if (n_args > 0) {
ui_wait_callback = args[0];
storage_init(wrapped_ui_wait_callback);
storage_init(wrapped_ui_wait_callback, HW_ENTROPY_DATA, HW_ENTROPY_LEN);
} else {
storage_init(NULL);
storage_init(NULL, HW_ENTROPY_DATA, HW_ENTROPY_LEN);
}
memzero(HW_ENTROPY_DATA, sizeof(HW_ENTROPY_DATA));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_init_obj, 0, 1, mod_trezorconfig_init);
@ -57,7 +63,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_init_obj, 0, 1, mod_
/// '''
STATIC mp_obj_t mod_trezorconfig_check_pin(mp_obj_t pin) {
uint32_t pin_i = trezor_obj_get_uint(pin);
if (sectrue != storage_check_pin(pin_i)) {
if (sectrue != storage_unlock(pin_i)) {
return mp_const_false;
}
return mp_const_true;
@ -78,6 +84,16 @@ STATIC mp_obj_t mod_trezorconfig_unlock(mp_obj_t pin) {
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorconfig_unlock_obj, mod_trezorconfig_unlock);
/// def lock() -> None:
/// '''
/// Locks the storage.
/// '''
STATIC mp_obj_t mod_trezorconfig_lock(void) {
storage_lock();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorconfig_lock_obj, mod_trezorconfig_lock);
/// def has_pin() -> bool:
/// '''
/// Returns True if storage has a configured PIN, False otherwise.
@ -90,6 +106,15 @@ STATIC mp_obj_t mod_trezorconfig_has_pin(void) {
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorconfig_has_pin_obj, mod_trezorconfig_has_pin);
/// def get_pin_rem() -> int:
/// '''
/// Returns the number of remaining PIN entry attempts.
/// '''
STATIC mp_obj_t mod_trezorconfig_get_pin_rem(void) {
return mp_obj_new_int_from_uint(storage_get_pin_rem());
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorconfig_get_pin_rem_obj, mod_trezorconfig_get_pin_rem);
/// def change_pin(pin: int, newpin: int) -> bool:
/// '''
/// Change PIN. Returns True on success, False on failure.
@ -106,21 +131,30 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorconfig_change_pin_obj, mod_trezorconf
/// def get(app: int, key: int, public: bool=False) -> bytes:
/// '''
/// Gets a value of given key for given app (or empty bytes if not set).
/// Gets the value of the given key for the given app (or None if not set).
/// Raises a RuntimeError if decryption or authentication of the stored value fails.
/// '''
STATIC mp_obj_t mod_trezorconfig_get(size_t n_args, const mp_obj_t *args) {
uint8_t app = trezor_obj_get_uint8(args[0]) & 0x7F;
uint8_t app = trezor_obj_get_uint8(args[0]) & 0x3F;
uint8_t key = trezor_obj_get_uint8(args[1]);
if (n_args > 2 && args[2] == mp_const_true) {
app |= 0x80;
}
uint16_t appkey = (app << 8) | key;
uint16_t len = 0;
const void *val;
if (sectrue != storage_get(appkey, &val, &len) || len == 0) {
if (sectrue != storage_get(appkey, NULL, 0, &len)) {
return mp_const_none;
}
if (len == 0) {
return mp_const_empty_bytes;
}
return mp_obj_new_bytes(val, len);
vstr_t vstr;
vstr_init_len(&vstr, len);
if (sectrue != storage_get(appkey, vstr.buf, vstr.len, &len)) {
vstr_clear(&vstr);
mp_raise_msg(&mp_type_RuntimeError, "Failed to get value from storage.");
}
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_get_obj, 2, 3, mod_trezorconfig_get);
@ -129,7 +163,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_get_obj, 2, 3, mod_t
/// Sets a value of given key for given app.
/// '''
STATIC mp_obj_t mod_trezorconfig_set(size_t n_args, const mp_obj_t *args) {
uint8_t app = trezor_obj_get_uint8(args[0]) & 0x7F;
uint8_t app = trezor_obj_get_uint8(args[0]) & 0x3F;
uint8_t key = trezor_obj_get_uint8(args[1]);
if (n_args > 3 && args[3] == mp_const_true) {
app |= 0x80;
@ -144,6 +178,72 @@ STATIC mp_obj_t mod_trezorconfig_set(size_t n_args, const mp_obj_t *args) {
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_set_obj, 3, 4, mod_trezorconfig_set);
/// def delete(app: int, key: int, public: bool=False) -> bool:
/// '''
/// Deletes the given key of the given app.
/// '''
STATIC mp_obj_t mod_trezorconfig_delete(size_t n_args, const mp_obj_t *args) {
uint8_t app = trezor_obj_get_uint8(args[0]) & 0x3F;
uint8_t key = trezor_obj_get_uint8(args[1]);
if (n_args > 2 && args[2] == mp_const_true) {
app |= 0x80;
}
uint16_t appkey = (app << 8) | key;
if (sectrue != storage_delete(appkey)) {
return mp_const_false;
}
return mp_const_true;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_delete_obj, 2, 3, mod_trezorconfig_delete);
/// def set_counter(app: int, key: int, count: int, writable_locked: bool=False) -> bool:
/// '''
/// Sets the given key of the given app as a counter with the given value.
/// '''
STATIC mp_obj_t mod_trezorconfig_set_counter(size_t n_args, const mp_obj_t *args) {
uint8_t app = trezor_obj_get_uint8(args[0]) & 0x3F;
uint8_t key = trezor_obj_get_uint8(args[1]);
if (n_args > 3 && args[3] == mp_const_true) {
app |= 0xC0;
} else {
app |= 0x80;
}
uint16_t appkey = (app << 8) | key;
if (args[2] == mp_const_none) {
if (sectrue != storage_delete(appkey)) {
return mp_const_false;
}
} else {
uint32_t count = trezor_obj_get_uint(args[2]);
if (sectrue != storage_set_counter(appkey, count)) {
return mp_const_false;
}
}
return mp_const_true;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_set_counter_obj, 3, 4, mod_trezorconfig_set_counter);
/// def next_counter(app: int, key: int, writable_locked: bool=False) -> bool:
/// '''
/// Increments the counter stored under the given key of the given app and returns the new value.
/// '''
STATIC mp_obj_t mod_trezorconfig_next_counter(size_t n_args, const mp_obj_t *args) {
uint8_t app = trezor_obj_get_uint8(args[0]) & 0x3F;
uint8_t key = trezor_obj_get_uint8(args[1]);
if (n_args > 2 && args[2] == mp_const_true) {
app |= 0xC0;
} else {
app |= 0x80;
}
uint16_t appkey = (app << 8) | key;
uint32_t count = 0;
if (sectrue != storage_next_counter(appkey, &count)) {
return mp_const_none;
}
return mp_obj_new_int_from_uint(count);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_next_counter_obj, 2, 3, mod_trezorconfig_next_counter);
/// def wipe() -> None:
/// '''
/// Erases the whole config. Use with caution!
@ -159,10 +259,15 @@ STATIC const mp_rom_map_elem_t mp_module_trezorconfig_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&mod_trezorconfig_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_check_pin), MP_ROM_PTR(&mod_trezorconfig_check_pin_obj) },
{ MP_ROM_QSTR(MP_QSTR_unlock), MP_ROM_PTR(&mod_trezorconfig_unlock_obj) },
{ MP_ROM_QSTR(MP_QSTR_lock), MP_ROM_PTR(&mod_trezorconfig_lock_obj) },
{ MP_ROM_QSTR(MP_QSTR_has_pin), MP_ROM_PTR(&mod_trezorconfig_has_pin_obj) },
{ MP_ROM_QSTR(MP_QSTR_get_pin_rem), MP_ROM_PTR(&mod_trezorconfig_get_pin_rem_obj) },
{ MP_ROM_QSTR(MP_QSTR_change_pin), MP_ROM_PTR(&mod_trezorconfig_change_pin_obj) },
{ MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&mod_trezorconfig_get_obj) },
{ MP_ROM_QSTR(MP_QSTR_set), MP_ROM_PTR(&mod_trezorconfig_set_obj) },
{ MP_ROM_QSTR(MP_QSTR_delete), MP_ROM_PTR(&mod_trezorconfig_delete_obj) },
{ MP_ROM_QSTR(MP_QSTR_set_counter), MP_ROM_PTR(&mod_trezorconfig_set_counter_obj) },
{ MP_ROM_QSTR(MP_QSTR_next_counter), MP_ROM_PTR(&mod_trezorconfig_next_counter_obj) },
{ MP_ROM_QSTR(MP_QSTR_wipe), MP_ROM_PTR(&mod_trezorconfig_wipe_obj) },
};
STATIC MP_DEFINE_CONST_DICT(mp_module_trezorconfig_globals, mp_module_trezorconfig_globals_table);

@ -1,305 +0,0 @@
/*
* This file is part of the TREZOR project, https://trezor.io/
*
* Copyright (c) SatoshiLabs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include "norcow.h"
#include "flash.h"
#include "common.h"
// NRCW = 4e524357
#define NORCOW_MAGIC ((uint32_t)0x5743524e)
#define NORCOW_MAGIC_LEN (sizeof(uint32_t))
static const uint8_t norcow_sectors[NORCOW_SECTOR_COUNT] = NORCOW_SECTORS;
static uint8_t norcow_active_sector = 0;
static uint32_t norcow_active_offset = NORCOW_MAGIC_LEN;
/*
* Returns pointer to sector, starting with offset
* Fails when there is not enough space for data of given size
*/
static const void *norcow_ptr(uint8_t sector, uint32_t offset, uint32_t size)
{
ensure(sectrue * (sector <= NORCOW_SECTOR_COUNT), "invalid sector");
return flash_get_address(norcow_sectors[sector], offset, size);
}
/*
* Writes data to given sector, starting from offset
*/
static secbool norcow_write(uint8_t sector, uint32_t offset, uint32_t prefix, const uint8_t *data, uint16_t len)
{
if (sector >= NORCOW_SECTOR_COUNT) {
return secfalse;
}
ensure(flash_unlock(), NULL);
// write prefix
ensure(flash_write_word(norcow_sectors[sector], offset, prefix), NULL);
if (len > 0) {
offset += sizeof(uint32_t);
// write data
for (uint16_t i = 0; i < len; i++, offset++) {
ensure(flash_write_byte(norcow_sectors[sector], offset, data[i]), NULL);
}
// pad with zeroes
for (; offset % 4; offset++) {
ensure(flash_write_byte(norcow_sectors[sector], offset, 0x00), NULL);
}
}
ensure(flash_lock(), NULL);
return sectrue;
}
/*
* Erases sector (and sets a magic)
*/
static void norcow_erase(uint8_t sector, secbool set_magic)
{
ensure(sectrue * (sector <= NORCOW_SECTOR_COUNT), "invalid sector");
ensure(flash_erase_sector(norcow_sectors[sector]), "erase failed");
if (sectrue == set_magic) {
ensure(norcow_write(sector, 0, NORCOW_MAGIC, NULL, 0), "set magic failed");
}
}
#define ALIGN4(X) (X) = ((X) + 3) & ~3
/*
* Reads one item starting from offset
*/
static secbool read_item(uint8_t sector, uint32_t offset, uint16_t *key, const void **val, uint16_t *len, uint32_t *pos)
{
*pos = offset;
const void *k = norcow_ptr(sector, *pos, 2);
if (k == NULL) return secfalse;
*pos += 2;
memcpy(key, k, sizeof(uint16_t));
if (*key == 0xFFFF) {
return secfalse;
}
const void *l = norcow_ptr(sector, *pos, 2);
if (l == NULL) return secfalse;
*pos += 2;
memcpy(len, l, sizeof(uint16_t));
*val = norcow_ptr(sector, *pos, *len);
if (*val == NULL) return secfalse;
*pos += *len;
ALIGN4(*pos);
return sectrue;
}
/*
* Writes one item starting from offset
*/
static secbool write_item(uint8_t sector, uint32_t offset, uint16_t key, const void *val, uint16_t len, uint32_t *pos)
{
uint32_t prefix = (len << 16) | key;
*pos = offset + sizeof(uint32_t) + len;
ALIGN4(*pos);
return norcow_write(sector, offset, prefix, val, len);
}
/*
* Finds item in given sector
*/
static secbool find_item(uint8_t sector, uint16_t key, const void **val, uint16_t *len)
{
*val = 0;
*len = 0;
uint32_t offset = NORCOW_MAGIC_LEN;
for (;;) {
uint16_t k, l;
const void *v;
uint32_t pos;
if (sectrue != read_item(sector, offset, &k, &v, &l, &pos)) {
break;
}
if (key == k) {
*val = v;
*len = l;
}
offset = pos;
}
return sectrue * (*val != NULL);
}
/*
* Finds first unused offset in given sector
*/
static uint32_t find_free_offset(uint8_t sector)
{
uint32_t offset = NORCOW_MAGIC_LEN;
for (;;) {
uint16_t key, len;
const void *val;
uint32_t pos;
if (sectrue != read_item(sector, offset, &key, &val, &len, &pos)) {
break;
}
offset = pos;
}
return offset;
}
/*
* Compacts active sector and sets new active sector
*/
static void compact()
{
uint8_t norcow_next_sector = (norcow_active_sector + 1) % NORCOW_SECTOR_COUNT;
norcow_erase(norcow_next_sector, sectrue);
uint32_t offset = NORCOW_MAGIC_LEN, offsetw = NORCOW_MAGIC_LEN;
for (;;) {
// read item
uint16_t k, l;
const void *v;
uint32_t pos;
secbool r = read_item(norcow_active_sector, offset, &k, &v, &l, &pos);
if (sectrue != r) {
break;
}
offset = pos;
// check if not already saved
const void *v2;
uint16_t l2;
r = find_item(norcow_next_sector, k, &v2, &l2);
if (sectrue == r) {
continue;
}
// scan for latest instance
uint32_t offsetr = offset;
for (;;) {
uint16_t k2;
uint32_t posr;
r = read_item(norcow_active_sector, offsetr, &k2, &v2, &l2, &posr);
if (sectrue != r) {
break;
}
if (k == k2) {
v = v2;
l = l2;
}
offsetr = posr;
}
// copy the last item
uint32_t posw;
ensure(write_item(norcow_next_sector, offsetw, k, v, l, &posw), "compaction write failed");
offsetw = posw;
}
norcow_erase(norcow_active_sector, secfalse);
norcow_active_sector = norcow_next_sector;
norcow_active_offset = find_free_offset(norcow_active_sector);
}
/*
* Initializes storage
*/
void norcow_init(void)
{
flash_init();
secbool found = secfalse;
// detect active sector - starts with magic
for (uint8_t i = 0; i < NORCOW_SECTOR_COUNT; i++) {
const uint32_t *magic = norcow_ptr(i, 0, NORCOW_MAGIC_LEN);
if (magic != NULL && *magic == NORCOW_MAGIC) {
found = sectrue;
norcow_active_sector = i;
break;
}
}
// no active sectors found - let's erase
if (sectrue == found) {
norcow_active_offset = find_free_offset(norcow_active_sector);
} else {
norcow_wipe();
}
}
/*
* Wipe the storage
*/
void norcow_wipe(void)
{
norcow_erase(0, sectrue);
for (uint8_t i = 1; i < NORCOW_SECTOR_COUNT; i++) {
norcow_erase(i, secfalse);
}
norcow_active_sector = 0;
norcow_active_offset = NORCOW_MAGIC_LEN;
}
/*
* Looks for the given key, returns status of the operation
*/
secbool norcow_get(uint16_t key, const void **val, uint16_t *len)
{
return find_item(norcow_active_sector, key, val, len);
}
/*
* Sets the given key, returns status of the operation
*/
secbool norcow_set(uint16_t key, const void *val, uint16_t len)
{
// check whether there is enough free space
// and compact if full
if (norcow_active_offset + sizeof(uint32_t) + len > NORCOW_SECTOR_SIZE) {
compact();
}
// write item
uint32_t pos;
secbool r = write_item(norcow_active_sector, norcow_active_offset, key, val, len, &pos);
if (sectrue == r) {
norcow_active_offset = pos;
}
return r;
}
/*
* Update a word in flash at the given pointer. The pointer must point
* into the NORCOW area.
*/
secbool norcow_update(uint16_t key, uint16_t offset, uint32_t value)
{
const void *ptr;
uint16_t len;
if (sectrue != find_item(norcow_active_sector, key, &ptr, &len)) {
return secfalse;
}
if ((offset & 3) != 0 || offset >= len) {
return secfalse;
}
uint32_t sector_offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_active_sector, 0, NORCOW_SECTOR_SIZE) + offset;
ensure(flash_unlock(), NULL);
ensure(flash_write_word(norcow_sectors[norcow_active_sector], sector_offset, value), NULL);
ensure(flash_lock(), NULL);
return sectrue;
}

@ -1,58 +0,0 @@
/*
* This file is part of the TREZOR project, https://trezor.io/
*
* Copyright (c) SatoshiLabs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __NORCOW_H__
#define __NORCOW_H__
#include <stdint.h>
#include "secbool.h"
/*
* Storage parameters
*/
#include "norcow_config.h"
/*
* Initialize storage
*/
void norcow_init(void);
/*
* Wipe the storage
*/
void norcow_wipe(void);
/*
* Looks for the given key, returns status of the operation
*/
secbool norcow_get(uint16_t key, const void **val, uint16_t *len);
/*
* Sets the given key, returns status of the operation
*/
secbool norcow_set(uint16_t key, const void *val, uint16_t len);
/*
* Update a word in flash in the given key at the given offset.
* Note that you can only change bits from 1 to 0.
*/
secbool norcow_update(uint16_t key, uint16_t offset, uint32_t value);
#endif

@ -22,6 +22,7 @@
#include "flash.h"
#define NORCOW_HEADER_LEN 0
#define NORCOW_SECTOR_COUNT 2
#if TREZOR_MODEL == T
@ -40,4 +41,9 @@
#endif
/*
* Current storage version.
*/
#define NORCOW_VERSION ((uint32_t)0x00000001)
#endif

@ -1,238 +0,0 @@
/*
* This file is part of the TREZOR project, https://trezor.io/
*
* Copyright (c) SatoshiLabs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include "common.h"
#include "norcow.h"
#include "storage.h"
// Norcow storage key of configured PIN.
#define PIN_KEY 0x0000
// Maximum PIN length.
#define PIN_MAXLEN 32
// Byte-length of flash section containing fail counters.
#define PIN_FAIL_KEY 0x0001
#define PIN_FAIL_SECTOR_SIZE 32
// Maximum number of failed unlock attempts.
#define PIN_MAX_TRIES 15
static secbool initialized = secfalse;
static secbool unlocked = secfalse;
static PIN_UI_WAIT_CALLBACK ui_callback = NULL;
void storage_init(PIN_UI_WAIT_CALLBACK callback)
{
initialized = secfalse;
unlocked = secfalse;
norcow_init();
initialized = sectrue;
ui_callback = callback;
}
static secbool pin_fails_reset(uint16_t ofs)
{
return norcow_update(PIN_FAIL_KEY, ofs, 0);
}
static secbool pin_fails_increase(const uint32_t *ptr, uint16_t ofs)
{
uint32_t ctr = *ptr;
ctr = ctr << 1;
if (sectrue != norcow_update(PIN_FAIL_KEY, ofs, ctr)) {
return secfalse;
}
uint32_t check = *ptr;
if (ctr != check) {
return secfalse;
}
return sectrue;
}
static void pin_fails_check_max(uint32_t ctr)
{
if (~ctr >= (1 << PIN_MAX_TRIES)) {
norcow_wipe();
ensure(secfalse, "pin_fails_check_max");
}
}
static secbool pin_cmp(const uint32_t pin)
{
const void *spin = NULL;
uint16_t spinlen = 0;
norcow_get(PIN_KEY, &spin, &spinlen);
if (NULL != spin && spinlen == sizeof(uint32_t)) {
return sectrue * (pin == *(const uint32_t*)spin);
} else {
return sectrue * (1 == pin);
}
}
static secbool pin_get_fails(const uint32_t **pinfail, uint32_t *pofs)
{
const void *vpinfail;
uint16_t pinfaillen;
unsigned int ofs;
// The PIN_FAIL_KEY points to an area of words, initialized to
// 0xffffffff (meaning no pin failures). The first non-zero word
// in this area is the current pin failure counter. If PIN_FAIL_KEY
// has no configuration or is empty, the pin failure counter is 0.
// We rely on the fact that flash allows to clear bits and we clear one
// bit to indicate pin failure. On success, the word is set to 0,
// indicating that the next word is the pin failure counter.
// Find the current pin failure counter
if (secfalse != norcow_get(PIN_FAIL_KEY, &vpinfail, &pinfaillen)) {
*pinfail = vpinfail;
for (ofs = 0; ofs < pinfaillen / sizeof(uint32_t); ofs++) {
if (((const uint32_t *) vpinfail)[ofs]) {
*pinfail = vpinfail;
*pofs = ofs;
return sectrue;
}
}
}
// No pin failure section, or all entries used -> create a new one.
uint32_t pinarea[PIN_FAIL_SECTOR_SIZE];
memset(pinarea, 0xff, sizeof(pinarea));
if (sectrue != norcow_set(PIN_FAIL_KEY, pinarea, sizeof(pinarea))) {
return secfalse;
}
if (sectrue != norcow_get(PIN_FAIL_KEY, &vpinfail, &pinfaillen)) {
return secfalse;
}
*pinfail = vpinfail;
*pofs = 0;
return sectrue;
}
secbool storage_check_pin(const uint32_t pin)
{
const uint32_t *pinfail = NULL;
uint32_t ofs;
uint32_t ctr;
// Get the pin failure counter
if (pin_get_fails(&pinfail, &ofs) != sectrue) {
return secfalse;
}
// Read current failure counter
ctr = pinfail[ofs];
// Wipe storage if too many failures
pin_fails_check_max(ctr);
// Sleep for ~ctr seconds before checking the PIN.
uint32_t progress;
for (uint32_t wait = ~ctr; wait > 0; wait--) {
for (int i = 0; i < 10; i++) {
if (ui_callback) {
if ((~ctr) > 1000000) { // precise enough
progress = (~ctr - wait) / ((~ctr) / 1000);
} else {
progress = ((~ctr - wait) * 10 + i) * 100 / (~ctr);
}
ui_callback(wait, progress);
}
hal_delay(100);
}
}
// Show last frame if we were waiting
if ((~ctr > 0) && ui_callback) {
ui_callback(0, 1000);
}
// First, we increase PIN fail counter in storage, even before checking the
// PIN. If the PIN is correct, we reset the counter afterwards. If not, we
// check if this is the last allowed attempt.
if (sectrue != pin_fails_increase(pinfail + ofs, ofs * sizeof(uint32_t))) {
return secfalse;
}
if (sectrue != pin_cmp(pin)) {
// Wipe storage if too many failures
pin_fails_check_max(ctr << 1);
return secfalse;
}
// Finally set the counter to 0 to indicate success.
return pin_fails_reset(ofs * sizeof(uint32_t));
}
secbool storage_unlock(const uint32_t pin)
{
unlocked = secfalse;
if (sectrue == initialized && sectrue == storage_check_pin(pin)) {
unlocked = sectrue;
}
return unlocked;
}
secbool storage_get(const uint16_t key, const void **val, uint16_t *len)
{
const uint8_t app = key >> 8;
// APP == 0 is reserved for PIN related values
if (sectrue != initialized || app == 0) {
return secfalse;
}
// top bit of APP set indicates the value can be read from unlocked device
if (sectrue != unlocked && ((app & 0x80) == 0)) {
return secfalse;
}
return norcow_get(key, val, len);
}
secbool storage_set(const uint16_t key, const void *val, uint16_t len)
{
const uint8_t app = key >> 8;
// APP == 0 is reserved for PIN related values
if (sectrue != initialized || sectrue != unlocked || app == 0) {
return secfalse;
}
return norcow_set(key, val, len);
}
secbool storage_has_pin(void)
{
if (sectrue != initialized) {
return secfalse;
}
return sectrue == pin_cmp(1) ? secfalse : sectrue;
}
secbool storage_change_pin(const uint32_t oldpin, const uint32_t newpin)
{
if (sectrue != initialized || sectrue != unlocked) {
return secfalse;
}
if (sectrue != storage_check_pin(oldpin)) {
return secfalse;
}
return norcow_set(PIN_KEY, &newpin, sizeof(uint32_t));
}
void storage_wipe(void)
{
norcow_wipe();
}

@ -1,38 +0,0 @@
/*
* This file is part of the TREZOR project, https://trezor.io/
*
* Copyright (c) SatoshiLabs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __STORAGE_H__
#define __STORAGE_H__
#include <stdint.h>
#include <stddef.h>
#include "secbool.h"
typedef void (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress);
void storage_init(PIN_UI_WAIT_CALLBACK callback);
void storage_wipe(void);
secbool storage_check_pin(const uint32_t pin);
secbool storage_unlock(const uint32_t pin);
secbool storage_has_pin(void);
secbool storage_change_pin(const uint32_t oldpin, const uint32_t newpin);
secbool storage_get(const uint16_t key, const void **val, uint16_t *len);
secbool storage_set(const uint16_t key, const void *val, uint16_t len);
#endif

@ -48,6 +48,8 @@ int main(void)
HAL_Init();
#endif
collect_hw_entropy();
#if TREZOR_MODEL == T
// Enable MPU
mpu_config();

@ -305,11 +305,11 @@ power_off:
static void test_wipe(void)
{
// erase start of the firmware (metadata) -> invalidate FW
ensure(flash_unlock(), NULL);
ensure(flash_unlock_write(), NULL);
for (int i = 0; i < 1024 / sizeof(uint32_t); i++) {
ensure(flash_write_word(FLASH_SECTOR_FIRMWARE_START, i * sizeof(uint32_t), 0x00000000), NULL);
}
ensure(flash_lock(), NULL);
ensure(flash_lock_write(), NULL);
display_clear();
display_text_center(DISPLAY_RESX / 2, DISPLAY_RESY / 2 + 10, "WIPED", -1, FONT_BOLD, COLOR_WHITE, COLOR_BLACK);
display_refresh();

@ -88,7 +88,7 @@ int main(void)
display_printf("\n");
display_printf("erased\n");
ensure(flash_unlock(), NULL);
ensure(flash_unlock_write(), NULL);
ensure(sdcard_power_on(), NULL);
@ -103,7 +103,7 @@ int main(void)
display_printf("done\n");
sdcard_power_off();
ensure(flash_lock(), NULL);
ensure(flash_lock_write(), NULL);
return 0;
}

@ -19,10 +19,14 @@
#include STM32_HAL_H
#include <string.h>
#include "common.h"
#include "display.h"
#include "rng.h"
#include "stm32f4xx_ll_utils.h"
void shutdown(void);
#define COLOR_FATAL_ERROR RGB16(0x7F, 0x00, 0x00)
@ -47,6 +51,53 @@ void __attribute__((noreturn)) __fatal_error(const char *expr, const char *msg,
#ifdef GITREV
display_printf("rev : %s\n", XSTR(GITREV));
#endif
display_printf("\nPlease contact TREZOR support.\n");
shutdown();
for (;;);
}
void __attribute__((noreturn)) error_shutdown(const char *line1, const char *line2, const char *line3, const char *line4)
{
display_orientation(0);
#ifdef TREZOR_FONT_NORMAL_ENABLE
display_clear();
display_bar(0, 0, DISPLAY_RESX, DISPLAY_RESY, COLOR_FATAL_ERROR);
int y = 32;
if (line1) {
display_text(8, y, line1, -1, FONT_NORMAL, COLOR_WHITE, COLOR_FATAL_ERROR);
y += 32;
}
if (line2) {
display_text(8, y, line2, -1, FONT_NORMAL, COLOR_WHITE, COLOR_FATAL_ERROR);
y += 32;
}
if (line3) {
display_text(8, y, line3, -1, FONT_NORMAL, COLOR_WHITE, COLOR_FATAL_ERROR);
y += 32;
}
if (line4) {
display_text(8, y, line4, -1, FONT_NORMAL, COLOR_WHITE, COLOR_FATAL_ERROR);
y += 32;
}
y += 32;
display_text(8, y, "Please unplug the device.", -1, FONT_NORMAL, COLOR_WHITE, COLOR_FATAL_ERROR);
#else
display_print_color(COLOR_WHITE, COLOR_FATAL_ERROR);
if (line1) {
display_printf("%s\n", line1);
}
if (line2) {
display_printf("%s\n", line2);
}
if (line3) {
display_printf("%s\n", line3);
}
if (line4) {
display_printf("%s\n", line4);
}
display_printf("\nPlease unplug the device.\n");
#endif
display_backlight(255);
shutdown();
for (;;);
}
@ -80,3 +131,15 @@ void __attribute__((noreturn)) __stack_chk_fail(void)
{
ensure(secfalse, "Stack smashing detected");
}
uint8_t HW_ENTROPY_DATA[HW_ENTROPY_LEN];
void collect_hw_entropy(void)
{
uint32_t w = LL_GetUID_Word0();
memcpy(HW_ENTROPY_DATA, &w, 4);
w = LL_GetUID_Word1();
memcpy(HW_ENTROPY_DATA + 4, &w, 4);
w = LL_GetUID_Word2();
memcpy(HW_ENTROPY_DATA + 8, &w, 4);
}

@ -34,6 +34,7 @@
#endif
void __attribute__((noreturn)) __fatal_error(const char *expr, const char *msg, const char *file, int line, const char *func);
void __attribute__((noreturn)) error_shutdown(const char *line1, const char *line2, const char *line3, const char *line4);
#define ensure(expr, msg) (((expr) == sectrue) ? (void)0 : __fatal_error(#expr, msg, __FILE__, __LINE__, __func__))
@ -43,6 +44,10 @@ void clear_otg_hs_memory(void);
extern uint32_t __stack_chk_guard;
void collect_hw_entropy(void);
#define HW_ENTROPY_LEN 12
extern uint8_t HW_ENTROPY_DATA[HW_ENTROPY_LEN];
// the following functions are defined in util.s
void memset_reg(volatile void *start, volatile void *stop, uint32_t val);

@ -58,14 +58,14 @@ void flash_init(void)
{
}
secbool flash_unlock(void)
secbool flash_unlock_write(void)
{
HAL_FLASH_Unlock();
FLASH->SR |= FLASH_STATUS_ALL_FLAGS; // clear all status flags
return sectrue;
}
secbool flash_lock(void)
secbool flash_lock_write(void)
{
HAL_FLASH_Lock();
return sectrue;
@ -86,7 +86,7 @@ const void *flash_get_address(uint8_t sector, uint32_t offset, uint32_t size)
secbool flash_erase_sectors(const uint8_t *sectors, int len, void (*progress)(int pos, int len))
{
ensure(flash_unlock(), NULL);
ensure(flash_unlock_write(), NULL);
FLASH_EraseInitTypeDef EraseInitStruct;
EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS;
EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3;
@ -98,14 +98,14 @@ secbool flash_erase_sectors(const uint8_t *sectors, int len, void (*progress)(in
EraseInitStruct.Sector = sectors[i];
uint32_t SectorError;
if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) {
ensure(flash_lock(), NULL);
ensure(flash_lock_write(), NULL);
return secfalse;
}
// check whether the sector was really deleted (contains only 0xFF)
const uint32_t addr_start = FLASH_SECTOR_TABLE[sectors[i]], addr_end = FLASH_SECTOR_TABLE[sectors[i] + 1];
for (uint32_t addr = addr_start; addr < addr_end; addr += 4) {
if (*((const uint32_t *)addr) != 0xFFFFFFFF) {
ensure(flash_lock(), NULL);
ensure(flash_lock_write(), NULL);
return secfalse;
}
}
@ -113,7 +113,7 @@ secbool flash_erase_sectors(const uint8_t *sectors, int len, void (*progress)(in
progress(i + 1, len);
}
}
ensure(flash_lock(), NULL);
ensure(flash_lock_write(), NULL);
return sectrue;
}
@ -123,7 +123,16 @@ secbool flash_write_byte(uint8_t sector, uint32_t offset, uint8_t data)
if (address == 0) {
return secfalse;
}
return sectrue * (HAL_OK == HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, address, data));
if (data != (data & *((const uint8_t *)address))) {
return secfalse;
}
if (HAL_OK != HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, address, data)) {
return secfalse;
}
if (data != *((const uint8_t *)address)) {
return secfalse;
}
return sectrue;
}
secbool flash_write_word(uint8_t sector, uint32_t offset, uint32_t data)
@ -135,7 +144,17 @@ secbool flash_write_word(uint8_t sector, uint32_t offset, uint32_t data)
if (offset % 4 != 0) {
return secfalse;
}
return sectrue * (HAL_OK == HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, address, data));
if (data != (data & *((const uint32_t *)address))) {
return secfalse;
}
if (HAL_OK != HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, address, data)) {
return secfalse;
}
if (data != *((const uint32_t *)address)) {
return secfalse;
}
return sectrue;
}
#define FLASH_OTP_LOCK_BASE 0x1FFF7A00U
@ -156,12 +175,12 @@ secbool flash_otp_write(uint8_t block, uint8_t offset, const uint8_t *data, uint
if (block >= FLASH_OTP_NUM_BLOCKS || offset + datalen > FLASH_OTP_BLOCK_SIZE) {
return secfalse;
}
ensure(flash_unlock(), NULL);
ensure(flash_unlock_write(), NULL);
for (uint8_t i = 0; i < datalen; i++) {
uint32_t address = FLASH_OTP_BASE + block * FLASH_OTP_BLOCK_SIZE + offset + i;
ensure(sectrue * (HAL_OK == HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, address, data[i])), NULL);
}
ensure(flash_lock(), NULL);
ensure(flash_lock_write(), NULL);
return sectrue;
}
@ -170,9 +189,9 @@ secbool flash_otp_lock(uint8_t block)
if (block >= FLASH_OTP_NUM_BLOCKS) {
return secfalse;
}
ensure(flash_unlock(), NULL);
ensure(flash_unlock_write(), NULL);
HAL_StatusTypeDef ret = HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, FLASH_OTP_LOCK_BASE + block, 0x00);
ensure(flash_lock(), NULL);
ensure(flash_lock_write(), NULL);
return sectrue * (ret == HAL_OK);
}

@ -69,13 +69,13 @@
void flash_init(void);
secbool __wur flash_unlock(void);
secbool __wur flash_lock(void);
secbool __wur flash_unlock_write(void);
secbool __wur flash_lock_write(void);
const void *flash_get_address(uint8_t sector, uint32_t offset, uint32_t size);
secbool __wur flash_erase_sectors(const uint8_t *sectors, int len, void (*progress)(int pos, int len));
static inline secbool flash_erase_sector(uint8_t sector) { return flash_erase_sectors(&sector, 1, NULL); }
static inline secbool flash_erase(uint8_t sector) { return flash_erase_sectors(&sector, 1, NULL); }
secbool __wur flash_write_byte(uint8_t sector, uint32_t offset, uint8_t data);
secbool __wur flash_write_word(uint8_t sector, uint32_t offset, uint32_t data);

@ -23,6 +23,7 @@
#include "common.h"
#include "display.h"
#include "memzero.h"
void __shutdown(void)
{
@ -59,12 +60,55 @@ void __attribute__((noreturn)) __fatal_error(const char *expr, const char *msg,
display_printf("rev : %s\n", XSTR(GITREV));
printf("rev : %s\n", XSTR(GITREV));
#endif
display_printf("\nPlease contact TREZOR support.\n");
printf("\nPlease contact TREZOR support.\n");
hal_delay(3000);
__shutdown();
for (;;);
}
void __attribute__((noreturn)) error_shutdown(const char *line1, const char *line2, const char *line3, const char *line4)
{
display_clear();
display_bar(0, 0, DISPLAY_RESX, DISPLAY_RESY, COLOR_FATAL_ERROR);
int y = 32;
if (line1) {
display_text(8, y, line1, -1, FONT_NORMAL, COLOR_WHITE, COLOR_FATAL_ERROR);
printf("%s\n", line1);
y += 32;
}
if (line2) {
display_text(8, y, line2, -1, FONT_NORMAL, COLOR_WHITE, COLOR_FATAL_ERROR);
printf("%s\n", line2);
y += 32;
}
if (line3) {
display_text(8, y, line3, -1, FONT_NORMAL, COLOR_WHITE, COLOR_FATAL_ERROR);
printf("%s\n", line3);
y += 32;
}
if (line4) {
display_text(8, y, line4, -1, FONT_NORMAL, COLOR_WHITE, COLOR_FATAL_ERROR);
printf("%s\n", line4);
y += 32;
}
y += 32;
display_text(8, y, "Please unplug the device.", -1, FONT_NORMAL, COLOR_WHITE, COLOR_FATAL_ERROR);
printf("\nPlease unplug the device.\n");
display_backlight(255);
hal_delay(5000);
__shutdown();
for (;;);
}
void hal_delay(uint32_t ms)
{
usleep(1000 * ms);
}
uint8_t HW_ENTROPY_DATA[HW_ENTROPY_LEN];
void collect_hw_entropy(void)
{
memzero(HW_ENTROPY_DATA, HW_ENTROPY_LEN);
}

@ -34,9 +34,14 @@
#endif
void __attribute__((noreturn)) __fatal_error(const char *expr, const char *msg, const char *file, int line, const char *func);
void __attribute__((noreturn)) error_shutdown(const char *line1, const char *line2, const char *line3, const char *line4);
#define ensure(expr, msg) (((expr) == sectrue) ? (void)0 : __fatal_error(#expr, msg, __FILE__, __LINE__, __func__))
void hal_delay(uint32_t ms);
void collect_hw_entropy(void);
#define HW_ENTROPY_LEN 12
extern uint8_t HW_ENTROPY_DATA[HW_ENTROPY_LEN];
#endif

@ -103,12 +103,12 @@ void flash_init(void)
atexit(flash_exit);
}
secbool flash_unlock(void)
secbool flash_unlock_write(void)
{
return sectrue;
}
secbool flash_lock(void)
secbool flash_lock_write(void)
{
return sectrue;
}

@ -50,6 +50,8 @@
#include "input.h"
#include "profile.h"
#include "common.h"
// Command line options, with their defaults
STATIC bool compile_only = false;
STATIC uint emit_opt = MP_EMIT_OPT_NONE;
@ -409,6 +411,8 @@ int main(int argc, char **argv) {
// Through TREZOR_PROFILE you can set the directory for trezor.flash file.
profile_init();
collect_hw_entropy();
#if MICROPY_PY_THREAD
mp_thread_init();
#endif

@ -11,7 +11,9 @@ class PinCancelled(Exception):
@ui.layout
async def request_pin(label=None, cancellable: bool = True) -> str:
async def request_pin(
label=None, attempts_remaining=None, cancellable: bool = True
) -> str:
def onchange():
c = dialog.cancel
if matrix.pin:
@ -36,7 +38,13 @@ async def request_pin(label=None, cancellable: bool = True) -> str:
if label is None:
label = "Enter your PIN"
matrix = PinMatrix(label)
sublabel = None
if attempts_remaining:
if attempts_remaining == 1:
sublabel = "This is your last attempt"
else:
sublabel = "{} attempts remaining".format(attempts_remaining)
matrix = PinMatrix(label, sublabel)
matrix.onchange = onchange
dialog = ConfirmDialog(matrix)
dialog.cancel.area = ui.grid(12)

@ -8,7 +8,11 @@ from apps.common import cache
HOMESCREEN_MAXSIZE = 16384
_STORAGE_VERSION = b"\x01"
_STORAGE_VERSION = b"\x02"
_FALSE_BYTE = b"\x00"
_TRUE_BYTE = b"\x01"
_COUNTER_HEAD_LEN = 4
_COUNTER_TAIL_LEN = 8
# fmt: off
_APP = const(0x01) # app namespace
@ -29,16 +33,27 @@ _NO_BACKUP = const(0x0D) # bool (0x01 or empty)
# fmt: on
def _set_bool(app: int, key: int, value: bool, public: bool = False) -> None:
if value:
config.set(app, key, _TRUE_BYTE, public)
else:
config.set(app, key, _FALSE_BYTE, public)
def _get_bool(app: int, key: int, public: bool = False) -> bool:
return config.get(app, key, public) == _TRUE_BYTE
def _new_device_id() -> str:
return hexlify(random.bytes(12)).decode().upper()
def get_device_id() -> str:
dev_id = config.get(_APP, _DEVICE_ID, True).decode() # public
dev_id = config.get(_APP, _DEVICE_ID, True) # public
if not dev_id:
dev_id = _new_device_id()
config.set(_APP, _DEVICE_ID, dev_id.encode(), True) # public
return dev_id
dev_id = _new_device_id().encode()
config.set(_APP, _DEVICE_ID, dev_id, True) # public
return dev_id.decode()
def is_initialized() -> bool:
@ -46,15 +61,21 @@ def is_initialized() -> bool:
def get_label() -> str:
return config.get(_APP, _LABEL, True).decode() # public
label = config.get(_APP, _LABEL, True) # public
if label is None:
return None
return label.decode()
def get_mnemonic() -> str:
return config.get(_APP, _MNEMONIC).decode()
mnemonic = config.get(_APP, _MNEMONIC)
if mnemonic is None:
return None
return mnemonic.decode()
def has_passphrase() -> bool:
return bool(config.get(_APP, _USE_PASSPHRASE))
return _get_bool(_APP, _USE_PASSPHRASE)
def get_homescreen() -> bytes:
@ -64,18 +85,13 @@ def get_homescreen() -> bytes:
def load_mnemonic(mnemonic: str, needs_backup: bool, no_backup: bool) -> None:
config.set(_APP, _MNEMONIC, mnemonic.encode())
config.set(_APP, _VERSION, _STORAGE_VERSION)
if no_backup:
config.set(_APP, _NO_BACKUP, b"\x01")
else:
config.set(_APP, _NO_BACKUP, b"")
if needs_backup:
config.set(_APP, _NEEDS_BACKUP, b"\x01")
else:
config.set(_APP, _NEEDS_BACKUP, b"")
_set_bool(_APP, _NO_BACKUP, no_backup)
if not no_backup:
_set_bool(_APP, _NEEDS_BACKUP, needs_backup)
def needs_backup() -> bool:
return bool(config.get(_APP, _NEEDS_BACKUP))
return _get_bool(_APP, _NEEDS_BACKUP)
def set_backed_up() -> None:
@ -83,18 +99,15 @@ def set_backed_up() -> None:
def unfinished_backup() -> bool:
return bool(config.get(_APP, _UNFINISHED_BACKUP))
return _get_bool(_APP, _UNFINISHED_BACKUP)
def set_unfinished_backup(state: bool) -> None:
if state:
config.set(_APP, _UNFINISHED_BACKUP, b"\x01")
else:
config.set(_APP, _UNFINISHED_BACKUP, b"")
_set_bool(_APP, _UNFINISHED_BACKUP, state)
def no_backup() -> bool:
return bool(config.get(_APP, _NO_BACKUP))
return _get_bool(_APP, _NO_BACKUP)
def get_passphrase_source() -> int:
@ -115,10 +128,8 @@ def load_settings(
) -> None:
if label is not None:
config.set(_APP, _LABEL, label.encode(), True) # public
if use_passphrase is True:
config.set(_APP, _USE_PASSPHRASE, b"\x01")
if use_passphrase is False:
config.set(_APP, _USE_PASSPHRASE, b"")
if use_passphrase is not None:
_set_bool(_APP, _USE_PASSPHRASE, use_passphrase)
if homescreen is not None:
if homescreen[:8] == b"TOIf\x90\x00\x90\x00":
if len(homescreen) <= HOMESCREEN_MAXSIZE:
@ -164,22 +175,27 @@ def set_autolock_delay_ms(delay_ms: int) -> None:
def next_u2f_counter() -> int:
b = config.get(_APP, _U2F_COUNTER)
if not b:
b = 0
else:
b = int.from_bytes(b, "big") + 1
set_u2f_counter(b)
return b
return config.next_counter(_APP, _U2F_COUNTER, True) # writable when locked
def set_u2f_counter(cntr: int):
if cntr:
config.set(_APP, _U2F_COUNTER, cntr.to_bytes(4, "big"))
else:
config.set(_APP, _U2F_COUNTER, b"")
def set_u2f_counter(cntr: int) -> None:
config.set_counter(_APP, _U2F_COUNTER, cntr, True) # writable when locked
def wipe():
config.wipe()
cache.clear()
def init_unlocked():
# Check for storage version upgrade.
version = config.get(_APP, _VERSION)
if version == b"\x01":
# Make the U2F counter public and writable even when storage is locked.
counter = config.get(_APP, _U2F_COUNTER)
if counter is not None:
config.set_counter(
_APP, _U2F_COUNTER, counter, True
) # writable when locked
config.delete(_APP, _U2F_COUNTER)
config.set(_APP, _VERSION, _STORAGE_VERSION)

@ -16,7 +16,7 @@ async def change_pin(ctx, msg):
# get current pin, return failure if invalid
if config.has_pin():
curpin = await request_pin_ack(ctx)
curpin = await request_pin_ack(ctx, "Enter old PIN", config.get_pin_rem())
if not config.check_pin(pin_to_int(curpin)):
raise wire.PinInvalid("PIN invalid")
else:
@ -44,19 +44,19 @@ def require_confirm_change_pin(ctx, msg):
if msg.remove and has_pin: # removing pin
text = Text("Remove PIN", ui.ICON_CONFIG)
text.normal("Do you really want to")
text.bold("remove current PIN?")
text.bold("disable PIN protection?")
return require_confirm(ctx, text)
if not msg.remove and has_pin: # changing pin
text = Text("Remove PIN", ui.ICON_CONFIG)
text = Text("Change PIN", ui.ICON_CONFIG)
text.normal("Do you really want to")
text.bold("change current PIN?")
text.bold("change the current PIN?")
return require_confirm(ctx, text)
if not msg.remove and not has_pin: # setting new pin
text = Text("Remove PIN", ui.ICON_CONFIG)
text = Text("Enable PIN", ui.ICON_CONFIG)
text.normal("Do you really want to")
text.bold("set new PIN?")
text.bold("enable PIN protection?")
return require_confirm(ctx, text)

@ -1,6 +1,7 @@
from trezor import config, log, loop, res, ui
from trezor.pin import pin_to_int, show_pin_timeout
from apps.common import storage
from apps.common.request_pin import request_pin
@ -9,12 +10,14 @@ async def bootscreen():
try:
if not config.has_pin():
config.unlock(pin_to_int(""))
storage.init_unlocked()
return
await lockscreen()
label = None
while True:
pin = await request_pin(label)
pin = await request_pin(label, config.get_pin_rem())
if config.unlock(pin_to_int(pin)):
storage.init_unlocked()
return
else:
label = "Wrong PIN, enter again"
@ -24,8 +27,6 @@ async def bootscreen():
async def lockscreen():
from apps.common import storage
label = storage.get_label()
image = storage.get_homescreen()
if not label:

@ -5,7 +5,7 @@ def pin_to_int(pin: str) -> int:
return int("1" + pin)
def show_pin_timeout(seconds: int, progress: int):
def show_pin_timeout(seconds: int, progress: int) -> bool:
if progress == 0:
ui.display.bar(0, 0, ui.WIDTH, ui.HEIGHT, ui.BG)
ui.display.text_center(
@ -37,3 +37,4 @@ def show_pin_timeout(seconds: int, progress: int):
ui.WIDTH,
)
ui.display.refresh()
return False

@ -19,8 +19,9 @@ def generate_digits():
class PinMatrix(ui.Widget):
def __init__(self, label, pin="", maxlength=9):
def __init__(self, label, sublabel, pin="", maxlength=9):
self.label = label
self.sublabel = sublabel
self.pin = pin
self.maxlength = maxlength
self.digits = generate_digits()
@ -48,7 +49,7 @@ class PinMatrix(ui.Widget):
return
# clear canvas under input line
display.bar(0, 0, ui.WIDTH, 45, ui.BG)
display.bar(0, 0, ui.WIDTH, 52, ui.BG)
if self.pin:
# input line with pin
@ -60,6 +61,12 @@ class PinMatrix(ui.Widget):
x = (box_w - l * padding) // 2
for i in range(0, l):
ui.display.bar_radius(x + i * padding, y, size, size, ui.GREY, ui.BG, 4)
elif self.sublabel:
# input line with header label and sublabel
display.text_center(ui.WIDTH // 2, 20, self.label, ui.BOLD, ui.GREY, ui.BG)
display.text_center(
ui.WIDTH // 2, 46, self.sublabel, ui.NORMAL, ui.GREY, ui.BG
)
else:
# input line with header label
display.text_center(ui.WIDTH // 2, 36, self.label, ui.BOLD, ui.GREY, ui.BG)

@ -0,0 +1,24 @@
from common import *
from trezor.pin import pin_to_int
from trezor import config
from apps.common import storage
class TestConfig(unittest.TestCase):
def test_counter(self):
config.init()
config.wipe()
for i in range(150):
self.assertEqual(storage.next_u2f_counter(), i)
storage.set_u2f_counter(350)
for i in range(351, 500):
self.assertEqual(storage.next_u2f_counter(), i)
storage.set_u2f_counter(0)
self.assertEqual(storage.next_u2f_counter(), 1)
storage.set_u2f_counter(None)
self.assertEqual(storage.next_u2f_counter(), 0)
if __name__ == '__main__':
unittest.main()

@ -11,7 +11,7 @@ PINKEY = 0x00
def random_entry():
while True:
appid, key = 1 + random.uniform(127), random.uniform(256)
appid, key = 1 + random.uniform(63), random.uniform(256)
if appid != PINAPP or key != PINKEY:
break
return appid, key
@ -37,8 +37,8 @@ class TestConfig(unittest.TestCase):
config.wipe()
v0 = config.get(1, 1)
v1 = config.get(1, 2)
self.assertEqual(v0, bytes())
self.assertEqual(v1, bytes())
self.assertEqual(v0, None)
self.assertEqual(v1, None)
def test_lock(self):
for _ in range(128):
@ -49,12 +49,11 @@ class TestConfig(unittest.TestCase):
value = random.bytes(16)
config.set(appid, key, value)
config.init()
self.assertEqual(config.get(appid, key), bytes())
self.assertEqual(config.get(appid, key), None)
with self.assertRaises(RuntimeError):
config.set(appid, key, bytes())
config.init()
config.wipe()
self.assertEqual(config.change_pin(pin_to_int(''), pin_to_int('000')), False)
def test_public(self):
config.init()
@ -79,7 +78,7 @@ class TestConfig(unittest.TestCase):
v1 = config.get(appid, key)
v2 = config.get(appid, key, True)
self.assertNotEqual(v1, v2)
self.assertEqual(v1, bytes())
self.assertEqual(v1, None)
self.assertEqual(v2, value16)
def test_change_pin(self):
@ -90,7 +89,7 @@ class TestConfig(unittest.TestCase):
config.set(PINAPP, PINKEY, b'value')
self.assertEqual(config.change_pin(pin_to_int('000'), pin_to_int('666')), False)
self.assertEqual(config.change_pin(pin_to_int(''), pin_to_int('000')), True)
self.assertEqual(config.get(PINAPP, PINKEY), bytes())
self.assertEqual(config.get(PINAPP, PINKEY), None)
config.set(1, 1, b'value')
config.init()
self.assertEqual(config.unlock(pin_to_int('000')), True)
@ -129,7 +128,7 @@ class TestConfig(unittest.TestCase):
for _ in range(128):
appid, key = random_entry()
value = config.get(appid, key)
self.assertEqual(value, bytes())
self.assertEqual(value, None)
if __name__ == '__main__':

@ -0,0 +1 @@
Subproject commit 13b256ab2c11791e0c13696a8c507787a374884f
Loading…
Cancel
Save