test.c 44.1 KB
Newer Older
1
2
/* Copyright (c) 2001-2004, Roger Dingledine.
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
Nick Mathewson's avatar
Nick Mathewson committed
3
 * Copyright (c) 2007-2016, The Tor Project, Inc. */
4
5
/* See LICENSE for licensing information */

6
7
8
9
10
/**
 * \file test.c
 * \brief Unit tests for many pieces of the lower level Tor modules.
 **/

Nick Mathewson's avatar
Nick Mathewson committed
11
#include "orconfig.h"
12

13
#include <stdio.h>
14
#ifdef HAVE_FCNTL_H
15
#include <fcntl.h>
16
17
#endif

18
#ifdef _WIN32
19
20
/* For mkdir() */
#include <direct.h>
Nick Mathewson's avatar
Nick Mathewson committed
21
#else
22
#include <dirent.h>
Nick Mathewson's avatar
Nick Mathewson committed
23
24
#endif

25
26
#include <math.h>

27
28
/* These macros pull in declarations for some functions and structures that
 * are typically file-private. */
29
#define GEOIP_PRIVATE
30
#define ROUTER_PRIVATE
31
#define CIRCUITSTATS_PRIVATE
32
#define CIRCUITLIST_PRIVATE
33
#define MAIN_PRIVATE
34
#define STATEFILE_PRIVATE
35

Nick Mathewson's avatar
Nick Mathewson committed
36
#include "or.h"
37
#include "backtrace.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
38
#include "buffers.h"
39
#include "circuitlist.h"
40
#include "circuitstats.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
41
#include "config.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
42
#include "connection_edge.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
43
#include "geoip.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
44
#include "rendcommon.h"
45
#include "rendcache.h"
46
47
#include "test.h"
#include "torgzip.h"
48
#include "main.h"
49
#include "memarea.h"
50
#include "onion.h"
51
#include "onion_ntor.h"
52
#include "onion_fast.h"
53
#include "onion_tap.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
54
#include "policies.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
55
#include "rephist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
56
#include "routerparse.h"
57
#include "statefile.h"
58
59
#include "crypto_curve25519.h"
#include "onion_ntor.h"
Nick Mathewson's avatar
Nick Mathewson committed
60

61
/** Run unit tests for the onion handshake code. */
62
static void
63
test_onion_handshake(void *arg)
Nick Mathewson's avatar
Nick Mathewson committed
64
{
65
  /* client-side */
66
  crypto_dh_t *c_dh = NULL;
67
  char c_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
68
69
  char c_keys[40];
  /* server-side */
70
  char s_buf[TAP_ONIONSKIN_REPLY_LEN];
71
  char s_keys[40];
72
  int i;
73
  /* shared */
74
  crypto_pk_t *pk = NULL, *pk2 = NULL;
75

76
  (void)arg;
77
  pk = pk_generate(0);
78
  pk2 = pk_generate(1);
79
80

  /* client handshake 1. */
81
  memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
82
  tt_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
83

84
85
86
87
88
89
90
91
92
93
94
95
  for (i = 1; i <= 3; ++i) {
    crypto_pk_t *k1, *k2;
    if (i==1) {
      /* server handshake: only one key known. */
      k1 = pk;  k2 = NULL;
    } else if (i==2) {
      /* server handshake: try the right key first. */
      k1 = pk;  k2 = pk2;
    } else {
      /* server handshake: try the right key second. */
      k1 = pk2; k2 = pk;
    }
Roger Dingledine's avatar
Roger Dingledine committed
96

97
98
    memset(s_buf, 0, TAP_ONIONSKIN_REPLY_LEN);
    memset(s_keys, 0, 40);
99
    tt_assert(! onion_skin_TAP_server_handshake(c_buf, k1, k2,
100
                                                  s_buf, s_keys, 40));
Roger Dingledine's avatar
Roger Dingledine committed
101

102
103
    /* client handshake 2 */
    memset(c_keys, 0, 40);
Sebastian Hahn's avatar
Sebastian Hahn committed
104
105
    tt_assert(! onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys,
                                                40, NULL));
106

107
    tt_mem_op(c_keys,OP_EQ, s_keys, 40);
108
    memset(s_buf, 0, 40);
109
    tt_mem_op(c_keys,OP_NE, s_buf, 40);
110
  }
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
 done:
  crypto_dh_free(c_dh);
  crypto_pk_free(pk);
  crypto_pk_free(pk2);
}

static void
test_bad_onion_handshake(void *arg)
{
  char junk_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  char junk_buf2[TAP_ONIONSKIN_CHALLENGE_LEN];
  /* client-side */
  crypto_dh_t *c_dh = NULL;
  char c_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  char c_keys[40];
  /* server-side */
  char s_buf[TAP_ONIONSKIN_REPLY_LEN];
  char s_keys[40];
  /* shared */
  crypto_pk_t *pk = NULL, *pk2 = NULL;

  (void)arg;

  pk = pk_generate(0);
  pk2 = pk_generate(1);

  /* Server: Case 1: the encrypted data is degenerate. */
  memset(junk_buf, 0, sizeof(junk_buf));
  crypto_pk_public_hybrid_encrypt(pk, junk_buf2, TAP_ONIONSKIN_CHALLENGE_LEN,
                               junk_buf, DH_KEY_LEN, PK_PKCS1_OAEP_PADDING, 1);
141
  tt_int_op(-1, OP_EQ,
142
143
144
145
146
147
148
149
            onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
                                            s_buf, s_keys, 40));

  /* Server: Case 2: the encrypted data is not long enough. */
  memset(junk_buf, 0, sizeof(junk_buf));
  memset(junk_buf2, 0, sizeof(junk_buf2));
  crypto_pk_public_encrypt(pk, junk_buf2, sizeof(junk_buf2),
                               junk_buf, 48, PK_PKCS1_OAEP_PADDING);
