X448 clamping uses dsize-relative offset (55 + bsize - dsize), which goes out of bounds when dsize < 56. This can corrupt memory when a user supplies an X448 private key shorter than 56 bytes. Use fixed X448_KEY_BYTES (56) instead. Set d->dsize = d->bsize after clamping to ensure repeated calls with the same key skip the byte-swap in crypto_bin_to_hpre_bin, which would otherwise corrupt the clamped data layout. Fixes: e9f59a4c5805 ("wd/sm2:Add sm2 algorithms") Signed-off-by: Weili Qian <qianweili@huawei.com> --- drv/hisi_hpre.c | 14 ++++++-------- include/drv/wd_ecc_drv.h | 2 ++ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/drv/hisi_hpre.c b/drv/hisi_hpre.c index 6d61fa4..a4523ab 100644 --- a/drv/hisi_hpre.c +++ b/drv/hisi_hpre.c @@ -1213,7 +1213,7 @@ static int ecc_prepare_prikey(struct wd_ecc_key *key, void **data, int id) struct wd_dtb *b = NULL; struct wd_dtb *n = NULL; struct wd_dtb *d = NULL; - __u32 bsize, dsize; + __u32 bsize; char *dat; int ret; @@ -1227,10 +1227,6 @@ static int ecc_prepare_prikey(struct wd_ecc_key *key, void **data, int id) if (ret) return ret; - /* X448 will do specific offset */ - if (id != WD_X448) - d->dsize = d->bsize; - /* * This is a pretreatment of X25519/X448, as described in RFC 7748: * For X25519, in order to decode 32 random bytes as an integer @@ -1245,16 +1241,18 @@ static int ecc_prepare_prikey(struct wd_ecc_key *key, void **data, int id) */ dat = d->data; bsize = d->bsize; - dsize = d->dsize; if (id == WD_X25519) { dat[31] &= 248; dat[0] &= 127; dat[0] |= 64; } else if (id == WD_X448) { - dat[55 + bsize - dsize] &= 252; - dat[0 + bsize - dsize] |= 128; + dat[bsize - 1] &= 252; + dat[bsize - X448_KEY_BYTES] |= 128; } + /* Ensure dsize equals bsize to skip byte-swap in crypto_bin_to_hpre_bin */ + d->dsize = d->bsize; + if (!big_than_one(dat, bsize)) { WD_ERR("failed to prepare ecc prikey: d <= 1!\n"); return -WD_EINVAL; diff --git a/include/drv/wd_ecc_drv.h b/include/drv/wd_ecc_drv.h index 585811e..fdc34f0 100644 --- a/include/drv/wd_ecc_drv.h +++ b/include/drv/wd_ecc_drv.h @@ -45,6 +45,8 @@ extern "C" { #define WD_X448 0x2 #define WD_SM2P256 0x3 +#define X448_KEY_BYTES 56 + /* ECC message format */ struct wd_ecc_msg { struct wd_ecc_req req; -- 2.43.0