You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1287 lines
40KB

  1. /*
  2. * This file is part of the TREZOR project, https://trezor.io/
  3. *
  4. * Copyright (c) SatoshiLabs
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <string.h>
  20. #include "common.h"
  21. #include "norcow.h"
  22. #include "storage.h"
  23. #include "pbkdf2.h"
  24. #include "sha2.h"
  25. #include "hmac.h"
  26. #include "rand.h"
  27. #include "memzero.h"
  28. #include "chacha20poly1305/rfc7539.h"
  29. #define LOW_MASK 0x55555555
  30. // The APP namespace which is reserved for storage related values.
  31. #define APP_STORAGE 0x00
  32. // Norcow storage key of the PIN entry log and PIN success log.
  33. #define PIN_LOGS_KEY ((APP_STORAGE << 8) | 0x01)
  34. // Norcow storage key of the combined salt, EDEK, ESAK and PIN verification code entry.
  35. #define EDEK_PVC_KEY ((APP_STORAGE << 8) | 0x02)
  36. // Norcow storage key of the PIN set flag.
  37. #define PIN_NOT_SET_KEY ((APP_STORAGE << 8) | 0x03)
  38. // Norcow storage key of the storage version.
  39. #define VERSION_KEY ((APP_STORAGE << 8) | 0x04)
  40. // Norcow storage key of the storage authentication tag.
  41. #define STORAGE_TAG_KEY ((APP_STORAGE << 8) | 0x05)
  42. // The PIN value corresponding to an empty PIN.
  43. #define PIN_EMPTY 1
  44. // Maximum number of failed unlock attempts.
  45. // NOTE: The PIN counter logic relies on this constant being less than or equal to 16.
  46. #define PIN_MAX_TRIES 16
  47. // The total number of iterations to use in PBKDF2.
  48. #define PIN_ITER_COUNT 20000
  49. // The number of seconds required to derive the KEK and KEIV.
  50. #define DERIVE_SECS 1
  51. // If the top bit of APP is set, then the value is not encrypted.
  52. #define FLAG_PUBLIC 0x80
  53. // If the top two bits of APP are set, then the value is not encrypted and it
  54. // can be written even when the storage is locked.
  55. #define FLAGS_WRITE 0xC0
  56. // The length of the guard key in words.
  57. #define GUARD_KEY_WORDS 1
  58. // The length of the PIN entry log or the PIN success log in words.
  59. #define PIN_LOG_WORDS 16
  60. // The length of a word in bytes.
  61. #define WORD_SIZE (sizeof(uint32_t))
  62. // The length of the hashed hardware salt in bytes.
  63. #define HARDWARE_SALT_SIZE SHA256_DIGEST_LENGTH
  64. // The length of the random salt in bytes.
  65. #define RANDOM_SALT_SIZE 4
  66. // The length of the data encryption key in bytes.
  67. #define DEK_SIZE 32
  68. // The length of the storage authentication key in bytes.
  69. #define SAK_SIZE 16
  70. // The combined length of the data encryption key and the storage authentication key in bytes.
  71. #define KEYS_SIZE (DEK_SIZE + SAK_SIZE)
  72. // The length of the PIN verification code in bytes.
  73. #define PVC_SIZE 8
  74. // The length of the storage authentication tag in bytes.
  75. #define STORAGE_TAG_SIZE 16
  76. // The length of the Poly1305 authentication tag in bytes.
  77. #define POLY1305_TAG_SIZE 16
  78. // The length of the ChaCha20 IV (aka nonce) in bytes as per RFC 7539.
  79. #define CHACHA20_IV_SIZE 12
  80. // The length of the ChaCha20 block in bytes.
  81. #define CHACHA20_BLOCK_SIZE 64
  82. // The length of the counter tail in words.
  83. #define COUNTER_TAIL_WORDS 2
  84. // Values used in the guard key integrity check.
  85. #define GUARD_KEY_MODULUS 6311
  86. #define GUARD_KEY_REMAINDER 15
  87. const char* const VERIFYING_PIN_MSG = "Verifying PIN";
  88. const char* const PROCESSING_MSG = "Processing";
  89. const char* const STARTING_MSG = "Starting up";
  90. static secbool initialized = secfalse;
  91. static secbool unlocked = secfalse;
  92. static PIN_UI_WAIT_CALLBACK ui_callback = NULL;
  93. static uint32_t ui_total = 0;
  94. static uint32_t ui_rem = 0;
  95. static const char *ui_message = NULL;
  96. static uint8_t cached_keys[KEYS_SIZE] = {0};
  97. static uint8_t *const cached_dek = cached_keys;
  98. static uint8_t *const cached_sak = cached_keys + DEK_SIZE;
  99. static uint8_t authentication_sum[SHA256_DIGEST_LENGTH] = {0};
  100. static uint8_t hardware_salt[HARDWARE_SALT_SIZE] = {0};
  101. static uint32_t norcow_active_version = 0;
  102. static const uint8_t TRUE_BYTE = 0x01;
  103. static const uint8_t FALSE_BYTE = 0x00;
  104. static void __handle_fault(const char *msg, const char *file, int line, const char *func);
  105. #define handle_fault(msg) (__handle_fault(msg, __FILE__, __LINE__, __func__))
  106. static secbool storage_upgrade(void);
  107. static secbool storage_set_encrypted(const uint16_t key, const void *val, const uint16_t len);
  108. static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len);
  109. static secbool secequal(const void* ptr1, const void* ptr2, size_t n) {
  110. const uint8_t* p1 = ptr1;
  111. const uint8_t* p2 = ptr2;
  112. uint8_t diff = 0;
  113. size_t i;
  114. for (i = 0; i < n; ++i) {
  115. diff |= *p1 ^ *p2;
  116. ++p1;
  117. ++p2;
  118. }
  119. // Check loop completion in case of a fault injection attack.
  120. if (i != n) {
  121. handle_fault("loop completion check");
  122. }
  123. return diff ? secfalse : sectrue;
  124. }
  125. static secbool secequal32(const uint32_t* ptr1, const uint32_t* ptr2, size_t n) {
  126. uint32_t diff = 0;
  127. size_t i;
  128. for (i = 0; i < n; ++i) {
  129. uint32_t mask = random32();
  130. diff |= (*ptr1 + mask - *ptr2) ^ mask;
  131. ++ptr1;
  132. ++ptr2;
  133. }
  134. // Check loop completion in case of a fault injection attack.
  135. if (i != n) {
  136. handle_fault("loop completion check");
  137. }
  138. return diff ? secfalse : sectrue;
  139. }
  140. static secbool is_protected(uint16_t key) {
  141. const uint8_t app = key >> 8;
  142. return ((app & FLAG_PUBLIC) == 0 && app != APP_STORAGE) ? sectrue : secfalse;
  143. }
  144. /*
  145. * Initialize the storage authentication tag for freshly wiped storage.
  146. */
  147. static secbool auth_init(void) {
  148. uint8_t tag[SHA256_DIGEST_LENGTH];
  149. memzero(authentication_sum, sizeof(authentication_sum));
  150. hmac_sha256(cached_sak, SAK_SIZE, authentication_sum, sizeof(authentication_sum), tag);
  151. return norcow_set(STORAGE_TAG_KEY, tag, STORAGE_TAG_SIZE);
  152. }
  153. /*
  154. * Update the storage authentication tag with the given key.
  155. */
  156. static secbool auth_update(uint16_t key) {
  157. if (sectrue != is_protected(key)) {
  158. return sectrue;
  159. }
  160. uint8_t tag[SHA256_DIGEST_LENGTH];
  161. hmac_sha256(cached_sak, SAK_SIZE, (uint8_t*)&key, sizeof(key), tag);
  162. for (uint32_t i = 0; i < SHA256_DIGEST_LENGTH; i++) {
  163. authentication_sum[i] ^= tag[i];
  164. }
  165. hmac_sha256(cached_sak, SAK_SIZE, authentication_sum, sizeof(authentication_sum), tag);
  166. return norcow_set(STORAGE_TAG_KEY, tag, STORAGE_TAG_SIZE);
  167. }
  168. /*
  169. * A secure version of norcow_set(), which updates the storage authentication tag.
  170. */
  171. static secbool auth_set(uint16_t key, const void *val, uint16_t len) {
  172. secbool found;
  173. secbool ret = norcow_set_ex(key, val, len, &found);
  174. if (sectrue == ret && secfalse == found) {
  175. ret = auth_update(key);
  176. if (sectrue != ret) {
  177. norcow_delete(key);
  178. }
  179. }
  180. return ret;
  181. }
  182. /*
  183. * A secure version of norcow_get(), which checks the storage authentication tag.
  184. */
  185. static secbool auth_get(uint16_t key, const void **val, uint16_t *len)
  186. {
  187. *val = NULL;
  188. *len = 0;
  189. uint32_t sum[SHA256_DIGEST_LENGTH/sizeof(uint32_t)] = {0};
  190. // Prepare inner and outer digest.
  191. uint32_t odig[SHA256_DIGEST_LENGTH / sizeof(uint32_t)];
  192. uint32_t idig[SHA256_DIGEST_LENGTH / sizeof(uint32_t)];
  193. hmac_sha256_prepare(cached_sak, SAK_SIZE, odig, idig);
  194. // Prepare SHA-256 message padding.
  195. uint32_t g[SHA256_BLOCK_LENGTH / sizeof(uint32_t)] = {0};
  196. uint32_t h[SHA256_BLOCK_LENGTH / sizeof(uint32_t)] = {0};
  197. g[15] = (SHA256_BLOCK_LENGTH + 2) * 8;
  198. h[15] = (SHA256_BLOCK_LENGTH + SHA256_DIGEST_LENGTH) * 8;
  199. h[8] = 0x80000000;
  200. uint32_t offset = 0;
  201. uint16_t k = 0;
  202. uint16_t l = 0;
  203. uint16_t tag_len = 0;
  204. uint16_t entry_count = 0; // Mitigation against fault injection.
  205. uint16_t other_count = 0; // Mitigation against fault injection.
  206. const void *v = NULL;
  207. const void *tag_val = NULL;
  208. while (sectrue == norcow_get_next(&offset, &k, &v, &l)) {
  209. ++entry_count;
  210. if (k == key) {
  211. *val = v;
  212. *len = l;
  213. } else {
  214. ++other_count;
  215. }
  216. if (sectrue != is_protected(k)) {
  217. if (k == STORAGE_TAG_KEY) {
  218. tag_val = v;
  219. tag_len = l;
  220. }
  221. continue;
  222. }
  223. g[0] = (((uint32_t)k & 0xff) << 24) | (((uint32_t)k & 0xff00) << 8) | 0x8000; // Add SHA message padding.
  224. sha256_Transform(idig, g, h);
  225. sha256_Transform(odig, h, h);
  226. for (uint32_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) {
  227. sum[i] ^= h[i];
  228. }
  229. }
  230. memcpy(h, sum, sizeof(sum));
  231. sha256_Transform(idig, h, h);
  232. sha256_Transform(odig, h, h);
  233. memzero(odig, sizeof(odig));
  234. memzero(idig, sizeof(idig));
  235. // Cache the authentication sum.
  236. for (size_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) {
  237. #if BYTE_ORDER == LITTLE_ENDIAN
  238. REVERSE32(sum[i], ((uint32_t*)authentication_sum)[i]);
  239. #else
  240. ((uint32_t*)authentication_sum)[i] = sum[i];
  241. #endif
  242. }
  243. // Check loop completion in case of a fault injection attack.
  244. if (secfalse != norcow_get_next(&offset, &k, &v, &l)) {
  245. handle_fault("loop completion check");
  246. }
  247. // Check storage authentication tag.
  248. #if BYTE_ORDER == LITTLE_ENDIAN
  249. for (size_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) {
  250. REVERSE32(h[i], h[i]);
  251. }
  252. #endif
  253. if (tag_val == NULL || tag_len != STORAGE_TAG_SIZE || sectrue != secequal(h, tag_val, STORAGE_TAG_SIZE)) {
  254. handle_fault("storage tag check");
  255. }
  256. if (*val == NULL) {
  257. // Check for fault injection.
  258. if (other_count != entry_count) {
  259. handle_fault("sanity check");
  260. }
  261. return secfalse;
  262. }
  263. return sectrue;
  264. }
  265. /*
  266. * Generates a delay of random length. Use this to protect sensitive code against fault injection.
  267. */
  268. static void wait_random(void)
  269. {
  270. #ifndef TREZOR_STORAGE_TEST
  271. int wait = random32() & 0xff;
  272. volatile int i = 0;
  273. volatile int j = wait;
  274. while (i < wait) {
  275. if (i + j != wait) {
  276. handle_fault("sanity check");
  277. }
  278. ++i;
  279. --j;
  280. }
  281. // Double-check loop completion.
  282. if (i != wait) {
  283. handle_fault("loop completion check");
  284. }
  285. #endif
  286. }
  287. static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA256_DIGEST_LENGTH], uint8_t keiv[SHA256_DIGEST_LENGTH])
  288. {
  289. #if BYTE_ORDER == BIG_ENDIAN
  290. REVERSE32(pin, pin);
  291. #endif
  292. uint8_t salt[HARDWARE_SALT_SIZE + RANDOM_SALT_SIZE];
  293. memcpy(salt, hardware_salt, HARDWARE_SALT_SIZE);
  294. memcpy(salt + HARDWARE_SALT_SIZE, random_salt, RANDOM_SALT_SIZE);
  295. uint32_t progress = (ui_total - ui_rem) * 1000 / ui_total;
  296. if (ui_callback && ui_message) {
  297. ui_callback(ui_rem, progress, ui_message);
  298. }
  299. PBKDF2_HMAC_SHA256_CTX ctx;
  300. pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 1);
  301. for (int i = 1; i <= 5; i++) {
  302. pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10);
  303. if (ui_callback && ui_message) {
  304. progress = ((ui_total - ui_rem) * 1000 + i * DERIVE_SECS * 100) / ui_total;
  305. ui_callback(ui_rem - i * DERIVE_SECS / 10, progress, ui_message);
  306. }
  307. }
  308. pbkdf2_hmac_sha256_Final(&ctx, kek);
  309. pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 2);
  310. for (int i = 6; i <= 10; i++) {
  311. pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10);
  312. if (ui_callback && ui_message) {
  313. progress = ((ui_total - ui_rem) * 1000 + i * DERIVE_SECS * 100) / ui_total;
  314. ui_callback(ui_rem - i * DERIVE_SECS / 10, progress, ui_message);
  315. }
  316. }
  317. pbkdf2_hmac_sha256_Final(&ctx, keiv);
  318. ui_rem -= DERIVE_SECS;
  319. memzero(&ctx, sizeof(PBKDF2_HMAC_SHA256_CTX));
  320. memzero(&pin, sizeof(pin));
  321. memzero(&salt, sizeof(salt));
  322. }
  323. static secbool set_pin(uint32_t pin)
  324. {
  325. uint8_t buffer[RANDOM_SALT_SIZE + KEYS_SIZE + POLY1305_TAG_SIZE];
  326. uint8_t *salt = buffer;
  327. uint8_t *ekeys = buffer + RANDOM_SALT_SIZE;
  328. uint8_t *pvc = buffer + RANDOM_SALT_SIZE + KEYS_SIZE;
  329. uint8_t kek[SHA256_DIGEST_LENGTH];
  330. uint8_t keiv[SHA256_DIGEST_LENGTH];
  331. chacha20poly1305_ctx ctx;
  332. random_buffer(salt, RANDOM_SALT_SIZE);
  333. derive_kek(pin, salt, kek, keiv);
  334. rfc7539_init(&ctx, kek, keiv);
  335. memzero(kek, sizeof(kek));
  336. memzero(keiv, sizeof(keiv));
  337. chacha20poly1305_encrypt(&ctx, cached_keys, ekeys, KEYS_SIZE);
  338. rfc7539_finish(&ctx, 0, KEYS_SIZE, pvc);
  339. memzero(&ctx, sizeof(ctx));
  340. secbool ret = norcow_set(EDEK_PVC_KEY, buffer, RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE);
  341. memzero(buffer, sizeof(buffer));
  342. if (ret == sectrue)
  343. {
  344. if (pin == PIN_EMPTY) {
  345. ret = norcow_set(PIN_NOT_SET_KEY, &TRUE_BYTE, sizeof(TRUE_BYTE));
  346. } else {
  347. ret = norcow_set(PIN_NOT_SET_KEY, &FALSE_BYTE, sizeof(FALSE_BYTE));
  348. }
  349. }
  350. memzero(&pin, sizeof(pin));
  351. return ret;
  352. }
  353. static secbool check_guard_key(const uint32_t guard_key)
  354. {
  355. if (guard_key % GUARD_KEY_MODULUS != GUARD_KEY_REMAINDER) {
  356. return secfalse;
  357. }
  358. // Check that each byte of (guard_key & 0xAAAAAAAA) has exactly two bits set.
  359. uint32_t count = (guard_key & 0x22222222) + ((guard_key >> 2) & 0x22222222);
  360. count = count + (count >> 4);
  361. if ((count & 0x0e0e0e0e) != 0x04040404) {
  362. return secfalse;
  363. }
  364. // Check that the guard_key does not contain a run of 5 (or more) zeros or ones.
  365. uint32_t zero_runs = ~guard_key;
  366. zero_runs = zero_runs & (zero_runs >> 2);
  367. zero_runs = zero_runs & (zero_runs >> 1);
  368. zero_runs = zero_runs & (zero_runs >> 1);
  369. uint32_t one_runs = guard_key;
  370. one_runs = one_runs & (one_runs >> 2);
  371. one_runs = one_runs & (one_runs >> 1);
  372. one_runs = one_runs & (one_runs >> 1);
  373. if ((one_runs != 0) || (zero_runs != 0)) {
  374. return secfalse;
  375. }
  376. return sectrue;
  377. }
  378. static uint32_t generate_guard_key(void)
  379. {
  380. uint32_t guard_key = 0;
  381. do {
  382. guard_key = random_uniform((UINT32_MAX/GUARD_KEY_MODULUS) + 1) * GUARD_KEY_MODULUS + GUARD_KEY_REMAINDER;
  383. } while (sectrue != check_guard_key(guard_key));
  384. return guard_key;
  385. }
  386. static secbool expand_guard_key(const uint32_t guard_key, uint32_t *guard_mask, uint32_t *guard)
  387. {
  388. if (sectrue != check_guard_key(guard_key)) {
  389. handle_fault("guard key check");
  390. return secfalse;
  391. }
  392. *guard_mask = ((guard_key & LOW_MASK) << 1) | ((~guard_key) & LOW_MASK);
  393. *guard = (((guard_key & LOW_MASK) << 1) & guard_key) | (((~guard_key) & LOW_MASK) & (guard_key >> 1));
  394. return sectrue;
  395. }
  396. static secbool pin_logs_init(uint32_t fails)
  397. {
  398. if (fails >= PIN_MAX_TRIES) {
  399. return secfalse;
  400. }
  401. // The format of the PIN_LOGS_KEY entry is:
  402. // guard_key (1 word), pin_success_log (PIN_LOG_WORDS), pin_entry_log (PIN_LOG_WORDS)
  403. uint32_t logs[GUARD_KEY_WORDS + 2*PIN_LOG_WORDS];
  404. logs[0] = generate_guard_key();
  405. uint32_t guard_mask;
  406. uint32_t guard;
  407. wait_random();
  408. if (sectrue != expand_guard_key(logs[0], &guard_mask, &guard)) {
  409. return secfalse;
  410. }
  411. uint32_t unused = guard | ~guard_mask;
  412. for (size_t i = 0; i < 2*PIN_LOG_WORDS; ++i) {
  413. logs[GUARD_KEY_WORDS + i] = unused;
  414. }
  415. // Set the first word of the PIN entry log to indicate the requested number of fails.
  416. logs[GUARD_KEY_WORDS + PIN_LOG_WORDS] = ((((uint32_t)0xFFFFFFFF) >> (2*fails)) & ~guard_mask) | guard;
  417. return norcow_set(PIN_LOGS_KEY, logs, sizeof(logs));
  418. }
  419. /*
  420. * Initializes the values of VERSION_KEY, EDEK_PVC_KEY, PIN_NOT_SET_KEY and PIN_LOGS_KEY using an empty PIN.
  421. * This function should be called to initialize freshly wiped storage.
  422. */
  423. static void init_wiped_storage(void)
  424. {
  425. if (sectrue != initialized) {
  426. // We cannot initialize the storage contents if the hardware_salt is not set.
  427. return;
  428. }
  429. random_buffer(cached_keys, sizeof(cached_keys));
  430. uint32_t version = NORCOW_VERSION;
  431. ensure(auth_init(), "set_storage_auth_tag failed");
  432. ensure(storage_set_encrypted(VERSION_KEY, &version, sizeof(version)), "set_storage_version failed");
  433. ensure(pin_logs_init(0), "init_pin_logs failed");
  434. ui_total = DERIVE_SECS;
  435. ui_rem = ui_total;
  436. ui_message = PROCESSING_MSG;
  437. ensure(set_pin(PIN_EMPTY), "init_pin failed");
  438. if (unlocked != sectrue) {
  439. memzero(cached_keys, sizeof(cached_keys));
  440. }
  441. }
  442. void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len)
  443. {
  444. initialized = secfalse;
  445. unlocked = secfalse;
  446. norcow_init(&norcow_active_version);
  447. initialized = sectrue;
  448. ui_callback = callback;
  449. sha256_Raw(salt, salt_len, hardware_salt);
  450. if (norcow_active_version < NORCOW_VERSION) {
  451. if (sectrue != storage_upgrade()) {
  452. storage_wipe();
  453. ensure(secfalse, "storage_upgrade failed");
  454. }
  455. }
  456. // If there is no EDEK, then generate a random DEK and SAK and store them.
  457. const void *val;
  458. uint16_t len;
  459. if (secfalse == norcow_get(EDEK_PVC_KEY, &val, &len)) {
  460. init_wiped_storage();
  461. }
  462. memzero(cached_keys, sizeof(cached_keys));
  463. }
  464. static secbool pin_fails_reset(void)
  465. {
  466. const void *logs = NULL;
  467. uint16_t len = 0;
  468. if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) {
  469. return secfalse;
  470. }
  471. uint32_t guard_mask;
  472. uint32_t guard;
  473. wait_random();
  474. if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) {
  475. return secfalse;
  476. }
  477. uint32_t unused = guard | ~guard_mask;
  478. const uint32_t *success_log = ((const uint32_t*)logs) + GUARD_KEY_WORDS;
  479. const uint32_t *entry_log = success_log + PIN_LOG_WORDS;
  480. for (size_t i = 0; i < PIN_LOG_WORDS; ++i) {
  481. if (entry_log[i] == unused) {
  482. return sectrue;
  483. }
  484. if (success_log[i] != guard) {
  485. if (sectrue != norcow_update_word(PIN_LOGS_KEY, sizeof(uint32_t)*(i + GUARD_KEY_WORDS), entry_log[i])) {
  486. return secfalse;
  487. }
  488. }
  489. }
  490. return pin_logs_init(0);
  491. }
  492. secbool storage_pin_fails_increase(void)
  493. {
  494. if (sectrue != initialized) {
  495. return secfalse;
  496. }
  497. const void *logs = NULL;
  498. uint16_t len = 0;
  499. wait_random();
  500. if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) {
  501. handle_fault("no PIN logs");
  502. return secfalse;
  503. }
  504. uint32_t guard_mask;
  505. uint32_t guard;
  506. wait_random();
  507. if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) {
  508. handle_fault("guard key expansion");
  509. return secfalse;
  510. }
  511. const uint32_t *entry_log = ((const uint32_t*)logs) + GUARD_KEY_WORDS + PIN_LOG_WORDS;
  512. for (size_t i = 0; i < PIN_LOG_WORDS; ++i) {
  513. wait_random();
  514. if ((entry_log[i] & guard_mask) != guard) {
  515. handle_fault("guard bits check");
  516. return secfalse;
  517. }
  518. if (entry_log[i] != guard) {
  519. wait_random();
  520. uint32_t word = entry_log[i] & ~guard_mask;
  521. word = ((word >> 1) | word) & LOW_MASK;
  522. word = (word >> 2) | (word >> 1);
  523. wait_random();
  524. if (sectrue != norcow_update_word(PIN_LOGS_KEY, sizeof(uint32_t)*(i + GUARD_KEY_WORDS + PIN_LOG_WORDS), (word & ~guard_mask) | guard)) {
  525. handle_fault("PIN logs update");
  526. return secfalse;
  527. }
  528. return sectrue;
  529. }
  530. }
  531. handle_fault("PIN log exhausted");
  532. return secfalse;
  533. }
  534. static uint32_t hamming_weight(uint32_t value)
  535. {
  536. value = value - ((value >> 1) & 0x55555555);
  537. value = (value & 0x33333333) + ((value >> 2) & 0x33333333);
  538. value = (value + (value >> 4)) & 0x0F0F0F0F;
  539. value = value + (value >> 8);
  540. value = value + (value >> 16);
  541. return value & 0x3F;
  542. }
  543. static secbool pin_get_fails(uint32_t *ctr)
  544. {
  545. *ctr = PIN_MAX_TRIES;
  546. const void *logs = NULL;
  547. uint16_t len = 0;
  548. wait_random();
  549. if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) {
  550. handle_fault("no PIN logs");
  551. return secfalse;
  552. }
  553. uint32_t guard_mask;
  554. uint32_t guard;
  555. wait_random();
  556. if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) {
  557. handle_fault("guard key expansion");
  558. return secfalse;
  559. }
  560. const uint32_t unused = guard | ~guard_mask;
  561. const uint32_t *success_log = ((const uint32_t*)logs) + GUARD_KEY_WORDS;
  562. const uint32_t *entry_log = success_log + PIN_LOG_WORDS;
  563. volatile int current = -1;
  564. volatile size_t i;
  565. for (i = 0; i < PIN_LOG_WORDS; ++i) {
  566. if ((entry_log[i] & guard_mask) != guard || (success_log[i] & guard_mask) != guard || (entry_log[i] & success_log[i]) != entry_log[i]) {
  567. handle_fault("PIN logs format check");
  568. return secfalse;
  569. }
  570. if (current == -1) {
  571. if (entry_log[i] != guard) {
  572. current = i;
  573. }
  574. } else {
  575. if (entry_log[i] != unused) {
  576. handle_fault("PIN entry log format check");
  577. return secfalse;
  578. }
  579. }
  580. }
  581. if (current < 0 || current >= PIN_LOG_WORDS || i != PIN_LOG_WORDS) {
  582. handle_fault("PIN log exhausted");
  583. return secfalse;
  584. }
  585. // Strip the guard bits from the current entry word and duplicate each data bit.
  586. wait_random();
  587. uint32_t word = entry_log[current] & ~guard_mask;
  588. word = ((word >> 1) | word ) & LOW_MASK;
  589. word = word | (word << 1);
  590. // Verify that the entry word has form 0*1*.
  591. if ((word & (word + 1)) != 0) {
  592. handle_fault("PIN entry log format check");
  593. return secfalse;
  594. }
  595. if (current == 0) {
  596. ++current;
  597. }
  598. // Count the number of set bits in the two current words of the success log.
  599. wait_random();
  600. *ctr = hamming_weight(success_log[current-1] ^ entry_log[current-1]) + hamming_weight(success_log[current] ^ entry_log[current]);
  601. return sectrue;
  602. }
  603. secbool storage_is_unlocked(void)
  604. {
  605. if (sectrue != initialized) {
  606. return secfalse;
  607. }
  608. return unlocked;
  609. }
  610. void storage_lock(void)
  611. {
  612. unlocked = secfalse;
  613. memzero(cached_keys, sizeof(cached_keys));
  614. memzero(authentication_sum, sizeof(authentication_sum));
  615. }
  616. static secbool decrypt_dek(const uint8_t *kek, const uint8_t *keiv)
  617. {
  618. const void *buffer = NULL;
  619. uint16_t len = 0;
  620. if (sectrue != initialized || sectrue != norcow_get(EDEK_PVC_KEY, &buffer, &len) || len != RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE) {
  621. handle_fault("no EDEK");
  622. return secfalse;
  623. }
  624. const uint8_t *ekeys = (const uint8_t*) buffer + RANDOM_SALT_SIZE;
  625. const uint32_t *pvc = (const uint32_t*) buffer + (RANDOM_SALT_SIZE + KEYS_SIZE)/sizeof(uint32_t);
  626. _Static_assert(((RANDOM_SALT_SIZE + KEYS_SIZE) & 3) == 0, "PVC unaligned");
  627. _Static_assert((PVC_SIZE & 3) == 0, "PVC size unaligned");
  628. uint8_t keys[KEYS_SIZE];
  629. uint8_t tag[POLY1305_TAG_SIZE] __attribute__((aligned(sizeof(uint32_t))));
  630. chacha20poly1305_ctx ctx;
  631. // Decrypt the data encryption key and the storage authentication key and check the PIN verification code.
  632. rfc7539_init(&ctx, kek, keiv);
  633. chacha20poly1305_decrypt(&ctx, ekeys, keys, KEYS_SIZE);
  634. rfc7539_finish(&ctx, 0, KEYS_SIZE, tag);
  635. memzero(&ctx, sizeof(ctx));
  636. wait_random();
  637. if (secequal32((const uint32_t*) tag, pvc, PVC_SIZE/sizeof(uint32_t)) != sectrue) {
  638. memzero(keys, sizeof(keys));
  639. memzero(tag, sizeof(tag));
  640. return secfalse;
  641. }
  642. memcpy(cached_keys, keys, sizeof(keys));
  643. memzero(keys, sizeof(keys));
  644. memzero(tag, sizeof(tag));
  645. // Check that the authenticated version number matches the norcow version.
  646. // NOTE: storage_get_encrypted() calls auth_get(), which initializes the authentication_sum.
  647. uint32_t version;
  648. if (sectrue != storage_get_encrypted(VERSION_KEY, &version, sizeof(version), &len) || len != sizeof(version) || version != norcow_active_version) {
  649. handle_fault("storage version check");
  650. return secfalse;
  651. }
  652. return sectrue;
  653. }
  654. static secbool unlock(uint32_t pin)
  655. {
  656. if (sectrue != initialized) {
  657. return secfalse;
  658. }
  659. // Get the pin failure counter
  660. uint32_t ctr;
  661. if (sectrue != pin_get_fails(&ctr)) {
  662. memzero(&pin, sizeof(pin));
  663. return secfalse;
  664. }
  665. // Wipe storage if too many failures
  666. wait_random();
  667. if (ctr >= PIN_MAX_TRIES) {
  668. storage_wipe();
  669. error_shutdown("Too many wrong PIN", "attempts. Storage has", "been wiped.", NULL);
  670. return secfalse;
  671. }
  672. // Sleep for 2^ctr - 1 seconds before checking the PIN.
  673. uint32_t wait = (1 << ctr) - 1;
  674. ui_total += wait;
  675. uint32_t progress = 0;
  676. for (ui_rem = ui_total; ui_rem > ui_total - wait; ui_rem--) {
  677. for (int i = 0; i < 10; i++) {
  678. if (ui_callback && ui_message) {
  679. if (ui_total > 1000000) { // precise enough
  680. progress = (ui_total - ui_rem) / (ui_total / 1000);
  681. } else {
  682. progress = ((ui_total - ui_rem) * 10 + i) * 100 / ui_total;
  683. }
  684. if (sectrue == ui_callback(ui_rem, progress, ui_message)) {
  685. return secfalse;
  686. }
  687. }
  688. hal_delay(100);
  689. }
  690. }
  691. // Read the random salt from EDEK_PVC_KEY and use it to derive the KEK and KEIV from the PIN.
  692. const void *salt = NULL;
  693. uint16_t len = 0;
  694. if (sectrue != initialized || sectrue != norcow_get(EDEK_PVC_KEY, &salt, &len) || len != RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE) {
  695. memzero(&pin, sizeof(pin));
  696. handle_fault("no EDEK");
  697. return secfalse;
  698. }
  699. uint8_t kek[SHA256_DIGEST_LENGTH];
  700. uint8_t keiv[SHA256_DIGEST_LENGTH];
  701. derive_kek(pin, (const uint8_t*) salt, kek, keiv);
  702. memzero(&pin, sizeof(pin));
  703. // First, we increase PIN fail counter in storage, even before checking the
  704. // PIN. If the PIN is correct, we reset the counter afterwards. If not, we
  705. // check if this is the last allowed attempt.
  706. if (sectrue != storage_pin_fails_increase()) {
  707. return secfalse;
  708. }
  709. // Check that the PIN fail counter was incremented.
  710. uint32_t ctr_ck;
  711. if (sectrue != pin_get_fails(&ctr_ck) || ctr + 1 != ctr_ck) {
  712. handle_fault("PIN counter increment");
  713. return secfalse;
  714. }
  715. // Check that the PIN was correct.
  716. if (sectrue != decrypt_dek(kek, keiv)) {
  717. // Wipe storage if too many failures
  718. wait_random();
  719. if (ctr + 1 >= PIN_MAX_TRIES) {
  720. storage_wipe();
  721. error_shutdown("Too many wrong PIN", "attempts. Storage has", "been wiped.", NULL);
  722. }
  723. return secfalse;
  724. }
  725. memzero(kek, sizeof(kek));
  726. memzero(keiv, sizeof(keiv));
  727. unlocked = sectrue;
  728. // Finally set the counter to 0 to indicate success.
  729. return pin_fails_reset();
  730. }
  731. secbool storage_unlock(uint32_t pin)
  732. {
  733. ui_total = DERIVE_SECS;
  734. ui_rem = ui_total;
  735. if (pin == PIN_EMPTY) {
  736. if (ui_message == NULL) {
  737. ui_message = STARTING_MSG;
  738. } else {
  739. ui_message = PROCESSING_MSG;
  740. }
  741. } else {
  742. ui_message = VERIFYING_PIN_MSG;
  743. }
  744. return unlock(pin);
  745. }
  746. /*
  747. * Finds the encrypted data stored under key and writes its length to len.
  748. * If val_dest is not NULL and max_len >= len, then the data is decrypted
  749. * to val_dest using cached_dek as the decryption key.
  750. */
  751. static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len)
  752. {
  753. const void *val_stored = NULL;
  754. if (sectrue != auth_get(key, &val_stored, len)) {
  755. return secfalse;
  756. }
  757. if (*len < CHACHA20_IV_SIZE + POLY1305_TAG_SIZE) {
  758. handle_fault("ciphertext length check");
  759. return secfalse;
  760. }
  761. *len -= CHACHA20_IV_SIZE + POLY1305_TAG_SIZE;
  762. if (val_dest == NULL) {
  763. return sectrue;
  764. }
  765. if (*len > max_len) {
  766. return secfalse;
  767. }
  768. const uint8_t *iv = (const uint8_t*) val_stored;
  769. const uint8_t *tag_stored = (const uint8_t*) val_stored + CHACHA20_IV_SIZE;
  770. const uint8_t *ciphertext = (const uint8_t*) val_stored + CHACHA20_IV_SIZE + POLY1305_TAG_SIZE;
  771. uint8_t tag_computed[POLY1305_TAG_SIZE];
  772. chacha20poly1305_ctx ctx;
  773. rfc7539_init(&ctx, cached_dek, iv);
  774. rfc7539_auth(&ctx, (const uint8_t*)&key, sizeof(key));
  775. chacha20poly1305_decrypt(&ctx, ciphertext, (uint8_t*) val_dest, *len);
  776. rfc7539_finish(&ctx, sizeof(key), *len, tag_computed);
  777. memzero(&ctx, sizeof(ctx));
  778. // Verify authentication tag.
  779. if (secequal(tag_computed, tag_stored, POLY1305_TAG_SIZE) != sectrue) {
  780. memzero(val_dest, max_len);
  781. memzero(tag_computed, sizeof(tag_computed));
  782. handle_fault("authentication tag check");
  783. return secfalse;
  784. }
  785. memzero(tag_computed, sizeof(tag_computed));
  786. return sectrue;
  787. }
  788. /*
  789. * Finds the data stored under key and writes its length to len. If val_dest is
  790. * not NULL and max_len >= len, then the data is copied to val_dest.
  791. */
  792. secbool storage_get(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len)
  793. {
  794. const uint8_t app = key >> 8;
  795. // APP == 0 is reserved for PIN related values
  796. if (sectrue != initialized || app == APP_STORAGE) {
  797. return secfalse;
  798. }
  799. // If the top bit of APP is set, then the value is not encrypted and can be read from a locked device.
  800. secbool ret = secfalse;
  801. if ((app & FLAG_PUBLIC) != 0) {
  802. const void *val_stored = NULL;
  803. if (sectrue != norcow_get(key, &val_stored, len)) {
  804. return secfalse;
  805. }
  806. if (val_dest == NULL) {
  807. return sectrue;
  808. }
  809. if (*len > max_len) {
  810. return secfalse;
  811. }
  812. memcpy(val_dest, val_stored, *len);
  813. ret = sectrue;
  814. } else {
  815. if (sectrue != unlocked) {
  816. return secfalse;
  817. }
  818. ret = storage_get_encrypted(key, val_dest, max_len, len);
  819. }
  820. return ret;
  821. }
  822. /*
  823. * Encrypts the data at val using cached_dek as the encryption key and stores the ciphertext under key.
  824. */
  825. static secbool storage_set_encrypted(const uint16_t key, const void *val, const uint16_t len)
  826. {
  827. if (len > UINT16_MAX - CHACHA20_IV_SIZE - POLY1305_TAG_SIZE) {
  828. return secfalse;
  829. }
  830. // Preallocate space on the flash storage.
  831. if (sectrue != auth_set(key, NULL, CHACHA20_IV_SIZE + POLY1305_TAG_SIZE + len)) {
  832. return secfalse;
  833. }
  834. // Write the IV to the flash.
  835. uint8_t buffer[CHACHA20_BLOCK_SIZE];
  836. random_buffer(buffer, CHACHA20_IV_SIZE);
  837. uint16_t offset = 0;
  838. if (sectrue != norcow_update_bytes(key, offset, buffer, CHACHA20_IV_SIZE)) {
  839. return secfalse;
  840. }
  841. offset += CHACHA20_IV_SIZE + POLY1305_TAG_SIZE;
  842. // Encrypt all blocks except for the last one.
  843. chacha20poly1305_ctx ctx;
  844. rfc7539_init(&ctx, cached_dek, buffer);
  845. rfc7539_auth(&ctx, (const uint8_t*)&key, sizeof(key));
  846. size_t i;
  847. for (i = 0; i + CHACHA20_BLOCK_SIZE < len; i += CHACHA20_BLOCK_SIZE, offset += CHACHA20_BLOCK_SIZE) {
  848. chacha20poly1305_encrypt(&ctx, ((const uint8_t*) val) + i, buffer, CHACHA20_BLOCK_SIZE);
  849. if (sectrue != norcow_update_bytes(key, offset, buffer, CHACHA20_BLOCK_SIZE)) {
  850. memzero(&ctx, sizeof(ctx));
  851. memzero(buffer, sizeof(buffer));
  852. return secfalse;
  853. }
  854. }
  855. // Encrypt final block and compute message authentication tag.
  856. chacha20poly1305_encrypt(&ctx, ((const uint8_t*) val) + i, buffer, len - i);
  857. secbool ret = norcow_update_bytes(key, offset, buffer, len - i);
  858. if (sectrue == ret) {
  859. rfc7539_finish(&ctx, sizeof(key), len, buffer);
  860. ret = norcow_update_bytes(key, CHACHA20_IV_SIZE, buffer, POLY1305_TAG_SIZE);
  861. }
  862. memzero(&ctx, sizeof(ctx));
  863. memzero(buffer, sizeof(buffer));
  864. return ret;
  865. }
  866. secbool storage_set(const uint16_t key, const void *val, const uint16_t len)
  867. {
  868. const uint8_t app = key >> 8;
  869. // APP == 0 is reserved for PIN related values
  870. if (sectrue != initialized || app == APP_STORAGE) {
  871. return secfalse;
  872. }
  873. if (sectrue != unlocked && (app & FLAGS_WRITE) != FLAGS_WRITE) {
  874. return secfalse;
  875. }
  876. secbool ret = secfalse;
  877. if ((app & FLAG_PUBLIC) != 0) {
  878. ret = norcow_set(key, val, len);
  879. } else {
  880. ret = storage_set_encrypted(key, val, len);
  881. }
  882. return ret;
  883. }
  884. secbool storage_delete(const uint16_t key)
  885. {
  886. const uint8_t app = key >> 8;
  887. // APP == 0 is reserved for storage related values
  888. if (sectrue != initialized || app == APP_STORAGE) {
  889. return secfalse;
  890. }
  891. if (sectrue != unlocked && (app & FLAGS_WRITE) != FLAGS_WRITE) {
  892. return secfalse;
  893. }
  894. secbool ret = norcow_delete(key);
  895. if (sectrue == ret) {
  896. ret = auth_update(key);
  897. }
  898. return ret;
  899. }
  900. secbool storage_set_counter(const uint16_t key, const uint32_t count)
  901. {
  902. const uint8_t app = key >> 8;
  903. if ((app & FLAG_PUBLIC) == 0) {
  904. return secfalse;
  905. }
  906. // The count is stored as a 32-bit integer followed by a tail of "1" bits,
  907. // which is used as a tally.
  908. uint32_t value[1 + COUNTER_TAIL_WORDS];
  909. memset(value, 0xff, sizeof(value));
  910. value[0] = count;
  911. return storage_set(key, value, sizeof(value));
  912. }
  913. secbool storage_next_counter(const uint16_t key, uint32_t *count)
  914. {
  915. const uint8_t app = key >> 8;
  916. // APP == 0 is reserved for PIN related values
  917. if (sectrue != initialized || app == APP_STORAGE || (app & FLAG_PUBLIC) == 0) {
  918. return secfalse;
  919. }
  920. if (sectrue != unlocked && (app & FLAGS_WRITE) != FLAGS_WRITE) {
  921. return secfalse;
  922. }
  923. uint16_t len = 0;
  924. const uint32_t *val_stored = NULL;
  925. if (sectrue != norcow_get(key, (const void**)&val_stored, &len)) {
  926. *count = 0;
  927. return storage_set_counter(key, 0);
  928. }
  929. if (len < sizeof(uint32_t) || len % sizeof(uint32_t) != 0) {
  930. return secfalse;
  931. }
  932. uint16_t len_words = len / sizeof(uint32_t);
  933. uint16_t i = 1;
  934. while (i < len_words && val_stored[i] == 0) {
  935. ++i;
  936. }
  937. *count = val_stored[0] + 1 + 32 * (i - 1);
  938. if (i < len_words) {
  939. *count += hamming_weight(~val_stored[i]);
  940. return norcow_update_word(key, sizeof(uint32_t) * i, val_stored[i] >> 1);
  941. } else {
  942. return storage_set_counter(key, *count);
  943. }
  944. }
  945. secbool storage_has_pin(void)
  946. {
  947. if (sectrue != initialized) {
  948. return secfalse;
  949. }
  950. const void *val = NULL;
  951. uint16_t len;
  952. if (sectrue != norcow_get(PIN_NOT_SET_KEY, &val, &len) || (len > 0 && *(uint8_t*)val != FALSE_BYTE)) {
  953. return secfalse;
  954. }
  955. return sectrue;
  956. }
  957. uint32_t storage_get_pin_rem(void)
  958. {
  959. if (sectrue != initialized) {
  960. return 0;
  961. }
  962. uint32_t ctr = 0;
  963. if (sectrue != pin_get_fails(&ctr)) {
  964. return 0;
  965. }
  966. return PIN_MAX_TRIES - ctr;
  967. }
  968. secbool storage_change_pin(uint32_t oldpin, uint32_t newpin)
  969. {
  970. if (sectrue != initialized) {
  971. return secfalse;
  972. }
  973. ui_total = 2 * DERIVE_SECS;
  974. ui_rem = ui_total;
  975. ui_message = (oldpin != PIN_EMPTY && newpin == PIN_EMPTY) ? VERIFYING_PIN_MSG : PROCESSING_MSG;
  976. if (sectrue != unlock(oldpin)) {
  977. return secfalse;
  978. }
  979. secbool ret = set_pin(newpin);
  980. memzero(&oldpin, sizeof(oldpin));
  981. memzero(&newpin, sizeof(newpin));
  982. return ret;
  983. }
  984. void storage_wipe(void)
  985. {
  986. norcow_wipe();
  987. norcow_active_version = NORCOW_VERSION;
  988. memzero(authentication_sum, sizeof(authentication_sum));
  989. memzero(cached_keys, sizeof(cached_keys));
  990. init_wiped_storage();
  991. }
  992. static void __handle_fault(const char *msg, const char *file, int line, const char *func)
  993. {
  994. static secbool in_progress = secfalse;
  995. // If fault handling is already in progress, then we are probably facing a fault injection attack, so wipe.
  996. if (secfalse != in_progress) {
  997. storage_wipe();
  998. __fatal_error("Fault detected", msg, file, line, func);
  999. }
  1000. // We use the PIN fail counter as a fault counter. Increment the counter, check that it was incremented and halt.
  1001. in_progress = sectrue;
  1002. uint32_t ctr;
  1003. if (sectrue != pin_get_fails(&ctr)) {
  1004. storage_wipe();
  1005. __fatal_error("Fault detected", msg, file, line, func);
  1006. }
  1007. if (sectrue != storage_pin_fails_increase()) {
  1008. storage_wipe();
  1009. __fatal_error("Fault detected", msg, file, line, func);
  1010. }
  1011. uint32_t ctr_new;
  1012. if (sectrue != pin_get_fails(&ctr_new) || ctr + 1 != ctr_new) {
  1013. storage_wipe();
  1014. }
  1015. __fatal_error("Fault detected", msg, file, line, func);
  1016. }
  1017. /*
  1018. * Reads the PIN fail counter in version 0 format. Returns the current number of failed PIN entries.
  1019. */
  1020. static secbool v0_pin_get_fails(uint32_t *ctr)
  1021. {
  1022. const uint16_t V0_PIN_FAIL_KEY = 0x0001;
  1023. // The PIN_FAIL_KEY points to an area of words, initialized to
  1024. // 0xffffffff (meaning no PIN failures). The first non-zero word
  1025. // in this area is the current PIN failure counter. If PIN_FAIL_KEY
  1026. // has no configuration or is empty, the PIN failure counter is 0.
  1027. // We rely on the fact that flash allows to clear bits and we clear one
  1028. // bit to indicate PIN failure. On success, the word is set to 0,
  1029. // indicating that the next word is the PIN failure counter.
  1030. // Find the current pin failure counter
  1031. const void *val = NULL;
  1032. uint16_t len = 0;
  1033. if (secfalse != norcow_get(V0_PIN_FAIL_KEY, &val, &len)) {
  1034. for (unsigned int i = 0; i < len / sizeof(uint32_t); i++) {
  1035. uint32_t word = ((const uint32_t*)val)[i];
  1036. if (word != 0) {
  1037. *ctr = hamming_weight(~word);
  1038. return sectrue;
  1039. }
  1040. }
  1041. }
  1042. // No PIN failures
  1043. *ctr = 0;
  1044. return sectrue;
  1045. }
  1046. static secbool storage_upgrade(void)
  1047. {
  1048. const uint16_t V0_PIN_KEY = 0x0000;
  1049. const uint16_t V0_PIN_FAIL_KEY = 0x0001;
  1050. uint16_t key = 0;
  1051. uint16_t len = 0;
  1052. const void *val = NULL;
  1053. if (norcow_active_version == 0) {
  1054. random_buffer(cached_keys, sizeof(cached_keys));
  1055. // Initialize the storage authentication tag.
  1056. auth_init();
  1057. // Set the new storage version number.
  1058. uint32_t version = NORCOW_VERSION;
  1059. if (sectrue != storage_set_encrypted(VERSION_KEY, &version, sizeof(version))) {
  1060. return secfalse;
  1061. }
  1062. // Set EDEK_PVC_KEY and PIN_NOT_SET_KEY.
  1063. ui_total = DERIVE_SECS;
  1064. ui_rem = ui_total;
  1065. ui_message = PROCESSING_MSG;
  1066. if (sectrue == norcow_get(V0_PIN_KEY, &val, &len)) {
  1067. set_pin(*(const uint32_t*)val);
  1068. } else {
  1069. set_pin(PIN_EMPTY);
  1070. }
  1071. // Convert PIN failure counter.
  1072. uint32_t fails = 0;
  1073. v0_pin_get_fails(&fails);
  1074. pin_logs_init(fails);
  1075. // Copy the remaining entries (encrypting the protected ones).
  1076. uint32_t offset = 0;
  1077. while (sectrue == norcow_get_next(&offset, &key, &val, &len)) {
  1078. if (key == V0_PIN_KEY || key == V0_PIN_FAIL_KEY) {
  1079. continue;
  1080. }
  1081. secbool ret;
  1082. if (((key >> 8) & FLAG_PUBLIC) != 0) {
  1083. ret = norcow_set(key, val, len);
  1084. } else {
  1085. ret = storage_set_encrypted(key, val, len);
  1086. }
  1087. if (sectrue != ret) {
  1088. return secfalse;
  1089. }
  1090. }
  1091. unlocked = secfalse;
  1092. memzero(cached_keys, sizeof(cached_keys));
  1093. } else {
  1094. return secfalse;
  1095. }
  1096. norcow_active_version = NORCOW_VERSION;
  1097. return norcow_upgrade_finish();
  1098. }