150
  tt_int_op(-1, OP_EQ,
151
152
153
154
155
            onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
                                            s_buf, s_keys, 40));

  /* client handshake 1: do it straight. */
  memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
156
  tt_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
157
158

  /* Server: Case 3: we just don't have the right key. */
159
  tt_int_op(-1, OP_EQ,
160
161
162
163
164
            onion_skin_TAP_server_handshake(c_buf, pk2, NULL,
                                            s_buf, s_keys, 40));

  /* Server: Case 4: The RSA-encrypted portion is corrupt. */
  c_buf[64] ^= 33;
165
  tt_int_op(-1, OP_EQ,
166
167
168
169
170
            onion_skin_TAP_server_handshake(c_buf, pk, NULL,
                                            s_buf, s_keys, 40));
  c_buf[64] ^= 33;

  /* (Let the server procede) */
171
  tt_int_op(0, OP_EQ,
172
173
174
175
            onion_skin_TAP_server_handshake(c_buf, pk, NULL,
                                            s_buf, s_keys, 40));

  /* Client: Case 1: The server sent back junk. */
176
  const char *msg = NULL;
177
  s_buf[64] ^= 33;
178
  tt_int_op(-1, OP_EQ,
179
            onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, &msg));
180
  s_buf[64] ^= 33;
181
182
  tt_str_op(msg, OP_EQ, "Digest DOES NOT MATCH on onion handshake. "
            "Bug or attack.");
183
184

  /* Let the client finish; make sure it can. */
185
  msg = NULL;
186
  tt_int_op(0, OP_EQ,
187
            onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, &msg));
188
  tt_mem_op(s_keys,OP_EQ, c_keys, 40);
189
  tt_ptr_op(msg, OP_EQ, NULL);
190
191
192

  /* Client: Case 2: The server sent back a degenerate DH. */
  memset(s_buf, 0, sizeof(s_buf));
193
  tt_int_op(-1, OP_EQ,
194
195
            onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, &msg));
  tt_str_op(msg, OP_EQ, "DH computation failed.");
196
197

 done:
198
199
200
  crypto_dh_free(c_dh);
  crypto_pk_free(pk);
  crypto_pk_free(pk2);
201
202
}

203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
static void
test_ntor_handshake(void *arg)
{
  /* client-side */
  ntor_handshake_state_t *c_state = NULL;
  uint8_t c_buf[NTOR_ONIONSKIN_LEN];
  uint8_t c_keys[400];

  /* server-side */
  di_digest256_map_t *s_keymap=NULL;
  curve25519_keypair_t s_keypair;
  uint8_t s_buf[NTOR_REPLY_LEN];
  uint8_t s_keys[400];

  /* shared */
  const curve25519_public_key_t *server_pubkey;
  uint8_t node_id[20] = "abcdefghijklmnopqrst";

  (void) arg;

  /* Make the server some keys */
  curve25519_secret_key_generate(&s_keypair.seckey, 0);
  curve25519_public_key_generate(&s_keypair.pubkey, &s_keypair.seckey);
  dimap_add_entry(&s_keymap, s_keypair.pubkey.public_key, &s_keypair);
  server_pubkey = &s_keypair.pubkey;

  /* client handshake 1. */
  memset(c_buf, 0, NTOR_ONIONSKIN_LEN);
231
  tt_int_op(0, OP_EQ, onion_skin_ntor_create(node_id, server_pubkey,
232
233
234
235
236
                                          &c_state, c_buf));

  /* server handshake */
  memset(s_buf, 0, NTOR_REPLY_LEN);
  memset(s_keys, 0, 40);
237
  tt_int_op(0, OP_EQ, onion_skin_ntor_server_handshake(c_buf, s_keymap, NULL,
238
                                                    node_id,
239
240
241
242
                                                    s_buf, s_keys, 400));

  /* client handshake 2 */
  memset(c_keys, 0, 40);
243
  tt_int_op(0, OP_EQ, onion_skin_ntor_client_handshake(c_state, s_buf,
244
                                                       c_keys, 400, NULL));
245

246
  tt_mem_op(c_keys,OP_EQ, s_keys, 400);
247
  memset(s_buf, 0, 40);
248
  tt_mem_op(c_keys,OP_NE, s_buf, 40);
249

250
251
252
253
254
255
256
257
258
  /* Now try with a bogus server response. Zero input should trigger
   * All The Problems. */
  memset(c_keys, 0, 400);
  memset(s_buf, 0, NTOR_REPLY_LEN);
  const char *msg = NULL;
  tt_int_op(-1, OP_EQ, onion_skin_ntor_client_handshake(c_state, s_buf,
                                                        c_keys, 400, &msg));
  tt_str_op(msg, OP_EQ, "Zero output from curve25519 handshake");

259
260
261
262
263
 done:
  ntor_handshake_state_free(c_state);
  dimap_free(s_keymap, NULL);
}

