]> granicus.if.org Git - transmission/commitdiff
#4400, #5462: Move random helpers to crypto-utils
authorMike Gelfand <mikedld@mikedld.com>
Thu, 4 Dec 2014 11:27:38 +0000 (11:27 +0000)
committerMike Gelfand <mikedld@mikedld.com>
Thu, 4 Dec 2014 11:27:38 +0000 (11:27 +0000)
On a way to factoring out OpenSSL support to a standalone file to ease
addition of other crypto libraries support in the future, move helpers
providing random numbers/data generation to crypto-utils.{c,h}. OpenSSL-
related functionality (generation of cryptographically strong random
data) is moved to crypto-utils-openssl.c.

Rename functions to follow currently accepted style:
* tr_cryptoRandBuf -> tr_rand_buffer
* tr_cryptoRandInt -> tr_rand_int
* tr_cryptoWeakRandInt -> tr_rand_int_weak

Fix rare case of invalid value being returned from tr_rand_int. Return
value for abs(INT_MIN) may be undefined and thus negative, and so
tr_rand_int will return negative value which is incorrect (out of
requested and expected range).

23 files changed:
libtransmission/Makefile.am
libtransmission/announcer-udp.c
libtransmission/announcer.c
libtransmission/bandwidth.c
libtransmission/bitfield-test.c
libtransmission/crypto-test.c
libtransmission/crypto-utils-openssl.c [new file with mode: 0644]
libtransmission/crypto-utils.c [new file with mode: 0644]
libtransmission/crypto-utils.h [new file with mode: 0644]
libtransmission/crypto.c
libtransmission/crypto.h
libtransmission/file-win32.c
libtransmission/handshake.c
libtransmission/makemeta-test.c
libtransmission/peer-io.c
libtransmission/peer-mgr.c
libtransmission/peer-msgs.c
libtransmission/rpc-server.c
libtransmission/session.c
libtransmission/torrent.c
libtransmission/tr-dht.c
libtransmission/tr-utp.c
libtransmission/utils-test.c

index b6d996a2ce5003ae2b6c1b4f289fc9583d7ecd66..8ddc21d306bed6c5c947c852cc72534313c8cdfd 100644 (file)
@@ -28,6 +28,8 @@ libtransmission_a_SOURCES = \
   completion.c \
   ConvertUTF.c \
   crypto.c \
+  crypto-utils.c \
+  crypto-utils-openssl.c \
   error.c \
   fdlimit.c \
   file.c \
@@ -89,6 +91,7 @@ noinst_HEADERS = \
   clients.h \
   ConvertUTF.h \
   crypto.h \
+  crypto-utils.h \
   completion.h \
   error.h \
   fdlimit.h \
index 6ba034e9a8c5029f164720a26498a820a78440eb..47f825a98aa7b682abbd47d8e38ecfacc0197951 100644 (file)
@@ -19,7 +19,7 @@
 #include "transmission.h"
 #include "announcer.h"
 #include "announcer-common.h"
-#include "crypto.h" /* tr_cryptoRandBuf () */
+#include "crypto-utils.h" /* tr_rand_buffer () */
 #include "log.h"
 #include "peer-io.h"
 #include "peer-mgr.h" /* tr_peerMgrCompactToPex () */
@@ -108,7 +108,7 @@ static tau_transaction_t
 tau_transaction_new (void)
 {
     tau_transaction_t tmp;
-    tr_cryptoRandBuf (&tmp, sizeof (tau_transaction_t));
+    tr_rand_buffer (&tmp, sizeof (tau_transaction_t));
     return tmp;
 }
 
index 662bd544fb6ec400c3319d93fe511990a26e0d7f..dee3a850012cbc0109f5ee761dfec9fb754eeb48 100644 (file)
@@ -21,7 +21,7 @@
 #include "transmission.h"
 #include "announcer.h"
 #include "announcer-common.h"
-#include "crypto.h" /* tr_cryptoRandInt (), tr_cryptoWeakRandInt () */
+#include "crypto-utils.h" /* tr_rand_int (), tr_rand_int_weak () */
 #include "log.h"
 #include "peer-mgr.h" /* tr_peerMgrCompactToPex () */
 #include "ptrarray.h"
@@ -167,7 +167,7 @@ tr_announcerInit (tr_session * session)
 
     a = tr_new0 (tr_announcer, 1);
     a->stops = TR_PTR_ARRAY_INIT;
