aboutsummaryrefslogtreecommitdiff
path: root/src/common
diff options
context:
space:
mode:
Diffstat (limited to 'src/common')
-rw-r--r--src/common/crypto.c21
-rw-r--r--src/common/crypto.h1
-rw-r--r--src/common/tortls.c3
3 files changed, 23 insertions, 2 deletions
diff --git a/src/common/crypto.c b/src/common/crypto.c
index 1b45639a7c..e723f3d5d2 100644
--- a/src/common/crypto.c
+++ b/src/common/crypto.c
@@ -2317,6 +2317,25 @@ crypto_rand_int(unsigned int max)
}
}
+/** Return a pseudorandom integer, chosen uniformly from the values <i>i</i>
+ * such that <b>min</b> &lt;= <i>i</i> &lt <b>max</b>.
+ *
+ * <b>min</b> MUST be in range [0, <b>max</b>).
+ * <b>max</b> MUST be in range (min, INT_MAX].
+ */
+int
+crypto_rand_int_range(unsigned int min, unsigned int max)
+{
+ tor_assert(min < max);
+ tor_assert(max <= INT_MAX);
+
+ /* The overflow is avoided here because crypto_rand_int() returns a value
+ * between 0 and (max - min - 1) with max being <= INT_MAX and min <= max.
+ * This is why we add 1 to the maximum value so we can actually get max as
+ * a return value. */
+ return min + crypto_rand_int(max - min);
+}
+
/** Return a pseudorandom 64-bit integer, chosen uniformly from the values
* between 0 and <b>max</b>-1. */
uint64_t
@@ -2379,7 +2398,7 @@ crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
if (min_rand_len > max_rand_len)
min_rand_len = max_rand_len;
- randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
+ randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
prefixlen = strlen(prefix);
resultlen = prefixlen + strlen(suffix) + randlen + 16;
diff --git a/src/common/crypto.h b/src/common/crypto.h
index aedc51b844..aa587fd08b 100644
--- a/src/common/crypto.h
+++ b/src/common/crypto.h
@@ -254,6 +254,7 @@ int crypto_seed_rng(int startup);
MOCK_DECL(int,crypto_rand,(char *to, size_t n));
int crypto_strongest_rand(uint8_t *out, size_t out_len);
int crypto_rand_int(unsigned int max);
+int crypto_rand_int_range(unsigned int min, unsigned int max);
uint64_t crypto_rand_uint64(uint64_t max);
double crypto_rand_double(void);
struct tor_weak_rng_t;
diff --git a/src/common/tortls.c b/src/common/tortls.c
index 32106eb2df..7809c1adaa 100644
--- a/src/common/tortls.c
+++ b/src/common/tortls.c
@@ -659,7 +659,8 @@ tor_tls_create_certificate(crypto_pk_t *rsa,
* than having it start right now. Don't choose quite uniformly, since
* then we might pick a time where we're about to expire. Lastly, be
* sure to start on a day boundary. */
- start_time = time(NULL) - crypto_rand_int(cert_lifetime) + 2*24*3600;
+ time_t now = time(NULL);
+ start_time = crypto_rand_int_range(now - cert_lifetime, now) + 2*24*3600;
start_time -= start_time % (24*3600);
tor_assert(rsa);