264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
static void
test_fast_handshake(void *arg)
{
  /* tests for the obsolete "CREATE_FAST" handshake. */
  (void) arg;
  fast_handshake_state_t *state = NULL;
  uint8_t client_handshake[CREATE_FAST_LEN];
  uint8_t server_handshake[CREATED_FAST_LEN];
  uint8_t s_keys[100], c_keys[100];

  /* First, test an entire handshake. */
  memset(client_handshake, 0, sizeof(client_handshake));
  tt_int_op(0, OP_EQ, fast_onionskin_create(&state, client_handshake));
  tt_assert(! tor_mem_is_zero((char*)client_handshake,
                              sizeof(client_handshake)));

  tt_int_op(0, OP_EQ,
            fast_server_handshake(client_handshake, server_handshake,
                                  s_keys, 100));
  const char *msg = NULL;
  tt_int_op(0, OP_EQ,
            fast_client_handshake(state, server_handshake, c_keys, 100, &msg));
  tt_ptr_op(msg, OP_EQ, NULL);
  tt_mem_op(s_keys, OP_EQ, c_keys, 100);

  /* Now test a failing handshake. */
  server_handshake[0] ^= 3;
  tt_int_op(-1, OP_EQ,
            fast_client_handshake(state, server_handshake, c_keys, 100, &msg));
  tt_str_op(msg, OP_EQ, "Digest DOES NOT MATCH on fast handshake. "
            "Bug or attack.");

 done:
  fast_handshake_state_free(state);
}

300
301
/** Run unit tests for the onion queues. */
static void
302
test_onion_queues(void *arg)
303
304
305
306
307
308
309
{
  uint8_t buf1[TAP_ONIONSKIN_CHALLENGE_LEN] = {0};
  uint8_t buf2[NTOR_ONIONSKIN_LEN] = {0};

  or_circuit_t *circ1 = or_circuit_new(0, NULL);
  or_circuit_t *circ2 = or_circuit_new(0, NULL);

310
  create_cell_t *onionskin = NULL, *create2_ptr;
311
312
  create_cell_t *create1 = tor_malloc_zero(sizeof(create_cell_t));
  create_cell_t *create2 = tor_malloc_zero(sizeof(create_cell_t));
313
  (void)arg;
314
  create2_ptr = create2; /* remember, but do not free */
315
316
317
318
319
320

  create_cell_init(create1, CELL_CREATE, ONION_HANDSHAKE_TYPE_TAP,
                   TAP_ONIONSKIN_CHALLENGE_LEN, buf1);
  create_cell_init(create2, CELL_CREATE, ONION_HANDSHAKE_TYPE_NTOR,
                   NTOR_ONIONSKIN_LEN, buf2);

321
322
  tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  tt_int_op(0,OP_EQ, onion_pending_add(circ1, create1));
323
  create1 = NULL;
324
  tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
325

326
327
  tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  tt_int_op(0,OP_EQ, onion_pending_add(circ2, create2));
328
  create2 = NULL;
329
  tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
330

331
332
333
334
  tt_ptr_op(circ2,OP_EQ, onion_next_task(&onionskin));
  tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  tt_ptr_op(onionskin, OP_EQ, create2_ptr);
335
336

  clear_pending_onions();
337
338
  tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
339
340

 done:
341
342
343
344
  circuit_free(TO_CIRCUIT(circ1));
  circuit_free(TO_CIRCUIT(circ2));
  tor_free(create1);
  tor_free(create2);
345
  tor_free(onionskin);
346
347
}

348
static void
349
test_circuit_timeout(void *arg)
350
351
352
353
354
355
356
357
358
359
360
361
362
{
  /* Plan:
   *  1. Generate 1000 samples
   *  2. Estimate parameters
   *  3. If difference, repeat
   *  4. Save state
   *  5. load state
   *  6. Estimate parameters
   *  7. compare differences
   */
  circuit_build_times_t initial;
  circuit_build_times_t estimate;
  circuit_build_times_t final;
363
  double timeout1, timeout2;
364
  or_state_t *state=NULL;
365
  int i, runs;
Mike Perry's avatar
Mike Perry committed
366
  double close_ms;
367
  (void)arg;
368

369
370
  initialize_periodic_events();

371
372
373
374
  circuit_build_times_init(&initial);
  circuit_build_times_init(&estimate);
  circuit_build_times_init(&final);

375
  state = or_state_new();
376

377
  circuitbuild_running_unit_tests();
378
#define timeout0 (build_time_t)(30*1000.0)
Mike Perry's avatar
Mike Perry committed
379
  initial.Xm = 3000;
Mike Perry's avatar
Mike Perry committed
380
381
  circuit_build_times_initial_alpha(&initial,
                                    CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
382
                                    timeout0);
Mike Perry's avatar
Mike Perry committed
383
384
385
  close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
                             CBT_DEFAULT_CLOSE_QUANTILE/100.0),
                 CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
