[PATCH] MPI helper of comparison, Least Leak Intended

NIIBE Yutaka gniibe at fsij.org
Wed Feb 12 01:21:15 CET 2025


Hello, Jussi,

Thank you for looking into the MPI helper of comparison.  Thanks a lot
to Jacob Bachmeyer, for joining discussion and give us insights.  Thank
you to Alicja Kario, too.

Jussi Kivilinna <jussi.kivilinna at iki.fi> wrote:
>    int
>    _gcry_mpih_cmp_lli (mpi_ptr_t up, mpi_ptr_t vp, mpi_size_t size)
>    {
>      mpi_size_t i;
>      mpi_limb_t res_gt = 0;
>      mpi_limb_t res_lt = 0;
>
>      for (i = 0; i < size ; i++)
>        {
>          mpi_limb_t gt, lt, eq, neq;
>          gt = mpih_ct_limb_greater_than (up[i], vp[i]);
>          lt = mpih_ct_limb_less_than (up[i], vp[i]);
>          neq = ct_limb_gen_mask(gt | lt);
>          eq = ct_limb_gen_inv_mask(gt | lt);
>          res_gt = (eq & res_gt) | (neq & gt);
>          res_lt = (eq & res_lt) | (neq & lt);
>        }
>
>      return (int)(res_gt - res_lt); /* return 0 if U==V, 1 if U>V, -1 if U<V */
>    }

Please apply and push this version, because it's the way the function
name suggests (returning -1, 0, 1).

If we will see any problem (about possible EM leakage or whatever), then
let us consider again in future.

> If returned value (0 vs 1 vs -1) could cause EM leakage, last line of function could be changed to something like:
>
>    return (int)(res_gt | (res_lt << 1)); /* return 0 if U==V, 1 if U>V, 2 if U<V */
>
> Or if having sign-bit set is important but we want to avoid "set all bits to ones" case, then only set sign-bit for "U<V":
>
>    return (int)(res_gt | (res_lt << (sizeof(int) * CHAR_BIT - 1))); /* return 0 if U==V, 1 if U>V, INT_MIN if U<V */

The current use of _gcry_mpih_cmp_ui is only at one place.  That is,
catching a wrong use case (where no inverse exists) in the function
mpih_invm_odd (libgcrypt/mpi/mpi-inv.c).  So, one of these changes would
be possible (in future, if needed).  But in such a case, I'd prefer
change of the function name (not cmp_ui, which suggests -1, 0, 1) so
that keeping least surprise.
-- 
a Japanese (Zen-Buddhist, so to say) who empbraces imperfection.



More information about the Gcrypt-devel mailing list