-    a->key = tr_cryptoRandInt (INT_MAX);
+    a->key = tr_rand_int (INT_MAX);
     a->session = session;
     a->slotsAvailable = MAX_CONCURRENT_TASKS;
     a->upkeepTimer = evtimer_new (session->event_base, onUpkeepTimer, a);
@@ -349,7 +349,7 @@ tierConstruct (tr_tier * tier, tr_torrent * tor)
     tier->scrapeIntervalSec = DEFAULT_SCRAPE_INTERVAL_SEC;
     tier->announceIntervalSec = DEFAULT_ANNOUNCE_INTERVAL_SEC;
     tier->announceMinIntervalSec = DEFAULT_ANNOUNCE_MIN_INTERVAL_SEC;
-    tier->scrapeAt = get_next_scrape_time (tor->session, tier, tr_cryptoWeakRandInt (180));
+    tier->scrapeAt = get_next_scrape_time (tor->session, tier, tr_rand_int_weak (180));
     tier->tor = tor;
 }
 
@@ -963,11 +963,11 @@ getRetryInterval (const tr_tracker * t)
     {
       case 0:  return 0;
       case 1:  return 20;
-      case 2:  return tr_cryptoWeakRandInt (60) + (60 * 5);
-      case 3:  return tr_cryptoWeakRandInt (60) + (60 * 15);
-      case 4:  return tr_cryptoWeakRandInt (60) + (60 * 30);
-      case 5:  return tr_cryptoWeakRandInt (60) + (60 * 60);
-      default: return tr_cryptoWeakRandInt (60) + (60 * 120);
+      case 2:  return tr_rand_int_weak (60) + (60 * 5);
+      case 3:  return tr_rand_int_weak (60) + (60 * 15);
+      case 4:  return tr_rand_int_weak (60) + (60 * 30);
+      case 5:  return tr_rand_int_weak (60) + (60 * 60);
+      default: return tr_rand_int_weak (60) + (60 * 120);
     }
 }
 
index 43217f236e3881adf3ad1e2eb67ba364b5ec5161..845c0d99e22abcdb4c84452cc22cba5bee5cdc97 100644 (file)
@@ -12,7 +12,7 @@
 
 #include "transmission.h"
 #include "bandwidth.h"
-#include "crypto.h" /* tr_cryptoWeakRandInt () */
+#include "crypto-utils.h" /* tr_rand_int_weak () */
 #include "log.h"
 #include "peer-io.h"
 #include "utils.h"
@@ -210,7 +210,7 @@ phaseOne (tr_ptrArray * peerArray, tr_direction dir)
   dbgmsg ("%d peers to go round-robin for %s", n, (dir==TR_UP?"upload":"download"));
   while (n > 0)
     {
-      const int i = tr_cryptoWeakRandInt (n); /* pick a peer at random */
+      const int i = tr_rand_int_weak (n); /* pick a peer at random */
 
       /* value of 3000 bytes chosen so that when using uTP we'll send a full-size
        * frame right away and leave enough buffered data for the next frame to go
index aa59ac6a3080e90837477cc0fe5395656103604c..2479341a5df9bcda72b6b693fb340104ebf5256a 100644 (file)
@@ -9,7 +9,7 @@
 
 #include <string.h> /* strlen () */
 #include "transmission.h"
-#include "crypto.h"
+#include "crypto-utils.h"
 #include "bitfield.h"
 #include "utils.h" /* tr_free */
 
@@ -24,16 +24,16 @@ test_bitfield_count_range (void)
   int end;
   int count1;
   int count2;
-  const int bitCount = 100 + tr_cryptoWeakRandInt (1000);
+  const int bitCount = 100 + tr_rand_int_weak (1000);
   tr_bitfield bf;
 
   /* generate a random bitfield */
   tr_bitfieldConstruct (&bf, bitCount);
-  for (i=0, n=tr_cryptoWeakRandInt (bitCount); i<n; ++i)
-    tr_bitfieldAdd (&bf, tr_cryptoWeakRandInt (bitCount));
-  begin = tr_cryptoWeakRandInt (bitCount);
+  for (i=0, n=tr_rand_int_weak (bitCount); i<n; ++i)
+    tr_bitfieldAdd (&bf, tr_rand_int_weak (bitCount));
+  begin = tr_rand_int_weak (bitCount);
   do
-    end = tr_cryptoWeakRandInt (bitCount);
+    end = tr_rand_int_weak (bitCount);
   while (end == begin);
 
   /* ensure end <= begin */
index 7d357c87402c231810535454b1ed781ceaa49f29..3a76226ef96e971826a8e56386478e52ada35f00 100644 (file)
@@ -11,6 +11,7 @@
 
 #include "transmission.h"
 #include "crypto.h"
+#include "crypto-utils.h"
 
 #include "libtransmission-test.h"
 
@@ -166,13 +167,30 @@ test_ssha1 (void)
   return 0;
 }
 