386
  do {
Mike Perry's avatar
Mike Perry committed
387
    for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
Mike Perry's avatar
Mike Perry committed
388
389
390
391
392
393
      build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);

      if (sample > close_ms) {
        circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
      } else {
        circuit_build_times_add_time(&estimate, sample);
394
395
396
397
      }
    }
    circuit_build_times_update_alpha(&estimate);
    timeout1 = circuit_build_times_calculate_timeout(&estimate,
Mike Perry's avatar
Mike Perry committed
398
                                  CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
399
    circuit_build_times_set_timeout(&estimate);
400
    log_notice(LD_CIRC, "Timeout1 is %f, Xm is %d", timeout1, estimate.Xm);
Mike Perry's avatar
Mike Perry committed
401
           /* 2% error */
402
  } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
Mike Perry's avatar
Mike Perry committed
403
                circuit_build_times_cdf(&initial, timeout1)) > 0.02);
404

405
  tt_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
406

407
408
  circuit_build_times_update_state(&estimate, state);
  circuit_build_times_free_timeouts(&final);
409
  tt_assert(circuit_build_times_parse_state(&final, state) == 0);
410
411
412

  circuit_build_times_update_alpha(&final);
  timeout2 = circuit_build_times_calculate_timeout(&final,
Mike Perry's avatar
Mike Perry committed
413
                                 CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
414
415

  circuit_build_times_set_timeout(&final);
416
  log_notice(LD_CIRC, "Timeout2 is %f, Xm is %d", timeout2, final.Xm);
417

418
  /* 5% here because some accuracy is lost due to histogram conversion */
419
  tt_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
420
                   circuit_build_times_cdf(&initial, timeout2)) < 0.05);
421

422
423
424
425
  for (runs = 0; runs < 50; runs++) {
    int build_times_idx = 0;
    int total_build_times = 0;

426
427
428
    final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
    estimate.close_ms = estimate.timeout_ms
                      = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
429

Mike Perry's avatar
Mike Perry committed
430
    for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
431
432
433
      circuit_build_times_network_circ_success(&estimate);
      circuit_build_times_add_time(&estimate,
            circuit_build_times_generate_sample(&estimate, 0,
Mike Perry's avatar
Mike Perry committed
434
                CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
435

436
437
438
      circuit_build_times_network_circ_success(&estimate);
      circuit_build_times_add_time(&final,
            circuit_build_times_generate_sample(&final, 0,
Mike Perry's avatar
Mike Perry committed
439
                CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
440
    }
441

442
443
    tt_assert(!circuit_build_times_network_check_changed(&estimate));
    tt_assert(!circuit_build_times_network_check_changed(&final));
444
445
446
447
448
449
450
451

    /* Reset liveness to be non-live */
    final.liveness.network_last_live = 0;
    estimate.liveness.network_last_live = 0;

    build_times_idx = estimate.build_times_idx;
    total_build_times = estimate.total_build_times;

452
453
    tt_assert(circuit_build_times_network_check_live(&estimate));
    tt_assert(circuit_build_times_network_check_live(&final));
454

455
456
457
458
    circuit_build_times_count_close(&estimate, 0,
            (time_t)(approx_time()-estimate.close_ms/1000.0-1));
    circuit_build_times_count_close(&final, 0,
            (time_t)(approx_time()-final.close_ms/1000.0-1));
459

460
461
    tt_assert(!circuit_build_times_network_check_live(&estimate));
    tt_assert(!circuit_build_times_network_check_live(&final));
462
463
464
465
466
467

    log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
             build_times_idx, estimate.build_times_idx,
             total_build_times, estimate.total_build_times);

    /* Check rollback index. Should match top of loop. */
468
    tt_assert(build_times_idx == estimate.build_times_idx);
469
470
471
    // This can fail if estimate.total_build_times == 1000, because
    // in that case, rewind actually causes us to lose timeouts
    if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
472
      tt_assert(total_build_times == estimate.total_build_times);
473
474
475
476
477
478

    /* Now simulate that the network has become live and we need
     * a change */
    circuit_build_times_network_is_live(&estimate);
    circuit_build_times_network_is_live(&final);

Mike Perry's avatar
Mike Perry committed
479
    for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
480
      circuit_build_times_count_timeout(&estimate, 1);
481

Mike Perry's avatar
Mike Perry committed
482
      if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
483
        circuit_build_times_count_timeout(&final, 1);
484
485
486
      }
    }

487
488
    tt_assert(estimate.liveness.after_firsthop_idx == 0);
    tt_assert(final.liveness.after_firsthop_idx ==
Mike Perry's avatar
Mike Perry committed
489
                CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
490

491
492
    tt_assert(circuit_build_times_network_check_live(&estimate));
    tt_assert(circuit_build_times_network_check_live(&final));
493

494
    circuit_build_times_count_timeout(&final, 1);
Sebastian Hahn's avatar
Sebastian Hahn committed
495
496
497
498
499
500
501
502

    /* Ensure return value for degenerate cases are clamped correctly */
    initial.alpha = INT32_MAX;
    tt_assert(circuit_build_times_calculate_timeout(&initial, .99999999) <=
              INT32_MAX);
    initial.alpha = 0;
    tt_assert(circuit_build_times_calculate_timeout(&initial, .5) <=
              INT32_MAX);
503
  }
504

Sebastian Hahn's avatar
Sebastian Hahn committed
505
 done:
506
507
508
509
  circuit_build_times_free_timeouts(&initial);
  circuit_build_times_free_timeouts(&estimate);
  circuit_build_times_free_timeouts(&final);
  or_state_free(state);
510
  teardown_periodic_events();
511
512
}

