From 781f1c24d02b03dd6b9718a5beaa9c287f0d0372 Mon Sep 17 00:00:00 2001 From: Pavol Rusnak Date: Thu, 24 Jan 2019 15:53:45 +0100 Subject: [PATCH 01/39] init --- norcow.c | 560 +++++++++++++++++++++++++++ norcow.h | 82 ++++ storage.c | 1093 +++++++++++++++++++++++++++++++++++++++++++++++++++++ storage.h | 39 ++ 4 files changed, 1774 insertions(+) create mode 100644 norcow.c create mode 100644 norcow.h create mode 100644 storage.c create mode 100644 storage.h diff --git a/norcow.c b/norcow.c new file mode 100644 index 000000000..fb7a1d450 --- /dev/null +++ b/norcow.c @@ -0,0 +1,560 @@ +/* + * 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 . + */ + +#include + +#include "norcow.h" +#include "flash.h" +#include "common.h" + +// NRC2 = 4e524332 +#define NORCOW_MAGIC ((uint32_t)0x3243524e) +// NRCW = 4e524357 +#define NORCOW_MAGIC_V0 ((uint32_t)0x5743524e) + +#define NORCOW_WORD_SIZE (sizeof(uint32_t)) +#define NORCOW_PREFIX_LEN NORCOW_WORD_SIZE +#define NORCOW_MAGIC_LEN NORCOW_WORD_SIZE +#define NORCOW_VERSION_LEN NORCOW_WORD_SIZE + +// The key value which is used to indicate that the entry is not set. +#define NORCOW_KEY_FREE (0xFFFF) + +// The key value which is used to indicate that the entry has been deleted. +#define NORCOW_KEY_DELETED (0x0000) + +// The offset from the beginning of the sector where stored items start. +#define NORCOW_STORAGE_START (NORCOW_HEADER_LEN + NORCOW_MAGIC_LEN + NORCOW_VERSION_LEN) + +// Map from sector index to sector number. +static const uint8_t norcow_sectors[NORCOW_SECTOR_COUNT] = NORCOW_SECTORS; + +// The index of the active reading sector and writing sector. These should be equal except when storage version upgrade or compaction is in progress. +static uint8_t norcow_active_sector = 0; +static uint8_t norcow_write_sector = 0; + +// The norcow version of the reading sector. +static uint32_t norcow_active_version = 0; + +// The offset of the first free item in the writing sector. +static uint32_t norcow_free_offset = 0; + +/* + * 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; + } + + if (offset + NORCOW_PREFIX_LEN + len > NORCOW_SECTOR_SIZE) { + return secfalse; + } + + ensure(flash_unlock(), NULL); + + // write prefix + ensure(flash_write_word(norcow_sectors[sector], offset, prefix), NULL); + offset += NORCOW_PREFIX_LEN; + + if (data != NULL) { + // write data + for (uint16_t i = 0; i < len; i++, offset++) { + ensure(flash_write_byte(norcow_sectors[sector], offset, data[i]), NULL); + } + } else { + offset += len; + } + + // pad with zeroes + for (; offset % NORCOW_WORD_SIZE; 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 erase_sector(uint8_t sector, secbool set_magic) +{ +#if NORCOW_HEADER_LEN > 0 + // Backup the sector header. + uint32_t header_backup[NORCOW_HEADER_LEN/sizeof(uint32_t)]; + const void *sector_start = norcow_ptr(sector, 0, NORCOW_HEADER_LEN); + memcpy(header_backup, sector_start, sizeof(header_backup)); +#endif + + ensure(flash_erase_sector(norcow_sectors[sector]), "erase failed"); + +#if NORCOW_HEADER_LEN > 0 + // Copy the sector header back. + for (uint32_t i = 0; i < NORCOW_HEADER_LEN/sizeof(uint32_t); ++i) { + ensure(flash_write_word(norcow_sectors[sector], i*sizeof(uint32_t), header_backup[i]), NULL); + } +#endif + + if (sectrue == set_magic) { + ensure(norcow_write(sector, NORCOW_HEADER_LEN, NORCOW_MAGIC, NULL, 0), "set magic failed"); + ensure(norcow_write(sector, NORCOW_HEADER_LEN + NORCOW_MAGIC_LEN, ~NORCOW_VERSION, NULL, 0), "set version 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 == NORCOW_KEY_FREE) { + 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 = ((uint32_t)len << 16) | key; + *pos = offset + NORCOW_PREFIX_LEN + len; + ALIGN4(*pos); + return norcow_write(sector, offset, prefix, val, len); +} + +/* + * Finds the offset from the beginning of the sector where stored items start. + */ +static secbool find_start_offset(uint8_t sector, uint32_t *offset, uint32_t *version) +{ + const uint32_t *magic = norcow_ptr(sector, NORCOW_HEADER_LEN, NORCOW_MAGIC_LEN + NORCOW_VERSION_LEN); + if (magic == NULL) { + return secfalse; + } + + if (*magic == NORCOW_MAGIC) { + *offset = NORCOW_STORAGE_START; + *version = ~(magic[1]); + } else if (*magic == NORCOW_MAGIC_V0) { + *offset = NORCOW_HEADER_LEN + NORCOW_MAGIC_LEN; + *version = 0; + } else { + return secfalse; + } + + return sectrue; +} + +/* + * Finds item in given sector + */ +static secbool find_item(uint8_t sector, uint16_t key, const void **val, uint16_t *len) +{ + *val = NULL; + *len = 0; + + uint32_t offset; + uint32_t version; + if (sectrue != find_start_offset(sector, &offset, &version)) { + return secfalse; + } + + 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; + uint32_t version; + if (sectrue != find_start_offset(sector, &offset, &version)) { + return secfalse; + } + + 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() +{ + uint32_t offsetr; + uint32_t version; + if (sectrue != find_start_offset(norcow_active_sector, &offsetr, &version)) { + return; + } + + norcow_write_sector = (norcow_active_sector + 1) % NORCOW_SECTOR_COUNT; + erase_sector(norcow_write_sector, sectrue); + uint32_t offsetw = NORCOW_STORAGE_START; + + for (;;) { + // read item + uint16_t k, l; + const void *v; + uint32_t posr; + secbool r = read_item(norcow_active_sector, offsetr, &k, &v, &l, &posr); + if (sectrue != r) { + break; + } + offsetr = posr; + + // skip deleted items + if (k == NORCOW_KEY_DELETED) { + continue; + } + + // copy the item + uint32_t posw; + ensure(write_item(norcow_write_sector, offsetw, k, v, l, &posw), "compaction write failed"); + offsetw = posw; + } + + erase_sector(norcow_active_sector, secfalse); + norcow_active_sector = norcow_write_sector; + norcow_active_version = NORCOW_VERSION; + norcow_free_offset = find_free_offset(norcow_write_sector); +} + +/* + * Initializes storage + */ +void norcow_init(uint32_t *norcow_version) +{ + flash_init(); + secbool found = secfalse; + *norcow_version = 0; + // detect active sector - starts with magic and has highest version + for (uint8_t i = 0; i < NORCOW_SECTOR_COUNT; i++) { + uint32_t offset; + if (sectrue == find_start_offset(i, &offset, &norcow_active_version) && norcow_active_version >= *norcow_version) { + found = sectrue; + norcow_active_sector = i; + *norcow_version = norcow_active_version; + } + } + + // If no active sectors found or version downgrade, then erase. + if (sectrue != found || *norcow_version > NORCOW_VERSION) { + norcow_wipe(); + *norcow_version = NORCOW_VERSION; + } else if (*norcow_version < NORCOW_VERSION) { + // Prepare write sector for storage upgrade. + norcow_write_sector = (norcow_active_sector + 1) % NORCOW_SECTOR_COUNT; + erase_sector(norcow_write_sector, sectrue); + norcow_free_offset = find_free_offset(norcow_write_sector); + } else { + norcow_write_sector = norcow_active_sector; + norcow_free_offset = find_free_offset(norcow_write_sector); + } +} + +/* + * Wipe the storage + */ +void norcow_wipe(void) +{ + erase_sector(0, sectrue); + for (uint8_t i = 1; i < NORCOW_SECTOR_COUNT; i++) { + erase_sector(i, secfalse); + } + norcow_active_sector = 0; + norcow_active_version = NORCOW_VERSION; + norcow_write_sector = 0; + norcow_free_offset = NORCOW_STORAGE_START; +} + +/* + * 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); +} + +/* + * Reads the next entry in the storage starting at offset. Returns secfalse if there is none. + */ +secbool norcow_get_next(uint32_t *offset, uint16_t *key, const void **val, uint16_t *len) +{ + if (*offset == 0) { + uint32_t version; + if (sectrue != find_start_offset(norcow_active_sector, offset, &version)) { + return secfalse; + } + } + + for (;;) { + uint32_t pos = 0; + secbool ret = read_item(norcow_active_sector, *offset, key, val, len, &pos); + if (sectrue != ret) { + break; + } + *offset = pos; + + // Skip deleted items. + if (*key == NORCOW_KEY_DELETED) { + continue; + } + + if (norcow_active_version == 0) { + // Check whether the item is the latest instance. + uint32_t offsetr = *offset; + for (;;) { + uint16_t k; + uint16_t l; + const void *v; + ret = read_item(norcow_active_sector, offsetr, &k, &v, &l, &offsetr); + if (sectrue != ret) { + // There is no newer instance of the item. + return sectrue; + } + if (*key == k) { + // There exists a newer instance of the item. + break; + } + } + } else { + return sectrue; + } + } + return secfalse; +} + +/* + * Sets the given key, returns status of the operation. If NULL is passed + * as val, then norcow_set allocates a new key of size len. The value should + * then be written using norcow_update_bytes(). + */ +secbool norcow_set(uint16_t key, const void *val, uint16_t len) +{ + secbool found; + return norcow_set_ex(key, val, len, &found); +} + +secbool norcow_set_ex(uint16_t key, const void *val, uint16_t len, secbool *found) +{ + // Key 0xffff is used as a marker to indicate that the entry is not set. + if (key == NORCOW_KEY_FREE) { + return secfalse; + } + + const uint8_t sector_num = norcow_sectors[norcow_write_sector]; + secbool ret = secfalse; + const void *ptr = NULL; + uint16_t len_old = 0; + *found = find_item(norcow_write_sector, key, &ptr, &len_old); + + // Try to update the entry if it already exists. + uint32_t offset = 0; + if (sectrue == *found) { + offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE); + if (val != NULL && len_old == len) { + ret = sectrue; + ensure(flash_unlock(), NULL); + for (uint16_t i = 0; i < len; i++) { + if (sectrue != flash_write_byte(sector_num, offset + i, ((const uint8_t*)val)[i])) { + ret = secfalse; + break; + } + } + ensure(flash_lock(), NULL); + } + } + + // If the update was not possible then write the entry as a new item. + if (secfalse == ret) { + // Delete the old item. + if (sectrue == *found) { + ensure(flash_unlock(), NULL); + + // Update the prefix to indicate that the old item has been deleted. + uint32_t prefix = (uint32_t)len_old << 16; + ensure(flash_write_word(sector_num, offset - NORCOW_PREFIX_LEN, prefix), NULL); + + // Delete the old item data. + uint32_t end = offset + len_old; + while (offset < end) { + ensure(flash_write_word(sector_num, offset, 0x00000000), NULL); + offset += NORCOW_WORD_SIZE; + } + + ensure(flash_lock(), NULL); + } + // Check whether there is enough free space and compact if full. + if (norcow_free_offset + NORCOW_PREFIX_LEN + len > NORCOW_SECTOR_SIZE) { + compact(); + } + // Write new item. + uint32_t pos; + ret = write_item(norcow_write_sector, norcow_free_offset, key, val, len, &pos); + if (sectrue == ret) { + norcow_free_offset = pos; + } + } + return ret; +} + +/* + * Deletes the given key, returns status of the operation. + */ +secbool norcow_delete(uint16_t key) +{ + // Key 0xffff is used as a marker to indicate that the entry is not set. + if (key == NORCOW_KEY_FREE) { + return secfalse; + } + + const uint8_t sector_num = norcow_sectors[norcow_write_sector]; + const void *ptr = NULL; + uint16_t len = 0; + if (sectrue != find_item(norcow_write_sector, key, &ptr, &len)) { + return secfalse; + } + + uint32_t offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE); + + ensure(flash_unlock(), NULL); + + // Update the prefix to indicate that the item has been deleted. + uint32_t prefix = (uint32_t)len << 16; + ensure(flash_write_word(sector_num, offset - NORCOW_PREFIX_LEN, prefix), NULL); + + // Delete the item data. + uint32_t end = offset + len; + while (offset < end) { + ensure(flash_write_word(sector_num, offset, 0x00000000), NULL); + offset += NORCOW_WORD_SIZE; + } + + ensure(flash_lock(), NULL); + + return sectrue; +} + +/* + * Update a word in flash at the given pointer. The pointer must point + * into the NORCOW area. + */ +secbool norcow_update_word(uint16_t key, uint16_t offset, uint32_t value) +{ + const void *ptr; + uint16_t len; + if (sectrue != find_item(norcow_write_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_write_sector, 0, NORCOW_SECTOR_SIZE) + offset; + ensure(flash_unlock(), NULL); + ensure(flash_write_word(norcow_sectors[norcow_write_sector], sector_offset, value), NULL); + ensure(flash_lock(), NULL); + return sectrue; +} + +/* + * Update the value of the given key starting at the given offset. + */ +secbool norcow_update_bytes(const uint16_t key, const uint16_t offset, const uint8_t *data, const uint16_t len) +{ + const void *ptr; + uint16_t allocated_len; + if (sectrue != find_item(norcow_write_sector, key, &ptr, &allocated_len)) { + return secfalse; + } + if (offset + len > allocated_len) { + return secfalse; + } + uint32_t sector_offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE) + offset; + uint8_t sector = norcow_sectors[norcow_write_sector]; + ensure(flash_unlock(), NULL); + for (uint16_t i = 0; i < len; i++, sector_offset++) { + ensure(flash_write_byte(sector, sector_offset, data[i]), NULL); + } + ensure(flash_lock(), NULL); + return sectrue; +} + +/* + * Complete storage version upgrade + */ +secbool norcow_upgrade_finish() +{ + erase_sector(norcow_active_sector, secfalse); + norcow_active_sector = norcow_write_sector; + norcow_active_version = NORCOW_VERSION; + return sectrue; +} diff --git a/norcow.h b/norcow.h new file mode 100644 index 000000000..953f6f1d0 --- /dev/null +++ b/norcow.h @@ -0,0 +1,82 @@ +/* + * 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 . + */ + +#ifndef __NORCOW_H__ +#define __NORCOW_H__ + +#include +#include "secbool.h" + +/* + * Storage parameters + */ + +#include "norcow_config.h" + +/* + * Initialize storage + */ +void norcow_init(uint32_t *norcow_version); + +/* + * 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); + +/* + * Reads the next entry in the storage starting at offset. Returns secfalse if there is none. + */ +secbool norcow_get_next(uint32_t *offset, uint16_t *key, const void **val, uint16_t *len); + +/* + * Sets the given key, returns status of the operation. If NULL is passed + * as val, then norcow_set allocates a new key of size len. The value should + * then be written using norcow_update_bytes(). + */ +secbool norcow_set(uint16_t key, const void *val, uint16_t len); +secbool norcow_set_ex(uint16_t key, const void *val, uint16_t len, secbool *found); + +/* + * Deletes the given key, returns status of the operation. + */ +secbool norcow_delete(uint16_t key); + +/* + * 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_word(uint16_t key, uint16_t offset, uint32_t value); + +/* + * Update the value of the given key starting at the given offset. + * Note that you can only change bits from 1 to 0. + */ +secbool norcow_update_bytes(const uint16_t key, const uint16_t offset, const uint8_t *data, const uint16_t len); + +/* + * Complete storage version upgrade + */ +secbool norcow_upgrade_finish(void); + +#endif diff --git a/storage.c b/storage.c new file mode 100644 index 000000000..4c150c048 --- /dev/null +++ b/storage.c @@ -0,0 +1,1093 @@ +/* + * 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 . + */ + +#include + +#include "common.h" +#include "norcow.h" +#include "storage.h" +#include "pbkdf2.h" +#include "sha2.h" +#include "hmac.h" +#include "rand.h" +#include "memzero.h" +#include "chacha20poly1305/rfc7539.h" + +#define LOW_MASK 0x55555555 + +// The APP namespace which is reserved for storage related values. +#define APP_STORAGE 0x00 + +// Norcow storage key of the PIN entry log and PIN success log. +#define PIN_LOGS_KEY ((APP_STORAGE << 8) | 0x01) + +// Norcow storage key of the combined salt, EDEK, ESAK and PIN verification code entry. +#define EDEK_PVC_KEY ((APP_STORAGE << 8) | 0x02) + +// Norcow storage key of the PIN set flag. +#define PIN_NOT_SET_KEY ((APP_STORAGE << 8) | 0x03) + +// Norcow storage key of the storage version. +#define VERSION_KEY ((APP_STORAGE << 8) | 0x04) + +// Norcow storage key of the storage authentication tag. +#define STORAGE_TAG_KEY ((APP_STORAGE << 8) | 0x05) + +// The PIN value corresponding to an empty PIN. +#define PIN_EMPTY 1 + +// Maximum number of failed unlock attempts. +// NOTE: The PIN counter logic relies on this constant being less than or equal to 16. +#define PIN_MAX_TRIES 16 + +// The total number of iterations to use in PBKDF2. +#define PIN_ITER_COUNT 20000 + +// If the top bit of APP is set, then the value is not encrypted. +#define FLAG_PUBLIC 0x80 + +// The length of the guard key in words. +#define GUARD_KEY_WORDS 1 + +// The length of the PIN entry log or the PIN success log in words. +#define PIN_LOG_WORDS 16 + +// The length of a word in bytes. +#define WORD_SIZE (sizeof(uint32_t)) + +// The length of the hashed hardware salt in bytes. +#define HARDWARE_SALT_SIZE SHA256_DIGEST_LENGTH + +// The length of the random salt in bytes. +#define RANDOM_SALT_SIZE 4 + +// The length of the data encryption key in bytes. +#define DEK_SIZE 32 + +// The length of the storage authentication key in bytes. +#define SAK_SIZE 16 + +// The combined length of the data encryption key and the storage authentication key in bytes. +#define KEYS_SIZE (DEK_SIZE + SAK_SIZE) + +// The length of the PIN verification code in bytes. +#define PVC_SIZE 8 + +// The length of the storage authentication tag in bytes. +#define STORAGE_TAG_SIZE 16 + +// The length of the Poly1305 authentication tag in bytes. +#define POLY1305_TAG_SIZE 16 + +// The length of the ChaCha20 IV (aka nonce) in bytes as per RFC 7539. +#define CHACHA20_IV_SIZE 12 + +// The length of the ChaCha20 block in bytes. +#define CHACHA20_BLOCK_SIZE 64 + +// Values used in the guard key integrity check. +#define GUARD_KEY_MODULUS 6311 +#define GUARD_KEY_REMAINDER 15 + +static secbool initialized = secfalse; +static secbool unlocked = secfalse; +static PIN_UI_WAIT_CALLBACK ui_callback = NULL; +static uint8_t cached_keys[KEYS_SIZE] = {0}; +static uint8_t *const cached_dek = cached_keys; +static uint8_t *const cached_sak = cached_keys + DEK_SIZE; +static uint8_t authentication_sum[SHA256_DIGEST_LENGTH] = {0}; +static uint8_t hardware_salt[HARDWARE_SALT_SIZE] = {0}; +static uint32_t norcow_active_version = 0; +static const uint8_t TRUE_BYTE = 0x01; +static const uint8_t FALSE_BYTE = 0x00; + +static void handle_fault(); +static secbool storage_upgrade(); +static secbool storage_set_encrypted(const uint16_t key, const void *val, const uint16_t len); +static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len); + +static secbool secequal(const void* ptr1, const void* ptr2, size_t n) { + const uint8_t* p1 = ptr1; + const uint8_t* p2 = ptr2; + uint8_t diff = 0; + size_t i; + for (i = 0; i < n; ++i) { + diff |= *p1 ^ *p2; + ++p1; + ++p2; + } + + // Check loop completion in case of a fault injection attack. + if (i != n) { + handle_fault(); + } + + return diff ? secfalse : sectrue; +} + +static secbool is_protected(uint16_t key) { + const uint8_t app = key >> 8; + return ((app & FLAG_PUBLIC) == 0 && app != APP_STORAGE) ? sectrue : secfalse; +} + +/* + * Initialize the storage authentication tag for freshly wiped storage. + */ +static secbool auth_init() { + uint8_t tag[SHA256_DIGEST_LENGTH]; + memzero(authentication_sum, sizeof(authentication_sum)); + hmac_sha256(cached_sak, SAK_SIZE, authentication_sum, sizeof(authentication_sum), tag); + return norcow_set(STORAGE_TAG_KEY, tag, STORAGE_TAG_SIZE); +} + +/* + * Update the storage authentication tag with the given key. + */ +static secbool auth_update(uint16_t key) { + if (sectrue != is_protected(key)) { + return sectrue; + } + + uint8_t tag[SHA256_DIGEST_LENGTH]; + hmac_sha256(cached_sak, SAK_SIZE, (uint8_t*)&key, sizeof(key), tag); + for (uint32_t i = 0; i < SHA256_DIGEST_LENGTH; i++) { + authentication_sum[i] ^= tag[i]; + } + hmac_sha256(cached_sak, SAK_SIZE, authentication_sum, sizeof(authentication_sum), tag); + return norcow_set(STORAGE_TAG_KEY, tag, STORAGE_TAG_SIZE); +} + +/* + * A secure version of norcow_set(), which updates the storage authentication tag. + */ +static secbool auth_set(uint16_t key, const void *val, uint16_t len) { + secbool found; + secbool ret = norcow_set_ex(key, val, len, &found); + if (sectrue == ret && secfalse == found) { + ret = auth_update(key); + if (sectrue != ret) { + norcow_delete(key); + } + } + return ret; +} + +/* + * A secure version of norcow_get(), which checks the storage authentication tag. + */ +static secbool auth_get(uint16_t key, const void **val, uint16_t *len) +{ + *val = NULL; + *len = 0; + uint32_t sum[SHA256_DIGEST_LENGTH/sizeof(uint32_t)] = {0}; + + // Prepare inner and outer digest. + uint32_t odig[SHA256_DIGEST_LENGTH / sizeof(uint32_t)]; + uint32_t idig[SHA256_DIGEST_LENGTH / sizeof(uint32_t)]; + hmac_sha256_prepare(cached_sak, SAK_SIZE, odig, idig); + + // Prepare SHA-256 message padding. + uint32_t g[SHA256_BLOCK_LENGTH / sizeof(uint32_t)] = {0}; + uint32_t h[SHA256_BLOCK_LENGTH / sizeof(uint32_t)] = {0}; + g[15] = (SHA256_BLOCK_LENGTH + 2) * 8; + h[15] = (SHA256_BLOCK_LENGTH + SHA256_DIGEST_LENGTH) * 8; + h[8] = 0x80000000; + + uint32_t offset = 0; + uint16_t k = 0; + uint16_t l = 0; + uint16_t tag_len = 0; + uint16_t entry_count = 0; // Mitigation against fault injection. + uint16_t other_count = 0; // Mitigation against fault injection. + const void *v = NULL; + const void *tag_val = NULL; + while (sectrue == norcow_get_next(&offset, &k, &v, &l)) { + ++entry_count; + if (k == key) { + *val = v; + *len = l; + } else { + ++other_count; + } + if (sectrue != is_protected(k)) { + if (k == STORAGE_TAG_KEY) { + tag_val = v; + tag_len = l; + } + continue; + } + g[0] = ((k & 0xff) << 24) | ((k & 0xff00) << 8) | 0x8000; // Add SHA message padding. + sha256_Transform(idig, g, h); + sha256_Transform(odig, h, h); + for (uint32_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) { + sum[i] ^= h[i]; + } + } + memcpy(h, sum, sizeof(sum)); + + sha256_Transform(idig, h, h); + sha256_Transform(odig, h, h); + + memzero(odig, sizeof(odig)); + memzero(idig, sizeof(idig)); + + // Cache the authentication sum. + for (size_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) { +#if BYTE_ORDER == LITTLE_ENDIAN + REVERSE32(((uint32_t*)authentication_sum)[i], sum[i]); +#else + ((uint32_t*)authentication_sum)[i] = sum[i]; +#endif + } + + // Check loop completion in case of a fault injection attack. + if (secfalse != norcow_get_next(&offset, &k, &v, &l)) { + handle_fault(); + } + + // Check storage authentication tag. +#if BYTE_ORDER == LITTLE_ENDIAN + for (size_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) { + REVERSE32(h[i], h[i]); + } +#endif + if (tag_val == NULL || tag_len != STORAGE_TAG_SIZE || sectrue != secequal(h, tag_val, STORAGE_TAG_SIZE)) { + handle_fault(); + } + + if (*val == NULL) { + // Check for fault injection. + if (other_count != entry_count) { + handle_fault(); + } + return secfalse; + } + return sectrue; +} + +/* + * Generates a delay of random length. Use this to protect sensitive code against fault injection. + */ +static void wait_random() +{ +#ifndef TREZOR_STORAGE_TEST + int wait = random32() & 0xff; + volatile int i = 0; + volatile int j = wait; + while (i < wait) { + if (i + j != wait) { + handle_fault(); + } + ++i; + --j; + } + + // Double-check loop completion. + if (i != wait) { + handle_fault(); + } +#endif +} + +static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA256_DIGEST_LENGTH], uint8_t keiv[SHA256_DIGEST_LENGTH]) +{ +#if BYTE_ORDER == BIG_ENDIAN + REVERSE32(pin, pin); +#endif + + uint8_t salt[HARDWARE_SALT_SIZE + RANDOM_SALT_SIZE]; + memcpy(salt, hardware_salt, HARDWARE_SALT_SIZE); + memcpy(salt + HARDWARE_SALT_SIZE, random_salt, RANDOM_SALT_SIZE); + + PBKDF2_HMAC_SHA256_CTX ctx; + pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 1); + pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT/2); + pbkdf2_hmac_sha256_Final(&ctx, kek); + pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 2); + pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT/2); + pbkdf2_hmac_sha256_Final(&ctx, keiv); + memzero(&ctx, sizeof(PBKDF2_HMAC_SHA256_CTX)); + memzero(&pin, sizeof(pin)); + memzero(&salt, sizeof(salt)); +} + +static secbool set_pin(uint32_t pin) +{ + uint8_t buffer[RANDOM_SALT_SIZE + KEYS_SIZE + POLY1305_TAG_SIZE]; + uint8_t *salt = buffer; + uint8_t *ekeys = buffer + RANDOM_SALT_SIZE; + uint8_t *pvc = buffer + RANDOM_SALT_SIZE + KEYS_SIZE; + + uint8_t kek[SHA256_DIGEST_LENGTH]; + uint8_t keiv[SHA256_DIGEST_LENGTH]; + chacha20poly1305_ctx ctx; + random_buffer(salt, RANDOM_SALT_SIZE); + derive_kek(pin, salt, kek, keiv); + rfc7539_init(&ctx, kek, keiv); + memzero(kek, sizeof(kek)); + memzero(keiv, sizeof(keiv)); + chacha20poly1305_encrypt(&ctx, cached_keys, ekeys, KEYS_SIZE); + rfc7539_finish(&ctx, 0, KEYS_SIZE, pvc); + memzero(&ctx, sizeof(ctx)); + secbool ret = norcow_set(EDEK_PVC_KEY, buffer, RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE); + memzero(buffer, sizeof(buffer)); + + if (ret == sectrue) + { + if (pin == PIN_EMPTY) { + ret = norcow_set(PIN_NOT_SET_KEY, &TRUE_BYTE, sizeof(TRUE_BYTE)); + } else { + ret = norcow_set(PIN_NOT_SET_KEY, &FALSE_BYTE, sizeof(FALSE_BYTE)); + } + } + + memzero(&pin, sizeof(pin)); + return ret; +} + +static secbool check_guard_key(const uint32_t guard_key) +{ + if (guard_key % GUARD_KEY_MODULUS != GUARD_KEY_REMAINDER) { + return secfalse; + } + + // Check that each byte of (guard_key & 0xAAAAAAAA) has exactly two bits set. + uint32_t count = (guard_key & 0x22222222) + ((guard_key >> 2) & 0x22222222); + count = count + (count >> 4); + if ((count & 0x0e0e0e0e) != 0x04040404) { + return secfalse; + } + + // Check that the guard_key does not contain a run of 5 (or more) zeros or ones. + uint32_t zero_runs = ~guard_key; + zero_runs = zero_runs & (zero_runs >> 2); + zero_runs = zero_runs & (zero_runs >> 1); + zero_runs = zero_runs & (zero_runs >> 1); + + uint32_t one_runs = guard_key; + one_runs = one_runs & (one_runs >> 2); + one_runs = one_runs & (one_runs >> 1); + one_runs = one_runs & (one_runs >> 1); + + if ((one_runs != 0) || (zero_runs != 0)) { + return secfalse; + } + + return sectrue; +} + +static uint32_t generate_guard_key() +{ + uint32_t guard_key = 0; + do { + guard_key = random_uniform((UINT32_MAX/GUARD_KEY_MODULUS) + 1) * GUARD_KEY_MODULUS + GUARD_KEY_REMAINDER; + } while (sectrue != check_guard_key(guard_key)); + return guard_key; +} + +static secbool expand_guard_key(const uint32_t guard_key, uint32_t *guard_mask, uint32_t *guard) +{ + if (sectrue != check_guard_key(guard_key)) { + handle_fault(); + return secfalse; + } + *guard_mask = ((guard_key & LOW_MASK) << 1) | ((~guard_key) & LOW_MASK); + *guard = (((guard_key & LOW_MASK) << 1) & guard_key) | (((~guard_key) & LOW_MASK) & (guard_key >> 1)); + return sectrue; +} + +static secbool pin_logs_init(uint32_t fails) +{ + if (fails >= PIN_MAX_TRIES) { + return secfalse; + } + + // The format of the PIN_LOGS_KEY entry is: + // guard_key (1 word), pin_success_log (PIN_LOG_WORDS), pin_entry_log (PIN_LOG_WORDS) + uint32_t logs[GUARD_KEY_WORDS + 2*PIN_LOG_WORDS]; + + logs[0] = generate_guard_key(); + + uint32_t guard_mask; + uint32_t guard; + wait_random(); + if (sectrue != expand_guard_key(logs[0], &guard_mask, &guard)) { + return secfalse; + } + + uint32_t unused = guard | ~guard_mask; + for (size_t i = 0; i < 2*PIN_LOG_WORDS; ++i) { + logs[GUARD_KEY_WORDS + i] = unused; + } + + // Set the first word of the PIN entry log to indicate the requested number of fails. + logs[GUARD_KEY_WORDS + PIN_LOG_WORDS] = ((((uint32_t)0xFFFFFFFF) >> (2*fails)) & ~guard_mask) | guard; + + return norcow_set(PIN_LOGS_KEY, logs, sizeof(logs)); +} + +/* + * Initializes the values of VERSION_KEY, EDEK_PVC_KEY, PIN_NOT_SET_KEY and PIN_LOGS_KEY using an empty PIN. + * This function should be called to initialize freshly wiped storage. + */ +static void init_wiped_storage() +{ + random_buffer(cached_keys, sizeof(cached_keys)); + uint32_t version = NORCOW_VERSION; + ensure(auth_init(), "failed to initialize storage authentication tag"); + ensure(storage_set_encrypted(VERSION_KEY, &version, sizeof(version)), "failed to set storage version"); + ensure(set_pin(PIN_EMPTY), "failed to initialize PIN"); + ensure(pin_logs_init(0), "failed to initialize PIN logs"); + if (unlocked != sectrue) { + memzero(cached_keys, sizeof(cached_keys)); + } +} + +void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len) +{ + initialized = secfalse; + unlocked = secfalse; + norcow_init(&norcow_active_version); + initialized = sectrue; + ui_callback = callback; + + sha256_Raw(salt, salt_len, hardware_salt); + + if (norcow_active_version < NORCOW_VERSION) { + if (sectrue != storage_upgrade()) { + storage_wipe(); + ensure(secfalse, "storage_upgrade"); + } + } + + // If there is no EDEK, then generate a random DEK and SAK and store them. + const void *val; + uint16_t len; + if (secfalse == norcow_get(EDEK_PVC_KEY, &val, &len)) { + init_wiped_storage(); + } + memzero(cached_keys, sizeof(cached_keys)); +} + +static secbool pin_fails_reset() +{ + const void *logs = NULL; + uint16_t len = 0; + + if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) { + return secfalse; + } + + uint32_t guard_mask; + uint32_t guard; + wait_random(); + if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) { + return secfalse; + } + + uint32_t unused = guard | ~guard_mask; + const uint32_t *success_log = ((const uint32_t*)logs) + GUARD_KEY_WORDS; + const uint32_t *entry_log = success_log + PIN_LOG_WORDS; + for (size_t i = 0; i < PIN_LOG_WORDS; ++i) { + if (entry_log[i] == unused) { + return sectrue; + } + if (success_log[i] != guard) { + if (sectrue != norcow_update_word(PIN_LOGS_KEY, sizeof(uint32_t)*(i + GUARD_KEY_WORDS), entry_log[i])) { + return secfalse; + } + } + } + return pin_logs_init(0); +} + +static secbool pin_fails_increase() +{ + const void *logs = NULL; + uint16_t len = 0; + + wait_random(); + if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) { + handle_fault(); + return secfalse; + } + + uint32_t guard_mask; + uint32_t guard; + wait_random(); + if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) { + handle_fault(); + return secfalse; + } + + const uint32_t *entry_log = ((const uint32_t*)logs) + GUARD_KEY_WORDS + PIN_LOG_WORDS; + for (size_t i = 0; i < PIN_LOG_WORDS; ++i) { + wait_random(); + if ((entry_log[i] & guard_mask) != guard) { + handle_fault(); + return secfalse; + } + if (entry_log[i] != guard) { + wait_random(); + uint32_t word = entry_log[i] & ~guard_mask; + word = ((word >> 1) | word) & LOW_MASK; + word = (word >> 2) | (word >> 1); + + wait_random(); + if (sectrue != norcow_update_word(PIN_LOGS_KEY, sizeof(uint32_t)*(i + GUARD_KEY_WORDS + PIN_LOG_WORDS), (word & ~guard_mask) | guard)) { + handle_fault(); + return secfalse; + } + return sectrue; + } + + } + handle_fault(); + return secfalse; +} + +static uint32_t hamming_weight(uint32_t value) +{ + value = value - ((value >> 1) & 0x55555555); + value = (value & 0x33333333) + ((value >> 2) & 0x33333333); + value = (value + (value >> 4)) & 0x0F0F0F0F; + value = value + (value >> 8); + value = value + (value >> 16); + return value & 0x3F; +} + +static secbool pin_get_fails(uint32_t *ctr) +{ + *ctr = PIN_MAX_TRIES; + + const void *logs = NULL; + uint16_t len = 0; + wait_random(); + if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) { + handle_fault(); + return secfalse; + } + + uint32_t guard_mask; + uint32_t guard; + wait_random(); + if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) { + handle_fault(); + return secfalse; + } + const uint32_t unused = guard | ~guard_mask; + + const uint32_t *success_log = ((const uint32_t*)logs) + GUARD_KEY_WORDS; + const uint32_t *entry_log = success_log + PIN_LOG_WORDS; + volatile int current = -1; + volatile size_t i; + for (i = 0; i < PIN_LOG_WORDS; ++i) { + if ((entry_log[i] & guard_mask) != guard || (success_log[i] & guard_mask) != guard || (entry_log[i] & success_log[i]) != entry_log[i]) { + handle_fault(); + return secfalse; + } + + if (current == -1) { + if (entry_log[i] != guard) { + current = i; + } + } else { + if (entry_log[i] != unused) { + handle_fault(); + return secfalse; + } + } + } + + if (current < 0 || current >= PIN_LOG_WORDS || i != PIN_LOG_WORDS) { + handle_fault(); + return secfalse; + } + + // Strip the guard bits from the current entry word and duplicate each data bit. + wait_random(); + uint32_t word = entry_log[current] & ~guard_mask; + word = ((word >> 1) | word ) & LOW_MASK; + word = word | (word << 1); + // Verify that the entry word has form 0*1*. + if ((word & (word + 1)) != 0) { + handle_fault(); + return secfalse; + } + + if (current == 0) { + ++current; + } + + // Count the number of set bits in the two current words of the success log. + wait_random(); + *ctr = hamming_weight(success_log[current-1] ^ entry_log[current-1]) + hamming_weight(success_log[current] ^ entry_log[current]); + return sectrue; +} + +static secbool unlock(uint32_t pin) +{ + const void *buffer = NULL; + uint16_t len = 0; + if (sectrue != initialized || sectrue != norcow_get(EDEK_PVC_KEY, &buffer, &len) || len != RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE) { + memzero(&pin, sizeof(pin)); + return secfalse; + } + + const uint8_t *salt = (const uint8_t*) buffer; + const uint8_t *ekeys = (const uint8_t*) buffer + RANDOM_SALT_SIZE; + const uint8_t *pvc = (const uint8_t*) buffer + RANDOM_SALT_SIZE + KEYS_SIZE; + uint8_t kek[SHA256_DIGEST_LENGTH]; + uint8_t keiv[SHA256_DIGEST_LENGTH]; + uint8_t keys[KEYS_SIZE]; + uint8_t tag[POLY1305_TAG_SIZE]; + chacha20poly1305_ctx ctx; + + // Decrypt the data encryption key and the storage authentication key and check the PIN verification code. + derive_kek(pin, salt, kek, keiv); + memzero(&pin, sizeof(pin)); + rfc7539_init(&ctx, kek, keiv); + memzero(kek, sizeof(kek)); + memzero(keiv, sizeof(keiv)); + chacha20poly1305_decrypt(&ctx, ekeys, keys, KEYS_SIZE); + rfc7539_finish(&ctx, 0, KEYS_SIZE, tag); + memzero(&ctx, sizeof(ctx)); + wait_random(); + if (secequal(tag, pvc, PVC_SIZE) != sectrue) { + memzero(keys, sizeof(keys)); + memzero(tag, sizeof(tag)); + return secfalse; + } + memcpy(cached_keys, keys, sizeof(keys)); + memzero(keys, sizeof(keys)); + memzero(tag, sizeof(tag)); + + // Call auth_get() to initialize the authentication_sum. + auth_get(0, &buffer, &len); + + // Check that the authenticated version number matches the norcow version. + uint32_t version; + if (sectrue != storage_get_encrypted(VERSION_KEY, &version, sizeof(version), &len) || len != sizeof(version) || version != norcow_active_version) { + handle_fault(); + return secfalse; + } + + return sectrue; +} + +secbool storage_unlock(uint32_t pin) +{ + // Get the pin failure counter + uint32_t ctr; + if (sectrue != pin_get_fails(&ctr)) { + memzero(&pin, sizeof(pin)); + return secfalse; + } + + // Wipe storage if too many failures + wait_random(); + if (ctr >= PIN_MAX_TRIES) { + storage_wipe(); + ensure(secfalse, "pin_fails_check_max"); + return secfalse; + } + + // Sleep for 2^(ctr-1) seconds before checking the PIN. + uint32_t wait = (1 << ctr) >> 1; + uint32_t progress; + for (uint32_t rem = wait; rem > 0; rem--) { + for (int i = 0; i < 10; i++) { + if (ui_callback) { + if (wait > 1000000) { // precise enough + progress = (wait - rem) / (wait / 1000); + } else { + progress = ((wait - rem) * 10 + i) * 100 / wait; + } + ui_callback(rem, progress); + } + hal_delay(100); + } + } + // Show last frame if we were waiting + if ((wait > 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()) { + memzero(&pin, sizeof(pin)); + return secfalse; + } + + // Check that the PIN fail counter was incremented. + uint32_t ctr_ck; + if (sectrue != pin_get_fails(&ctr_ck) || ctr + 1 != ctr_ck) { + handle_fault(); + return secfalse; + } + + if (sectrue != unlock(pin)) { + // Wipe storage if too many failures + wait_random(); + if (ctr + 1 >= PIN_MAX_TRIES) { + storage_wipe(); + ensure(secfalse, "pin_fails_check_max"); + } + return secfalse; + } + memzero(&pin, sizeof(pin)); + unlocked = sectrue; + + // Finally set the counter to 0 to indicate success. + return pin_fails_reset(); +} + +/* + * Finds the encrypted data stored under key and writes its length to len. + * If val_dest is not NULL and max_len >= len, then the data is decrypted + * to val_dest using cached_dek as the decryption key. + */ +static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len) +{ + const void *val_stored = NULL; + + if (sectrue != auth_get(key, &val_stored, len)) { + return secfalse; + } + + if (*len < CHACHA20_IV_SIZE + POLY1305_TAG_SIZE) { + handle_fault(); + return secfalse; + } + *len -= CHACHA20_IV_SIZE + POLY1305_TAG_SIZE; + + if (val_dest == NULL) { + return sectrue; + } + + if (*len > max_len) { + return secfalse; + } + + const uint8_t *iv = (const uint8_t*) val_stored; + const uint8_t *ciphertext = (const uint8_t*) val_stored + CHACHA20_IV_SIZE; + const uint8_t *tag_stored = (const uint8_t*) val_stored + CHACHA20_IV_SIZE + *len; + uint8_t tag_computed[POLY1305_TAG_SIZE]; + chacha20poly1305_ctx ctx; + rfc7539_init(&ctx, cached_dek, iv); + rfc7539_auth(&ctx, (const uint8_t*)&key, sizeof(key)); + chacha20poly1305_decrypt(&ctx, ciphertext, (uint8_t*) val_dest, *len); + rfc7539_finish(&ctx, sizeof(key), *len, tag_computed); + memzero(&ctx, sizeof(ctx)); + + // Verify authentication tag. + if (secequal(tag_computed, tag_stored, POLY1305_TAG_SIZE) != sectrue) { + memzero(val_dest, max_len); + memzero(tag_computed, sizeof(tag_computed)); + handle_fault(); + return secfalse; + } + + memzero(tag_computed, sizeof(tag_computed)); + return sectrue; +} + +/* + * Finds the data stored under key and writes its length to len. If val_dest is + * not NULL and max_len >= len, then the data is copied to val_dest. + */ +secbool storage_get(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len) +{ + const uint8_t app = key >> 8; + // APP == 0 is reserved for PIN related values + if (sectrue != initialized || app == APP_STORAGE) { + return secfalse; + } + + // If the top bit of APP is set, then the value is not encrypted and can be read from an unlocked device. + secbool ret = secfalse; + if ((app & FLAG_PUBLIC) != 0) { + const void *val_stored = NULL; + if (sectrue != norcow_get(key, &val_stored, len)) { + return secfalse; + } + if (val_dest == NULL) { + return sectrue; + } + if (*len > max_len) { + return secfalse; + } + memcpy(val_dest, val_stored, *len); + ret = sectrue; + } else { + if (sectrue != unlocked) { + return secfalse; + } + ret = storage_get_encrypted(key, val_dest, max_len, len); + } + + return ret; +} + +/* + * Encrypts the data at val using cached_dek as the encryption key and stores the ciphertext under key. + */ +static secbool storage_set_encrypted(const uint16_t key, const void *val, const uint16_t len) +{ + // Preallocate space on the flash storage. + uint16_t offset = 0; + if (sectrue != auth_set(key, NULL, CHACHA20_IV_SIZE + len + POLY1305_TAG_SIZE)) { + return secfalse; + } + + // Write the IV to the flash. + uint8_t buffer[CHACHA20_BLOCK_SIZE + POLY1305_TAG_SIZE]; + random_buffer(buffer, CHACHA20_IV_SIZE); + if (sectrue != norcow_update_bytes(key, offset, buffer, CHACHA20_IV_SIZE)) { + return secfalse; + } + offset += CHACHA20_IV_SIZE; + + // Encrypt all blocks except for the last one. + chacha20poly1305_ctx ctx; + rfc7539_init(&ctx, cached_dek, buffer); + rfc7539_auth(&ctx, (const uint8_t*)&key, sizeof(key)); + size_t i; + for (i = 0; i + CHACHA20_BLOCK_SIZE < len; i += CHACHA20_BLOCK_SIZE, offset += CHACHA20_BLOCK_SIZE) { + chacha20poly1305_encrypt(&ctx, ((const uint8_t*) val) + i, buffer, CHACHA20_BLOCK_SIZE); + if (sectrue != norcow_update_bytes(key, offset, buffer, CHACHA20_BLOCK_SIZE)) { + memzero(&ctx, sizeof(ctx)); + memzero(buffer, sizeof(buffer)); + return secfalse; + } + } + + // Encrypt final block and compute message authentication tag. + chacha20poly1305_encrypt(&ctx, ((const uint8_t*) val) + i, buffer, len - i); + rfc7539_finish(&ctx, sizeof(key), len, buffer + len - i); + secbool ret = norcow_update_bytes(key, offset, buffer, len - i + POLY1305_TAG_SIZE); + memzero(&ctx, sizeof(ctx)); + memzero(buffer, sizeof(buffer)); + return ret; +} + +secbool storage_set(const uint16_t key, const void *val, const uint16_t len) +{ + const uint8_t app = key >> 8; + + // APP == 0 is reserved for PIN related values + if (sectrue != initialized || sectrue != unlocked || app == APP_STORAGE) { + return secfalse; + } + + secbool ret = secfalse; + if ((app & FLAG_PUBLIC) != 0) { + ret = norcow_set(key, val, len); + } else { + ret = storage_set_encrypted(key, val, len); + } + return ret; +} + +secbool storage_delete(const uint16_t key) +{ + const uint8_t app = key >> 8; + + // APP == 0 is reserved for storage related values + if (sectrue != initialized || sectrue != unlocked || app == APP_STORAGE) { + return secfalse; + } + + secbool ret = norcow_delete(key); + if (sectrue == ret) { + ret = auth_update(key); + } + return ret; +} + +secbool storage_has_pin(void) +{ + if (sectrue != initialized) { + return secfalse; + } + + const void *val = NULL; + uint16_t len; + if (sectrue != norcow_get(PIN_NOT_SET_KEY, &val, &len) || (len > 0 && *(uint8_t*)val != FALSE_BYTE)) { + return secfalse; + } + return sectrue; +} + +uint32_t storage_get_pin_rem(void) +{ + uint32_t ctr = 0; + if (sectrue != pin_get_fails(&ctr)) { + return 0; + } + return PIN_MAX_TRIES - ctr; +} + +secbool storage_change_pin(uint32_t oldpin, uint32_t newpin) +{ + if (sectrue != initialized || sectrue != unlocked) { + return secfalse; + } + if (sectrue != storage_unlock(oldpin)) { + return secfalse; + } + secbool ret = set_pin(newpin); + memzero(&oldpin, sizeof(oldpin)); + memzero(&newpin, sizeof(newpin)); + return ret; +} + +void storage_wipe(void) +{ + norcow_wipe(); + norcow_active_version = NORCOW_VERSION; + memzero(authentication_sum, sizeof(authentication_sum)); + memzero(cached_keys, sizeof(cached_keys)); + init_wiped_storage(); +} + +static void handle_fault() +{ + static secbool in_progress = secfalse; + + // If fault handling is already in progress, then we are probably facing a fault injection attack, so wipe. + if (secfalse != in_progress) { + storage_wipe(); + ensure(secfalse, "fault detected"); + } + + // We use the PIN fail counter as a fault counter. Increment the counter, check that it was incremented and halt. + in_progress = sectrue; + uint32_t ctr; + if (sectrue != pin_get_fails(&ctr)) { + storage_wipe(); + ensure(secfalse, "fault detected"); + } + + if (sectrue != pin_fails_increase()) { + storage_wipe(); + ensure(secfalse, "fault detected"); + } + + uint32_t ctr_new; + if (sectrue != pin_get_fails(&ctr_new) || ctr + 1 != ctr_new) { + storage_wipe(); + } + ensure(secfalse, "fault detected"); +} + +/* + * Reads the PIN fail counter in version 0 format. Returns the current number of failed PIN entries. + */ +static secbool v0_pin_get_fails(uint32_t *ctr) +{ + const uint16_t V0_PIN_FAIL_KEY = 0x0001; + // 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 + const void *val = NULL; + uint16_t len = 0; + if (secfalse != norcow_get(V0_PIN_FAIL_KEY, &val, &len)) { + for (unsigned int i = 0; i < len / sizeof(uint32_t); i++) { + uint32_t word = ((const uint32_t*)val)[i]; + if (word != 0) { + *ctr = hamming_weight(~word); + return sectrue; + } + } + } + + // No PIN failures + *ctr = 0; + return sectrue; +} + +static secbool storage_upgrade() +{ + const uint16_t V0_PIN_KEY = 0x0000; + const uint16_t V0_PIN_FAIL_KEY = 0x0001; + uint16_t key = 0; + uint16_t len = 0; + const void *val = NULL; + + if (norcow_active_version == 0) { + random_buffer(cached_keys, sizeof(cached_keys)); + + // Initialize the storage authentication tag. + auth_init(); + + // Set the new storage version number. + uint32_t version = NORCOW_VERSION; + if (sectrue != storage_set_encrypted(VERSION_KEY, &version, sizeof(version))) { + return secfalse; + } + + // Set EDEK_PVC_KEY and PIN_NOT_SET_KEY. + if (sectrue == norcow_get(V0_PIN_KEY, &val, &len)) { + set_pin(*(const uint32_t*)val); + } else { + set_pin(PIN_EMPTY); + } + + // Convert PIN failure counter. + uint32_t fails = 0; + v0_pin_get_fails(&fails); + pin_logs_init(fails); + + // Copy the remaining entries (encrypting the protected ones). + uint32_t offset = 0; + while (sectrue == norcow_get_next(&offset, &key, &val, &len)) { + if (key == V0_PIN_KEY || key == V0_PIN_FAIL_KEY) { + continue; + } + + secbool ret; + if (((key >> 8) & FLAG_PUBLIC) != 0) { + ret = norcow_set(key, val, len); + } else { + ret = storage_set_encrypted(key, val, len); + } + + if (sectrue != ret) { + return secfalse; + } + } + + unlocked = secfalse; + memzero(cached_keys, sizeof(cached_keys)); + } else { + return secfalse; + } + + norcow_active_version = NORCOW_VERSION; + return norcow_upgrade_finish(); +} diff --git a/storage.h b/storage.h new file mode 100644 index 000000000..00e7bd074 --- /dev/null +++ b/storage.h @@ -0,0 +1,39 @@ +/* + * 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 . + */ + +#ifndef __STORAGE_H__ +#define __STORAGE_H__ + +#include +#include +#include "secbool.h" + +typedef void (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress); + +void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len); +void storage_wipe(void); +secbool storage_unlock(const uint32_t pin); +secbool storage_has_pin(void); +uint32_t storage_get_pin_rem(void); +secbool storage_change_pin(const uint32_t oldpin, const uint32_t newpin); +secbool storage_get(const uint16_t key, void *val, const uint16_t max_len, uint16_t *len); +secbool storage_set(const uint16_t key, const void *val, uint16_t len); +secbool storage_delete(const uint16_t key); + +#endif From 638a933e22f89008170042634a6f12a1474e0d60 Mon Sep 17 00:00:00 2001 From: Pavol Rusnak Date: Thu, 24 Jan 2019 15:57:18 +0100 Subject: [PATCH 02/39] add COPYING --- COPYING | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 COPYING diff --git a/COPYING b/COPYING new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. From 8970e2bdebb3334ddd0bacf41c66be79e78880f8 Mon Sep 17 00:00:00 2001 From: Pavol Rusnak Date: Thu, 24 Jan 2019 16:01:47 +0100 Subject: [PATCH 03/39] add .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..5761abcfd --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.o From f24c6e31f6f4ad59bff7699a841783f35671dc4a Mon Sep 17 00:00:00 2001 From: Tomas Susanka Date: Fri, 25 Jan 2019 10:19:33 +0100 Subject: [PATCH 04/39] readme: import from google docs --- README.md | 282 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 282 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..c0733722b --- /dev/null +++ b/README.md @@ -0,0 +1,282 @@ +# Trezor Storage + +This repository contains the implementation of Trezor's internal storage, which is common for both trezor-mcu (Trezor One) and trezor-core (Trezor T). This README also contains a detailed description of the cryptographic design. + +All tests are located in the [trezor-storage-test](https://github.com/trezor/trezor-storage-test) repository, which also includes a Python implementation to run tests against this C production version and the Python one. + +## Summary + +The PIN is no longer stored in the flash storage. A new entry is added to the flash storage consisting of a 256-bit encrypted data encryption key (EDEK) followed by a 128-bit encrypted storage authentication key (ESAK) and a 64-bit PIN verification code (PVC). The PIN is used to decrypt the EDEK and ESAK and the PVC is be used to verify that the correct PIN was used. The resulting data encryption key (DEK) is then used to encrypt/decrypt protected entries in the flash storage. We use Chacha20Poly1305 as defined in [RFC 7539](https://tools.ietf.org/html/rfc7539) to encrypt the EDEK and the protected entries. The storage authentication key (SAK) is used to authenticate the list of (APP, KEY) values for all protected entries that have been set in the storage. This prevents an attacker from erasing or adding entries to the storage. + +## Storage format + +The current format of the entries in the flash storage is: + +| Data | KEY | APP | LEN | DATA | +|----------------|-----|-----|-----|------| +| Length (bytes) | 1 | 1 | 2 | LEN | + +Entries fall into three categories: + +| Category | Condition | Read | Write | +|-----------|-----------------|--------------------|--------------------| +| Private | APP = 0 | Never | Never | +| Protected | 1 ≤ APP ≤ 127 | Only when unlocked | Only when unlocked | +| Public | 128 ≤ APP ≤ 255 | Always | Only when unlocked | + +Private values are used to store storage-specific information and cannot be directly accessed through the storage interface. Currently the above conditions are enforced only in software, but not cryptographically. We propose that protected entries shall have the following new format:z + +| Data | KEY | APP | LEN | IV | ENCRDATA | TAG | +|----------------|-----|-----|-----|----|----------|-----| +| Length (bytes) | 1 | 1 | 2 | 12 | LEN - 28 | 16 | + +The LEN value thus indicates the total length of IV, ENCRDATA and TAG. The format of public entries shall remain unchanged. + +The random salt (32 bits), EDEK (256 bits), ESAK (128 bits) and PVC (64 bits) will be stored in a single entry under APP=0, KEY=2: + +| Data | KEY | APP | LEN | SALT | EDEK | ESAK | PVC | +|----------------|-----|-----|-------|------|------|------|-----| +| Length (bytes) | 1 | 1 | 2 | 4 | 32 | 16 | 8 | +| Value | 02 | 00 | 3C 00 | | | | | + +The storage authentication tag (128 bits) will be stored in a single entry under APP=0, KEY=5: + +| Data | KEY | APP | LEN | TAG | +|----------------|-----|-----|-------|-----| +| Length (bytes) | 1 | 1 | 2 | 16 | +| Value | 05 | 00 | 20 00 | | + +Furthermore, if any entry is overwritten, the old entry will be erased, i.e., overwritten with 0. We could then also use APP=0, KEY=0 as marker that the entry is erased (currently this is the marker for the PIN entry that we wouldn't need anymore). + +## PIN verification and decryption of protected entries in flash storage + +1. From the flash storage read the entry containing the random salt, EDEK and PVC. +2. Gather constant data from various system resources such as the ProcessorID (aka Unique device ID) and any hardware serial numbers that are available. The concatenation of this data with the random salt will be referred to as *salt*. +3. Prompt the user to enter the PIN. Prefix the entered PIN with a "1" digit in base 10 and convert the integer to 4 bytes in little endian byte order. Then compute: + + `PBKDF2(PRF = HMAC-SHA256, Password = pin, Salt = salt, iterations = 10000, dkLen = 352 bits)` + + The first 256 bits of the output will be used as the key encryption key (KEK) and the remaining 96 bits will be used as the key encryption initialization vector (KEIV). + + *Note: Since two blocks of output need to be produced in PBKDF2 the total number of iterations is 20000.* + +4. Compute: + + `(dek, tag) = ChaCha20Poly1305Decrypt(kek, keiv, edek)` + +5. Compare the PVC read from the flash storage with the first 64 bits of the computed tag value. If there is a mismatch, then fail. Otherwise store the DEK in a global variable. + +6. When a protected entry needs to be decrypted, load the IV, ENCRDATA and TAG of the entry and compute: + + `(data, tag) = ChaCha20Poly1305Decrypt(dek, iv, (key || app), encrdata)` + + where the APP and KEY of the entry is used as two bytes of associated data. Compare the TAG read from the flash storage with the computed tag value. If there is a mismatch, then fail. + +## Initializing the EDEK + +1. When the storage is initialized, generate the 32 bit random salt and 256 bit DEK using a cryptographically secure random number generator. + +2. Set a boolean value in the storage denoting that the PIN has not been set. Use an empty PIN to derive the KEK and KEIV as described above. + +3. Encrypt the DEK using the derived KEK and KEIV: + + `(edek, tag) = ChaCha20Poly1305Encrypt(kek, keiv, dek)` + +4. Store the random salt, EDEK value and the first 64 bits of the tag as the PVC. + +## Setting a new PIN + +1. If the PIN has already been set, then prompt the user to enter the old PIN value, check the PVC and compute the DEK as described above in steps 1-4. + +2. Generate a new 32 bit random salt and prompt the user to enter the new PIN value. Use these values to derive the new KEK and KEIV as described above. + +3. Encrypt the DEK using the new KEK and KEIV: + + `(edek, tag) = ChaCha20Poly1305Encrypt(kek, keiv, dek)` + +4. Store the new EDEK value and the first 64 bits of the tag as the new PVC. This operation should be atomic, i.e. either both values should be stored or neither. Overwrite the old values of the EDEK and PVC with zeros. + +## Encryption of protected entries in flash storage + +Whenever the value of an entry needs to be updated, a fresh IV is generated using a cryptographically secure random number generator and the data is encrypted as `(encrdata, tag) = ChaCha20Poly1305Encrypt(dek, iv, (key || app), data)`. + +## Storage authentication + +The storage authentication key (SAK) will be used to generate a storage authentication tag (SAT) for the list of all (APP, KEY) values of protected entries (1 ≤ APP ≤ 127) that have been set in the storage. The SAT will be checked during every get operation. When a new protected entry is added to the storage or when a protected entry is deleted from the storage, the value of the SAT will be updated. The value of the SAT is defined as the first 16 bytes of + +`HMAC-SHA-256(SAK, ⨁i HMAC-SHA-256(SAK, KEYi || APPi))` + +where `⨁` denotes the n-ary bitwise XOR operation and KEYi || APPi is a two-byte encoding of the value of the i-th (APP, KEY) such that 1 ≤ APP ≤ 127. + +## Design rationale + +- The purpose of the PBKDF2 function is to thwart brute-force attacks in case the attacker is able to circumvent the PIN entry counter mechanism but does not have full access to the contents of the flash storage of the device, e.g. fault injection attacks. For an attacker that would be able to read the flash storage and obtain the salt, the PBKDF2 with 20000 iterations and a 4- to 9-digit PIN would not pose an obstacle. + +- The reason why we propose to use a separate data encryption key rather than using the output of PBKDF2 directly to encrypt the sensitive entries is so that when the user decides to change their PIN, only the EDEK needs to be reencrypted, but the remaining entries do not need to be updated. + +- We propose to use ChaCha20 for encryption, because as a stream cipher it has no padding overhead and its implementation is readily available in trezor-crypto. A possible alternative to using ChaCha20Poly1305 for DEK encryption is to use AES-CTR with HMAC in an encrypt-then-MAC scheme. A possible alternative to using ChaCha20 for encryption of other data entries is to use AES-XTS (XEX-based tweaked-codebook mode with ciphertext stealing), which was designed specifically for disk-encryption. The APP || KEY value would be used as the tweak. + - Advantages of AES-XTS: + - Does not require an initialization vector. + - Ensures better diffusion than a stream cipher, which eliminates the above concerns about malleability and fault injection attacks. + - Disadvantages of AES-XTS: + - Not implemented in trezor-crypto. + - Requires two keys of length at least 128 bits. +- A 32-bit PVC would be sufficient to verify the PIN value, since there would be less than a 1 in 4 chance that there exists a false PIN, which has the same PVC as the correct PIN. Nevertheless, we decided to go with a 64-bit PVC to achieve a larger security margin. The chance that there exists a false PIN, which has the same PVC as the correct PIN, then drops below 1 in 10^10. The existence of a false PIN does not appear to pose a security weakness, since the false PIN cannot be used to decrypt the protected entries. +- Instead of using separate IVs for each entry we considered using a single IV for the entire sector. Upon sector compaction a new IV would have to be generated and the encrypted data would have to be reencrypted under the new IV. A possible issue with this approach is that compaction cannot happen without the DEK, i.e. generally data could not be written to the flash storage without knowing the PIN. This property might not always be desirable. + +## New measures for PIN entry counter protection + +Our current implementation of the PIN entry counter is vulnerable to fault injection attacks. + +Under the current implementation the PIN counter storage entry consists of 32 words initialized to 0xFFFFFFFF. The first non-zero word in this area is the current PIN failure counter. Before verifying the PIN the lowest bit with value 1 is set to 0, i.e. a value of FFFFFFFC indicates two PIN entries. Upon successful PIN entry, the word is set to 0x00000000, indicating that the next word is the PIN failure counter. Allegedly, by manipulating the voltage on the USB input an attacker can convince the device to read the PIN entry counter as 0xFFFFFFFF even if some of the bits have been set to 0. + +### Design goals + +- Make it easy to decrement the counter by changing a 1 bit to 0. +- Make it hard to reset the counter by a fault injection, i.e. counter values should not have an overly simple binary representation like 0xFFFFFFFF. +- If possible, use two or more different methods of checking the counter value so that an attacker has to mount different fault injection attacks to succeed. +- Optimize the format for successful PIN entry. +- Minimize the number of branching operations. Avoid loops, instead utilize bitwise and arithmetic operations when processing the PIN counter data. + +### Proposal summary + +Under the current implementation, for every unsuccessful PIN entry we discard one bit from the counter, while for every successful PIN entry we discard an entire word. In the new implementation we would like to optimize the counter operations for successful PIN entry. + +The basic idea is that there will be two binary logs stored in the flash storage, e.g.: + +``` +...0001111111111111... pin_success_log +...0000001111111111... pin_entry_log +``` + +Before every PIN verification the highest 1-bit in the pin_entry_log will be set to 0. If the verification succeeds, then the corresponding bit in the pin_success_log will also be set to 0. The example above shows the status of the logs when the last three PIN entries were not successful. + +In actual fact the logs will not be written to the flash storage exactly as shown above, but they will be stored in a form that should protect them against fault injection attacks. Only half of the stored bits will carry information, the other half will act as "guard bits". So a stored value ...001110... could look like ...0g0gg1g11g0g..., where g denotes a guard bit. The positions and the values of the guard bits will be determined by a guard key. The guard_key will be a randomly generated uint32 value stored as an entry in the flash memory in cleartext. The assumption behind this is that an attacker attempting to reset or decrement the PIN counter by a fault injection is not able to read the flash storage. However, the value of guard_key also needs to be protected against fault injection, so the set of valid guard_key values should be limited by some condition which is easy to verify, such as guard_key mod M == C, where M and C a suitably chosen constants. The constants should be chosen so that the binary representation of any valid guard_key value has Hamming weight between 8 and 24. + +### Storage format + +The PIN log will replace the current PIN_FAIL_KEY entry (APP = 0, KEY = 1). The DATA part of the entry will consist of 33 words (132 bytes, assuming 32-bit words): +guard_key (1 word), pin_success_log (16 words), pin_entry_log (16 words) + +Each log will be stored in big-endian word order. The byte order of each word is platform dependent. + +### Guard key validation + +The guard_key is said to be valid if the following three conditions hold true: + +1. Each byte of the binary representation of the guard_key has a balanced number of zeros and ones at the positions corresponding to the guard values (that is those bits in the mask 0xAAAAAAAA) +2. The guard_key binary representation does not contain a run of 5 (or more) zeros or ones. +3. The guard_key integer representation is congruent to 15 modulo 6311. + +Key validity can be checked with this function: + +```c +int key_validity(uint32_t guard_key) +{ + uint32_t count = (guard_key & 0x22222222) + ((guard_key >> 2) & 0x22222222); + count = count + (count >> 4); + + uint32_t zero_runs = ~guard_key; + zero_runs = zero_runs & (zero_runs >> 2); + zero_runs = zero_runs & (zero_runs >> 1); + zero_runs = zero_runs & (zero_runs >> 1); + uint32_t one_runs = guard_key; + one_runs = one_runs & (one_runs >> 2); + one_runs = one_runs & (one_runs >> 1); + one_runs = one_runs & (one_runs >> 1); + + return ((count & 0x0e0e0e0e) == 0x04040404) & (one_runs == 0) & (zero_runs == 0) & (guard_key % 6311 == 15); +} +``` + +### Key generation + +The guard_key may be generated in the following way: + +1. Generate a random integer r in such that 0 ≤ r ≤ 680552 with uniform probability. +2. Set r = r * 6311 + 15. +3. If key_validity(r) is not true go back to the step 1. + +Note that on average steps 1 to 3 are repeated about one hundred times. + +### Key expansion + +The guard_key is read from storage, its value is checked for validity and used to compute the guard_mask (indicating the positions of the guard bits) and guard value (indicating the values of the guard bits on their actual positions): + +```c +LOW_MASK = 0x55555555 +guard_mask = ((guard_key & LOW_MASK) << 1) | + ((~guard_key) & LOW_MASK) +guard = (((guard_key & LOW_MASK) << 1) & guard_key) | + (((~guard_key) & LOW_MASK) & (guard_key >> 1)) +``` + +**Explanation**: + +The guard_key contains two pieces of information. The position of the guard bits but also their corresponding values. The bitwise format of the guard_key is `vpvpvp...vp`. The bits labelled `p` indicate the position of each guard bit and the bits labelled `v` indicate its value. + +The guard_mask is derived from the guard_key and has the form `xyxyxy...xy` where x+y = 1 (in other words, there is exactly one 1 bit in each pair xy). First, we set the `x` bits: + +`(guard_key & LOW_MASK) << 1` + +and the `y` bits to its corresponding complement: + +`(~guard_key) & LOW_MASK` + +That ensures that only one 1 bit is present in each pair xy. The guard value is equal to the bits labelled "v" in the guard_key but only at the positions indicated by the guard_mask. The guard value is therefore equal to: + +``` + --------- x bits mask -------- & -- guard_key -- +guard = (((guard_key & LOW_MASK) << 1) & guard_key) | + ----- y bits mask ---- & - guard_key shifted to v bits + (((~guard_key) & LOW_MASK) & (guard_key >> 1)) +``` + +### Log initialization +Each log will be stored as 16 consecutive words each initialized to: + +`guard | ~guard_mask` + +### Removing and adding guard bits + +After reading a word from the flash storage we will verify the format by checking the condition + +`(word & guard_mask) == guard` + +and then remove the guard bits as follows: + +``` +word = word & ~guard_mask +word = ((word >> 1) | word ) & LOW_MASK +word = word | (word << 1) +``` + +This operation replaces each guard bit with the value of its neighbouring bit, e.g. ...0g0gg1g11g0g… is converted to ...000011111100… Thus each non-guard bit is duplicated. + +The guard bits can be added back as follows: + +`word = (word & ~guard_mask) | guard` + +### Determining the number of PIN failures + +Remove the guard bits from the words of the pin_entry_log using the operations described above and verify that the result has form 0*1* by checking the condition: + +`word & (word + 1) == 0` + +Then verify that the pin_entry_log and pin_success_log are in sync by checking the condition: + +`pin_entry_log & pin_success_log == pin_entry_log` + +Finally, determine the current number of PIN failures by counting the number of set bits in the evaluation of the following expression: + +`pin_success_log xor pin_entry_log` + +Note that the number of set bits in a word can be counted using bitwise and arithmetic operations. For a 32-bit word the following can be used: + +```c +count = word - ((word >> 1) & 0x55555555) +count = (count & 0x33333333) + ((count >> 2) & 0x33333333) +count = (count + (count >> 4)) & 0x0F0F0F0F +count = count + (count >> 8) +count = (count + (count >> 16)) & 0x3F +``` From a73e147ceb6f14750d8aa3e64a0aeffc60f3513c Mon Sep 17 00:00:00 2001 From: Tomas Susanka Date: Fri, 25 Jan 2019 15:07:36 +0100 Subject: [PATCH 05/39] readme: remove future tense; and key derivation image; other small typos --- README.md | 77 ++++---- docs/key-derivation.odg | Bin 0 -> 13948 bytes docs/key-derivation.svg | 411 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 454 insertions(+), 34 deletions(-) create mode 100644 docs/key-derivation.odg create mode 100644 docs/key-derivation.svg diff --git a/README.md b/README.md index c0733722b..537e9157d 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,6 @@ The PIN is no longer stored in the flash storage. A new entry is added to the fl ## Storage format -The current format of the entries in the flash storage is: - -| Data | KEY | APP | LEN | DATA | -|----------------|-----|-----|-----|------| -| Length (bytes) | 1 | 1 | 2 | LEN | - Entries fall into three categories: | Category | Condition | Read | Write | @@ -24,33 +18,40 @@ Entries fall into three categories: | Protected | 1 ≤ APP ≤ 127 | Only when unlocked | Only when unlocked | | Public | 128 ≤ APP ≤ 255 | Always | Only when unlocked | -Private values are used to store storage-specific information and cannot be directly accessed through the storage interface. Currently the above conditions are enforced only in software, but not cryptographically. We propose that protected entries shall have the following new format:z +The format of public entries has remained unchanged, that is: + +| Data | KEY | APP | LEN | DATA | +|----------------|-----|-----|-----|------| +| Length (bytes) | 1 | 1 | 2 | LEN | + +Private values are used to store storage-specific information and cannot be directly accessed through the storage interface. Protected entries have the following new format: | Data | KEY | APP | LEN | IV | ENCRDATA | TAG | |----------------|-----|-----|-----|----|----------|-----| | Length (bytes) | 1 | 1 | 2 | 12 | LEN - 28 | 16 | -The LEN value thus indicates the total length of IV, ENCRDATA and TAG. The format of public entries shall remain unchanged. +The LEN value thus indicates the total length of IV, ENCRDATA and TAG. -The random salt (32 bits), EDEK (256 bits), ESAK (128 bits) and PVC (64 bits) will be stored in a single entry under APP=0, KEY=2: +The random salt (32 bits), EDEK (256 bits), ESAK (128 bits) and PVC (64 bits) is stored in a single entry under APP=0, KEY=2: | Data | KEY | APP | LEN | SALT | EDEK | ESAK | PVC | |----------------|-----|-----|-------|------|------|------|-----| | Length (bytes) | 1 | 1 | 2 | 4 | 32 | 16 | 8 | | Value | 02 | 00 | 3C 00 | | | | | -The storage authentication tag (128 bits) will be stored in a single entry under APP=0, KEY=5: +The storage authentication tag (128 bits) is stored in a single entry under APP=0, KEY=5: | Data | KEY | APP | LEN | TAG | |----------------|-----|-----|-------|-----| | Length (bytes) | 1 | 1 | 2 | 16 | | Value | 05 | 00 | 20 00 | | -Furthermore, if any entry is overwritten, the old entry will be erased, i.e., overwritten with 0. We could then also use APP=0, KEY=0 as marker that the entry is erased (currently this is the marker for the PIN entry that we wouldn't need anymore). +Furthermore, if any entry is overwritten, the old entry is erased, i.e., overwritten with 0. We are also using APP=0, KEY=0 as marker that the entry is erased (this was formerly used for the PIN entry, which is not needed anymore). ## PIN verification and decryption of protected entries in flash storage 1. From the flash storage read the entry containing the random salt, EDEK and PVC. + 2. Gather constant data from various system resources such as the ProcessorID (aka Unique device ID) and any hardware serial numbers that are available. The concatenation of this data with the random salt will be referred to as *salt*. 3. Prompt the user to enter the PIN. Prefix the entered PIN with a "1" digit in base 10 and convert the integer to 4 bytes in little endian byte order. Then compute: @@ -72,6 +73,8 @@ Furthermore, if any entry is overwritten, the old entry will be erased, i.e., ov where the APP and KEY of the entry is used as two bytes of associated data. Compare the TAG read from the flash storage with the computed tag value. If there is a mismatch, then fail. +![summary](docs/key-derivation.svg) + ## Initializing the EDEK 1. When the storage is initialized, generate the 32 bit random salt and 256 bit DEK using a cryptographically secure random number generator. @@ -104,31 +107,33 @@ Whenever the value of an entry needs to be updated, a fresh IV is generated usin The storage authentication key (SAK) will be used to generate a storage authentication tag (SAT) for the list of all (APP, KEY) values of protected entries (1 ≤ APP ≤ 127) that have been set in the storage. The SAT will be checked during every get operation. When a new protected entry is added to the storage or when a protected entry is deleted from the storage, the value of the SAT will be updated. The value of the SAT is defined as the first 16 bytes of -`HMAC-SHA-256(SAK, ⨁i HMAC-SHA-256(SAK, KEYi || APPi))` +`HMAC-SHA-256(SAK, ⨁i HMAC-SHA-256(SAK, KEY_i || APP_i))` -where `⨁` denotes the n-ary bitwise XOR operation and KEYi || APPi is a two-byte encoding of the value of the i-th (APP, KEY) such that 1 ≤ APP ≤ 127. +where `⨁` denotes the n-ary bitwise XOR operation and KEY_i || APP_i is a two-byte encoding of the value of the *i*-th (APP, KEY) such that 1 ≤ APP ≤ 127. ## Design rationale - The purpose of the PBKDF2 function is to thwart brute-force attacks in case the attacker is able to circumvent the PIN entry counter mechanism but does not have full access to the contents of the flash storage of the device, e.g. fault injection attacks. For an attacker that would be able to read the flash storage and obtain the salt, the PBKDF2 with 20000 iterations and a 4- to 9-digit PIN would not pose an obstacle. -- The reason why we propose to use a separate data encryption key rather than using the output of PBKDF2 directly to encrypt the sensitive entries is so that when the user decides to change their PIN, only the EDEK needs to be reencrypted, but the remaining entries do not need to be updated. +- The reason why we use a separate data encryption key rather than using the output of PBKDF2 directly to encrypt the sensitive entries is so that when the user decides to change their PIN, only the EDEK needs to be reencrypted, but the remaining entries do not need to be updated. -- We propose to use ChaCha20 for encryption, because as a stream cipher it has no padding overhead and its implementation is readily available in trezor-crypto. A possible alternative to using ChaCha20Poly1305 for DEK encryption is to use AES-CTR with HMAC in an encrypt-then-MAC scheme. A possible alternative to using ChaCha20 for encryption of other data entries is to use AES-XTS (XEX-based tweaked-codebook mode with ciphertext stealing), which was designed specifically for disk-encryption. The APP || KEY value would be used as the tweak. +- We se ChaCha20 for encryption, because as a stream cipher it has no padding overhead and its implementation is readily available in trezor-crypto. A possible alternative to using ChaCha20Poly1305 for DEK encryption is to use AES-CTR with HMAC in an encrypt-then-MAC scheme. A possible alternative to using ChaCha20 for encryption of other data entries is to use AES-XTS (XEX-based tweaked-codebook mode with ciphertext stealing), which was designed specifically for disk-encryption. The APP || KEY value would be used as the tweak. - Advantages of AES-XTS: - Does not require an initialization vector. - Ensures better diffusion than a stream cipher, which eliminates the above concerns about malleability and fault injection attacks. - Disadvantages of AES-XTS: - Not implemented in trezor-crypto. - Requires two keys of length at least 128 bits. + - A 32-bit PVC would be sufficient to verify the PIN value, since there would be less than a 1 in 4 chance that there exists a false PIN, which has the same PVC as the correct PIN. Nevertheless, we decided to go with a 64-bit PVC to achieve a larger security margin. The chance that there exists a false PIN, which has the same PVC as the correct PIN, then drops below 1 in 10^10. The existence of a false PIN does not appear to pose a security weakness, since the false PIN cannot be used to decrypt the protected entries. + - Instead of using separate IVs for each entry we considered using a single IV for the entire sector. Upon sector compaction a new IV would have to be generated and the encrypted data would have to be reencrypted under the new IV. A possible issue with this approach is that compaction cannot happen without the DEK, i.e. generally data could not be written to the flash storage without knowing the PIN. This property might not always be desirable. ## New measures for PIN entry counter protection -Our current implementation of the PIN entry counter is vulnerable to fault injection attacks. +The former implementation of the PIN entry counter was vulnerable to fault injection attacks. -Under the current implementation the PIN counter storage entry consists of 32 words initialized to 0xFFFFFFFF. The first non-zero word in this area is the current PIN failure counter. Before verifying the PIN the lowest bit with value 1 is set to 0, i.e. a value of FFFFFFFC indicates two PIN entries. Upon successful PIN entry, the word is set to 0x00000000, indicating that the next word is the PIN failure counter. Allegedly, by manipulating the voltage on the USB input an attacker can convince the device to read the PIN entry counter as 0xFFFFFFFF even if some of the bits have been set to 0. +Under the former implementation the PIN counter storage entry consisted of 32 words initialized to 0xFFFFFFFF. The first non-zero word in this area was the current PIN failure counter. Before verifying the PIN the lowest bit with value 1 was set to 0, i.e. a value of FFFFFFFC indicated two PIN entries. Upon successful PIN entry, the word was set to 0x00000000, indicating that the next word was the PIN failure counter. Allegedly, by manipulating the voltage on the USB input an attacker could convince the device to read the PIN entry counter as 0xFFFFFFFF even if some of the bits had been set to 0. ### Design goals @@ -140,31 +145,34 @@ Under the current implementation the PIN counter storage entry consists of 32 wo ### Proposal summary -Under the current implementation, for every unsuccessful PIN entry we discard one bit from the counter, while for every successful PIN entry we discard an entire word. In the new implementation we would like to optimize the counter operations for successful PIN entry. +Under the former implementation, for every unsuccessful PIN entry we discarded one bit from the counter, while for every successful PIN entry we discard an entire word. In the new implementation we optimize the counter operations for successful PIN entry. -The basic idea is that there will be two binary logs stored in the flash storage, e.g.: +The basic idea is that there are two binary logs stored in the flash storage, e.g.: ``` ...0001111111111111... pin_success_log ...0000001111111111... pin_entry_log ``` -Before every PIN verification the highest 1-bit in the pin_entry_log will be set to 0. If the verification succeeds, then the corresponding bit in the pin_success_log will also be set to 0. The example above shows the status of the logs when the last three PIN entries were not successful. +Before every PIN verification the highest 1-bit in the pin_entry_log is set to 0. If the verification succeeds, then the corresponding bit in the pin_success_log is also set to 0. The example above shows the status of the logs when the last three PIN entries were not successful. -In actual fact the logs will not be written to the flash storage exactly as shown above, but they will be stored in a form that should protect them against fault injection attacks. Only half of the stored bits will carry information, the other half will act as "guard bits". So a stored value ...001110... could look like ...0g0gg1g11g0g..., where g denotes a guard bit. The positions and the values of the guard bits will be determined by a guard key. The guard_key will be a randomly generated uint32 value stored as an entry in the flash memory in cleartext. The assumption behind this is that an attacker attempting to reset or decrement the PIN counter by a fault injection is not able to read the flash storage. However, the value of guard_key also needs to be protected against fault injection, so the set of valid guard_key values should be limited by some condition which is easy to verify, such as guard_key mod M == C, where M and C a suitably chosen constants. The constants should be chosen so that the binary representation of any valid guard_key value has Hamming weight between 8 and 24. +In actual fact the logs are not written to the flash storage exactly as shown above, but they are stored in a form that should protect them against fault injection attacks. Only half of the stored bits carry information, the other half acts as "guard bits". So a stored value `...001110...` could look like `...0g0gg1g11g0g...`, where g denotes a guard bit. The positions and the values of the guard bits are determined by a guard key. The guard_key is a randomly generated uint32 value stored as an entry in the flash memory in cleartext. The assumption behind this is that an attacker attempting to reset or decrement the PIN counter by a fault injection is not able to read the flash storage. However, the value of guard_key also needs to be protected against fault injection, so the set of valid guard_key values should be limited by some condition which is easy to verify, such as guard_key mod M == C, where M and C a suitably chosen constants. The constants should be chosen so that the binary representation of any valid guard_key value has Hamming weight between 8 and 24. These conditions are discussed below. ### Storage format -The PIN log will replace the current PIN_FAIL_KEY entry (APP = 0, KEY = 1). The DATA part of the entry will consist of 33 words (132 bytes, assuming 32-bit words): -guard_key (1 word), pin_success_log (16 words), pin_entry_log (16 words) +The PIN log has APP = 0 and KEY = 1. The DATA part of the entry consists of 33 words (132 bytes, assuming 32-bit words): -Each log will be stored in big-endian word order. The byte order of each word is platform dependent. +- guard_key (1 word) +- pin_success_log (16 words) +- pin_entry_log (16 words) + +Each log is stored in big-endian word order. The byte order of each word is platform dependent. ### Guard key validation The guard_key is said to be valid if the following three conditions hold true: -1. Each byte of the binary representation of the guard_key has a balanced number of zeros and ones at the positions corresponding to the guard values (that is those bits in the mask 0xAAAAAAAA) +1. Each byte of the binary representation of the guard_key has a balanced number of zeros and ones at the positions corresponding to the guard values (that is those bits in the mask 0xAAAAAAAA). 2. The guard_key binary representation does not contain a run of 5 (or more) zeros or ones. 3. The guard_key integer representation is congruent to 15 modulo 6311. @@ -193,9 +201,9 @@ int key_validity(uint32_t guard_key) The guard_key may be generated in the following way: -1. Generate a random integer r in such that 0 ≤ r ≤ 680552 with uniform probability. -2. Set r = r * 6311 + 15. -3. If key_validity(r) is not true go back to the step 1. +1. Generate a random integer *r* in such that 0 ≤ *r* ≤ 680552 with uniform probability. +2. Set *r* = *r* * 6311 + 15. +3. If *key_validity(r)* is not true go back to the step 1. Note that on average steps 1 to 3 are repeated about one hundred times. @@ -223,23 +231,24 @@ and the `y` bits to its corresponding complement: `(~guard_key) & LOW_MASK` -That ensures that only one 1 bit is present in each pair xy. The guard value is equal to the bits labelled "v" in the guard_key but only at the positions indicated by the guard_mask. The guard value is therefore equal to: +That ensures that only one 1 bit is present in each pair `xy`. The guard value is equal to the bits labelled `v` in the guard_key but only at the positions indicated by the guard_mask. The guard value is therefore equal to: ``` - --------- x bits mask -------- & -- guard_key -- + -------- x bits mask --------- & -- guard_key -- guard = (((guard_key & LOW_MASK) << 1) & guard_key) | ----- y bits mask ---- & - guard_key shifted to v bits (((~guard_key) & LOW_MASK) & (guard_key >> 1)) ``` ### Log initialization -Each log will be stored as 16 consecutive words each initialized to: + +Each log is stored as 16 consecutive words each initialized to: `guard | ~guard_mask` ### Removing and adding guard bits -After reading a word from the flash storage we will verify the format by checking the condition +After reading a word from the flash storage we verify the format by checking the condition: `(word & guard_mask) == guard` @@ -251,7 +260,7 @@ word = ((word >> 1) | word ) & LOW_MASK word = word | (word << 1) ``` -This operation replaces each guard bit with the value of its neighbouring bit, e.g. ...0g0gg1g11g0g… is converted to ...000011111100… Thus each non-guard bit is duplicated. +This operation replaces each guard bit with the value of its neighbouring bit, e.g. `…0g0gg1g11g0g…` is converted to `…000011111100…` Thus each non-guard bit is duplicated. The guard bits can be added back as follows: @@ -259,7 +268,7 @@ The guard bits can be added back as follows: ### Determining the number of PIN failures -Remove the guard bits from the words of the pin_entry_log using the operations described above and verify that the result has form 0*1* by checking the condition: +Remove the guard bits from the words of the pin_entry_log using the operations described above and verify that the result has form 0\*1\* by checking the condition: `word & (word + 1) == 0` diff --git a/docs/key-derivation.odg b/docs/key-derivation.odg new file mode 100644 index 0000000000000000000000000000000000000000..44d684d45d474bc195656eacc563c8266c8bb538 GIT binary patch literal 13948 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 gditl#(fq^eDkBd1;VumTz({eJrY0PI{MX8-^I literal 0 HcmV?d00001 diff --git a/docs/key-derivation.svg b/docs/key-derivation.svg new file mode 100644 index 000000000..1408faf65 --- /dev/null +++ b/docs/key-derivation.svg @@ -0,0 +1,411 @@ + +image/svg+xmlSALT +PVC +EDEK +32b +256b +64b +PBKDF2 +PIN ++ hardware salt +KEIV +KEK +256b +96b +ChaCha20Poly1305 +iv +cipher +text +PVC’ +SAK +128b +64b +first 64b of MAC +plain text +Flash +key +ESAK +128b +DEK +256b + \ No newline at end of file From 7be7709c70af823216b1f4a44af39bebf5a4fb07 Mon Sep 17 00:00:00 2001 From: andrew Date: Fri, 25 Jan 2019 16:23:20 +0100 Subject: [PATCH 06/39] Fix strict-prototypes warnings by explicitly specifying void when a function accepts no arguments. --- norcow.c | 4 ++-- storage.c | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/norcow.c b/norcow.c index fb7a1d450..afc72ce3f 100644 --- a/norcow.c +++ b/norcow.c @@ -248,7 +248,7 @@ static uint32_t find_free_offset(uint8_t sector) /* * Compacts active sector and sets new active sector */ -static void compact() +static void compact(void) { uint32_t offsetr; uint32_t version; @@ -551,7 +551,7 @@ secbool norcow_update_bytes(const uint16_t key, const uint16_t offset, const uin /* * Complete storage version upgrade */ -secbool norcow_upgrade_finish() +secbool norcow_upgrade_finish(void) { erase_sector(norcow_active_sector, secfalse); norcow_active_sector = norcow_write_sector; diff --git a/storage.c b/storage.c index 4c150c048..b491ce51d 100644 --- a/storage.c +++ b/storage.c @@ -117,8 +117,8 @@ static uint32_t norcow_active_version = 0; static const uint8_t TRUE_BYTE = 0x01; static const uint8_t FALSE_BYTE = 0x00; -static void handle_fault(); -static secbool storage_upgrade(); +static void handle_fault(void); +static secbool storage_upgrade(void); static secbool storage_set_encrypted(const uint16_t key, const void *val, const uint16_t len); static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len); @@ -149,7 +149,7 @@ static secbool is_protected(uint16_t key) { /* * Initialize the storage authentication tag for freshly wiped storage. */ -static secbool auth_init() { +static secbool auth_init(void) { uint8_t tag[SHA256_DIGEST_LENGTH]; memzero(authentication_sum, sizeof(authentication_sum)); hmac_sha256(cached_sak, SAK_SIZE, authentication_sum, sizeof(authentication_sum), tag); @@ -284,7 +284,7 @@ static secbool auth_get(uint16_t key, const void **val, uint16_t *len) /* * Generates a delay of random length. Use this to protect sensitive code against fault injection. */ -static void wait_random() +static void wait_random(void) { #ifndef TREZOR_STORAGE_TEST int wait = random32() & 0xff; @@ -392,7 +392,7 @@ static secbool check_guard_key(const uint32_t guard_key) return sectrue; } -static uint32_t generate_guard_key() +static uint32_t generate_guard_key(void) { uint32_t guard_key = 0; do { @@ -446,7 +446,7 @@ static secbool pin_logs_init(uint32_t fails) * Initializes the values of VERSION_KEY, EDEK_PVC_KEY, PIN_NOT_SET_KEY and PIN_LOGS_KEY using an empty PIN. * This function should be called to initialize freshly wiped storage. */ -static void init_wiped_storage() +static void init_wiped_storage(void) { random_buffer(cached_keys, sizeof(cached_keys)); uint32_t version = NORCOW_VERSION; @@ -485,7 +485,7 @@ void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint memzero(cached_keys, sizeof(cached_keys)); } -static secbool pin_fails_reset() +static secbool pin_fails_reset(void) { const void *logs = NULL; uint16_t len = 0; @@ -517,7 +517,7 @@ static secbool pin_fails_reset() return pin_logs_init(0); } -static secbool pin_fails_increase() +static secbool pin_fails_increase(void) { const void *logs = NULL; uint16_t len = 0; @@ -969,7 +969,7 @@ void storage_wipe(void) init_wiped_storage(); } -static void handle_fault() +static void handle_fault(void) { static secbool in_progress = secfalse; @@ -1031,7 +1031,7 @@ static secbool v0_pin_get_fails(uint32_t *ctr) return sectrue; } -static secbool storage_upgrade() +static secbool storage_upgrade(void) { const uint16_t V0_PIN_KEY = 0x0000; const uint16_t V0_PIN_FAIL_KEY = 0x0001; From 65fdd534274ae42de43c51a1e2bf46a023e212df Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 28 Jan 2019 16:02:09 +0100 Subject: [PATCH 07/39] Rename flash_unlock() to flash_unlock_write() to resolve name collision with libopencm3 in trezor-mcu. --- norcow.c | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/norcow.c b/norcow.c index afc72ce3f..a12686ab9 100644 --- a/norcow.c +++ b/norcow.c @@ -78,7 +78,7 @@ static secbool norcow_write(uint8_t sector, uint32_t offset, uint32_t prefix, co return secfalse; } - ensure(flash_unlock(), NULL); + ensure(flash_unlock_write(), NULL); // write prefix ensure(flash_write_word(norcow_sectors[sector], offset, prefix), NULL); @@ -98,7 +98,7 @@ static secbool norcow_write(uint8_t sector, uint32_t offset, uint32_t prefix, co ensure(flash_write_byte(norcow_sectors[sector], offset, 0x00), NULL); } - ensure(flash_lock(), NULL); + ensure(flash_lock_write(), NULL); return sectrue; } @@ -423,14 +423,14 @@ secbool norcow_set_ex(uint16_t key, const void *val, uint16_t len, secbool *foun offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE); if (val != NULL && len_old == len) { ret = sectrue; - ensure(flash_unlock(), NULL); + ensure(flash_unlock_write(), NULL); for (uint16_t i = 0; i < len; i++) { if (sectrue != flash_write_byte(sector_num, offset + i, ((const uint8_t*)val)[i])) { ret = secfalse; break; } } - ensure(flash_lock(), NULL); + ensure(flash_lock_write(), NULL); } } @@ -438,7 +438,7 @@ secbool norcow_set_ex(uint16_t key, const void *val, uint16_t len, secbool *foun if (secfalse == ret) { // Delete the old item. if (sectrue == *found) { - ensure(flash_unlock(), NULL); + ensure(flash_unlock_write(), NULL); // Update the prefix to indicate that the old item has been deleted. uint32_t prefix = (uint32_t)len_old << 16; @@ -451,7 +451,7 @@ secbool norcow_set_ex(uint16_t key, const void *val, uint16_t len, secbool *foun offset += NORCOW_WORD_SIZE; } - ensure(flash_lock(), NULL); + ensure(flash_lock_write(), NULL); } // Check whether there is enough free space and compact if full. if (norcow_free_offset + NORCOW_PREFIX_LEN + len > NORCOW_SECTOR_SIZE) { @@ -486,7 +486,7 @@ secbool norcow_delete(uint16_t key) uint32_t offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE); - ensure(flash_unlock(), NULL); + ensure(flash_unlock_write(), NULL); // Update the prefix to indicate that the item has been deleted. uint32_t prefix = (uint32_t)len << 16; @@ -499,7 +499,7 @@ secbool norcow_delete(uint16_t key) offset += NORCOW_WORD_SIZE; } - ensure(flash_lock(), NULL); + ensure(flash_lock_write(), NULL); return sectrue; } @@ -519,9 +519,9 @@ secbool norcow_update_word(uint16_t key, uint16_t offset, uint32_t value) return secfalse; } uint32_t sector_offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE) + offset; - ensure(flash_unlock(), NULL); + ensure(flash_unlock_write(), NULL); ensure(flash_write_word(norcow_sectors[norcow_write_sector], sector_offset, value), NULL); - ensure(flash_lock(), NULL); + ensure(flash_lock_write(), NULL); return sectrue; } @@ -540,11 +540,11 @@ secbool norcow_update_bytes(const uint16_t key, const uint16_t offset, const uin } uint32_t sector_offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE) + offset; uint8_t sector = norcow_sectors[norcow_write_sector]; - ensure(flash_unlock(), NULL); + ensure(flash_unlock_write(), NULL); for (uint16_t i = 0; i < len; i++, sector_offset++) { ensure(flash_write_byte(sector, sector_offset, data[i]), NULL); } - ensure(flash_lock(), NULL); + ensure(flash_lock_write(), NULL); return sectrue; } From fc29df6f874efa649bc3520c247b2169ffb563bf Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 28 Jan 2019 16:24:48 +0100 Subject: [PATCH 08/39] Rename flash_erase_sector() to flash_erase() to resolve name collision with libopencm3 in trezor-mcu. --- norcow.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/norcow.c b/norcow.c index a12686ab9..f2f2487e9 100644 --- a/norcow.c +++ b/norcow.c @@ -114,7 +114,7 @@ static void erase_sector(uint8_t sector, secbool set_magic) memcpy(header_backup, sector_start, sizeof(header_backup)); #endif - ensure(flash_erase_sector(norcow_sectors[sector]), "erase failed"); + ensure(flash_erase(norcow_sectors[sector]), "erase failed"); #if NORCOW_HEADER_LEN > 0 // Copy the sector header back. From d49e3c9f3c1f1d10149ae9bdc70ba113f9b72507 Mon Sep 17 00:00:00 2001 From: andrew Date: Wed, 30 Jan 2019 16:22:50 +0100 Subject: [PATCH 09/39] Add storage_wipe_ex() which allows to specify the new PIN and the PIN fail count. --- storage.c | 19 ++++++++++++------- storage.h | 1 + 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/storage.c b/storage.c index b491ce51d..4d551f63e 100644 --- a/storage.c +++ b/storage.c @@ -443,17 +443,17 @@ static secbool pin_logs_init(uint32_t fails) } /* - * Initializes the values of VERSION_KEY, EDEK_PVC_KEY, PIN_NOT_SET_KEY and PIN_LOGS_KEY using an empty PIN. + * Initializes the values of VERSION_KEY, EDEK_PVC_KEY, PIN_NOT_SET_KEY and PIN_LOGS_KEY using the given PIN. * This function should be called to initialize freshly wiped storage. */ -static void init_wiped_storage(void) +static void init_wiped_storage(uint32_t new_pin, uint32_t pin_fail_count) { random_buffer(cached_keys, sizeof(cached_keys)); uint32_t version = NORCOW_VERSION; ensure(auth_init(), "failed to initialize storage authentication tag"); ensure(storage_set_encrypted(VERSION_KEY, &version, sizeof(version)), "failed to set storage version"); - ensure(set_pin(PIN_EMPTY), "failed to initialize PIN"); - ensure(pin_logs_init(0), "failed to initialize PIN logs"); + ensure(set_pin(new_pin), "failed to initialize PIN"); + ensure(pin_logs_init(pin_fail_count), "failed to initialize PIN logs"); if (unlocked != sectrue) { memzero(cached_keys, sizeof(cached_keys)); } @@ -480,7 +480,7 @@ void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint const void *val; uint16_t len; if (secfalse == norcow_get(EDEK_PVC_KEY, &val, &len)) { - init_wiped_storage(); + init_wiped_storage(PIN_EMPTY, 0); } memzero(cached_keys, sizeof(cached_keys)); } @@ -960,13 +960,18 @@ secbool storage_change_pin(uint32_t oldpin, uint32_t newpin) return ret; } -void storage_wipe(void) +void storage_wipe_ex(uint32_t new_pin, uint32_t pin_fail_count) { norcow_wipe(); norcow_active_version = NORCOW_VERSION; memzero(authentication_sum, sizeof(authentication_sum)); memzero(cached_keys, sizeof(cached_keys)); - init_wiped_storage(); + init_wiped_storage(new_pin, pin_fail_count); +} + +void storage_wipe(void) +{ + storage_wipe_ex(PIN_EMPTY, 0); } static void handle_fault(void) diff --git a/storage.h b/storage.h index 00e7bd074..21509deaa 100644 --- a/storage.h +++ b/storage.h @@ -28,6 +28,7 @@ typedef void (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress); void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len); void storage_wipe(void); +void storage_wipe_ex(uint32_t new_pin, uint32_t pin_fail_count); secbool storage_unlock(const uint32_t pin); secbool storage_has_pin(void); uint32_t storage_get_pin_rem(void); From 7228b299b3c2f001aa43c683d4cce92953a081dc Mon Sep 17 00:00:00 2001 From: andrew Date: Wed, 30 Jan 2019 16:34:57 +0100 Subject: [PATCH 10/39] Add storage_lock(). --- storage.c | 7 +++++++ storage.h | 1 + 2 files changed, 8 insertions(+) diff --git a/storage.c b/storage.c index 4d551f63e..bb8909454 100644 --- a/storage.c +++ b/storage.c @@ -641,6 +641,13 @@ static secbool pin_get_fails(uint32_t *ctr) return sectrue; } +void storage_lock(void) +{ + unlocked = secfalse; + memzero(cached_keys, sizeof(cached_keys)); + memzero(authentication_sum, sizeof(authentication_sum)); +} + static secbool unlock(uint32_t pin) { const void *buffer = NULL; diff --git a/storage.h b/storage.h index 21509deaa..8b5af7e2f 100644 --- a/storage.h +++ b/storage.h @@ -29,6 +29,7 @@ typedef void (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress); void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len); void storage_wipe(void); void storage_wipe_ex(uint32_t new_pin, uint32_t pin_fail_count); +void storage_lock(void); secbool storage_unlock(const uint32_t pin); secbool storage_has_pin(void); uint32_t storage_get_pin_rem(void); From 7e8c4e783d2670c37cd0c7f5c69d981e60304b94 Mon Sep 17 00:00:00 2001 From: andrew Date: Wed, 30 Jan 2019 17:31:51 +0100 Subject: [PATCH 11/39] Revert "Add storage_wipe_ex() which allows to specify the new PIN and the PIN fail count." This reverts commit d49e3c9f3c1f1d10149ae9bdc70ba113f9b72507. --- storage.c | 19 +++++++------------ storage.h | 1 - 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/storage.c b/storage.c index bb8909454..8d8c0e3b7 100644 --- a/storage.c +++ b/storage.c @@ -443,17 +443,17 @@ static secbool pin_logs_init(uint32_t fails) } /* - * Initializes the values of VERSION_KEY, EDEK_PVC_KEY, PIN_NOT_SET_KEY and PIN_LOGS_KEY using the given PIN. + * Initializes the values of VERSION_KEY, EDEK_PVC_KEY, PIN_NOT_SET_KEY and PIN_LOGS_KEY using an empty PIN. * This function should be called to initialize freshly wiped storage. */ -static void init_wiped_storage(uint32_t new_pin, uint32_t pin_fail_count) +static void init_wiped_storage(void) { random_buffer(cached_keys, sizeof(cached_keys)); uint32_t version = NORCOW_VERSION; ensure(auth_init(), "failed to initialize storage authentication tag"); ensure(storage_set_encrypted(VERSION_KEY, &version, sizeof(version)), "failed to set storage version"); - ensure(set_pin(new_pin), "failed to initialize PIN"); - ensure(pin_logs_init(pin_fail_count), "failed to initialize PIN logs"); + ensure(set_pin(PIN_EMPTY), "failed to initialize PIN"); + ensure(pin_logs_init(0), "failed to initialize PIN logs"); if (unlocked != sectrue) { memzero(cached_keys, sizeof(cached_keys)); } @@ -480,7 +480,7 @@ void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint const void *val; uint16_t len; if (secfalse == norcow_get(EDEK_PVC_KEY, &val, &len)) { - init_wiped_storage(PIN_EMPTY, 0); + init_wiped_storage(); } memzero(cached_keys, sizeof(cached_keys)); } @@ -967,18 +967,13 @@ secbool storage_change_pin(uint32_t oldpin, uint32_t newpin) return ret; } -void storage_wipe_ex(uint32_t new_pin, uint32_t pin_fail_count) +void storage_wipe(void) { norcow_wipe(); norcow_active_version = NORCOW_VERSION; memzero(authentication_sum, sizeof(authentication_sum)); memzero(cached_keys, sizeof(cached_keys)); - init_wiped_storage(new_pin, pin_fail_count); -} - -void storage_wipe(void) -{ - storage_wipe_ex(PIN_EMPTY, 0); + init_wiped_storage(); } static void handle_fault(void) diff --git a/storage.h b/storage.h index 8b5af7e2f..db3b05177 100644 --- a/storage.h +++ b/storage.h @@ -28,7 +28,6 @@ typedef void (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress); void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len); void storage_wipe(void); -void storage_wipe_ex(uint32_t new_pin, uint32_t pin_fail_count); void storage_lock(void); secbool storage_unlock(const uint32_t pin); secbool storage_has_pin(void); From ebe884ab4df399248b4a6270aba47868049b8786 Mon Sep 17 00:00:00 2001 From: andrew Date: Wed, 30 Jan 2019 17:33:48 +0100 Subject: [PATCH 12/39] Make storage_pin_fails_increase() public. --- storage.c | 6 +++--- storage.h | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/storage.c b/storage.c index 8d8c0e3b7..61cd9fae8 100644 --- a/storage.c +++ b/storage.c @@ -517,7 +517,7 @@ static secbool pin_fails_reset(void) return pin_logs_init(0); } -static secbool pin_fails_increase(void) +secbool storage_pin_fails_increase(void) { const void *logs = NULL; uint16_t len = 0; @@ -739,7 +739,7 @@ secbool storage_unlock(uint32_t pin) // 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()) { + if (sectrue != storage_pin_fails_increase()) { memzero(&pin, sizeof(pin)); return secfalse; } @@ -994,7 +994,7 @@ static void handle_fault(void) ensure(secfalse, "fault detected"); } - if (sectrue != pin_fails_increase()) { + if (sectrue != storage_pin_fails_increase()) { storage_wipe(); ensure(secfalse, "fault detected"); } diff --git a/storage.h b/storage.h index db3b05177..b6c8762b9 100644 --- a/storage.h +++ b/storage.h @@ -31,6 +31,7 @@ void storage_wipe(void); void storage_lock(void); secbool storage_unlock(const uint32_t pin); secbool storage_has_pin(void); +secbool storage_pin_fails_increase(void); uint32_t storage_get_pin_rem(void); secbool storage_change_pin(const uint32_t oldpin, const uint32_t newpin); secbool storage_get(const uint16_t key, void *val, const uint16_t max_len, uint16_t *len); From 840f7461ee6f0c5cb0db75c46018615dbd5b0256 Mon Sep 17 00:00:00 2001 From: andrew Date: Wed, 30 Jan 2019 17:36:02 +0100 Subject: [PATCH 13/39] Add storage_is_unlocked(). --- storage.c | 5 +++++ storage.h | 1 + 2 files changed, 6 insertions(+) diff --git a/storage.c b/storage.c index 61cd9fae8..adf0e42ab 100644 --- a/storage.c +++ b/storage.c @@ -641,6 +641,11 @@ static secbool pin_get_fails(uint32_t *ctr) return sectrue; } +secbool storage_is_unlocked(void) +{ + return unlocked; +} + void storage_lock(void) { unlocked = secfalse; diff --git a/storage.h b/storage.h index b6c8762b9..5c62d92ee 100644 --- a/storage.h +++ b/storage.h @@ -28,6 +28,7 @@ typedef void (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress); void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len); void storage_wipe(void); +secbool storage_is_unlocked(void); void storage_lock(void); secbool storage_unlock(const uint32_t pin); secbool storage_has_pin(void); From 2888c1109563f32febb2eda9aed1130c07c6672b Mon Sep 17 00:00:00 2001 From: andrew Date: Thu, 31 Jan 2019 17:52:51 +0100 Subject: [PATCH 14/39] Bugfix: Unlock flash when copying sector header. --- norcow.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/norcow.c b/norcow.c index f2f2487e9..3ef5d6f9c 100644 --- a/norcow.c +++ b/norcow.c @@ -118,9 +118,11 @@ static void erase_sector(uint8_t sector, secbool set_magic) #if NORCOW_HEADER_LEN > 0 // Copy the sector header back. + ensure(flash_unlock_write(), NULL); for (uint32_t i = 0; i < NORCOW_HEADER_LEN/sizeof(uint32_t); ++i) { ensure(flash_write_word(norcow_sectors[sector], i*sizeof(uint32_t), header_backup[i]), NULL); } + ensure(flash_lock_write(), NULL); #endif if (sectrue == set_magic) { From 8fc03a5a95d3b75b29909a9f030fd74b294bf63b Mon Sep 17 00:00:00 2001 From: andrew Date: Fri, 1 Feb 2019 20:46:16 +0100 Subject: [PATCH 15/39] Fix bug in auth_get() when storing the authentication_sum. Remove the superfluous auth_get() call in unlock(). --- storage.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/storage.c b/storage.c index adf0e42ab..ae0d7d78c 100644 --- a/storage.c +++ b/storage.c @@ -250,7 +250,7 @@ static secbool auth_get(uint16_t key, const void **val, uint16_t *len) // Cache the authentication sum. for (size_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) { #if BYTE_ORDER == LITTLE_ENDIAN - REVERSE32(((uint32_t*)authentication_sum)[i], sum[i]); + REVERSE32(sum[i], ((uint32_t*)authentication_sum)[i]); #else ((uint32_t*)authentication_sum)[i] = sum[i]; #endif @@ -690,10 +690,8 @@ static secbool unlock(uint32_t pin) memzero(keys, sizeof(keys)); memzero(tag, sizeof(tag)); - // Call auth_get() to initialize the authentication_sum. - auth_get(0, &buffer, &len); - // Check that the authenticated version number matches the norcow version. + // NOTE: storage_get_encrypted() calls auth_get(), which initializes the authentication_sum. uint32_t version; if (sectrue != storage_get_encrypted(VERSION_KEY, &version, sizeof(version), &len) || len != sizeof(version) || version != norcow_active_version) { handle_fault(); From 6d9a4962a427717100517d59a4dcc1012199f0f5 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 4 Feb 2019 17:32:58 +0100 Subject: [PATCH 16/39] Check the 'initialized' flag in storage_*() functions before doing anything. --- storage.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/storage.c b/storage.c index ae0d7d78c..6e0f1144a 100644 --- a/storage.c +++ b/storage.c @@ -448,6 +448,10 @@ static secbool pin_logs_init(uint32_t fails) */ static void init_wiped_storage(void) { + if (sectrue != initialized) { + // We cannot initialize the storage contents if the hardware_salt is not set. + return; + } random_buffer(cached_keys, sizeof(cached_keys)); uint32_t version = NORCOW_VERSION; ensure(auth_init(), "failed to initialize storage authentication tag"); @@ -519,6 +523,10 @@ static secbool pin_fails_reset(void) secbool storage_pin_fails_increase(void) { + if (sectrue != initialized) { + return secfalse; + } + const void *logs = NULL; uint16_t len = 0; @@ -643,6 +651,10 @@ static secbool pin_get_fails(uint32_t *ctr) secbool storage_is_unlocked(void) { + if (sectrue != initialized) { + return secfalse; + } + return unlocked; } @@ -703,6 +715,10 @@ static secbool unlock(uint32_t pin) secbool storage_unlock(uint32_t pin) { + if (sectrue != initialized) { + return secfalse; + } + // Get the pin failure counter uint32_t ctr; if (sectrue != pin_get_fails(&ctr)) { @@ -949,6 +965,10 @@ secbool storage_has_pin(void) uint32_t storage_get_pin_rem(void) { + if (sectrue != initialized) { + return 0; + } + uint32_t ctr = 0; if (sectrue != pin_get_fails(&ctr)) { return 0; From 47cd563c815671509bd61f7921e16fbd3a3d7001 Mon Sep 17 00:00:00 2001 From: andrew Date: Wed, 6 Feb 2019 13:43:15 +0100 Subject: [PATCH 17/39] Interrupt the PIN wait dialog if the PIN_UI_WAIT_CALLBACK function returns sectrue. --- storage.c | 8 ++++++-- storage.h | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/storage.c b/storage.c index 6e0f1144a..992805eeb 100644 --- a/storage.c +++ b/storage.c @@ -745,14 +745,18 @@ secbool storage_unlock(uint32_t pin) } else { progress = ((wait - rem) * 10 + i) * 100 / wait; } - ui_callback(rem, progress); + if (sectrue == ui_callback(rem, progress)) { + return secfalse; + } } hal_delay(100); } } // Show last frame if we were waiting if ((wait > 0) && ui_callback) { - ui_callback(0, 1000); + if (sectrue == ui_callback(0, 1000)) { + return secfalse; + } } // First, we increase PIN fail counter in storage, even before checking the diff --git a/storage.h b/storage.h index 5c62d92ee..2c8ca48f6 100644 --- a/storage.h +++ b/storage.h @@ -24,7 +24,7 @@ #include #include "secbool.h" -typedef void (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress); +typedef secbool (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress); void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len); void storage_wipe(void); From 2862d679ac9fc9500306968bed8c6cd5789ce1f2 Mon Sep 17 00:00:00 2001 From: andrew Date: Wed, 6 Feb 2019 13:47:09 +0100 Subject: [PATCH 18/39] Do not require storage to be unlocked prior to calling storage_change_pin(). The function checks the old PIN anyway. --- storage.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/storage.c b/storage.c index 992805eeb..c0e2d4342 100644 --- a/storage.c +++ b/storage.c @@ -982,7 +982,7 @@ uint32_t storage_get_pin_rem(void) secbool storage_change_pin(uint32_t oldpin, uint32_t newpin) { - if (sectrue != initialized || sectrue != unlocked) { + if (sectrue != initialized) { return secfalse; } if (sectrue != storage_unlock(oldpin)) { From 4429888b9325d200b699a90f7a0e1a07d08f09c0 Mon Sep 17 00:00:00 2001 From: andrew Date: Wed, 6 Feb 2019 17:42:10 +0100 Subject: [PATCH 19/39] Use error_shutdown() to display 'Too many wrong PIN attempts. Storage has been wiped.' --- storage.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/storage.c b/storage.c index c0e2d4342..ec856f7de 100644 --- a/storage.c +++ b/storage.c @@ -730,7 +730,7 @@ secbool storage_unlock(uint32_t pin) wait_random(); if (ctr >= PIN_MAX_TRIES) { storage_wipe(); - ensure(secfalse, "pin_fails_check_max"); + error_shutdown("Too many wrong PIN", "attempts. Storage has", "been wiped.", NULL); return secfalse; } @@ -779,7 +779,7 @@ secbool storage_unlock(uint32_t pin) wait_random(); if (ctr + 1 >= PIN_MAX_TRIES) { storage_wipe(); - ensure(secfalse, "pin_fails_check_max"); + error_shutdown("Too many wrong PIN", "attempts. Storage has", "been wiped.", NULL); } return secfalse; } From 0497802014edf03cdcce8cb70889d5a6e0bd3361 Mon Sep 17 00:00:00 2001 From: andrew Date: Thu, 7 Feb 2019 14:03:25 +0100 Subject: [PATCH 20/39] Display more information when handle_fault() is invoked to help diagnose bugs. We might want to remove this in the next release. --- storage.c | 58 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/storage.c b/storage.c index ec856f7de..36f38b12b 100644 --- a/storage.c +++ b/storage.c @@ -117,7 +117,9 @@ static uint32_t norcow_active_version = 0; static const uint8_t TRUE_BYTE = 0x01; static const uint8_t FALSE_BYTE = 0x00; -static void handle_fault(void); +static void __handle_fault(const char *msg, const char *file, int line, const char *func); +#define handle_fault(msg) (__handle_fault(msg, __FILE__, __LINE__, __func__)) + static secbool storage_upgrade(void); static secbool storage_set_encrypted(const uint16_t key, const void *val, const uint16_t len); static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len); @@ -135,7 +137,7 @@ static secbool secequal(const void* ptr1, const void* ptr2, size_t n) { // Check loop completion in case of a fault injection attack. if (i != n) { - handle_fault(); + handle_fault("loop completion check"); } return diff ? secfalse : sectrue; @@ -258,7 +260,7 @@ static secbool auth_get(uint16_t key, const void **val, uint16_t *len) // Check loop completion in case of a fault injection attack. if (secfalse != norcow_get_next(&offset, &k, &v, &l)) { - handle_fault(); + handle_fault("loop completion check"); } // Check storage authentication tag. @@ -268,13 +270,13 @@ static secbool auth_get(uint16_t key, const void **val, uint16_t *len) } #endif if (tag_val == NULL || tag_len != STORAGE_TAG_SIZE || sectrue != secequal(h, tag_val, STORAGE_TAG_SIZE)) { - handle_fault(); + handle_fault("storage tag check"); } if (*val == NULL) { // Check for fault injection. if (other_count != entry_count) { - handle_fault(); + handle_fault("sanity check"); } return secfalse; } @@ -292,7 +294,7 @@ static void wait_random(void) volatile int j = wait; while (i < wait) { if (i + j != wait) { - handle_fault(); + handle_fault("sanity check"); } ++i; --j; @@ -300,7 +302,7 @@ static void wait_random(void) // Double-check loop completion. if (i != wait) { - handle_fault(); + handle_fault("loop completion check"); } #endif } @@ -404,7 +406,7 @@ static uint32_t generate_guard_key(void) static secbool expand_guard_key(const uint32_t guard_key, uint32_t *guard_mask, uint32_t *guard) { if (sectrue != check_guard_key(guard_key)) { - handle_fault(); + handle_fault("guard key check"); return secfalse; } *guard_mask = ((guard_key & LOW_MASK) << 1) | ((~guard_key) & LOW_MASK); @@ -532,7 +534,7 @@ secbool storage_pin_fails_increase(void) wait_random(); if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) { - handle_fault(); + handle_fault("no PIN logs"); return secfalse; } @@ -540,7 +542,7 @@ secbool storage_pin_fails_increase(void) uint32_t guard; wait_random(); if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) { - handle_fault(); + handle_fault("guard key expansion"); return secfalse; } @@ -548,7 +550,7 @@ secbool storage_pin_fails_increase(void) for (size_t i = 0; i < PIN_LOG_WORDS; ++i) { wait_random(); if ((entry_log[i] & guard_mask) != guard) { - handle_fault(); + handle_fault("guard bits check"); return secfalse; } if (entry_log[i] != guard) { @@ -559,14 +561,14 @@ secbool storage_pin_fails_increase(void) wait_random(); if (sectrue != norcow_update_word(PIN_LOGS_KEY, sizeof(uint32_t)*(i + GUARD_KEY_WORDS + PIN_LOG_WORDS), (word & ~guard_mask) | guard)) { - handle_fault(); + handle_fault("PIN logs update"); return secfalse; } return sectrue; } } - handle_fault(); + handle_fault("PIN log exhausted"); return secfalse; } @@ -588,7 +590,7 @@ static secbool pin_get_fails(uint32_t *ctr) uint16_t len = 0; wait_random(); if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) { - handle_fault(); + handle_fault("no PIN logs"); return secfalse; } @@ -596,7 +598,7 @@ static secbool pin_get_fails(uint32_t *ctr) uint32_t guard; wait_random(); if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) { - handle_fault(); + handle_fault("guard key expansion"); return secfalse; } const uint32_t unused = guard | ~guard_mask; @@ -607,7 +609,7 @@ static secbool pin_get_fails(uint32_t *ctr) volatile size_t i; for (i = 0; i < PIN_LOG_WORDS; ++i) { if ((entry_log[i] & guard_mask) != guard || (success_log[i] & guard_mask) != guard || (entry_log[i] & success_log[i]) != entry_log[i]) { - handle_fault(); + handle_fault("PIN logs format check"); return secfalse; } @@ -617,14 +619,14 @@ static secbool pin_get_fails(uint32_t *ctr) } } else { if (entry_log[i] != unused) { - handle_fault(); + handle_fault("PIN entry log format check"); return secfalse; } } } if (current < 0 || current >= PIN_LOG_WORDS || i != PIN_LOG_WORDS) { - handle_fault(); + handle_fault("PIN log exhausted"); return secfalse; } @@ -635,7 +637,7 @@ static secbool pin_get_fails(uint32_t *ctr) word = word | (word << 1); // Verify that the entry word has form 0*1*. if ((word & (word + 1)) != 0) { - handle_fault(); + handle_fault("PIN entry log format check"); return secfalse; } @@ -706,7 +708,7 @@ static secbool unlock(uint32_t pin) // NOTE: storage_get_encrypted() calls auth_get(), which initializes the authentication_sum. uint32_t version; if (sectrue != storage_get_encrypted(VERSION_KEY, &version, sizeof(version), &len) || len != sizeof(version) || version != norcow_active_version) { - handle_fault(); + handle_fault("storage version check"); return secfalse; } @@ -770,7 +772,7 @@ secbool storage_unlock(uint32_t pin) // Check that the PIN fail counter was incremented. uint32_t ctr_ck; if (sectrue != pin_get_fails(&ctr_ck) || ctr + 1 != ctr_ck) { - handle_fault(); + handle_fault("PIN counter increment"); return secfalse; } @@ -804,7 +806,7 @@ static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const u } if (*len < CHACHA20_IV_SIZE + POLY1305_TAG_SIZE) { - handle_fault(); + handle_fault("ciphertext length check"); return secfalse; } *len -= CHACHA20_IV_SIZE + POLY1305_TAG_SIZE; @@ -832,7 +834,7 @@ static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const u if (secequal(tag_computed, tag_stored, POLY1305_TAG_SIZE) != sectrue) { memzero(val_dest, max_len); memzero(tag_computed, sizeof(tag_computed)); - handle_fault(); + handle_fault("authentication tag check"); return secfalse; } @@ -1003,14 +1005,14 @@ void storage_wipe(void) init_wiped_storage(); } -static void handle_fault(void) +static void __handle_fault(const char *msg, const char *file, int line, const char *func) { static secbool in_progress = secfalse; // If fault handling is already in progress, then we are probably facing a fault injection attack, so wipe. if (secfalse != in_progress) { storage_wipe(); - ensure(secfalse, "fault detected"); + __fatal_error("Fault detected", msg, file, line, func); } // We use the PIN fail counter as a fault counter. Increment the counter, check that it was incremented and halt. @@ -1018,19 +1020,19 @@ static void handle_fault(void) uint32_t ctr; if (sectrue != pin_get_fails(&ctr)) { storage_wipe(); - ensure(secfalse, "fault detected"); + __fatal_error("Fault detected", msg, file, line, func); } if (sectrue != storage_pin_fails_increase()) { storage_wipe(); - ensure(secfalse, "fault detected"); + __fatal_error("Fault detected", msg, file, line, func); } uint32_t ctr_new; if (sectrue != pin_get_fails(&ctr_new) || ctr + 1 != ctr_new) { storage_wipe(); } - ensure(secfalse, "fault detected"); + __fatal_error("Fault detected", msg, file, line, func); } /* From 18fa9999742fcd350e873c7c6785829947afc389 Mon Sep 17 00:00:00 2001 From: andrew Date: Fri, 8 Feb 2019 17:50:27 +0100 Subject: [PATCH 21/39] Support entries which are writable even when the storage is locked. Needed for U2F counter on Trezor 1. --- storage.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/storage.c b/storage.c index 36f38b12b..3854dd9d5 100644 --- a/storage.c +++ b/storage.c @@ -62,6 +62,10 @@ // If the top bit of APP is set, then the value is not encrypted. #define FLAG_PUBLIC 0x80 +// If the top two bits of APP are set, then the value is not encrypted and it +// can be written even when the storage is locked. +#define FLAGS_WRITE 0xC0 + // The length of the guard key in words. #define GUARD_KEY_WORDS 1 @@ -926,7 +930,11 @@ secbool storage_set(const uint16_t key, const void *val, const uint16_t len) const uint8_t app = key >> 8; // APP == 0 is reserved for PIN related values - if (sectrue != initialized || sectrue != unlocked || app == APP_STORAGE) { + if (sectrue != initialized || app == APP_STORAGE) { + return secfalse; + } + + if (sectrue != unlocked && (app & FLAGS_WRITE) != FLAGS_WRITE) { return secfalse; } @@ -944,7 +952,11 @@ secbool storage_delete(const uint16_t key) const uint8_t app = key >> 8; // APP == 0 is reserved for storage related values - if (sectrue != initialized || sectrue != unlocked || app == APP_STORAGE) { + if (sectrue != initialized || app == APP_STORAGE) { + return secfalse; + } + + if (sectrue != unlocked && (app & FLAGS_WRITE) != FLAGS_WRITE) { return secfalse; } From 5c2765740db064c99fe54cbae79f74a3d767973c Mon Sep 17 00:00:00 2001 From: andrew Date: Fri, 8 Feb 2019 20:24:55 +0100 Subject: [PATCH 22/39] Add efficient counter implementation. --- storage.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- storage.h | 2 ++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/storage.c b/storage.c index 3854dd9d5..d37d96466 100644 --- a/storage.c +++ b/storage.c @@ -105,6 +105,9 @@ // The length of the ChaCha20 block in bytes. #define CHACHA20_BLOCK_SIZE 64 +// The length of the counter tail in bytes. +#define COUNTER_TAIL_LEN 8 + // Values used in the guard key integrity check. #define GUARD_KEY_MODULUS 6311 #define GUARD_KEY_REMAINDER 15 @@ -858,7 +861,7 @@ secbool storage_get(const uint16_t key, void *val_dest, const uint16_t max_len, return secfalse; } - // If the top bit of APP is set, then the value is not encrypted and can be read from an unlocked device. + // If the top bit of APP is set, then the value is not encrypted and can be read from a locked device. secbool ret = secfalse; if ((app & FLAG_PUBLIC) != 0) { const void *val_stored = NULL; @@ -967,6 +970,60 @@ secbool storage_delete(const uint16_t key) return ret; } +secbool storage_set_counter(const uint16_t key, const uint32_t count) +{ + const uint8_t app = key >> 8; + if ((app & FLAG_PUBLIC) == 0) { + return secfalse; + } + + // The count is stored as a 32-bit integer followed by a tail of "1" bits, + // which is used as a tally. + uint8_t value[sizeof(count) + COUNTER_TAIL_LEN]; + memset(value, 0xff, sizeof(value)); + *((uint32_t*)value) = count; + return storage_set(key, value, sizeof(value)); +} + +secbool storage_next_counter(const uint16_t key, uint32_t *count) +{ + const uint8_t app = key >> 8; + // APP == 0 is reserved for PIN related values + if (sectrue != initialized || app == APP_STORAGE || (app & FLAG_PUBLIC) == 0) { + return secfalse; + } + + if (sectrue != unlocked && (app & FLAGS_WRITE) != FLAGS_WRITE) { + return secfalse; + } + + uint16_t len = 0; + const uint32_t *val_stored = NULL; + if (sectrue != norcow_get(key, (const void**)&val_stored, &len)) { + *count = 0; + return storage_set_counter(key, 0); + } + + if (len < sizeof(uint32_t) || len % sizeof(uint32_t) != 0) { + return secfalse; + } + uint16_t len_words = len / sizeof(uint32_t); + + uint16_t i = 1; + while (i < len_words && val_stored[i] == 0) { + ++i; + } + + *count = val_stored[0] + 1 + 32 * (i - 1); + + if (i < len_words) { + *count += hamming_weight(~val_stored[i]); + return norcow_update_word(key, sizeof(uint32_t) * i, val_stored[i] >> 1); + } else { + return storage_set_counter(key, *count); + } +} + secbool storage_has_pin(void) { if (sectrue != initialized) { diff --git a/storage.h b/storage.h index 2c8ca48f6..460b30071 100644 --- a/storage.h +++ b/storage.h @@ -38,5 +38,7 @@ secbool storage_change_pin(const uint32_t oldpin, const uint32_t newpin); secbool storage_get(const uint16_t key, void *val, const uint16_t max_len, uint16_t *len); secbool storage_set(const uint16_t key, const void *val, uint16_t len); secbool storage_delete(const uint16_t key); +secbool storage_set_counter(const uint16_t key, const uint32_t count); +secbool storage_next_counter(const uint16_t key, uint32_t *count); #endif From f05a2ff9ccb4562ba4bd8a75a3607bbf24a0c074 Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Mon, 11 Feb 2019 17:46:46 +0100 Subject: [PATCH 23/39] Fix aliasing issue in storage_set_counter(). --- storage.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/storage.c b/storage.c index d37d96466..9cb396cbf 100644 --- a/storage.c +++ b/storage.c @@ -105,8 +105,8 @@ // The length of the ChaCha20 block in bytes. #define CHACHA20_BLOCK_SIZE 64 -// The length of the counter tail in bytes. -#define COUNTER_TAIL_LEN 8 +// The length of the counter tail in words. +#define COUNTER_TAIL_WORDS 2 // Values used in the guard key integrity check. #define GUARD_KEY_MODULUS 6311 @@ -979,9 +979,9 @@ secbool storage_set_counter(const uint16_t key, const uint32_t count) // The count is stored as a 32-bit integer followed by a tail of "1" bits, // which is used as a tally. - uint8_t value[sizeof(count) + COUNTER_TAIL_LEN]; + uint32_t value[1 + COUNTER_TAIL_WORDS]; memset(value, 0xff, sizeof(value)); - *((uint32_t*)value) = count; + value[0] = count; return storage_set(key, value, sizeof(value)); } From ce90a12b537fab1251f27ebf48bc99252edf1a09 Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Tue, 12 Feb 2019 13:31:19 +0100 Subject: [PATCH 24/39] Treat missing EDEK as a fault. --- storage.c | 1 + 1 file changed, 1 insertion(+) diff --git a/storage.c b/storage.c index 9cb396cbf..5a20ba578 100644 --- a/storage.c +++ b/storage.c @@ -680,6 +680,7 @@ static secbool unlock(uint32_t pin) uint16_t len = 0; if (sectrue != initialized || sectrue != norcow_get(EDEK_PVC_KEY, &buffer, &len) || len != RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE) { memzero(&pin, sizeof(pin)); + handle_fault("no EDEK"); return secfalse; } From 13b256ab2c11791e0c13696a8c507787a374884f Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Tue, 12 Feb 2019 13:43:42 +0100 Subject: [PATCH 25/39] Shorten error messages to better display on Trezor 1 screen. --- storage.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/storage.c b/storage.c index 5a20ba578..16ebe6597 100644 --- a/storage.c +++ b/storage.c @@ -463,10 +463,10 @@ static void init_wiped_storage(void) } random_buffer(cached_keys, sizeof(cached_keys)); uint32_t version = NORCOW_VERSION; - ensure(auth_init(), "failed to initialize storage authentication tag"); - ensure(storage_set_encrypted(VERSION_KEY, &version, sizeof(version)), "failed to set storage version"); - ensure(set_pin(PIN_EMPTY), "failed to initialize PIN"); - ensure(pin_logs_init(0), "failed to initialize PIN logs"); + ensure(auth_init(), "set_storage_auth_tag failed"); + ensure(storage_set_encrypted(VERSION_KEY, &version, sizeof(version)), "set_storage_version failed"); + ensure(pin_logs_init(0), "init_pin_logs failed"); + ensure(set_pin(PIN_EMPTY), "init_pin failed"); if (unlocked != sectrue) { memzero(cached_keys, sizeof(cached_keys)); } @@ -485,7 +485,7 @@ void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint if (norcow_active_version < NORCOW_VERSION) { if (sectrue != storage_upgrade()) { storage_wipe(); - ensure(secfalse, "storage_upgrade"); + ensure(secfalse, "storage_upgrade failed"); } } From 94cb1a4dbe2e28aaaf36cd741800cf5c1b16e08f Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Thu, 14 Feb 2019 16:52:35 +0100 Subject: [PATCH 26/39] Before checking the PIN sleep for 2^ctr - 1 seconds instead of 2^(ctr-1) seconds. --- storage.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/storage.c b/storage.c index 16ebe6597..2611f7cf7 100644 --- a/storage.c +++ b/storage.c @@ -744,8 +744,8 @@ secbool storage_unlock(uint32_t pin) return secfalse; } - // Sleep for 2^(ctr-1) seconds before checking the PIN. - uint32_t wait = (1 << ctr) >> 1; + // Sleep for 2^ctr - 1 seconds before checking the PIN. + uint32_t wait = (1 << ctr) - 1; uint32_t progress; for (uint32_t rem = wait; rem > 0; rem--) { for (int i = 0; i < 10; i++) { From 5688a9e47e6d0d21b63ac22924199de2da696db7 Mon Sep 17 00:00:00 2001 From: Pavol Rusnak Date: Fri, 15 Feb 2019 14:11:16 +0100 Subject: [PATCH 27/39] gitignore: add *.d --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 5761abcfd..6142305dc 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ *.o +*.d From 38e92407c7607567b1331f76ee7953867e0c21a6 Mon Sep 17 00:00:00 2001 From: Pavol Rusnak Date: Mon, 18 Feb 2019 19:19:17 +0100 Subject: [PATCH 28/39] show progress in derive_kek --- storage.c | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/storage.c b/storage.c index 2611f7cf7..1823c33c5 100644 --- a/storage.c +++ b/storage.c @@ -314,7 +314,7 @@ static void wait_random(void) #endif } -static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA256_DIGEST_LENGTH], uint8_t keiv[SHA256_DIGEST_LENGTH]) +static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA256_DIGEST_LENGTH], uint8_t keiv[SHA256_DIGEST_LENGTH], secbool show_progress) { #if BYTE_ORDER == BIG_ENDIAN REVERSE32(pin, pin); @@ -326,10 +326,20 @@ static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA PBKDF2_HMAC_SHA256_CTX ctx; pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 1); - pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT/2); + for (int i = 1; i <= 5; i++) { + pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10); + if (show_progress && ui_callback) { + ui_callback(0, 900 + i * 10); + } + } pbkdf2_hmac_sha256_Final(&ctx, kek); pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 2); - pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT/2); + for (int i = 6; i <= 10; i++) { + pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10); + if (show_progress && ui_callback) { + ui_callback(0, 900 + i * 10); + } + } pbkdf2_hmac_sha256_Final(&ctx, keiv); memzero(&ctx, sizeof(PBKDF2_HMAC_SHA256_CTX)); memzero(&pin, sizeof(pin)); @@ -347,7 +357,7 @@ static secbool set_pin(uint32_t pin) uint8_t keiv[SHA256_DIGEST_LENGTH]; chacha20poly1305_ctx ctx; random_buffer(salt, RANDOM_SALT_SIZE); - derive_kek(pin, salt, kek, keiv); + derive_kek(pin, salt, kek, keiv, secfalse); rfc7539_init(&ctx, kek, keiv); memzero(kek, sizeof(kek)); memzero(keiv, sizeof(keiv)); @@ -694,7 +704,7 @@ static secbool unlock(uint32_t pin) chacha20poly1305_ctx ctx; // Decrypt the data encryption key and the storage authentication key and check the PIN verification code. - derive_kek(pin, salt, kek, keiv); + derive_kek(pin, salt, kek, keiv, sectrue); memzero(&pin, sizeof(pin)); rfc7539_init(&ctx, kek, keiv); memzero(kek, sizeof(kek)); @@ -751,9 +761,9 @@ secbool storage_unlock(uint32_t pin) for (int i = 0; i < 10; i++) { if (ui_callback) { if (wait > 1000000) { // precise enough - progress = (wait - rem) / (wait / 1000); + progress = (wait - rem) / (wait / 900); } else { - progress = ((wait - rem) * 10 + i) * 100 / wait; + progress = ((wait - rem) * 10 + i) * 90 / wait; } if (sectrue == ui_callback(rem, progress)) { return secfalse; @@ -764,7 +774,7 @@ secbool storage_unlock(uint32_t pin) } // Show last frame if we were waiting if ((wait > 0) && ui_callback) { - if (sectrue == ui_callback(0, 1000)) { + if (sectrue == ui_callback(0, 900)) { return secfalse; } } From d7e7d8ef27cd57480d5c4eed17541f9a5bc72f72 Mon Sep 17 00:00:00 2001 From: Pavol Rusnak Date: Mon, 18 Feb 2019 19:29:25 +0100 Subject: [PATCH 29/39] show ui_callback always (before and after) --- storage.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/storage.c b/storage.c index 1823c33c5..53e7ca11e 100644 --- a/storage.c +++ b/storage.c @@ -754,8 +754,13 @@ secbool storage_unlock(uint32_t pin) return secfalse; } - // Sleep for 2^ctr - 1 seconds before checking the PIN. uint32_t wait = (1 << ctr) - 1; + if (ui_callback) { + if (sectrue == ui_callback(wait, 0)) { + return secfalse; + } + } + // Sleep for 2^ctr - 1 seconds before checking the PIN. uint32_t progress; for (uint32_t rem = wait; rem > 0; rem--) { for (int i = 0; i < 10; i++) { @@ -772,8 +777,7 @@ secbool storage_unlock(uint32_t pin) hal_delay(100); } } - // Show last frame if we were waiting - if ((wait > 0) && ui_callback) { + if (ui_callback) { if (sectrue == ui_callback(0, 900)) { return secfalse; } From d715873ee62d776ddc0f85028f7622374d4e0fe7 Mon Sep 17 00:00:00 2001 From: Pavol Rusnak Date: Tue, 19 Feb 2019 15:31:07 +0100 Subject: [PATCH 30/39] callback: change ratio to 80% waiting, 20% deriving KEK --- storage.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/storage.c b/storage.c index 53e7ca11e..40a506e20 100644 --- a/storage.c +++ b/storage.c @@ -329,7 +329,7 @@ static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA for (int i = 1; i <= 5; i++) { pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10); if (show_progress && ui_callback) { - ui_callback(0, 900 + i * 10); + ui_callback(0, 800 + i * 20); } } pbkdf2_hmac_sha256_Final(&ctx, kek); @@ -337,7 +337,7 @@ static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA for (int i = 6; i <= 10; i++) { pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10); if (show_progress && ui_callback) { - ui_callback(0, 900 + i * 10); + ui_callback(0, 800 + i * 20); } } pbkdf2_hmac_sha256_Final(&ctx, keiv); @@ -766,9 +766,9 @@ secbool storage_unlock(uint32_t pin) for (int i = 0; i < 10; i++) { if (ui_callback) { if (wait > 1000000) { // precise enough - progress = (wait - rem) / (wait / 900); + progress = (wait - rem) / (wait / 800); } else { - progress = ((wait - rem) * 10 + i) * 90 / wait; + progress = ((wait - rem) * 10 + i) * 80 / wait; } if (sectrue == ui_callback(rem, progress)) { return secfalse; @@ -778,7 +778,7 @@ secbool storage_unlock(uint32_t pin) } } if (ui_callback) { - if (sectrue == ui_callback(0, 900)) { + if (sectrue == ui_callback(0, 800)) { return secfalse; } } From 5b49878cdbefb58b42302d64a71bca9a1868c4ad Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Wed, 20 Feb 2019 18:27:19 +0100 Subject: [PATCH 31/39] Check that the input to storage_set_encrypted() doesn't exceed the maximum length of 65507. --- storage.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/storage.c b/storage.c index 40a506e20..5d17ef24c 100644 --- a/storage.c +++ b/storage.c @@ -906,8 +906,11 @@ secbool storage_get(const uint16_t key, void *val_dest, const uint16_t max_len, */ static secbool storage_set_encrypted(const uint16_t key, const void *val, const uint16_t len) { + if (len > UINT16_MAX - CHACHA20_IV_SIZE - POLY1305_TAG_SIZE) { + return secfalse; + } + // Preallocate space on the flash storage. - uint16_t offset = 0; if (sectrue != auth_set(key, NULL, CHACHA20_IV_SIZE + len + POLY1305_TAG_SIZE)) { return secfalse; } @@ -915,6 +918,7 @@ static secbool storage_set_encrypted(const uint16_t key, const void *val, const // Write the IV to the flash. uint8_t buffer[CHACHA20_BLOCK_SIZE + POLY1305_TAG_SIZE]; random_buffer(buffer, CHACHA20_IV_SIZE); + uint16_t offset = 0; if (sectrue != norcow_update_bytes(key, offset, buffer, CHACHA20_IV_SIZE)) { return secfalse; } From 9100a3ee640c6466d8638dd9ea2e906978b6e474 Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Thu, 21 Feb 2019 14:32:19 +0100 Subject: [PATCH 32/39] Improve PVC check to mitigate side channel attacks by adding randomization and using word-wise comparison. --- storage.c | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/storage.c b/storage.c index 5d17ef24c..b8915f80c 100644 --- a/storage.c +++ b/storage.c @@ -150,6 +150,24 @@ static secbool secequal(const void* ptr1, const void* ptr2, size_t n) { return diff ? secfalse : sectrue; } +static secbool secequal32(const uint32_t* ptr1, const uint32_t* ptr2, size_t n) { + uint32_t diff = 0; + size_t i; + for (i = 0; i < n; ++i) { + uint32_t mask = random32(); + diff |= (*ptr1 + mask - *ptr2) ^ mask; + ++ptr1; + ++ptr2; + } + + // Check loop completion in case of a fault injection attack. + if (i != n) { + handle_fault("loop completion check"); + } + + return diff ? secfalse : sectrue; +} + static secbool is_protected(uint16_t key) { const uint8_t app = key >> 8; return ((app & FLAG_PUBLIC) == 0 && app != APP_STORAGE) ? sectrue : secfalse; @@ -696,11 +714,14 @@ static secbool unlock(uint32_t pin) const uint8_t *salt = (const uint8_t*) buffer; const uint8_t *ekeys = (const uint8_t*) buffer + RANDOM_SALT_SIZE; - const uint8_t *pvc = (const uint8_t*) buffer + RANDOM_SALT_SIZE + KEYS_SIZE; + const uint32_t *pvc = (const uint32_t*) buffer + (RANDOM_SALT_SIZE + KEYS_SIZE)/sizeof(uint32_t); + _Static_assert(((RANDOM_SALT_SIZE + KEYS_SIZE) & 3) == 0, "PVC unaligned"); + _Static_assert((PVC_SIZE & 3) == 0, "PVC size unaligned"); + uint8_t kek[SHA256_DIGEST_LENGTH]; uint8_t keiv[SHA256_DIGEST_LENGTH]; uint8_t keys[KEYS_SIZE]; - uint8_t tag[POLY1305_TAG_SIZE]; + uint8_t tag[POLY1305_TAG_SIZE] __attribute__((aligned(sizeof(uint32_t)))); chacha20poly1305_ctx ctx; // Decrypt the data encryption key and the storage authentication key and check the PIN verification code. @@ -713,7 +734,7 @@ static secbool unlock(uint32_t pin) rfc7539_finish(&ctx, 0, KEYS_SIZE, tag); memzero(&ctx, sizeof(ctx)); wait_random(); - if (secequal(tag, pvc, PVC_SIZE) != sectrue) { + if (secequal32((const uint32_t*) tag, pvc, PVC_SIZE/sizeof(uint32_t)) != sectrue) { memzero(keys, sizeof(keys)); memzero(tag, sizeof(tag)); return secfalse; From e55737c4b1648c619d654eb25fa06fe381c5a1d4 Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Thu, 21 Feb 2019 15:22:46 +0100 Subject: [PATCH 33/39] Change encrypted entry format to (IV || tag || ciphertext). --- storage.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/storage.c b/storage.c index b8915f80c..d3751ac73 100644 --- a/storage.c +++ b/storage.c @@ -863,8 +863,8 @@ static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const u } const uint8_t *iv = (const uint8_t*) val_stored; - const uint8_t *ciphertext = (const uint8_t*) val_stored + CHACHA20_IV_SIZE; - const uint8_t *tag_stored = (const uint8_t*) val_stored + CHACHA20_IV_SIZE + *len; + const uint8_t *tag_stored = (const uint8_t*) val_stored + CHACHA20_IV_SIZE; + const uint8_t *ciphertext = (const uint8_t*) val_stored + CHACHA20_IV_SIZE + POLY1305_TAG_SIZE; uint8_t tag_computed[POLY1305_TAG_SIZE]; chacha20poly1305_ctx ctx; rfc7539_init(&ctx, cached_dek, iv); @@ -932,18 +932,18 @@ static secbool storage_set_encrypted(const uint16_t key, const void *val, const } // Preallocate space on the flash storage. - if (sectrue != auth_set(key, NULL, CHACHA20_IV_SIZE + len + POLY1305_TAG_SIZE)) { + if (sectrue != auth_set(key, NULL, CHACHA20_IV_SIZE + POLY1305_TAG_SIZE + len)) { return secfalse; } // Write the IV to the flash. - uint8_t buffer[CHACHA20_BLOCK_SIZE + POLY1305_TAG_SIZE]; + uint8_t buffer[CHACHA20_BLOCK_SIZE]; random_buffer(buffer, CHACHA20_IV_SIZE); uint16_t offset = 0; if (sectrue != norcow_update_bytes(key, offset, buffer, CHACHA20_IV_SIZE)) { return secfalse; } - offset += CHACHA20_IV_SIZE; + offset += CHACHA20_IV_SIZE + POLY1305_TAG_SIZE; // Encrypt all blocks except for the last one. chacha20poly1305_ctx ctx; @@ -961,8 +961,11 @@ static secbool storage_set_encrypted(const uint16_t key, const void *val, const // Encrypt final block and compute message authentication tag. chacha20poly1305_encrypt(&ctx, ((const uint8_t*) val) + i, buffer, len - i); - rfc7539_finish(&ctx, sizeof(key), len, buffer + len - i); - secbool ret = norcow_update_bytes(key, offset, buffer, len - i + POLY1305_TAG_SIZE); + secbool ret = norcow_update_bytes(key, offset, buffer, len - i); + if (sectrue == ret) { + rfc7539_finish(&ctx, sizeof(key), len, buffer); + ret = norcow_update_bytes(key, CHACHA20_IV_SIZE, buffer, POLY1305_TAG_SIZE); + } memzero(&ctx, sizeof(ctx)); memzero(buffer, sizeof(buffer)); return ret; From a109cc26c066e4bbd72dd69dc0a5db05be67491e Mon Sep 17 00:00:00 2001 From: Tomas Susanka Date: Thu, 21 Feb 2019 16:24:05 +0100 Subject: [PATCH 34/39] README: swap ENCRDATA and TAG as introduced in previous commit --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 537e9157d..f44352a28 100644 --- a/README.md +++ b/README.md @@ -26,11 +26,11 @@ The format of public entries has remained unchanged, that is: Private values are used to store storage-specific information and cannot be directly accessed through the storage interface. Protected entries have the following new format: -| Data | KEY | APP | LEN | IV | ENCRDATA | TAG | -|----------------|-----|-----|-----|----|----------|-----| -| Length (bytes) | 1 | 1 | 2 | 12 | LEN - 28 | 16 | +| Data | KEY | APP | LEN | IV | TAG | ENCRDATA | +|----------------|-----|-----|-----|----|-----|----------| +| Length (bytes) | 1 | 1 | 2 | 12 | 16 | LEN - 28 | -The LEN value thus indicates the total length of IV, ENCRDATA and TAG. +The LEN value thus indicates the total length of IV, TAG and ENCRDATA. The random salt (32 bits), EDEK (256 bits), ESAK (128 bits) and PVC (64 bits) is stored in a single entry under APP=0, KEY=2: From 1b9329b6fa5b6ee0d54d90dd2e94a32fea75c133 Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Fri, 22 Feb 2019 11:26:28 +0100 Subject: [PATCH 35/39] Fix undefined integer shift. --- storage.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/storage.c b/storage.c index d3751ac73..ad03968e6 100644 --- a/storage.c +++ b/storage.c @@ -259,7 +259,7 @@ static secbool auth_get(uint16_t key, const void **val, uint16_t *len) } continue; } - g[0] = ((k & 0xff) << 24) | ((k & 0xff00) << 8) | 0x8000; // Add SHA message padding. + g[0] = (((uint32_t)k & 0xff) << 24) | (((uint32_t)k & 0xff00) << 8) | 0x8000; // Add SHA message padding. sha256_Transform(idig, g, h); sha256_Transform(odig, h, h); for (uint32_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) { From cf9e276c6e48dcfe78cd1695dc4ed014ef93b879 Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Fri, 22 Feb 2019 18:45:49 +0100 Subject: [PATCH 36/39] In derive_kek() show 'Processing' instead of 'Verifying PIN' if the PIN is empty or the device is not being unlocked. --- storage.c | 21 +++++++++++++-------- storage.h | 2 +- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/storage.c b/storage.c index ad03968e6..445408446 100644 --- a/storage.c +++ b/storage.c @@ -112,6 +112,9 @@ #define GUARD_KEY_MODULUS 6311 #define GUARD_KEY_REMAINDER 15 +const char* const VERIFYING_PIN_MSG = "Verifying PIN"; +const char* const PROCESSING_MSG = "Processing"; + static secbool initialized = secfalse; static secbool unlocked = secfalse; static PIN_UI_WAIT_CALLBACK ui_callback = NULL; @@ -332,7 +335,7 @@ static void wait_random(void) #endif } -static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA256_DIGEST_LENGTH], uint8_t keiv[SHA256_DIGEST_LENGTH], secbool show_progress) +static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA256_DIGEST_LENGTH], uint8_t keiv[SHA256_DIGEST_LENGTH], secbool unlocking) { #if BYTE_ORDER == BIG_ENDIAN REVERSE32(pin, pin); @@ -342,20 +345,22 @@ static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA memcpy(salt, hardware_salt, HARDWARE_SALT_SIZE); memcpy(salt + HARDWARE_SALT_SIZE, random_salt, RANDOM_SALT_SIZE); + const char* message = (pin == PIN_EMPTY || unlocking != sectrue) ? PROCESSING_MSG : VERIFYING_PIN_MSG; + PBKDF2_HMAC_SHA256_CTX ctx; pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 1); for (int i = 1; i <= 5; i++) { pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10); - if (show_progress && ui_callback) { - ui_callback(0, 800 + i * 20); + if (ui_callback) { + ui_callback(0, 800 + i * 20, message); } } pbkdf2_hmac_sha256_Final(&ctx, kek); pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 2); for (int i = 6; i <= 10; i++) { pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10); - if (show_progress && ui_callback) { - ui_callback(0, 800 + i * 20); + if (ui_callback) { + ui_callback(0, 800 + i * 20, message); } } pbkdf2_hmac_sha256_Final(&ctx, keiv); @@ -777,7 +782,7 @@ secbool storage_unlock(uint32_t pin) uint32_t wait = (1 << ctr) - 1; if (ui_callback) { - if (sectrue == ui_callback(wait, 0)) { + if (sectrue == ui_callback(wait, 0, VERIFYING_PIN_MSG)) { return secfalse; } } @@ -791,7 +796,7 @@ secbool storage_unlock(uint32_t pin) } else { progress = ((wait - rem) * 10 + i) * 80 / wait; } - if (sectrue == ui_callback(rem, progress)) { + if (sectrue == ui_callback(rem, progress, VERIFYING_PIN_MSG)) { return secfalse; } } @@ -799,7 +804,7 @@ secbool storage_unlock(uint32_t pin) } } if (ui_callback) { - if (sectrue == ui_callback(0, 800)) { + if (sectrue == ui_callback(0, 800, VERIFYING_PIN_MSG)) { return secfalse; } } diff --git a/storage.h b/storage.h index 460b30071..e3a163247 100644 --- a/storage.h +++ b/storage.h @@ -24,7 +24,7 @@ #include #include "secbool.h" -typedef secbool (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress); +typedef secbool (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress, const char* message); void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len); void storage_wipe(void); From 0e897f673a2150607bae553e21604b253352644e Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Fri, 22 Feb 2019 19:04:14 +0100 Subject: [PATCH 37/39] In unlock() show 'Processing' instead of 'Verifying PIN' if the PIN is empty. --- storage.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/storage.c b/storage.c index 445408446..0f1df2862 100644 --- a/storage.c +++ b/storage.c @@ -780,9 +780,11 @@ secbool storage_unlock(uint32_t pin) return secfalse; } + const char* message = (pin == PIN_EMPTY) ? PROCESSING_MSG : VERIFYING_PIN_MSG; + uint32_t wait = (1 << ctr) - 1; if (ui_callback) { - if (sectrue == ui_callback(wait, 0, VERIFYING_PIN_MSG)) { + if (sectrue == ui_callback(wait, 0, message)) { return secfalse; } } @@ -796,7 +798,7 @@ secbool storage_unlock(uint32_t pin) } else { progress = ((wait - rem) * 10 + i) * 80 / wait; } - if (sectrue == ui_callback(rem, progress, VERIFYING_PIN_MSG)) { + if (sectrue == ui_callback(rem, progress, message)) { return secfalse; } } @@ -804,7 +806,7 @@ secbool storage_unlock(uint32_t pin) } } if (ui_callback) { - if (sectrue == ui_callback(0, 800, VERIFYING_PIN_MSG)) { + if (sectrue == ui_callback(0, 800, message)) { return secfalse; } } From 511fc205b284605651348512c5c5c2c95a642fa1 Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Sat, 23 Feb 2019 01:52:25 +0100 Subject: [PATCH 38/39] Improve the information which gets passed to ui_callback(). Exact total remaining time, smooth progress and better messages. --- storage.c | 95 ++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 63 insertions(+), 32 deletions(-) diff --git a/storage.c b/storage.c index 0f1df2862..af9c3db63 100644 --- a/storage.c +++ b/storage.c @@ -59,6 +59,9 @@ // The total number of iterations to use in PBKDF2. #define PIN_ITER_COUNT 20000 +// The number of seconds required to derive the KEK and KEIV. +#define DERIVE_SECS 1 + // If the top bit of APP is set, then the value is not encrypted. #define FLAG_PUBLIC 0x80 @@ -114,10 +117,14 @@ const char* const VERIFYING_PIN_MSG = "Verifying PIN"; const char* const PROCESSING_MSG = "Processing"; +const char* const STARTING_MSG = "Starting up"; static secbool initialized = secfalse; static secbool unlocked = secfalse; static PIN_UI_WAIT_CALLBACK ui_callback = NULL; +static uint32_t ui_total = 0; +static uint32_t ui_rem = 0; +static const char *ui_message = NULL; static uint8_t cached_keys[KEYS_SIZE] = {0}; static uint8_t *const cached_dek = cached_keys; static uint8_t *const cached_sak = cached_keys + DEK_SIZE; @@ -335,7 +342,7 @@ static void wait_random(void) #endif } -static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA256_DIGEST_LENGTH], uint8_t keiv[SHA256_DIGEST_LENGTH], secbool unlocking) +static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA256_DIGEST_LENGTH], uint8_t keiv[SHA256_DIGEST_LENGTH]) { #if BYTE_ORDER == BIG_ENDIAN REVERSE32(pin, pin); @@ -345,25 +352,33 @@ static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA memcpy(salt, hardware_salt, HARDWARE_SALT_SIZE); memcpy(salt + HARDWARE_SALT_SIZE, random_salt, RANDOM_SALT_SIZE); - const char* message = (pin == PIN_EMPTY || unlocking != sectrue) ? PROCESSING_MSG : VERIFYING_PIN_MSG; + uint32_t progress = (ui_total - ui_rem) * 1000 / ui_total; + if (ui_callback && ui_message) { + ui_callback(ui_rem, progress, ui_message); + } PBKDF2_HMAC_SHA256_CTX ctx; pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 1); for (int i = 1; i <= 5; i++) { pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10); - if (ui_callback) { - ui_callback(0, 800 + i * 20, message); + if (ui_callback && ui_message) { + progress = ((ui_total - ui_rem) * 1000 + i * DERIVE_SECS * 100) / ui_total; + ui_callback(ui_rem - i * DERIVE_SECS / 10, progress, ui_message); } } pbkdf2_hmac_sha256_Final(&ctx, kek); + pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 2); for (int i = 6; i <= 10; i++) { pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10); - if (ui_callback) { - ui_callback(0, 800 + i * 20, message); + if (ui_callback && ui_message) { + progress = ((ui_total - ui_rem) * 1000 + i * DERIVE_SECS * 100) / ui_total; + ui_callback(ui_rem - i * DERIVE_SECS / 10, progress, ui_message); } } pbkdf2_hmac_sha256_Final(&ctx, keiv); + + ui_rem -= DERIVE_SECS; memzero(&ctx, sizeof(PBKDF2_HMAC_SHA256_CTX)); memzero(&pin, sizeof(pin)); memzero(&salt, sizeof(salt)); @@ -380,7 +395,7 @@ static secbool set_pin(uint32_t pin) uint8_t keiv[SHA256_DIGEST_LENGTH]; chacha20poly1305_ctx ctx; random_buffer(salt, RANDOM_SALT_SIZE); - derive_kek(pin, salt, kek, keiv, secfalse); + derive_kek(pin, salt, kek, keiv); rfc7539_init(&ctx, kek, keiv); memzero(kek, sizeof(kek)); memzero(keiv, sizeof(keiv)); @@ -499,6 +514,9 @@ static void init_wiped_storage(void) ensure(auth_init(), "set_storage_auth_tag failed"); ensure(storage_set_encrypted(VERSION_KEY, &version, sizeof(version)), "set_storage_version failed"); ensure(pin_logs_init(0), "init_pin_logs failed"); + ui_total = DERIVE_SECS; + ui_rem = ui_total; + ui_message = PROCESSING_MSG; ensure(set_pin(PIN_EMPTY), "init_pin failed"); if (unlocked != sectrue) { memzero(cached_keys, sizeof(cached_keys)); @@ -707,7 +725,7 @@ void storage_lock(void) memzero(authentication_sum, sizeof(authentication_sum)); } -static secbool unlock(uint32_t pin) +static secbool decrypt_dek(uint32_t pin) { const void *buffer = NULL; uint16_t len = 0; @@ -730,7 +748,7 @@ static secbool unlock(uint32_t pin) chacha20poly1305_ctx ctx; // Decrypt the data encryption key and the storage authentication key and check the PIN verification code. - derive_kek(pin, salt, kek, keiv, sectrue); + derive_kek(pin, salt, kek, keiv); memzero(&pin, sizeof(pin)); rfc7539_init(&ctx, kek, keiv); memzero(kek, sizeof(kek)); @@ -759,7 +777,7 @@ static secbool unlock(uint32_t pin) return sectrue; } -secbool storage_unlock(uint32_t pin) +static secbool unlock(uint32_t pin) { if (sectrue != initialized) { return secfalse; @@ -780,36 +798,25 @@ secbool storage_unlock(uint32_t pin) return secfalse; } - const char* message = (pin == PIN_EMPTY) ? PROCESSING_MSG : VERIFYING_PIN_MSG; - - uint32_t wait = (1 << ctr) - 1; - if (ui_callback) { - if (sectrue == ui_callback(wait, 0, message)) { - return secfalse; - } - } // Sleep for 2^ctr - 1 seconds before checking the PIN. - uint32_t progress; - for (uint32_t rem = wait; rem > 0; rem--) { + uint32_t wait = (1 << ctr) - 1; + ui_total += wait; + uint32_t progress = 0; + for (ui_rem = ui_total; ui_rem > ui_total - wait; ui_rem--) { for (int i = 0; i < 10; i++) { - if (ui_callback) { - if (wait > 1000000) { // precise enough - progress = (wait - rem) / (wait / 800); + if (ui_callback && ui_message) { + if (ui_total > 1000000) { // precise enough + progress = (ui_total - ui_rem) / (ui_total / 1000); } else { - progress = ((wait - rem) * 10 + i) * 80 / wait; + progress = ((ui_total - ui_rem) * 10 + i) * 100 / ui_total; } - if (sectrue == ui_callback(rem, progress, message)) { + if (sectrue == ui_callback(ui_rem, progress, ui_message)) { return secfalse; } } hal_delay(100); } } - if (ui_callback) { - if (sectrue == ui_callback(0, 800, message)) { - return secfalse; - } - } // 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 @@ -826,7 +833,7 @@ secbool storage_unlock(uint32_t pin) return secfalse; } - if (sectrue != unlock(pin)) { + if (sectrue != decrypt_dek(pin)) { // Wipe storage if too many failures wait_random(); if (ctr + 1 >= PIN_MAX_TRIES) { @@ -842,6 +849,22 @@ secbool storage_unlock(uint32_t pin) return pin_fails_reset(); } +secbool storage_unlock(uint32_t pin) +{ + ui_total = DERIVE_SECS; + ui_rem = ui_total; + if (pin == PIN_EMPTY) { + if (ui_message == NULL) { + ui_message = STARTING_MSG; + } else { + ui_message = PROCESSING_MSG; + } + } else { + ui_message = VERIFYING_PIN_MSG; + } + return unlock(pin); +} + /* * Finds the encrypted data stored under key and writes its length to len. * If val_dest is not NULL and max_len >= len, then the data is decrypted @@ -1106,7 +1129,12 @@ secbool storage_change_pin(uint32_t oldpin, uint32_t newpin) if (sectrue != initialized) { return secfalse; } - if (sectrue != storage_unlock(oldpin)) { + + ui_total = 2 * DERIVE_SECS; + ui_rem = ui_total; + ui_message = (oldpin != PIN_EMPTY && newpin == PIN_EMPTY) ? VERIFYING_PIN_MSG : PROCESSING_MSG; + + if (sectrue != unlock(oldpin)) { return secfalse; } secbool ret = set_pin(newpin); @@ -1207,6 +1235,9 @@ static secbool storage_upgrade(void) } // Set EDEK_PVC_KEY and PIN_NOT_SET_KEY. + ui_total = DERIVE_SECS; + ui_rem = ui_total; + ui_message = PROCESSING_MSG; if (sectrue == norcow_get(V0_PIN_KEY, &val, &len)) { set_pin(*(const uint32_t*)val); } else { From d710db50fec29913a113d93a05d9f6262762a1de Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Wed, 20 Mar 2019 14:49:19 +0100 Subject: [PATCH 39/39] Increment PIN fail counter after deriving the KEK and KEIV from the PIN. --- storage.c | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/storage.c b/storage.c index af9c3db63..655e85c31 100644 --- a/storage.c +++ b/storage.c @@ -725,34 +725,26 @@ void storage_lock(void) memzero(authentication_sum, sizeof(authentication_sum)); } -static secbool decrypt_dek(uint32_t pin) +static secbool decrypt_dek(const uint8_t *kek, const uint8_t *keiv) { const void *buffer = NULL; uint16_t len = 0; if (sectrue != initialized || sectrue != norcow_get(EDEK_PVC_KEY, &buffer, &len) || len != RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE) { - memzero(&pin, sizeof(pin)); handle_fault("no EDEK"); return secfalse; } - const uint8_t *salt = (const uint8_t*) buffer; const uint8_t *ekeys = (const uint8_t*) buffer + RANDOM_SALT_SIZE; const uint32_t *pvc = (const uint32_t*) buffer + (RANDOM_SALT_SIZE + KEYS_SIZE)/sizeof(uint32_t); _Static_assert(((RANDOM_SALT_SIZE + KEYS_SIZE) & 3) == 0, "PVC unaligned"); _Static_assert((PVC_SIZE & 3) == 0, "PVC size unaligned"); - uint8_t kek[SHA256_DIGEST_LENGTH]; - uint8_t keiv[SHA256_DIGEST_LENGTH]; uint8_t keys[KEYS_SIZE]; uint8_t tag[POLY1305_TAG_SIZE] __attribute__((aligned(sizeof(uint32_t)))); chacha20poly1305_ctx ctx; // Decrypt the data encryption key and the storage authentication key and check the PIN verification code. - derive_kek(pin, salt, kek, keiv); - memzero(&pin, sizeof(pin)); rfc7539_init(&ctx, kek, keiv); - memzero(kek, sizeof(kek)); - memzero(keiv, sizeof(keiv)); chacha20poly1305_decrypt(&ctx, ekeys, keys, KEYS_SIZE); rfc7539_finish(&ctx, 0, KEYS_SIZE, tag); memzero(&ctx, sizeof(ctx)); @@ -818,11 +810,23 @@ static secbool unlock(uint32_t pin) } } + // Read the random salt from EDEK_PVC_KEY and use it to derive the KEK and KEIV from the PIN. + const void *salt = NULL; + uint16_t len = 0; + if (sectrue != initialized || sectrue != norcow_get(EDEK_PVC_KEY, &salt, &len) || len != RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE) { + memzero(&pin, sizeof(pin)); + handle_fault("no EDEK"); + return secfalse; + } + uint8_t kek[SHA256_DIGEST_LENGTH]; + uint8_t keiv[SHA256_DIGEST_LENGTH]; + derive_kek(pin, (const uint8_t*) salt, kek, keiv); + memzero(&pin, sizeof(pin)); + // 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 != storage_pin_fails_increase()) { - memzero(&pin, sizeof(pin)); return secfalse; } @@ -833,7 +837,8 @@ static secbool unlock(uint32_t pin) return secfalse; } - if (sectrue != decrypt_dek(pin)) { + // Check that the PIN was correct. + if (sectrue != decrypt_dek(kek, keiv)) { // Wipe storage if too many failures wait_random(); if (ctr + 1 >= PIN_MAX_TRIES) { @@ -842,7 +847,9 @@ static secbool unlock(uint32_t pin) } return secfalse; } - memzero(&pin, sizeof(pin)); + memzero(kek, sizeof(kek)); + memzero(keiv, sizeof(keiv)); + unlocked = sectrue; // Finally set the counter to 0 to indicate success.