test.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2017, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file test.c
  7. * \brief Unit tests for many pieces of the lower level Tor modules.
  8. **/
  9. #include "orconfig.h"
  10. #include <stdio.h>
  11. #ifdef HAVE_FCNTL_H
  12. #include <fcntl.h>
  13. #endif
  14. #ifdef _WIN32
  15. /* For mkdir() */
  16. #include <direct.h>
  17. #else
  18. #include <dirent.h>
  19. #endif /* defined(_WIN32) */
  20. /* These macros pull in declarations for some functions and structures that
  21. * are typically file-private. */
  22. #define ROUTER_PRIVATE
  23. #define CIRCUITSTATS_PRIVATE
  24. #define CIRCUITLIST_PRIVATE
  25. #define MAIN_PRIVATE
  26. #define STATEFILE_PRIVATE
  27. /*
  28. * Linux doesn't provide lround in math.h by default, but mac os does...
  29. * It's best just to leave math.h out of the picture entirely.
  30. */
  31. //#include <math.h>
  32. long int lround(double x);
  33. double fabs(double x);
  34. #include "or.h"
  35. #include "backtrace.h"
  36. #include "buffers.h"
  37. #include "circuitlist.h"
  38. #include "circuitstats.h"
  39. #include "compress.h"
  40. #include "config.h"
  41. #include "connection_edge.h"
  42. #include "rendcommon.h"
  43. #include "rendcache.h"
  44. #include "test.h"
  45. #include "main.h"
  46. #include "memarea.h"
  47. #include "onion.h"
  48. #include "onion_ntor.h"
  49. #include "onion_fast.h"
  50. #include "onion_tap.h"
  51. #include "policies.h"
  52. #include "rephist.h"
  53. #include "routerparse.h"
  54. #include "statefile.h"
  55. #include "crypto_curve25519.h"
  56. /** Run unit tests for the onion handshake code. */
  57. static void
  58. test_onion_handshake(void *arg)
  59. {
  60. /* client-side */
  61. crypto_dh_t *c_dh = NULL;
  62. char c_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  63. char c_keys[40];
  64. /* server-side */
  65. char s_buf[TAP_ONIONSKIN_REPLY_LEN];
  66. char s_keys[40];
  67. int i;
  68. /* shared */
  69. crypto_pk_t *pk = NULL, *pk2 = NULL;
  70. (void)arg;
  71. pk = pk_generate(0);
  72. pk2 = pk_generate(1);
  73. /* client handshake 1. */
  74. memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
  75. tt_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
  76. for (i = 1; i <= 3; ++i) {
  77. crypto_pk_t *k1, *k2;
  78. if (i==1) {
  79. /* server handshake: only one key known. */
  80. k1 = pk; k2 = NULL;
  81. } else if (i==2) {
  82. /* server handshake: try the right key first. */
  83. k1 = pk; k2 = pk2;
  84. } else {
  85. /* server handshake: try the right key second. */
  86. k1 = pk2; k2 = pk;
  87. }
  88. memset(s_buf, 0, TAP_ONIONSKIN_REPLY_LEN);
  89. memset(s_keys, 0, 40);
  90. tt_assert(! onion_skin_TAP_server_handshake(c_buf, k1, k2,
  91. s_buf, s_keys, 40));
  92. /* client handshake 2 */
  93. memset(c_keys, 0, 40);
  94. tt_assert(! onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys,
  95. 40, NULL));
  96. tt_mem_op(c_keys,OP_EQ, s_keys, 40);
  97. memset(s_buf, 0, 40);
  98. tt_mem_op(c_keys,OP_NE, s_buf, 40);
  99. }
  100. done:
  101. crypto_dh_free(c_dh);
  102. crypto_pk_free(pk);
  103. crypto_pk_free(pk2);
  104. }
  105. static void
  106. test_bad_onion_handshake(void *arg)
  107. {
  108. char junk_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  109. char junk_buf2[TAP_ONIONSKIN_CHALLENGE_LEN];
  110. /* client-side */
  111. crypto_dh_t *c_dh = NULL;
  112. char c_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  113. char c_keys[40];
  114. /* server-side */
  115. char s_buf[TAP_ONIONSKIN_REPLY_LEN];
  116. char s_keys[40];
  117. /* shared */
  118. crypto_pk_t *pk = NULL, *pk2 = NULL;
  119. (void)arg;
  120. pk = pk_generate(0);
  121. pk2 = pk_generate(1);
  122. /* Server: Case 1: the encrypted data is degenerate. */
  123. memset(junk_buf, 0, sizeof(junk_buf));
  124. crypto_pk_obsolete_public_hybrid_encrypt(pk,
  125. junk_buf2, TAP_ONIONSKIN_CHALLENGE_LEN,
  126. junk_buf, DH_KEY_LEN, PK_PKCS1_OAEP_PADDING, 1);
  127. tt_int_op(-1, OP_EQ,
  128. onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
  129. s_buf, s_keys, 40));
  130. /* Server: Case 2: the encrypted data is not long enough. */
  131. memset(junk_buf, 0, sizeof(junk_buf));
  132. memset(junk_buf2, 0, sizeof(junk_buf2));
  133. crypto_pk_public_encrypt(pk, junk_buf2, sizeof(junk_buf2),
  134. junk_buf, 48, PK_PKCS1_OAEP_PADDING);
  135. tt_int_op(-1, OP_EQ,
  136. onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
  137. s_buf, s_keys, 40));
  138. /* client handshake 1: do it straight. */
  139. memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
  140. tt_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
  141. /* Server: Case 3: we just don't have the right key. */
  142. tt_int_op(-1, OP_EQ,
  143. onion_skin_TAP_server_handshake(c_buf, pk2, NULL,
  144. s_buf, s_keys, 40));
  145. /* Server: Case 4: The RSA-encrypted portion is corrupt. */
  146. c_buf[64] ^= 33;
  147. tt_int_op(-1, OP_EQ,
  148. onion_skin_TAP_server_handshake(c_buf, pk, NULL,
  149. s_buf, s_keys, 40));
  150. c_buf[64] ^= 33;
  151. /* (Let the server proceed) */
  152. tt_int_op(0, OP_EQ,
  153. onion_skin_TAP_server_handshake(c_buf, pk, NULL,
  154. s_buf, s_keys, 40));
  155. /* Client: Case 1: The server sent back junk. */
  156. const char *msg = NULL;
  157. s_buf[64] ^= 33;
  158. tt_int_op(-1, OP_EQ,
  159. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, &msg));
  160. s_buf[64] ^= 33;
  161. tt_str_op(msg, OP_EQ, "Digest DOES NOT MATCH on onion handshake. "
  162. "Bug or attack.");
  163. /* Let the client finish; make sure it can. */
  164. msg = NULL;
  165. tt_int_op(0, OP_EQ,
  166. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, &msg));
  167. tt_mem_op(s_keys,OP_EQ, c_keys, 40);
  168. tt_ptr_op(msg, OP_EQ, NULL);
  169. /* Client: Case 2: The server sent back a degenerate DH. */
  170. memset(s_buf, 0, sizeof(s_buf));
  171. tt_int_op(-1, OP_EQ,
  172. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, &msg));
  173. tt_str_op(msg, OP_EQ, "DH computation failed.");
  174. done:
  175. crypto_dh_free(c_dh);
  176. crypto_pk_free(pk);
  177. crypto_pk_free(pk2);
  178. }
  179. static void
  180. test_ntor_handshake(void *arg)
  181. {
  182. /* client-side */
  183. ntor_handshake_state_t *c_state = NULL;
  184. uint8_t c_buf[NTOR_ONIONSKIN_LEN];
  185. uint8_t c_keys[400];
  186. /* server-side */
  187. di_digest256_map_t *s_keymap=NULL;
  188. curve25519_keypair_t s_keypair;
  189. uint8_t s_buf[NTOR_REPLY_LEN];
  190. uint8_t s_keys[400];
  191. /* shared */
  192. const curve25519_public_key_t *server_pubkey;
  193. uint8_t node_id[20] = "abcdefghijklmnopqrst";
  194. (void) arg;
  195. /* Make the server some keys */
  196. curve25519_secret_key_generate(&s_keypair.seckey, 0);
  197. curve25519_public_key_generate(&s_keypair.pubkey, &s_keypair.seckey);
  198. dimap_add_entry(&s_keymap, s_keypair.pubkey.public_key, &s_keypair);
  199. server_pubkey = &s_keypair.pubkey;
  200. /* client handshake 1. */
  201. memset(c_buf, 0, NTOR_ONIONSKIN_LEN);
  202. tt_int_op(0, OP_EQ, onion_skin_ntor_create(node_id, server_pubkey,
  203. &c_state, c_buf));
  204. /* server handshake */
  205. memset(s_buf, 0, NTOR_REPLY_LEN);
  206. memset(s_keys, 0, 40);
  207. tt_int_op(0, OP_EQ, onion_skin_ntor_server_handshake(c_buf, s_keymap, NULL,
  208. node_id,
  209. s_buf, s_keys, 400));
  210. /* client handshake 2 */
  211. memset(c_keys, 0, 40);
  212. tt_int_op(0, OP_EQ, onion_skin_ntor_client_handshake(c_state, s_buf,
  213. c_keys, 400, NULL));
  214. tt_mem_op(c_keys,OP_EQ, s_keys, 400);
  215. memset(s_buf, 0, 40);
  216. tt_mem_op(c_keys,OP_NE, s_buf, 40);
  217. /* Now try with a bogus server response. Zero input should trigger
  218. * All The Problems. */
  219. memset(c_keys, 0, 400);
  220. memset(s_buf, 0, NTOR_REPLY_LEN);
  221. const char *msg = NULL;
  222. tt_int_op(-1, OP_EQ, onion_skin_ntor_client_handshake(c_state, s_buf,
  223. c_keys, 400, &msg));
  224. tt_str_op(msg, OP_EQ, "Zero output from curve25519 handshake");
  225. done:
  226. ntor_handshake_state_free(c_state);
  227. dimap_free(s_keymap, NULL);
  228. }
  229. static void
  230. test_fast_handshake(void *arg)
  231. {
  232. /* tests for the obsolete "CREATE_FAST" handshake. */
  233. (void) arg;
  234. fast_handshake_state_t *state = NULL;
  235. uint8_t client_handshake[CREATE_FAST_LEN];
  236. uint8_t server_handshake[CREATED_FAST_LEN];
  237. uint8_t s_keys[100], c_keys[100];
  238. /* First, test an entire handshake. */
  239. memset(client_handshake, 0, sizeof(client_handshake));
  240. tt_int_op(0, OP_EQ, fast_onionskin_create(&state, client_handshake));
  241. tt_assert(! tor_mem_is_zero((char*)client_handshake,
  242. sizeof(client_handshake)));
  243. tt_int_op(0, OP_EQ,
  244. fast_server_handshake(client_handshake, server_handshake,
  245. s_keys, 100));
  246. const char *msg = NULL;
  247. tt_int_op(0, OP_EQ,
  248. fast_client_handshake(state, server_handshake, c_keys, 100, &msg));
  249. tt_ptr_op(msg, OP_EQ, NULL);
  250. tt_mem_op(s_keys, OP_EQ, c_keys, 100);
  251. /* Now test a failing handshake. */
  252. server_handshake[0] ^= 3;
  253. tt_int_op(-1, OP_EQ,
  254. fast_client_handshake(state, server_handshake, c_keys, 100, &msg));
  255. tt_str_op(msg, OP_EQ, "Digest DOES NOT MATCH on fast handshake. "
  256. "Bug or attack.");
  257. done:
  258. fast_handshake_state_free(state);
  259. }
  260. /** Run unit tests for the onion queues. */
  261. static void
  262. test_onion_queues(void *arg)
  263. {
  264. uint8_t buf1[TAP_ONIONSKIN_CHALLENGE_LEN] = {0};
  265. uint8_t buf2[NTOR_ONIONSKIN_LEN] = {0};
  266. or_circuit_t *circ1 = or_circuit_new(0, NULL);
  267. or_circuit_t *circ2 = or_circuit_new(0, NULL);
  268. create_cell_t *onionskin = NULL, *create2_ptr;
  269. create_cell_t *create1 = tor_malloc_zero(sizeof(create_cell_t));
  270. create_cell_t *create2 = tor_malloc_zero(sizeof(create_cell_t));
  271. (void)arg;
  272. create2_ptr = create2; /* remember, but do not free */
  273. create_cell_init(create1, CELL_CREATE, ONION_HANDSHAKE_TYPE_TAP,
  274. TAP_ONIONSKIN_CHALLENGE_LEN, buf1);
  275. create_cell_init(create2, CELL_CREATE, ONION_HANDSHAKE_TYPE_NTOR,
  276. NTOR_ONIONSKIN_LEN, buf2);
  277. tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  278. tt_int_op(0,OP_EQ, onion_pending_add(circ1, create1));
  279. create1 = NULL;
  280. tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  281. tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  282. tt_int_op(0,OP_EQ, onion_pending_add(circ2, create2));
  283. create2 = NULL;
  284. tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  285. tt_ptr_op(circ2,OP_EQ, onion_next_task(&onionskin));
  286. tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  287. tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  288. tt_ptr_op(onionskin, OP_EQ, create2_ptr);
  289. clear_pending_onions();
  290. tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  291. tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  292. done:
  293. circuit_free_(TO_CIRCUIT(circ1));
  294. circuit_free_(TO_CIRCUIT(circ2));
  295. tor_free(create1);
  296. tor_free(create2);
  297. tor_free(onionskin);
  298. }
  299. static crypto_cipher_t *crypto_rand_aes_cipher = NULL;
  300. // Mock replacement for crypto_rand: Generates bytes from a provided AES_CTR
  301. // cipher in <b>crypto_rand_aes_cipher</b>.
  302. static void
  303. crypto_rand_deterministic_aes(char *out, size_t n)
  304. {
  305. tor_assert(crypto_rand_aes_cipher);
  306. memset(out, 0, n);
  307. crypto_cipher_crypt_inplace(crypto_rand_aes_cipher, out, n);
  308. }
  309. static void
  310. test_circuit_timeout(void *arg)
  311. {
  312. /* Plan:
  313. * 1. Generate 1000 samples
  314. * 2. Estimate parameters
  315. * 3. If difference, repeat
  316. * 4. Save state
  317. * 5. load state
  318. * 6. Estimate parameters
  319. * 7. compare differences
  320. */
  321. circuit_build_times_t initial;
  322. circuit_build_times_t estimate;
  323. circuit_build_times_t final;
  324. double timeout1, timeout2;
  325. or_state_t *state=NULL;
  326. int i, runs;
  327. double close_ms;
  328. (void)arg;
  329. initialize_periodic_events();
  330. circuit_build_times_init(&initial);
  331. circuit_build_times_init(&estimate);
  332. circuit_build_times_init(&final);
  333. state = or_state_new();
  334. // Use a deterministic RNG here, or else we'll get nondeterministic
  335. // coverage in some of the circuitstats functions.
  336. MOCK(crypto_rand, crypto_rand_deterministic_aes);
  337. crypto_rand_aes_cipher = crypto_cipher_new("xyzzyplughplover");
  338. circuitbuild_running_unit_tests();
  339. #define timeout0 (build_time_t)(30*1000.0)
  340. initial.Xm = 3000;
  341. circuit_build_times_initial_alpha(&initial,
  342. CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
  343. timeout0);
  344. close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
  345. CBT_DEFAULT_CLOSE_QUANTILE/100.0),
  346. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
  347. do {
  348. for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
  349. build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);
  350. if (sample > close_ms) {
  351. circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
  352. } else {
  353. circuit_build_times_add_time(&estimate, sample);
  354. }
  355. }
  356. circuit_build_times_update_alpha(&estimate);
  357. timeout1 = circuit_build_times_calculate_timeout(&estimate,
  358. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  359. circuit_build_times_set_timeout(&estimate);
  360. log_notice(LD_CIRC, "Timeout1 is %f, Xm is %d", timeout1, estimate.Xm);
  361. /* 2% error */
  362. } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
  363. circuit_build_times_cdf(&initial, timeout1)) > 0.02);
  364. tt_int_op(estimate.total_build_times, OP_LE, CBT_NCIRCUITS_TO_OBSERVE);
  365. circuit_build_times_update_state(&estimate, state);
  366. circuit_build_times_free_timeouts(&final);
  367. tt_int_op(circuit_build_times_parse_state(&final, state), OP_EQ, 0);
  368. circuit_build_times_update_alpha(&final);
  369. timeout2 = circuit_build_times_calculate_timeout(&final,
  370. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  371. circuit_build_times_set_timeout(&final);
  372. log_notice(LD_CIRC, "Timeout2 is %f, Xm is %d", timeout2, final.Xm);
  373. /* 5% here because some accuracy is lost due to histogram conversion */
  374. tt_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
  375. circuit_build_times_cdf(&initial, timeout2)) < 0.05);
  376. for (runs = 0; runs < 50; runs++) {
  377. int build_times_idx = 0;
  378. int total_build_times = 0;
  379. final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  380. estimate.close_ms = estimate.timeout_ms
  381. = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  382. for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
  383. circuit_build_times_network_circ_success(&estimate);
  384. circuit_build_times_add_time(&estimate,
  385. circuit_build_times_generate_sample(&estimate, 0,
  386. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  387. circuit_build_times_network_circ_success(&estimate);
  388. circuit_build_times_add_time(&final,
  389. circuit_build_times_generate_sample(&final, 0,
  390. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  391. }
  392. tt_assert(!circuit_build_times_network_check_changed(&estimate));
  393. tt_assert(!circuit_build_times_network_check_changed(&final));
  394. /* Reset liveness to be non-live */
  395. final.liveness.network_last_live = 0;
  396. estimate.liveness.network_last_live = 0;
  397. build_times_idx = estimate.build_times_idx;
  398. total_build_times = estimate.total_build_times;
  399. tt_assert(circuit_build_times_network_check_live(&estimate));
  400. tt_assert(circuit_build_times_network_check_live(&final));
  401. circuit_build_times_count_close(&estimate, 0,
  402. (time_t)(approx_time()-estimate.close_ms/1000.0-1));
  403. circuit_build_times_count_close(&final, 0,
  404. (time_t)(approx_time()-final.close_ms/1000.0-1));
  405. tt_assert(!circuit_build_times_network_check_live(&estimate));
  406. tt_assert(!circuit_build_times_network_check_live(&final));
  407. log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
  408. build_times_idx, estimate.build_times_idx,
  409. total_build_times, estimate.total_build_times);
  410. /* Check rollback index. Should match top of loop. */
  411. tt_assert(build_times_idx == estimate.build_times_idx);
  412. // This can fail if estimate.total_build_times == 1000, because
  413. // in that case, rewind actually causes us to lose timeouts
  414. if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
  415. tt_assert(total_build_times == estimate.total_build_times);
  416. /* Now simulate that the network has become live and we need
  417. * a change */
  418. circuit_build_times_network_is_live(&estimate);
  419. circuit_build_times_network_is_live(&final);
  420. for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
  421. circuit_build_times_count_timeout(&estimate, 1);
  422. if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
  423. circuit_build_times_count_timeout(&final, 1);
  424. }
  425. }
  426. tt_int_op(estimate.liveness.after_firsthop_idx, OP_EQ, 0);
  427. tt_assert(final.liveness.after_firsthop_idx ==
  428. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
  429. tt_assert(circuit_build_times_network_check_live(&estimate));
  430. tt_assert(circuit_build_times_network_check_live(&final));
  431. circuit_build_times_count_timeout(&final, 1);
  432. /* Ensure return value for degenerate cases are clamped correctly */
  433. initial.alpha = INT32_MAX;
  434. tt_assert(circuit_build_times_calculate_timeout(&initial, .99999999) <=
  435. INT32_MAX);
  436. initial.alpha = 0;
  437. tt_assert(circuit_build_times_calculate_timeout(&initial, .5) <=
  438. INT32_MAX);
  439. }
  440. done:
  441. circuit_build_times_free_timeouts(&initial);
  442. circuit_build_times_free_timeouts(&estimate);
  443. circuit_build_times_free_timeouts(&final);
  444. or_state_free(state);
  445. teardown_periodic_events();
  446. UNMOCK(crypto_rand);
  447. crypto_cipher_free(crypto_rand_aes_cipher);
  448. }
  449. /** Test encoding and parsing of rendezvous service descriptors. */
  450. static void
  451. test_rend_fns(void *arg)
  452. {
  453. rend_service_descriptor_t *generated = NULL, *parsed = NULL;
  454. char service_id[DIGEST_LEN];
  455. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  456. const char *next_desc;
  457. smartlist_t *descs = smartlist_new();
  458. char computed_desc_id[DIGEST_LEN];
  459. char parsed_desc_id[DIGEST_LEN];
  460. crypto_pk_t *pk1 = NULL, *pk2 = NULL;
  461. time_t now;
  462. char *intro_points_encrypted = NULL;
  463. size_t intro_points_size;
  464. size_t encoded_size;
  465. int i;
  466. (void)arg;
  467. /* Initialize the service cache. */
  468. rend_cache_init();
  469. pk1 = pk_generate(0);
  470. pk2 = pk_generate(1);
  471. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  472. generated->pk = crypto_pk_dup_key(pk1);
  473. crypto_pk_get_digest(generated->pk, service_id);
  474. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  475. service_id, REND_SERVICE_ID_LEN);
  476. now = time(NULL);
  477. generated->timestamp = now;
  478. generated->version = 2;
  479. generated->protocols = 42;
  480. generated->intro_nodes = smartlist_new();
  481. for (i = 0; i < 3; i++) {
  482. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  483. crypto_pk_t *okey = pk_generate(2 + i);
  484. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  485. intro->extend_info->onion_key = okey;
  486. crypto_pk_get_digest(intro->extend_info->onion_key,
  487. intro->extend_info->identity_digest);
  488. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  489. intro->extend_info->nickname[0] = '$';
  490. base16_encode(intro->extend_info->nickname + 1,
  491. sizeof(intro->extend_info->nickname) - 1,
  492. intro->extend_info->identity_digest, DIGEST_LEN);
  493. /* Does not cover all IP addresses. */
  494. tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
  495. intro->extend_info->port = 1 + crypto_rand_int(65535);
  496. intro->intro_key = crypto_pk_dup_key(pk2);
  497. smartlist_add(generated->intro_nodes, intro);
  498. }
  499. int rv = rend_encode_v2_descriptors(descs, generated, now, 0,
  500. REND_NO_AUTH, NULL, NULL);
  501. tt_int_op(rv, OP_GT, 0);
  502. rv = rend_compute_v2_desc_id(computed_desc_id, service_id_base32, NULL,
  503. now, 0);
  504. tt_int_op(rv, OP_EQ, 0);
  505. tt_mem_op(((rend_encoded_v2_service_descriptor_t *)
  506. smartlist_get(descs, 0))->desc_id, OP_EQ,
  507. computed_desc_id, DIGEST_LEN);
  508. rv = rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  509. &intro_points_encrypted, &intro_points_size, &encoded_size,
  510. &next_desc,
  511. ((rend_encoded_v2_service_descriptor_t *)smartlist_get(descs, 0))
  512. ->desc_str, 1);
  513. tt_int_op(rv, OP_EQ, 0);
  514. tt_assert(parsed);
  515. tt_mem_op(((rend_encoded_v2_service_descriptor_t *)
  516. smartlist_get(descs, 0))->desc_id,OP_EQ, parsed_desc_id, DIGEST_LEN);
  517. tt_int_op(rend_parse_introduction_points(parsed, intro_points_encrypted,
  518. intro_points_size),OP_EQ, 3);
  519. tt_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  520. tt_int_op(parsed->timestamp,OP_EQ, now);
  521. tt_int_op(parsed->version,OP_EQ, 2);
  522. tt_int_op(parsed->protocols,OP_EQ, 42);
  523. tt_int_op(smartlist_len(parsed->intro_nodes),OP_EQ, 3);
  524. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  525. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  526. *gen_intro = smartlist_get(generated->intro_nodes, i);
  527. extend_info_t *par_info = par_intro->extend_info;
  528. extend_info_t *gen_info = gen_intro->extend_info;
  529. tt_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  530. tt_mem_op(gen_info->identity_digest,OP_EQ, par_info->identity_digest,
  531. DIGEST_LEN);
  532. tt_str_op(gen_info->nickname,OP_EQ, par_info->nickname);
  533. tt_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
  534. tt_int_op(gen_info->port,OP_EQ, par_info->port);
  535. }
  536. rend_service_descriptor_free(parsed);
  537. rend_service_descriptor_free(generated);
  538. parsed = generated = NULL;
  539. done:
  540. if (descs) {
  541. for (i = 0; i < smartlist_len(descs); i++)
  542. rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
  543. smartlist_free(descs);
  544. }
  545. if (parsed)
  546. rend_service_descriptor_free(parsed);
  547. if (generated)
  548. rend_service_descriptor_free(generated);
  549. if (pk1)
  550. crypto_pk_free(pk1);
  551. if (pk2)
  552. crypto_pk_free(pk2);
  553. tor_free(intro_points_encrypted);
  554. }
  555. /** Run unit tests for stats code. */
  556. static void
  557. test_stats(void *arg)
  558. {
  559. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  560. char *s = NULL;
  561. int i;
  562. /* Start with testing exit port statistics; we shouldn't collect exit
  563. * stats without initializing them. */
  564. (void)arg;
  565. rep_hist_note_exit_stream_opened(80);
  566. rep_hist_note_exit_bytes(80, 100, 10000);
  567. s = rep_hist_format_exit_stats(now + 86400);
  568. tt_ptr_op(s, OP_EQ, NULL);
  569. /* Initialize stats, note some streams and bytes, and generate history
  570. * string. */
  571. rep_hist_exit_stats_init(now);
  572. rep_hist_note_exit_stream_opened(80);
  573. rep_hist_note_exit_bytes(80, 100, 10000);
  574. rep_hist_note_exit_stream_opened(443);
  575. rep_hist_note_exit_bytes(443, 100, 10000);
  576. rep_hist_note_exit_bytes(443, 100, 10000);
  577. s = rep_hist_format_exit_stats(now + 86400);
  578. tt_str_op("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  579. "exit-kibibytes-written 80=1,443=1,other=0\n"
  580. "exit-kibibytes-read 80=10,443=20,other=0\n"
  581. "exit-streams-opened 80=4,443=4,other=0\n",OP_EQ, s);
  582. tor_free(s);
  583. /* Add a few bytes on 10 more ports and ensure that only the top 10
  584. * ports are contained in the history string. */
  585. for (i = 50; i < 60; i++) {
  586. rep_hist_note_exit_bytes(i, i, i);
  587. rep_hist_note_exit_stream_opened(i);
  588. }
  589. s = rep_hist_format_exit_stats(now + 86400);
  590. tt_str_op("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  591. "exit-kibibytes-written 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  592. "59=1,80=1,443=1,other=1\n"
  593. "exit-kibibytes-read 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  594. "59=1,80=10,443=20,other=1\n"
  595. "exit-streams-opened 52=4,53=4,54=4,55=4,56=4,57=4,58=4,"
  596. "59=4,80=4,443=4,other=4\n",OP_EQ, s);
  597. tor_free(s);
  598. /* Stop collecting stats, add some bytes, and ensure we don't generate
  599. * a history string. */
  600. rep_hist_exit_stats_term();
  601. rep_hist_note_exit_bytes(80, 100, 10000);
  602. s = rep_hist_format_exit_stats(now + 86400);
  603. tt_ptr_op(s, OP_EQ, NULL);
  604. /* Re-start stats, add some bytes, reset stats, and see what history we
  605. * get when observing no streams or bytes at all. */
  606. rep_hist_exit_stats_init(now);
  607. rep_hist_note_exit_stream_opened(80);
  608. rep_hist_note_exit_bytes(80, 100, 10000);
  609. rep_hist_reset_exit_stats(now);
  610. s = rep_hist_format_exit_stats(now + 86400);
  611. tt_str_op("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  612. "exit-kibibytes-written other=0\n"
  613. "exit-kibibytes-read other=0\n"
  614. "exit-streams-opened other=0\n",OP_EQ, s);
  615. tor_free(s);
  616. /* Continue with testing connection statistics; we shouldn't collect
  617. * conn stats without initializing them. */
  618. rep_hist_note_or_conn_bytes(1, 20, 400, now);
  619. s = rep_hist_format_conn_stats(now + 86400);
  620. tt_ptr_op(s, OP_EQ, NULL);
  621. /* Initialize stats, note bytes, and generate history string. */
  622. rep_hist_conn_stats_init(now);
  623. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  624. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  625. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  626. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  627. s = rep_hist_format_conn_stats(now + 86400);
  628. tt_str_op("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,1,0\n",OP_EQ, s);
  629. tor_free(s);
  630. /* Stop collecting stats, add some bytes, and ensure we don't generate
  631. * a history string. */
  632. rep_hist_conn_stats_term();
  633. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  634. s = rep_hist_format_conn_stats(now + 86400);
  635. tt_ptr_op(s, OP_EQ, NULL);
  636. /* Re-start stats, add some bytes, reset stats, and see what history we
  637. * get when observing no bytes at all. */
  638. rep_hist_conn_stats_init(now);
  639. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  640. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  641. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  642. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  643. rep_hist_reset_conn_stats(now);
  644. s = rep_hist_format_conn_stats(now + 86400);
  645. tt_str_op("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,0,0\n",OP_EQ, s);
  646. tor_free(s);
  647. /* Continue with testing buffer statistics; we shouldn't collect buffer
  648. * stats without initializing them. */
  649. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  650. s = rep_hist_format_buffer_stats(now + 86400);
  651. tt_ptr_op(s, OP_EQ, NULL);
  652. /* Initialize stats, add statistics for a single circuit, and generate
  653. * the history string. */
  654. rep_hist_buffer_stats_init(now);
  655. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  656. s = rep_hist_format_buffer_stats(now + 86400);
  657. tt_str_op("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  658. "cell-processed-cells 20,0,0,0,0,0,0,0,0,0\n"
  659. "cell-queued-cells 2.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  660. "0.00,0.00\n"
  661. "cell-time-in-queue 2,0,0,0,0,0,0,0,0,0\n"
  662. "cell-circuits-per-decile 1\n",OP_EQ, s);
  663. tor_free(s);
  664. /* Add nineteen more circuit statistics to the one that's already in the
  665. * history to see that the math works correctly. */
  666. for (i = 21; i < 30; i++)
  667. rep_hist_add_buffer_stats(2.0, 2.0, i);
  668. for (i = 20; i < 30; i++)
  669. rep_hist_add_buffer_stats(3.5, 3.5, i);
  670. s = rep_hist_format_buffer_stats(now + 86400);
  671. tt_str_op("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  672. "cell-processed-cells 29,28,27,26,25,24,23,22,21,20\n"
  673. "cell-queued-cells 2.75,2.75,2.75,2.75,2.75,2.75,2.75,2.75,"
  674. "2.75,2.75\n"
  675. "cell-time-in-queue 3,3,3,3,3,3,3,3,3,3\n"
  676. "cell-circuits-per-decile 2\n",OP_EQ, s);
  677. tor_free(s);
  678. /* Stop collecting stats, add statistics for one circuit, and ensure we
  679. * don't generate a history string. */
  680. rep_hist_buffer_stats_term();
  681. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  682. s = rep_hist_format_buffer_stats(now + 86400);
  683. tt_ptr_op(s, OP_EQ, NULL);
  684. /* Re-start stats, add statistics for one circuit, reset stats, and make
  685. * sure that the history has all zeros. */
  686. rep_hist_buffer_stats_init(now);
  687. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  688. rep_hist_reset_buffer_stats(now);
  689. s = rep_hist_format_buffer_stats(now + 86400);
  690. tt_str_op("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  691. "cell-processed-cells 0,0,0,0,0,0,0,0,0,0\n"
  692. "cell-queued-cells 0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  693. "0.00,0.00\n"
  694. "cell-time-in-queue 0,0,0,0,0,0,0,0,0,0\n"
  695. "cell-circuits-per-decile 0\n",OP_EQ, s);
  696. done:
  697. tor_free(s);
  698. }
  699. #define ENT(name) \
  700. { #name, test_ ## name , 0, NULL, NULL }
  701. #define FORK(name) \
  702. { #name, test_ ## name , TT_FORK, NULL, NULL }
  703. static struct testcase_t test_array[] = {
  704. ENT(onion_handshake),
  705. { "bad_onion_handshake", test_bad_onion_handshake, 0, NULL, NULL },
  706. ENT(onion_queues),
  707. { "ntor_handshake", test_ntor_handshake, 0, NULL, NULL },
  708. { "fast_handshake", test_fast_handshake, 0, NULL, NULL },
  709. FORK(circuit_timeout),
  710. FORK(rend_fns),
  711. FORK(stats),
  712. END_OF_TESTCASES
  713. };
  714. struct testgroup_t testgroups[] = {
  715. { "", test_array },
  716. { "accounting/", accounting_tests },
  717. { "addr/", addr_tests },
  718. { "address/", address_tests },
  719. { "address_set/", address_set_tests },
  720. { "bridges/", bridges_tests },
  721. { "buffer/", buffer_tests },
  722. { "bwmgt/", bwmgt_tests },
  723. { "cellfmt/", cell_format_tests },
  724. { "cellqueue/", cell_queue_tests },
  725. { "channel/", channel_tests },
  726. { "channelpadding/", channelpadding_tests },
  727. { "channeltls/", channeltls_tests },
  728. { "checkdir/", checkdir_tests },
  729. { "circuitbuild/", circuitbuild_tests },
  730. { "circuitlist/", circuitlist_tests },
  731. { "circuitmux/", circuitmux_tests },
  732. { "circuituse/", circuituse_tests },
  733. { "circuitstats/", circuitstats_tests },
  734. { "compat/libevent/", compat_libevent_tests },
  735. { "config/", config_tests },
  736. { "connection/", connection_tests },
  737. { "conscache/", conscache_tests },
  738. { "consdiff/", consdiff_tests },
  739. { "consdiffmgr/", consdiffmgr_tests },
  740. { "container/", container_tests },
  741. { "control/", controller_tests },
  742. { "control/event/", controller_event_tests },
  743. { "crypto/", crypto_tests },
  744. { "crypto/openssl/", crypto_openssl_tests },
  745. { "dir/", dir_tests },
  746. { "dir_handle_get/", dir_handle_get_tests },
  747. { "dir/md/", microdesc_tests },
  748. { "dos/", dos_tests },
  749. { "entryconn/", entryconn_tests },
  750. { "entrynodes/", entrynodes_tests },
  751. { "guardfraction/", guardfraction_tests },
  752. { "extorport/", extorport_tests },
  753. { "geoip/", geoip_tests },
  754. { "legacy_hs/", hs_tests },
  755. { "hs_cache/", hs_cache },
  756. { "hs_cell/", hs_cell_tests },
  757. { "hs_common/", hs_common_tests },
  758. { "hs_config/", hs_config_tests },
  759. { "hs_control/", hs_control_tests },
  760. { "hs_descriptor/", hs_descriptor },
  761. { "hs_ntor/", hs_ntor_tests },
  762. { "hs_service/", hs_service_tests },
  763. { "hs_client/", hs_client_tests },
  764. { "hs_intropoint/", hs_intropoint_tests },
  765. { "introduce/", introduce_tests },
  766. { "keypin/", keypin_tests },
  767. { "link-handshake/", link_handshake_tests },
  768. { "nodelist/", nodelist_tests },
  769. { "oom/", oom_tests },
  770. { "oos/", oos_tests },
  771. { "options/", options_tests },
  772. { "periodic-event/" , periodic_event_tests },
  773. { "policy/" , policy_tests },
  774. { "procmon/", procmon_tests },
  775. { "proto/http/", proto_http_tests },
  776. { "proto/misc/", proto_misc_tests },
  777. { "protover/", protover_tests },
  778. { "pt/", pt_tests },
  779. { "relay/" , relay_tests },
  780. { "relaycell/", relaycell_tests },
  781. { "relaycrypt/", relaycrypt_tests },
  782. { "rend_cache/", rend_cache_tests },
  783. { "replaycache/", replaycache_tests },
  784. { "router/", router_tests },
  785. { "routerkeys/", routerkeys_tests },
  786. { "routerlist/", routerlist_tests },
  787. { "routerset/" , routerset_tests },
  788. { "scheduler/", scheduler_tests },
  789. { "socks/", socks_tests },
  790. { "shared-random/", sr_tests },
  791. { "status/" , status_tests },
  792. { "storagedir/", storagedir_tests },
  793. { "tortls/", tortls_tests },
  794. { "util/", util_tests },
  795. { "util/format/", util_format_tests },
  796. { "util/logging/", logging_tests },
  797. { "util/process/", util_process_tests },
  798. { "util/pubsub/", pubsub_tests },
  799. { "util/thread/", thread_tests },
  800. { "util/handle/", handle_tests },
  801. { "dns/", dns_tests },
  802. END_OF_GROUPS
  803. };