513
/** Test encoding and parsing of rendezvous service descriptors. */
514
static void
515
test_rend_fns(void *arg)
516
{
517
  rend_service_descriptor_t *generated = NULL, *parsed = NULL;
518
  char service_id[DIGEST_LEN];
519
  char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
520
  const char *next_desc;
521
  smartlist_t *descs = smartlist_new();
522
523
  char computed_desc_id[DIGEST_LEN];
  char parsed_desc_id[DIGEST_LEN];
524
  crypto_pk_t *pk1 = NULL, *pk2 = NULL;
525
  time_t now;
526
  char *intro_points_encrypted = NULL;
527
528
529
  size_t intro_points_size;
  size_t encoded_size;
  int i;
530
531
532
533
  char address1[] = "fooaddress.onion";
  char address2[] = "aaaaaaaaaaaaaaaa.onion";
  char address3[] = "fooaddress.exit";
  char address4[] = "www.torproject.org";
534
535
536
  char address5[] = "foo.abcdefghijklmnop.onion";
  char address6[] = "foo.bar.abcdefghijklmnop.onion";
  char address7[] = ".abcdefghijklmnop.onion";
537

538
  (void)arg;
539
540
  tt_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
  tt_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
541
  tt_str_op(address2,OP_EQ, "aaaaaaaaaaaaaaaa");
542
543
544
  tt_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
  tt_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
  tt_assert(ONION_HOSTNAME == parse_extended_hostname(address5));
545
  tt_str_op(address5,OP_EQ, "abcdefghijklmnop");
546
  tt_assert(ONION_HOSTNAME == parse_extended_hostname(address6));
547
  tt_str_op(address6,OP_EQ, "abcdefghijklmnop");
548
  tt_assert(BAD_HOSTNAME == parse_extended_hostname(address7));
549

550
551
552
  /* Initialize the service cache. */
  rend_cache_init();

553
554
555
556
557
  pk1 = pk_generate(0);
  pk2 = pk_generate(1);
  generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  generated->pk = crypto_pk_dup_key(pk1);
  crypto_pk_get_digest(generated->pk, service_id);
558
559
  base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
                service_id, REND_SERVICE_ID_LEN);
560
561
562
563
  now = time(NULL);
  generated->timestamp = now;
  generated->version = 2;
  generated->protocols = 42;
564
  generated->intro_nodes = smartlist_new();
565

566
567
  for (i = 0; i < 3; i++) {
    rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
568
    crypto_pk_t *okey = pk_generate(2 + i);
569
    intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
Nick Mathewson's avatar
Nick Mathewson committed
570
    intro->extend_info->onion_key = okey;
571
572
    crypto_pk_get_digest(intro->extend_info->onion_key,
                         intro->extend_info->identity_digest);
573
    //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
574
575
576
577
    intro->extend_info->nickname[0] = '$';
    base16_encode(intro->extend_info->nickname + 1,
                  sizeof(intro->extend_info->nickname) - 1,
                  intro->extend_info->identity_digest, DIGEST_LEN);
578
579
    /* Does not cover all IP addresses. */
    tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
580
    intro->extend_info->port = 1 + crypto_rand_int(65535);
581
    intro->intro_key = crypto_pk_dup_key(pk2);
582
    smartlist_add(generated->intro_nodes, intro);
583
  }
584
  tt_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
585
                                         REND_NO_AUTH, NULL, NULL) > 0);
586
  tt_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
587
                                      NULL, now, 0) == 0);
588
  tt_mem_op(((rend_encoded_v2_service_descriptor_t *)
589
             smartlist_get(descs, 0))->desc_id, OP_EQ,
590
            computed_desc_id, DIGEST_LEN);
591
  tt_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
592
593
594
595
596
597
                                             &intro_points_encrypted,
                                             &intro_points_size,
                                             &encoded_size,
                                              &next_desc,
                             ((rend_encoded_v2_service_descriptor_t *)
                                 smartlist_get(descs, 0))->desc_str, 1) == 0);
598
599
  tt_assert(parsed);
  tt_mem_op(((rend_encoded_v2_service_descriptor_t *)
Nick Mathewson's avatar
Nick Mathewson committed
600
         smartlist_get(descs, 0))->desc_id,OP_EQ, parsed_desc_id, DIGEST_LEN);
601
  tt_int_op(rend_parse_introduction_points(parsed, intro_points_encrypted,
602
                                         intro_points_size),OP_EQ, 3);
603
  tt_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