+static int
+test_random (void)
+{
+  int i;
+
+  /* test that tr_rand_int () stays in-bounds */
+  for (i = 0; i < 100000; ++i)
+    {
+      const int val = tr_rand_int (100);
+      check (val >= 0);
+      check (val < 100);
+    }
+
+  return 0;
+}
+
 int
 main (void)
 {
   const testFunc tests[] = { test_torrent_hash,
                              test_encrypt_decrypt,
                              test_sha1,
-                             test_ssha1 };
+                             test_ssha1,
+                             test_random };
 
   return runTests (tests, NUM_TESTS (tests));
 }
diff --git a/libtransmission/crypto-utils-openssl.c b/libtransmission/crypto-utils-openssl.c
new file mode 100644 (file)
index 0000000..556573b
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * This file Copyright (C) 2007-2014 Mnemosyne LLC
+ *
+ * It may be used under the GNU GPL versions 2 or 3
+ * or any future license endorsed by Mnemosyne LLC.
+ *
+ * $Id$
+ */
+
+#include <assert.h>
+
+#include <openssl/err.h>
+#include <openssl/rand.h>
+
+#include "transmission.h"
+#include "crypto-utils.h"
+#include "log.h"
+
+/***
+****
+***/
+
+#define MY_NAME "tr_crypto_utils"
+
+static void
+log_openssl_error (const char * file,
+                   int          line)
+{
+  const unsigned long error_code = ERR_get_error ();
+
+  if (tr_logLevelIsActive (TR_LOG_ERROR))
+    {
+      char buf[512];
+
+#ifndef TR_LIGHTWEIGHT
+      static bool strings_loaded = false;
+      if (!strings_loaded)
+        {
+          ERR_load_crypto_strings ();
+          strings_loaded = true;
+        }
+#endif
+
+      ERR_error_string_n (error_code, buf, sizeof (buf));
+      tr_logAddMessage (file, line, TR_LOG_ERROR, MY_NAME, "OpenSSL error: %s", buf);
+    }
+}
+
+#define log_error() log_openssl_error(__FILE__, __LINE__)
+
+static bool
+check_openssl_result (int          result,
+                      int          expected_result,
+                      bool         expected_equal,
+                      const char * file,
+                      int          line)
+{
+  const bool ret = (result == expected_result) == expected_equal;
+  if (!ret)
+    log_openssl_error (file, line);
+  return ret;
+}
+
+#define check_result(result) check_openssl_result ((result), 1, true, __FILE__, __LINE__)
+#define check_result_eq(result, x_result) check_openssl_result ((result), (x_result), true, __FILE__, __LINE__)
+#define check_result_neq(result, x_result) check_openssl_result ((result), (x_result), false, __FILE__, __LINE__)
+
+static bool
+check_openssl_pointer (void       * pointer,
+                       const char * file,
+                       int          line)
+{
+  const bool ret = pointer != NULL;
+  if (!ret)
+    log_openssl_error (file, line);
+  return ret;
+}
+
+#define check_pointer(pointer) check_openssl_pointer ((pointer), __FILE__, __LINE__)
+
+/***
+****
+***/
+
+bool
+tr_rand_buffer (void   * buffer,
+                size_t   length)
+{
+  assert (buffer != NULL);
+
+  return check_result (RAND_bytes (buffer, (int) length));
+}
diff --git a/libtransmission/crypto-utils.c b/libtransmission/crypto-utils.c
new file mode 100644 (file)
index 0000000..0be9177
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * This file Copyright (C) 2007-2014 Mnemosyne LLC
+ *
+ * It may be used under the GNU GPL versions 2 or 3
+ * or any future license endorsed by Mnemosyne LLC.
+ *
+ * $Id$
+ */
+
+#include <assert.h>
+#include <stdlib.h> /* abs (), srand (), rand () */
+
+#include "transmission.h"
+#include "crypto-utils.h"
+#include "utils.h"
+
+/***
+****
+***/
+
+int
+tr_rand_int (int upper_bound)
+{
+  int noise;
+
+  assert (upper_bound > 0);
+
+  while (tr_rand_buffer (&noise, sizeof (noise)))
+    {
+      noise = abs(noise) % upper_bound;
+      /* abs(INT_MIN) is undefined and could return negative value */
+      if (noise >= 0)
+        return noise;
+    }
+
+  /* fall back to a weaker implementation... */
+  return tr_rand_int_weak (upper_bound);
+}
+
+int
+tr_rand_int_weak (int upper_bound)
+{
+  static bool init = false;
+
+  assert (upper_bound > 0);
+
+  if (!init)
+    {
+      srand (tr_time_msec ());
+      init = true;
+    }
+
+  return rand () % upper_bound;
+}
diff --git a/libtransmission/crypto-utils.h b/libtransmission/crypto-utils.h
new file mode 100644 (file)
index 0000000..5189e12
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * This file Copyright (C) 2007-2014 Mnemosyne LLC
+ *
+ * It may be used under the GNU GPL versions 2 or 3
+ * or any future license endorsed by Mnemosyne LLC.
+ *
+ * $Id$
+ */
+
+#ifndef TR_CRYPTO_UTILS_H
+#define TR_CRYPTO_UTILS_H
+
+#include <stddef.h>
+
+/**
+*** @addtogroup utils Utilities
+*** @{
+**/
+
+/**
+ * @brief Returns a random number in the range of [0...upper_bound).
+ */
+int              tr_rand_int           (int              upper_bound);
+
+/**
+ * @brief Returns a pseudorandom number in the range of [0...upper_bound).
+ *
+ * This is faster, BUT WEAKER, than tr_rand_int () and never be used in sensitive cases.
+ * @see tr_rand_int ()
+ */
+int              tr_rand_int_weak      (int              upper_bound);
+
+/**
+ * @brief Fill a buffer with random bytes.
+ */
+bool             tr_rand_buffer        (void           * buffer,
+                                        size_t           length);
+
+/** @} */
+
+#endif /* TR_CRYPTO_UTILS_H */
index 8aec65aa530c3c4564b9a835c07b011d4c4cf801..d801cdc28940892dd3d158ef761e250f8616a5f3 100644 (file)
@@ -8,9 +8,7 @@
  */
 
 #include <assert.h>
