From 8d5c06102b08949cf796035e1ca27474d43c26a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Vejpustek?= Date: Fri, 6 Dec 2024 12:37:44 +0100 Subject: [PATCH] fix(crypto): make ge25519_cmove_stride4b constant time --- .../ed25519-donna/ed25519-donna-impl-base.c | 26 +++++++++++++------ shell.nix | 4 +-- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/crypto/ed25519-donna/ed25519-donna-impl-base.c b/crypto/ed25519-donna/ed25519-donna-impl-base.c index b6e435bd2cf..f8a5abba6c6 100644 --- a/crypto/ed25519-donna/ed25519-donna-impl-base.c +++ b/crypto/ed25519-donna/ed25519-donna-impl-base.c @@ -397,10 +397,15 @@ static void ge25519_cmove_stride4(long * r, long * p, long * pos, long * n, int y1 = p[1]; y2 = p[2]; y3 = p[3]; - x0 = flag ? y0 : x0; - x1 = flag ? y1 : x1; - x2 = flag ? y2 : x2; - x3 = flag ? y3 : x3; + + const long mask_y = -flag; + const long mask_x = ~mask_y; + + // x = flag ? y : x + x0 = (y0 & mask_y) | (x0 & mask_x); + x1 = (y1 & mask_y) | (x1 & mask_x); + x2 = (y2 & mask_y) | (x2 & mask_x); + x3 = (y3 & mask_y) | (x3 & mask_x); } r[0] = x0; r[1] = x1; @@ -417,10 +422,15 @@ static void ge25519_cmove_stride4b(long * r, long * p, long * pos, long * n, int y1 = p[1]; y2 = p[2]; y3 = p[3]; - x0 = flag ? y0 : x0; - x1 = flag ? y1 : x1; - x2 = flag ? y2 : x2; - x3 = flag ? y3 : x3; + + const long mask_y = -flag; + const long mask_x = ~mask_y; + + // x = flag ? y : x + x0 = (y0 & mask_y) | (x0 & mask_x); + x1 = (y1 & mask_y) | (x1 & mask_x); + x2 = (y2 & mask_y) | (x2 & mask_x); + x3 = (y3 & mask_y) | (x3 & mask_x); } r[0] = x0; r[1] = x1; diff --git a/shell.nix b/shell.nix index 05d7f1bda76..fc9bffc28f3 100644 --- a/shell.nix +++ b/shell.nix @@ -95,9 +95,7 @@ stdenvNoCC.mkDerivation ({ editorconfig-checker gcc-arm-embedded # GCC <14 seems to have broken varargs handling on arm64-darwin which makes micropython crash. - # GCC 14 causes crypto tests to fail in CI due to emitting non-constant-time instructions, - # and it's probably a good idea to keep it the same version as gcc-arm-embedded anyway - # https://github.com/trezor/trezor-firmware/issues/4393 + # We want to keep the version of gcc the same as the version of gcc-arm-embedded on other platforms. (if stdenv.isDarwin then gcc14 else gcc12) git gitAndTools.git-subrepo