604
605
606
607
  tt_int_op(parsed->timestamp,OP_EQ, now);
  tt_int_op(parsed->version,OP_EQ, 2);
  tt_int_op(parsed->protocols,OP_EQ, 42);
  tt_int_op(smartlist_len(parsed->intro_nodes),OP_EQ, 3);
608
609
610
611
612
  for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
    rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
      *gen_intro = smartlist_get(generated->intro_nodes, i);
    extend_info_t *par_info = par_intro->extend_info;
    extend_info_t *gen_info = gen_intro->extend_info;
613
    tt_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
614
    tt_mem_op(gen_info->identity_digest,OP_EQ, par_info->identity_digest,
615
               DIGEST_LEN);
616
    tt_str_op(gen_info->nickname,OP_EQ, par_info->nickname);
617
    tt_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
618
    tt_int_op(gen_info->port,OP_EQ, par_info->port);
619
  }
620

621
622
623
624
  rend_service_descriptor_free(parsed);
  rend_service_descriptor_free(generated);
  parsed = generated = NULL;

625
 done:
626
627
628
629
630
631
632
633
634
635
  if (descs) {
    for (i = 0; i < smartlist_len(descs); i++)
      rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
    smartlist_free(descs);
  }
  if (parsed)
    rend_service_descriptor_free(parsed);
  if (generated)
    rend_service_descriptor_free(generated);
  if (pk1)
636
    crypto_pk_free(pk1);
Nick Mathewson's avatar
Nick Mathewson committed
637
  if (pk2)
638
    crypto_pk_free(pk2);
639
  tor_free(intro_points_encrypted);
640
641
}

642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
  /* Record odd numbered fake-IPs using ipv6, even numbered fake-IPs
   * using ipv4.  Since our fake geoip database is the same between
   * ipv4 and ipv6, we should get the same result no matter which
   * address family we pick for each IP. */
#define SET_TEST_ADDRESS(i) do {                \
    if ((i) & 1) {                              \
      SET_TEST_IPV6(i);                         \
      tor_addr_from_in6(&addr, &in6);           \
    } else {                                    \
      tor_addr_from_ipv4h(&addr, (uint32_t) i); \
    }                                           \
  } while (0)

  /* Make sure that country ID actually works. */
#define SET_TEST_IPV6(i) \
  do {                                                          \
    set_uint32(in6.s6_addr + 12, htonl((uint32_t) (i)));        \
  } while (0)
#define CHECK_COUNTRY(country, val) do {                                \
    /* test ipv4 country lookup */                                      \
662
    tt_str_op(country, OP_EQ,                                              \
663
664
665
               geoip_get_country_name(geoip_get_country_by_ipv4(val))); \
    /* test ipv6 country lookup */                                      \
    SET_TEST_IPV6(val);                                                 \
666
    tt_str_op(country, OP_EQ,                                              \
667
668
669
               geoip_get_country_name(geoip_get_country_by_ipv6(&in6))); \
  } while (0)