-#include <inttypes.h> /* uint8_t */
 #include <stdarg.h>
-#include <stdlib.h> /* abs () */
 #include <string.h> /* memcpy (), memset (), strcmp () */
 
 #include <openssl/bn.h>
 #include <openssl/err.h>
 #include <openssl/rc4.h>
 #include <openssl/sha.h>
-#include <openssl/rand.h>
 
 #include "transmission.h"
 #include "crypto.h"
+#include "crypto-utils.h"
 #include "log.h"
 #include "utils.h"
 
@@ -294,49 +292,6 @@ tr_cryptoHasTorrentHash (const tr_crypto * crypto)
   return crypto->torrentHashIsSet;
 }
 
-int
-tr_cryptoRandInt (int upperBound)
-{
-  int noise;
-  int val;
-
-  assert (upperBound > 0);
-
-  if (RAND_pseudo_bytes ((unsigned char *) &noise, sizeof noise) >= 0)
-    {
-      val = abs (noise) % upperBound;
-    }
-  else /* fall back to a weaker implementation... */
-    {
-      val = tr_cryptoWeakRandInt (upperBound);
-    }
-
-  return val;
-}
-
-int
-tr_cryptoWeakRandInt (int upperBound)
-{
-  static bool init = false;
-
-  assert (upperBound > 0);
-
-  if (!init)
-    {
-      srand (tr_time_msec ());
-      init = true;
-    }
-
-  return rand () % upperBound;
-}
-
-void
-tr_cryptoRandBuf (void * buf, size_t len)
-{
-  if (RAND_pseudo_bytes ((unsigned char*)buf, len) != 1)
-    logErrorFromSSL ();
-}
-
 /***
 ****
 ***/
@@ -356,7 +311,7 @@ tr_ssha1 (const void * plaintext)
   uint8_t sha[SHA_DIGEST_LENGTH];
   char buf[2*SHA_DIGEST_LENGTH + saltval_len + 2];
 
-  tr_cryptoRandBuf (salt, saltval_len);
+  tr_rand_buffer (salt, saltval_len);
   for (i=0; i<saltval_len; ++i)
     salt[i] = salter[ salt[i] % salter_len ];
 
index 88559ebcec562bebd4817e6fc7407acbaebec74c..9728179502d7c8330be4ea0a8a6bac12f674536c 100644 (file)
@@ -94,21 +94,6 @@ void tr_sha1 (uint8_t    * setme,
               ...) TR_GNUC_NULL_TERMINATED;
 
 
