1
0
mirror of https://git.tartarus.org/simon/putty.git synced 2025-07-02 03:52:49 -05:00

Replace random_byte() with random_read().

This is in preparation for a PRNG revamp which will want to have a
well defined boundary for any given request-for-randomness, so that it
can destroy the evidence afterwards. So no more looping round calling
random_byte() and then stopping when we feel like it: now you say up
front how many random bytes you want, and call random_read() which
gives you that many in one go.

Most of the call sites that had to be fixed are fairly mechanical, and
quite a few ended up more concise afterwards. A few became more
cumbersome, such as mp_random_bits, in which the new API doesn't let
me load the random bytes directly into the target integer without
triggering undefined behaviour, so instead I have to allocate a
separate temporary buffer.

The _most_ interesting call site was in the PKCS#1 v1.5 padding code
in sshrsa.c (used in SSH-1), in which you need a stream of _nonzero_
random bytes. The previous code just looped on random_byte, retrying
if it got a zero. Now I'm doing a much more interesting thing with an
mpint, essentially scaling a binary fraction repeatedly to extract a
number in the range [0,255) and then adding 1 to it.
This commit is contained in:
Simon Tatham
2019-01-22 19:43:27 +00:00
parent 76aa3f6f7a
commit 628e794832
21 changed files with 108 additions and 101 deletions

13
mpint.h
View File

@ -364,9 +364,9 @@ mp_int *mp_rshift_fixed(mp_int *x, size_t shift);
/*
* Generate a random mp_int.
*
* The _function_ definitions here will expect to be given a gen_byte
* The _function_ definitions here will expect to be given a gen_data
* function that provides random data. Normally you'd use this using
* random_byte() from random.c, and the macro wrappers automate that.
* random_read() from random.c, and the macro wrappers automate that.
*
* (This is a bit of a dodge to avoid mpint.c having a link-time
* dependency on random.c, so that programs can link against one but
@ -376,10 +376,11 @@ mp_int *mp_rshift_fixed(mp_int *x, size_t shift);
* mp_random_bits[_fn] returns an integer 0 <= n < 2^bits.
* mp_random_in_range[_fn](lo,hi) returns an integer lo <= n < hi.
*/
mp_int *mp_random_bits_fn(size_t bits, int (*gen_byte)(void));
typedef void (*random_read_fn_t)(void *, size_t);
mp_int *mp_random_bits_fn(size_t bits, random_read_fn_t randfn);
mp_int *mp_random_in_range_fn(
mp_int *lo_inclusive, mp_int *hi_exclusive, int (*gen_byte)(void));
#define mp_random_bits(bits) mp_random_bits_fn(bits, random_byte)
#define mp_random_in_range(lo, hi) mp_random_in_range_fn(lo, hi, random_byte)
mp_int *lo_inclusive, mp_int *hi_exclusive, random_read_fn_t randfn);
#define mp_random_bits(bits) mp_random_bits_fn(bits, random_read)
#define mp_random_in_range(lo, hi) mp_random_in_range_fn(lo, hi, random_read)
#endif /* PUTTY_MPINT_H */