670
/** Run unit tests for GeoIP code. */
671
static void
672
test_geoip(void *arg)
673
674
{
  int i, j;
675
  time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
676
  char *s = NULL, *v = NULL;
Karsten Loesing's avatar
Karsten Loesing committed
677
678
  const char *bridge_stats_1 =
      "bridge-stats-end 2010-08-12 13:27:30 (86400 s)\n"
679
      "bridge-ips zz=24,xy=8\n"
680
681
      "bridge-ip-versions v4=16,v6=16\n"
      "bridge-ip-transports <OR>=24\n",
Karsten Loesing's avatar
Karsten Loesing committed
682
  *dirreq_stats_1 =
683
684
685
686
687
688
      "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
      "dirreq-v3-ips ab=8\n"
      "dirreq-v3-reqs ab=8\n"
      "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
          "not-modified=0,busy=0\n"
      "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
689
      "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
690
691
692
693
694
695
696
  *dirreq_stats_2 =
      "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
      "dirreq-v3-ips \n"
      "dirreq-v3-reqs \n"
      "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
          "not-modified=0,busy=0\n"
      "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
697
      "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
698
699
700
701
702
703
704
  *dirreq_stats_3 =
      "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
      "dirreq-v3-ips \n"
      "dirreq-v3-reqs \n"
      "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
          "not-modified=0,busy=0\n"
      "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
705
      "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
706
707
708
709
710
711
712
  *dirreq_stats_4 =
      "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
      "dirreq-v3-ips \n"
      "dirreq-v3-reqs \n"
      "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
          "not-modified=0,busy=0\n"
      "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
713
      "dirreq-v3-tunneled-dl complete=0,timeout=0,running=4\n",
714
715
716
717
718
719
  *entry_stats_1 =
      "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
      "entry-ips ab=8\n",
  *entry_stats_2 =
      "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
      "entry-ips \n";
720
  tor_addr_t addr;
nils's avatar
nils committed
721
  struct in6_addr in6;
722
723
724
725

  /* Populate the DB a bit.  Add these in order, since we can't do the final
   * 'sort' step.  These aren't very good IP addresses, but they're perfectly
   * fine uint32_t values. */
726
  (void)arg;
727
728
729
730
731
732
  tt_int_op(0,OP_EQ, geoip_parse_entry("10,50,AB", AF_INET));
  tt_int_op(0,OP_EQ, geoip_parse_entry("52,90,XY", AF_INET));
  tt_int_op(0,OP_EQ, geoip_parse_entry("95,100,AB", AF_INET));
  tt_int_op(0,OP_EQ, geoip_parse_entry("\"105\",\"140\",\"ZZ\"", AF_INET));
  tt_int_op(0,OP_EQ, geoip_parse_entry("\"150\",\"190\",\"XY\"", AF_INET));
  tt_int_op(0,OP_EQ, geoip_parse_entry("\"200\",\"250\",\"AB\"", AF_INET));
733

nils's avatar
nils committed
734
  /* Populate the IPv6 DB equivalently with fake IPs in the same range */
735
736
737
738
739
740
  tt_int_op(0,OP_EQ, geoip_parse_entry("::a,::32,AB", AF_INET6));
  tt_int_op(0,OP_EQ, geoip_parse_entry("::34,::5a,XY", AF_INET6));
  tt_int_op(0,OP_EQ, geoip_parse_entry("::5f,::64,AB", AF_INET6));
  tt_int_op(0,OP_EQ, geoip_parse_entry("::69,::8c,ZZ", AF_INET6));
  tt_int_op(0,OP_EQ, geoip_parse_entry("::96,::be,XY", AF_INET6));
  tt_int_op(0,OP_EQ, geoip_parse_entry("::c8,::fa,AB", AF_INET6));
741

742
  /* We should have 4 countries: ??, ab, xy, zz. */
743
  tt_int_op(4,OP_EQ, geoip_get_n_countries());
nils's avatar
nils committed
744
745
746
747
748
749
750
751
752
753
  memset(&in6, 0, sizeof(in6));

  CHECK_COUNTRY("??", 3);
  CHECK_COUNTRY("ab", 32);
  CHECK_COUNTRY("??", 5);
  CHECK_COUNTRY("??", 51);
  CHECK_COUNTRY("xy", 150);
  CHECK_COUNTRY("xy", 190);
  CHECK_COUNTRY("??", 2000);

754
  tt_int_op(0,OP_EQ, geoip_get_country_by_ipv4(3));
nils's avatar
nils committed
755
  SET_TEST_IPV6(3);
756
  tt_int_op(0,OP_EQ, geoip_get_country_by_ipv6(&in6));
nils's avatar
nils committed
757

758
759
  get_options_mutable()->BridgeRelay = 1;
  get_options_mutable()->BridgeRecordUsageByCountry = 1;
760
  /* Put 9 observations in AB... */
761
  for (i=32; i < 40; ++i) {
nils's avatar
nils committed
762
    SET_TEST_ADDRESS(i);
763
    geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-7200);
764
  }
765
  SET_TEST_ADDRESS(225);
766
  geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-7200);
767
768
  /* and 3 observations in XY, several times. */
  for (j=0; j < 10; ++j)
769
    for (i=52; i < 55; ++i) {
nils's avatar
nils committed
770
      SET_TEST_ADDRESS(i);
771
      geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-3600);
772
    }
773
  /* and 17 observations in ZZ... */
774
  for (i=110; i < 127; ++i) {
nils's avatar
nils committed
775
    SET_TEST_ADDRESS(i);
776
    geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
777
  }
778
  geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
779
780
  tt_assert(s);
  tt_assert(v);
781
782
  tt_str_op("zz=24,ab=16,xy=8",OP_EQ, s);
  tt_str_op("v4=16,v6=16",OP_EQ, v);
783
  tor_free(s);
784
  tor_free(v);
785

786
  /* Now clear out all the AB observations. */
787
  geoip_remove_old_clients(now-6000);
788
  geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
789
790
  tt_assert(s);
  tt_assert(v);
791
792
  tt_str_op("zz=24,xy=8",OP_EQ, s);
  tt_str_op("v4=16,v6=16",OP_EQ, v);
793
794
  tor_free(s);
  tor_free(v);
795

Karsten Loesing's avatar
Karsten Loesing committed
796
797
798
  /* Start testing bridge statistics by making sure that we don't output
   * bridge stats without initializing them. */
  s = geoip_format_bridge_stats(now + 86400);
799
  tt_assert(!s);
Karsten Loesing's avatar
Karsten Loesing committed
800
801
802
803
804

  /* Initialize stats and generate the bridge-stats history string out of
   * the connecting clients added above. */
  geoip_bridge_stats_init(now);
  s = geoip_format_bridge_stats(now + 86400);
805
  tt_assert(s);
806
  tt_str_op(bridge_stats_1,OP_EQ, s);
Karsten Loesing's avatar
Karsten Loesing committed
807
808
809
810
811
812
  tor_free(s);

  /* Stop collecting bridge stats and make sure we don't write a history
   * string anymore. */
  geoip_bridge_stats_term();
  s = geoip_format_bridge_stats(now + 86400);
813
  tt_assert(!s);
Karsten Loesing's avatar
Karsten Loesing committed
814

815
816
  /* Stop being a bridge and start being a directory mirror that gathers
   * directory request statistics. */
817
  geoip_bridge_stats_term();