-/** @brief returns a random number in the range of [0...n) */
-int tr_cryptoRandInt (int n);
-
-/**
- * @brief returns a pseudorandom number in the range of [0...n)
- *
- * This is faster, BUT WEAKER, than tr_cryptoRandInt () and never
- * be used in sensitive cases.
- * @see tr_cryptoRandInt ()
- */
-int            tr_cryptoWeakRandInt (int n);
-
-/** @brief fill a buffer with random bytes */
-void  tr_cryptoRandBuf (void * buf, size_t len);
-
 /** @brief generate a SSHA password from its plaintext source */
 char*  tr_ssha1 (const void * plaintext);
 
index d9028ca942456cf5a8e329dd1705c5707f845026..3c36b00732d9563c7977069bd6a98b2c2ab77128 100644 (file)
@@ -14,7 +14,7 @@
 #include <winioctl.h> /* FSCTL_SET_SPARSE */
 
 #include "transmission.h"
-#include "crypto.h" /* tr_cryptoRandInt () */
+#include "crypto-utils.h" /* tr_rand_int () */
 #include "file.h"
 #include "utils.h"
 
@@ -205,7 +205,7 @@ create_temp_path (char      * path_template,
 
       while (i > 0 && path_template[i - 1] == 'X')
         {
-          const int c = tr_cryptoRandInt (26 + 26 + 10);
+          const int c = tr_rand_int (26 + 26 + 10);
           path[i - 1] = c < 26 ? c + 'A' : (c < 26 + 26 ? (c - 26) + 'a' : (c - 26 - 26) + '0');
           --i;
         }
index 15f2acca1a28cc031307725cd0b1355cd9d36f09..25c91b8623b21ab7eba8713ce72dd773ffc7ec50 100644 (file)
@@ -16,7 +16,7 @@
 
 #include "transmission.h"
 #include "clients.h"
-#include "crypto.h"
+#include "crypto-utils.h"
 #include "handshake.h"
 #include "log.h"
 #include "peer-io.h"
@@ -324,8 +324,8 @@ sendYa (tr_handshake * handshake)
   walk += len;
 
   /* add some bullshit padding */
-  len = tr_cryptoRandInt (PadA_MAXLEN);
-  tr_cryptoRandBuf (walk, len);
+  len = tr_rand_int (PadA_MAXLEN);
+  tr_rand_buffer (walk, len);
   walk += len;
 
   /* send it */
@@ -748,8 +748,8 @@ readYa (tr_handshake    * handshake,
   myKey = tr_cryptoGetMyPublicKey (handshake->crypto, &len);
   memcpy (walk, myKey, len);
   walk += len;
-  len = tr_cryptoRandInt (PadB_MAXLEN);
-  tr_cryptoRandBuf (walk, len);
+  len = tr_rand_int (PadB_MAXLEN);
+  tr_rand_buffer (walk, len);
   walk += len;
 
   setReadState (handshake, AWAITING_PAD_A);
index f6c3c5eaabde2e1305d86e8edfd8a80656361f4a..b6d0ede1bc4ef44501121fd3b3ccd28b77d144f3 100644 (file)
@@ -10,7 +10,7 @@
 #include "libtransmission-test.h"
 
 #include "transmission.h"
-#include "crypto.h"
+#include "crypto-utils.h"
 #include "file.h"
 #include "makemeta.h"
 
@@ -229,14 +229,14 @@ test_single_directory_random_payload_impl (const tr_tracker_info * trackers,
   size_t payloadCount;
 
   /* build random payloads */
-  payloadCount = 1 + tr_cryptoWeakRandInt (maxFileCount);
+  payloadCount = 1 + tr_rand_int_weak (maxFileCount);
   payloads = tr_new0 (void*, payloadCount);
   payloadSizes = tr_new0 (size_t, payloadCount);
   for (i=0; i<payloadCount; i++)
     {
-      const size_t n = 1 + tr_cryptoWeakRandInt (maxFileSize);
+      const size_t n = 1 + tr_rand_int_weak (maxFileSize);
       payloads[i] = tr_new (char, n);
-      tr_cryptoRandBuf (payloads[i], n);
+      tr_rand_buffer (payloads[i], n);
       payloadSizes[i] = n;
     }
 
index 3dc055b713815c23d53d72635e6fbfb96ac60e2e..5a6f24179dbc903ff02f1eefa16b0a095b16a6eb 100644 (file)
@@ -20,7 +20,6 @@
 #include "transmission.h"
 #include "session.h"
 #include "bandwidth.h"
-#include "crypto.h"
 #include "log.h"
 #include "net.h"
 #include "peer-common.h" /* MAX_BLOCK_SIZE */
index 2ba95dfc1885a071f4430545c2736c8a7590c344..62f5e36c99509a58529e7bb69af80fa8dae749f4 100644 (file)
@@ -24,7 +24,7 @@
 #include "cache.h"
 #include "clients.h"
 #include "completion.h"
-#include "crypto.h"
+#include "crypto-utils.h"
 #include "handshake.h"
 #include "log.h"
 #include "net.h"
@@ -1097,7 +1097,7 @@ pieceListRebuild (tr_swarm * s)
           struct weighted_piece * piece = pieces + i;
           piece->index = pool[i];
           piece->requestCount = 0;
-          piece->salt = tr_cryptoWeakRandInt (4096);
+          piece->salt = tr_rand_int_weak (4096);
         }
 
       /* if we already had a list of pieces, merge it into
@@ -1863,7 +1863,7 @@ ensureAtomExists (tr_swarm          * s,
 
   if (a == NULL)
     {
-      const int jitter = tr_cryptoWeakRandInt (60*10);
+      const int jitter = tr_rand_int_weak (60*10);
       a = tr_new0 (struct peer_atom, 1);
       a->addr = *addr;
       a->port = port;
@@ -2948,7 +2948,7 @@ rechokeDownloads (tr_swarm * s)
 
               rechoke[rechoke_count].peer = peer;
               rechoke[rechoke_count].rechoke_state = rechoke_state;
-              rechoke[rechoke_count].salt = tr_cryptoWeakRandInt (INT_MAX);
+              rechoke[rechoke_count].salt = tr_rand_int_weak (INT_MAX);
               rechoke_count++;
             }
 
@@ -3088,7 +3088,7 @@ rechokeUploads (tr_swarm * s, const uint64_t now)
           n->isInterested = tr_peerMsgsIsPeerInterested (msgs);
           n->wasChoked    = tr_peerMsgsIsPeerChoked (msgs);
           n->rate         = getRate (s->tor, atom, now);
-          n->salt         = tr_cryptoWeakRandInt (INT_MAX);
+          n->salt         = tr_rand_int_weak (INT_MAX);
           n->isChoked     = true;
         }
     }
@@ -3139,7 +3139,7 @@ rechokeUploads (tr_swarm * s, const uint64_t now)
 
       if ((n = tr_ptrArraySize (&randPool)))
         {
-          c = tr_ptrArrayNth (&randPool, tr_cryptoWeakRandInt (n));
+          c = tr_ptrArrayNth (&randPool, tr_rand_int_weak (n));
           c->isChoked = false;
           s->optimistic = c->msgs;
           s->optimisticUnchokeTimeScaler = OPTIMISTIC_UNCHOKE_MULTIPLIER;
@@ -3982,7 +3982,7 @@ getPeerCandidates (tr_session * session, int * candidateCount, int max)
 
           if (isPeerCandidate (tor, atom, now))
             {
-              const uint8_t salt = tr_cryptoWeakRandInt (1024);
+              const uint8_t salt = tr_rand_int_weak (1024);
               walk->tor = tor;
               walk->atom = atom;
               walk->score = getPeerCandidateScore (tor, atom, salt);
index cf93f8cb58c67930b32c03b95aeea03dc16f4f1d..5d8998c5b0e2d3e406c8e2e78038365d6e07d413 100644 (file)
@@ -20,7 +20,6 @@
 #include "transmission.h"
 #include "cache.h"
 #include "completion.h"
-#include "crypto.h" /* tr_sha1 () */
 #include "file.h"
 #include "log.h"
 #include "peer-io.h"
index de7516fd247beeb0c7de58c5af859366416cddb8..367819493d6b6df2c8a1c3021a12644b824584d4 100644 (file)
@@ -19,7 +19,8 @@
 #include <event2/http_struct.h> /* TODO: eventually remove this */
 
 #include "transmission.h"
-#include "crypto.h" /* tr_cryptoRandBuf (), tr_ssha1_matches () */
+#include "crypto.h" /* tr_ssha1_matches () */
+#include "crypto-utils.h" /* tr_rand_buffer () */
 #include "fdlimit.h"
 #include "list.h"
 #include "log.h"
@@ -91,7 +92,7 @@ get_current_session_id (struct tr_rpc_server * server)
       const size_t pool_size = strlen (pool);
       unsigned char * buf = tr_new (unsigned char, n+1);
 
-      tr_cryptoRandBuf (buf, n);
+      tr_rand_buffer (buf, n);
       for (i=0; i<n; ++i)
         buf[i] = pool[ buf[i] % pool_size ];
       buf[n] = '\0';
index f782966d2c9a0a43aebf57af9a2c60938014efc0..e7084bb6c864ae640c516fa741f7e264132d1241 100644 (file)
@@ -28,7 +28,7 @@
 #include "bandwidth.h"
 #include "blocklist.h"
 #include "cache.h"
-#include "crypto.h"
+#include "crypto-utils.h"
 #include "fdlimit.h"
 #include "file.h"
 #include "list.h"
@@ -78,7 +78,7 @@ enum
 static tr_port
 getRandomPort (tr_session * s)
 {
-  return tr_cryptoWeakRandInt (s->randomPortHigh - s->randomPortLow + 1) + s->randomPortLow;
+  return tr_rand_int_weak (s->randomPortHigh - s->randomPortLow + 1) + s->randomPortLow;
 }
 
 /* Generate a peer id : "-TRxyzb-" + 12 random alphanumeric
@@ -96,7 +96,7 @@ tr_peerIdInit (uint8_t * buf)
 
   memcpy (buf, PEERID_PREFIX, 8);
 
-  tr_cryptoRandBuf (buf+8, 11);
+  tr_rand_buffer (buf+8, 11);
   for (i=8; i<19; ++i)
     {
       val = buf[i] % base;
index 3b1568ecf9584c33f163f63ab61d41c8121b7ba3..ea2e8d45001f9e75cb8b3081e7e4e15f4724bdf7 100644 (file)
@@ -31,6 +31,7 @@
 #include "cache.h"
 #include "completion.h"
 #include "crypto.h" /* for tr_sha1 */
+#include "crypto-utils.h"
 #include "error.h"
 #include "fdlimit.h" /* tr_fdTorrentClose */
 #include "file.h"
@@ -1648,8 +1649,8 @@ torrentStartImpl (void * vtor)
 
   tr_torrentResetTransferStats (tor);
   tr_announcerTorrentStarted (tor);
-  tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt (20);
-  tor->dhtAnnounce6At = now + tr_cryptoWeakRandInt (20);
+  tor->dhtAnnounceAt = now + tr_rand_int_weak (20);
+  tor->dhtAnnounce6At = now + tr_rand_int_weak (20);
   tor->lpdAnnounceAt = now;
   tr_peerMgrStartTorrent (tor);
 
index 49c95908a31e48eba726f53e944b5ea88326e77b..e40d268322f64b76b0ca6908d88244003a38b70d 100644 (file)
@@ -50,6 +50,7 @@
 /* libT */
 #include "transmission.h"
 #include "crypto.h"
+#include "crypto-utils.h"
 #include "file.h"
 #include "log.h"
 #include "net.h"
@@ -93,7 +94,7 @@ static void
 nap (int roughly_sec)
 {
     const int roughly_msec = roughly_sec * 1000;
-    const int msec = roughly_msec/2 + tr_cryptoWeakRandInt (roughly_msec);
+    const int msec = roughly_msec/2 + tr_rand_int_weak (roughly_msec);
     tr_wait_msec (msec);
 }
 
@@ -307,7 +308,7 @@ tr_dhtInit (tr_session *ss)
         /* Note that DHT ids need to be distributed uniformly,
          * so it should be something truly random. */
         tr_logAddNamedInfo ("DHT", "Generating new id");
-        tr_cryptoRandBuf (myid, 20);
+        tr_rand_buffer (myid, 20);
     }
 
     rc = dht_init (ss->udp_socket, ss->udp6_socket, myid, NULL);
@@ -325,7 +326,7 @@ tr_dhtInit (tr_session *ss)
     tr_threadNew (dht_bootstrap, cl);
 
     dht_timer = evtimer_new (session->event_base, timer_callback, session);
-    tr_timerAdd (dht_timer, 0, tr_cryptoWeakRandInt (1000000));
+    tr_timerAdd (dht_timer, 0, tr_rand_int_weak (1000000));
 
     tr_logAddNamedDbg ("DHT", "DHT initialized");
 
@@ -609,8 +610,8 @@ tr_dhtUpkeep (tr_session * session)
             const int rc = tr_dhtAnnounce (tor, AF_INET, 1);
 
             tor->dhtAnnounceAt = now + ((rc == 0)
-                                     ? 5 + tr_cryptoWeakRandInt (5)
-                                     : 25 * 60 + tr_cryptoWeakRandInt (3*60));
+                                     ? 5 + tr_rand_int_weak (5)
+                                     : 25 * 60 + tr_rand_int_weak (3*60));
         }
 
         if (tor->dhtAnnounce6At <= now)
