From 7d31bdcf78457bf5dd4a60f2e10774e06ae9ded1 Mon Sep 17 00:00:00 2001 From: Jan Pochyla Date: Tue, 26 Sep 2017 17:26:34 +0200 Subject: [PATCH] modtrezorutils: add consteq --- embed/extmod/modtrezorutils/modtrezorutils.c | 29 ++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/embed/extmod/modtrezorutils/modtrezorutils.c b/embed/extmod/modtrezorutils/modtrezorutils.c index bcefe70c4..6ff7036c6 100644 --- a/embed/extmod/modtrezorutils/modtrezorutils.c +++ b/embed/extmod/modtrezorutils/modtrezorutils.c @@ -12,6 +12,34 @@ #include #include "common.h" +/// def consteq(sec: bytes, pub: bytes) -> bool: +/// ''' +/// Compares the private information in `sec` with public, user-provided +/// information in `pub`. Runs in constant time, corresponding to a length +/// of `pub`. Can access memory behind valid length of `sec`, caller is +/// expected to avoid any invalid memory access. +/// ''' +STATIC mp_obj_t mod_trezorutils_consteq(mp_obj_t sec, mp_obj_t pub) { + mp_buffer_info_t secbuf; + mp_get_buffer_raise(sec, &secbuf, MP_BUFFER_READ); + mp_buffer_info_t pubbuf; + mp_get_buffer_raise(pub, &pubbuf, MP_BUFFER_READ); + + size_t diff = secbuf.len - pubbuf.len; + for (size_t i = 0; i < pubbuf.len; i++) { + const uint8_t *s = (uint8_t *)secbuf.buf; + const uint8_t *p = (uint8_t *)pubbuf.buf; + diff |= s[i] - p[i]; + } + + if (diff == 0) { + return mp_const_true; + } else { + return mp_const_false; + } +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorutils_consteq_obj, mod_trezorutils_consteq); + /// def memcpy(dst: bytearray, dst_ofs: int, /// src: bytearray, src_ofs: int, /// n: int) -> int: @@ -68,6 +96,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorutils_halt_obj, 0, 1, mod_t STATIC const mp_rom_map_elem_t mp_module_trezorutils_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_trezorutils) }, + { MP_ROM_QSTR(MP_QSTR_consteq), MP_ROM_PTR(&mod_trezorutils_consteq_obj) }, { MP_ROM_QSTR(MP_QSTR_memcpy), MP_ROM_PTR(&mod_trezorutils_memcpy_obj) }, { MP_ROM_QSTR(MP_QSTR_halt), MP_ROM_PTR(&mod_trezorutils_halt_obj) }, };