818
819
820
821
822
823
  get_options_mutable()->BridgeRelay = 0;
  get_options_mutable()->BridgeRecordUsageByCountry = 0;
  get_options_mutable()->DirReqStatistics = 1;

  /* Start testing dirreq statistics by making sure that we don't collect
   * dirreq stats without initializing them. */
nils's avatar
nils committed
824
  SET_TEST_ADDRESS(100);
825
  geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
826
  s = geoip_format_dirreq_stats(now + 86400);
827
  tt_assert(!s);
828
829
830
831

  /* Initialize stats, note one connecting client, and generate the
   * dirreq-stats history string. */
  geoip_dirreq_stats_init(now);
nils's avatar
nils committed
832
  SET_TEST_ADDRESS(100);
833
  geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
834
  s = geoip_format_dirreq_stats(now + 86400);
835
  tt_str_op(dirreq_stats_1,OP_EQ, s);
836
837
838
839
840
  tor_free(s);

  /* Stop collecting stats, add another connecting client, and ensure we
   * don't generate a history string. */
  geoip_dirreq_stats_term();
nils's avatar
nils committed
841
  SET_TEST_ADDRESS(101);
842
  geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
843
  s = geoip_format_dirreq_stats(now + 86400);
844
  tt_assert(!s);
845
846
847
848

  /* Re-start stats, add a connecting client, reset stats, and make sure
   * that we get an all empty history string. */
  geoip_dirreq_stats_init(now);
nils's avatar
nils committed
849
  SET_TEST_ADDRESS(100);
850
  geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
851
852
  geoip_reset_dirreq_stats(now);
  s = geoip_format_dirreq_stats(now + 86400);
853
  tt_str_op(dirreq_stats_2,OP_EQ, s);
854
855
856
857
  tor_free(s);

  /* Note a successful network status response and make sure that it
   * appears in the history string. */
858
  geoip_note_ns_response(GEOIP_SUCCESS);
859
  s = geoip_format_dirreq_stats(now + 86400);
860
  tt_str_op(dirreq_stats_3,OP_EQ, s);
861
862
863
  tor_free(s);

  /* Start a tunneled directory request. */
864
  geoip_start_dirreq((uint64_t) 1, 1024, DIRREQ_TUNNELED);
865
  s = geoip_format_dirreq_stats(now + 86400);
866
  tt_str_op(dirreq_stats_4,OP_EQ, s);
Nick Mathewson's avatar
Nick Mathewson committed
867
  tor_free(s);
868

869
870
871
872
873
874
875
876
  /* Stop collecting directory request statistics and start gathering
   * entry stats. */
  geoip_dirreq_stats_term();
  get_options_mutable()->DirReqStatistics = 0;
  get_options_mutable()->EntryStatistics = 1;

  /* Start testing entry statistics by making sure that we don't collect
   * anything without initializing entry stats. */
nils's avatar
nils committed
877
  SET_TEST_ADDRESS(100);
878
  geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
879
  s = geoip_format_entry_stats(now + 86400);
880
  tt_assert(!s);
881
882
883
884

  /* Initialize stats, note one connecting client, and generate the
   * entry-stats history string. */
  geoip_entry_stats_init(now);
nils's avatar
nils committed
885
  SET_TEST_ADDRESS(100);
886
  geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
887
  s = geoip_format_entry_stats(now + 86400);
888
  tt_str_op(entry_stats_1,OP_EQ, s);
889
890
891
892
893
  tor_free(s);

  /* Stop collecting stats, add another connecting client, and ensure we
   * don't generate a history string. */
  geoip_entry_stats_term();
nils's avatar
nils committed
894
  SET_TEST_ADDRESS(101);
895
  geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
896
  s = geoip_format_entry_stats(now + 86400);
897
  tt_assert(!s);
898
899
900
901

  /* Re-start stats, add a connecting client, reset stats, and make sure
   * that we get an all empty history string. */
  geoip_entry_stats_init(now);
nils's avatar
nils committed
902
  SET_TEST_ADDRESS(100);
903
  geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
904
905
  geoip_reset_entry_stats(now);
  s = geoip_format_entry_stats(now + 86400);
906
  tt_str_op(entry_stats_2,OP_EQ, s);
907
908
  tor_free(s);

909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
  /* Test the OOM handler. Add a client, run the OOM. */
  geoip_entry_stats_init(now);
  SET_TEST_ADDRESS(100);
  geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL,
                         now - (12 * 60 * 60));
  /* We've seen this 12 hours ago. Run the OOM, it should clean the entry
   * because it is above the minimum cutoff of 4 hours. */
  size_t bytes_removed = geoip_client_cache_handle_oom(now, 1000);
  tt_size_op(bytes_removed, OP_GT, 0);

  /* Do it again but this time with an entry with a lower cutoff. */
  geoip_entry_stats_init(now);
  SET_TEST_ADDRESS(100);
  geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL,
                         now - (3 * 60 * 60));
  bytes_removed = geoip_client_cache_handle_oom(now, 1000);
  tt_size_op(bytes_removed, OP_EQ, 0);

927
928
929
930
  /* Stop collecting entry statistics. */
  geoip_entry_stats_term();
  get_options_mutable()->EntryStatistics = 0;