@@ -618,8 +619,8 @@ tr_dhtUpkeep (tr_session * session)
             const int rc = tr_dhtAnnounce (tor, AF_INET6, 1);
 
             tor->dhtAnnounce6At = now + ((rc == 0)
-                                      ? 5 + tr_cryptoWeakRandInt (5)
-                                      : 25 * 60 + tr_cryptoWeakRandInt (3*60));
+                                      ? 5 + tr_rand_int_weak (5)
+                                      : 25 * 60 + tr_rand_int_weak (3*60));
         }
     }
 }
@@ -652,7 +653,7 @@ tr_dhtCallback (unsigned char *buf, int buflen,
 
     /* Being slightly late is fine,
        and has the added benefit of adding some jitter. */
-    tr_timerAdd (dht_timer, tosleep, tr_cryptoWeakRandInt (1000000));
+    tr_timerAdd (dht_timer, tosleep, tr_rand_int_weak (1000000));
 }
 
 static void
@@ -688,6 +689,6 @@ dht_hash (void *hash_return, int hash_size,
 int
 dht_random_bytes (void * buf, size_t size)
 {
-    tr_cryptoRandBuf (buf, size);
+    tr_rand_buffer (buf, size);
     return size;
 }
index 1c072735066947f0bc7311157f5822a0a8ccaa99..199cbb1e64ef6d40ef441540135f03468cb53d63 100644 (file)
@@ -31,7 +31,7 @@ THE SOFTWARE.
 #include "log.h"
 #include "net.h"
 #include "session.h"
-#include "crypto.h" /* tr_cryptoWeakRandInt () */
+#include "crypto-utils.h" /* tr_rand_int_weak () */
 #include "peer-mgr.h"
 #include "tr-utp.h"
 #include "utils.h"
@@ -143,7 +143,7 @@ reset_timer (tr_session *ss)
     int usec;
     if (tr_sessionIsUTPEnabled (ss)) {
         sec = 0;
-        usec = UTP_INTERVAL_US / 2 + tr_cryptoWeakRandInt (UTP_INTERVAL_US);
+        usec = UTP_INTERVAL_US / 2 + tr_rand_int_weak (UTP_INTERVAL_US);
     } else {
         /* If somebody has disabled uTP, then we still want to run
            UTP_CheckTimeouts, in order to let closed sockets finish
@@ -151,7 +151,7 @@ reset_timer (tr_session *ss)
            interested in that happening in a timely manner, we might as
            well use a large timeout. */
         sec = 2;
-        usec = tr_cryptoWeakRandInt (1000000);
+        usec = tr_rand_int_weak (1000000);
     }
     tr_timerAdd (utp_timer, sec, usec);
 }
index 281adfdee82cb44ec303191f5f78c64563bc7ebd..2ff9b8b7f5727fd9ceb2485803eeea9158288e45 100644 (file)
@@ -21,7 +21,7 @@
 #include "transmission.h"
 #include "ConvertUTF.h" /* tr_utf8_validate*/
 #include "platform.h"
-#include "crypto.h"
+#include "crypto-utils.h" /* tr_rand_int_weak */
 #include "utils.h"
 #include "web.h"
 
@@ -243,7 +243,7 @@ test_quickFindFirst_Iteration (const size_t k, const size_t n, int * buf, int ra
 
   /* populate buf with random ints */
   for (i=0; i<n; ++i)
-    buf[i] = tr_cryptoWeakRandInt (range);
+    buf[i] = tr_rand_int_weak (range);
 
   /* find the best k */
   tr_quickfindFirstK (buf, n, sizeof(int), compareInts, k);
@@ -412,22 +412,6 @@ test_truncd (void)
   return 0;
 }
 
-static int
-test_cryptoRand (void)
-{
-  int i;
-
-  /* test that tr_cryptoRandInt () stays in-bounds */
-  for (i = 0; i < 100000; ++i)
-    {
-      const int val = tr_cryptoRandInt (100);
-       check (val >= 0);
-       check (val < 100);
-    }
-
-  return 0;
-}
-
 static char *
 test_strdup_printf_valist (const char * fmt, ...)
 {
@@ -536,7 +520,6 @@ main (void)
   const testFunc tests[] = { test_array,
                              test_base64,
                              test_buildpath,
-                             test_cryptoRand,
                              test_hex,
                              test_lowerbound,
                              test_quickfindFirst,