rendservice.c 47.2 KB
Newer Older
1
2
/* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
 * Copyright (c) 2007, The Tor Project, Inc. */
Nick Mathewson's avatar
Nick Mathewson committed
3
4
/* See LICENSE for licensing information */
/* $Id$ */
5
6
const char rendservice_c_id[] =
  "$Id$";
Nick Mathewson's avatar
Nick Mathewson committed
7

Roger Dingledine's avatar
Roger Dingledine committed
8
9
10
11
/**
 * \file rendservice.c
 * \brief The hidden-service side of rendezvous functionality.
 **/
Nick Mathewson's avatar
Nick Mathewson committed
12
13
14

#include "or.h"

15
16
static origin_circuit_t *find_intro_circuit(routerinfo_t *router,
                                            const char *pk_digest);
17

Roger Dingledine's avatar
Roger Dingledine committed
18
/** Represents the mapping from a virtual port of a rendezvous service to
Nick Mathewson's avatar
Nick Mathewson committed
19
20
21
22
23
 * a real port on some IP.
 */
typedef struct rend_service_port_config_t {
  uint16_t virtual_port;
  uint16_t real_port;
24
  uint32_t real_addr;
Nick Mathewson's avatar
Nick Mathewson committed
25
26
} rend_service_port_config_t;

Roger Dingledine's avatar
Roger Dingledine committed
27
/** Try to maintain this many intro points per service if possible. */
Nick Mathewson's avatar
Nick Mathewson committed
28
29
#define NUM_INTRO_POINTS 3

30
/** If we can't build our intro circuits, don't retry for this long. */
31
#define INTRO_CIRC_RETRY_PERIOD (60*5)
32
33
/** Don't try to build more than this many circuits before giving up
 * for a while.*/
34
#define MAX_INTRO_CIRCS_PER_PERIOD 10
35
36
/** How many times will a hidden service operator attempt to connect to
 * a requested rendezvous point before giving up? */
37
38
39
40
#define MAX_REND_FAILURES 30
/** How many seconds should we spend trying to connect to a requested
 * rendezvous point before giving up? */
#define MAX_REND_TIMEOUT 30
41

Roger Dingledine's avatar
Roger Dingledine committed
42
/** Represents a single hidden service running at this OP. */
Nick Mathewson's avatar
Nick Mathewson committed
43
typedef struct rend_service_t {
Roger Dingledine's avatar
Roger Dingledine committed
44
45
46
47
48
  /** Fields specified in config file */
  char *directory; /**< where in the filesystem it stores it */
  smartlist_t *ports; /**< List of rend_service_port_config_t */
  char *intro_prefer_nodes; /**< comma-separated list of nicknames */
  char *intro_exclude_nodes; /**< comma-separated list of nicknames */
Nick Mathewson's avatar
Nick Mathewson committed
49
50
  /* Other fields */
  crypto_pk_env_t *private_key;
51
  char service_id[REND_SERVICE_ID_LEN_BASE32+1];
52
  char pk_digest[DIGEST_LEN];
Roger Dingledine's avatar
Roger Dingledine committed
53
  smartlist_t *intro_nodes; /**< list of hexdigests for intro points we have,
54
                             * or are trying to establish. */
55
56
  strmap_t *intro_keys; /**< map from intro node hexdigest to key; only
                          * used for versioned hidden service descriptors. */
57
58
59
  time_t intro_period_started;
  int n_intro_circuits_launched; /**< count of intro circuits we have
                                  * established in this period. */
60
  /* DOCDOC undocumented versions */
Nick Mathewson's avatar
Nick Mathewson committed
61
  rend_service_descriptor_t *desc;
62
  time_t desc_is_dirty;
63
  time_t next_upload_time;
Roger Dingledine's avatar
Roger Dingledine committed
64
  int descriptor_version; /**< Rendezvous descriptor version that will be
65
                           * published. */
Nick Mathewson's avatar
Nick Mathewson committed
66
67
} rend_service_t;

Roger Dingledine's avatar
Roger Dingledine committed
68
/** A list of rend_service_t's for services run on this OP.
Nick Mathewson's avatar
Nick Mathewson committed
69
70
71
 */
static smartlist_t *rend_service_list = NULL;

72
/** Return the number of rendezvous services we have configured. */
73
74
75
int
num_rend_services(void)
{
76
77
78
79
80
  if (!rend_service_list)
    return 0;
  return smartlist_len(rend_service_list);
}

81
/** Helper: Release the storage held by the intro key in <b>_ent</b>.
82
83
84
85
86
87
88
89
 */
static void
intro_key_free(void *_ent)
{
  crypto_pk_env_t *ent = _ent;
  crypto_free_pk_env(ent);
}

Nick Mathewson's avatar
Nick Mathewson committed
90
/** Release the storage held by <b>service</b>.
91
 */
92
93
static void
rend_service_free(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
94
{
95
96
97
98
99
100
  if (!service) return;
  tor_free(service->directory);
  SMARTLIST_FOREACH(service->ports, void*, p, tor_free(p));
  smartlist_free(service->ports);
  if (service->private_key)
    crypto_free_pk_env(service->private_key);
101
102
  if (service->intro_keys)
    strmap_free(service->intro_keys, intro_key_free);
103
104
105
106
107
108
109
  tor_free(service->intro_prefer_nodes);
  tor_free(service->intro_exclude_nodes);
  SMARTLIST_FOREACH(service->intro_nodes, void*, p, tor_free(p));
  smartlist_free(service->intro_nodes);
  if (service->desc)
    rend_service_descriptor_free(service->desc);
  tor_free(service);
Nick Mathewson's avatar
Nick Mathewson committed
110
111
}

Roger Dingledine's avatar
Roger Dingledine committed
112
/** Release all the storage held in rend_service_list.
113
 */
114
115
void
rend_service_free_all(void)
Nick Mathewson's avatar
Nick Mathewson committed
116
117
118
119
{
  if (!rend_service_list) {
    return;
  }
Nick Mathewson's avatar
Nick Mathewson committed
120
121
  SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
                    rend_service_free(ptr));
Nick Mathewson's avatar
Nick Mathewson committed
122
  smartlist_free(rend_service_list);
123
  rend_service_list = NULL;
Nick Mathewson's avatar
Nick Mathewson committed
124
125
}

Nick Mathewson's avatar
Nick Mathewson committed
126
/** Validate <b>service</b> and add it to rend_service_list if possible.
127
 */
128
static void
Roger Dingledine's avatar
Roger Dingledine committed
129
rend_add_service(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
130
131
132
133
134
{
  int i;
  rend_service_port_config_t *p;
  struct in_addr addr;

Nick Mathewson's avatar
Nick Mathewson committed
135
136
137
138
  if (!service->intro_prefer_nodes)
    service->intro_prefer_nodes = tor_strdup("");
  if (!service->intro_exclude_nodes)
    service->intro_exclude_nodes = tor_strdup("");
139
  service->intro_nodes = smartlist_create();
140
  service->intro_keys = strmap_new();
Nick Mathewson's avatar
Nick Mathewson committed
141

142
143
  /* If the service is configured to publish unversioned (v0) and versioned
   * descriptors (v2 or higher), split it up into two separate services. */
144
  if (service->descriptor_version == -1) {
145
146
147
148
149
150
151
152
153
154
155
156
157
    rend_service_t *v0_service = tor_malloc_zero(sizeof(rend_service_t));
    v0_service->directory = tor_strdup(service->directory);
    v0_service->ports = smartlist_create();
    SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p, {
      rend_service_port_config_t *copy =
        tor_malloc_zero(sizeof(rend_service_port_config_t));
      memcpy(copy, p, sizeof(rend_service_port_config_t));
      smartlist_add(v0_service->ports, copy);
    });
    v0_service->intro_nodes = smartlist_create();
    v0_service->intro_prefer_nodes = tor_strdup(service->intro_prefer_nodes);
    v0_service->intro_exclude_nodes = tor_strdup(service->intro_exclude_nodes);
    v0_service->intro_period_started = service->intro_period_started;
158
    v0_service->descriptor_version = 0; /* Unversioned descriptor. */
Roger Dingledine's avatar
Roger Dingledine committed
159
    rend_add_service(v0_service);
160

161
    service->descriptor_version = 2; /* Versioned descriptor. */
162
163
  }

Nick Mathewson's avatar
Nick Mathewson committed
164
  if (!smartlist_len(service->ports)) {
165
    log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
Nick Mathewson's avatar
Nick Mathewson committed
166
167
    rend_service_free(service);
  } else {
Nick Mathewson's avatar
Nick Mathewson committed
168
    smartlist_set_capacity(service->ports, -1);
Nick Mathewson's avatar
Nick Mathewson committed
169
    smartlist_add(rend_service_list, service);
170
171
    log_debug(LD_REND,"Configuring service with directory \"%s\"",
              service->directory);
Nick Mathewson's avatar
Nick Mathewson committed
172
    for (i = 0; i < smartlist_len(service->ports); ++i) {
173
      char addrbuf[INET_NTOA_BUF_LEN];
Nick Mathewson's avatar
Nick Mathewson committed
174
      p = smartlist_get(service->ports, i);
175
      addr.s_addr = htonl(p->real_addr);
176
      tor_inet_ntoa(&addr, addrbuf, sizeof(addrbuf));
177
178
      log_debug(LD_REND,"Service maps port %d to %s:%d",
                p->virtual_port, addrbuf, p->real_port);
Nick Mathewson's avatar
Nick Mathewson committed
179
180
181
182
    }
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
183
/** Parses a real-port to virtual-port mapping and returns a new
184
185
186
 * rend_service_port_config_t.
 *
 * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
Nick Mathewson's avatar
Nick Mathewson committed
187
188
 *
 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
Nick Mathewson's avatar
Nick Mathewson committed
189
 */
190
191
static rend_service_port_config_t *
parse_port_config(const char *string)
Nick Mathewson's avatar
Nick Mathewson committed
192
{
193
  smartlist_t *sl;
194
  int virtport;
195
196
  int realport;
  uint16_t p;
197
  uint32_t addr;
198
199
200
201
  const char *addrport;
  rend_service_port_config_t *result = NULL;

  sl = smartlist_create();
202
203
  smartlist_split_string(sl, string, " ",
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
204
  if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
205
    log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
206
    goto err;
Nick Mathewson's avatar
Nick Mathewson committed
207
  }
208
209

  virtport = atoi(smartlist_get(sl,0));
Nick Mathewson's avatar
Nick Mathewson committed
210
  if (virtport < 1 || virtport > 65535) {
211
212
    log_warn(LD_CONFIG, "Missing or invalid port in hidden service port "
             "configuration.");
213
    goto err;
Nick Mathewson's avatar
Nick Mathewson committed
214
  }
215
216

  if (smartlist_len(sl) == 1) {
Nick Mathewson's avatar
Nick Mathewson committed
217
218
    /* No addr:port part; use default. */
    realport = virtport;
219
220
    addr = 0x7F000001u; /* 127.0.0.1 */
  } else {
221
222
    addrport = smartlist_get(sl,1);
    if (strchr(addrport, ':') || strchr(addrport, '.')) {
223
      if (parse_addr_port(LOG_WARN, addrport, NULL, &addr, &p)<0) {
224
225
        log_warn(LD_CONFIG,"Unparseable address in hidden service port "
                 "configuration.");
226
227
228
229
230
231
232
233
234
        goto err;
      }
      realport = p?p:virtport;
    } else {
      /* No addr:port, no addr -- must be port. */
      realport = atoi(addrport);
      if (realport < 1 || realport > 65535)
        goto err;
      addr = 0x7F000001u; /* Default to 127.0.0.1 */
235
    }
Nick Mathewson's avatar
Nick Mathewson committed
236
237
238
239
240
  }

  result = tor_malloc(sizeof(rend_service_port_config_t));
  result->virtual_port = virtport;
  result->real_port = realport;
241
  result->real_addr = addr;
242
243
244
 err:
  SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  smartlist_free(sl);
Nick Mathewson's avatar
Nick Mathewson committed
245
246
247
  return result;
}

Roger Dingledine's avatar
Roger Dingledine committed
248
/** Set up rend_service_list, based on the values of HiddenServiceDir and
Nick Mathewson's avatar
Nick Mathewson committed
249
 * HiddenServicePort in <b>options</b>.  Return 0 on success and -1 on
250
251
 * failure.  (If <b>validate_only</b> is set, parse, warn and return as
 * normal, but don't actually change the configured services.)
Nick Mathewson's avatar
Nick Mathewson committed
252
 */
253
254
int
rend_config_services(or_options_t *options, int validate_only)
Nick Mathewson's avatar
Nick Mathewson committed
255
{
256
  config_line_t *line;
Nick Mathewson's avatar
Nick Mathewson committed
257
258
  rend_service_t *service = NULL;
  rend_service_port_config_t *portcfg;
259

260
  if (!validate_only) {
261
    rend_service_free_all();
262
263
    rend_service_list = smartlist_create();
  }
Nick Mathewson's avatar
Nick Mathewson committed
264
265
266

  for (line = options->RendConfigLines; line; line = line->next) {
    if (!strcasecmp(line->key, "HiddenServiceDir")) {
267
268
269
270
      if (service) {
        if (validate_only)
          rend_service_free(service);
        else
Roger Dingledine's avatar
Roger Dingledine committed
271
          rend_add_service(service);
272
      }
Nick Mathewson's avatar
Nick Mathewson committed
273
274
275
      service = tor_malloc_zero(sizeof(rend_service_t));
      service->directory = tor_strdup(line->value);
      service->ports = smartlist_create();
Nick Mathewson's avatar
Nick Mathewson committed
276
      service->intro_nodes = smartlist_create();
277
      service->intro_period_started = time(NULL);
278
      service->descriptor_version = -1; /**< All descriptor versions. */
279
280
281
      continue;
    }
    if (!service) {
282
283
      log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
               line->key);
284
285
286
287
      rend_service_free(service);
      return -1;
    }
    if (!strcasecmp(line->key, "HiddenServicePort")) {
Nick Mathewson's avatar
Nick Mathewson committed
288
289
      portcfg = parse_port_config(line->value);
      if (!portcfg) {
Roger Dingledine's avatar
tabs    
Roger Dingledine committed
290
291
        rend_service_free(service);
        return -1;
Nick Mathewson's avatar
Nick Mathewson committed
292
293
      }
      smartlist_add(service->ports, portcfg);
294
    } else if (!strcasecmp(line->key, "HiddenServiceNodes")) {
Nick Mathewson's avatar
Nick Mathewson committed
295
      if (service->intro_prefer_nodes) {
296
297
298
        log_warn(LD_CONFIG,
                 "Got multiple HiddenServiceNodes lines for a single "
                 "service.");
299
300
        return -1;
      }
Nick Mathewson's avatar
Nick Mathewson committed
301
      service->intro_prefer_nodes = tor_strdup(line->value);
302
    } else if (!strcasecmp(line->key, "HiddenServiceExcludeNodes")) {
303
      if (service->intro_exclude_nodes) {
304
305
306
        log_warn(LD_CONFIG,
                 "Got multiple HiddenServiceExcludedNodes lines for "
                 "a single service.");
307
308
309
        return -1;
      }
      service->intro_exclude_nodes = tor_strdup(line->value);
310
311
312
    } else {
      smartlist_t *versions;
      char *version_str;
313
      int i, version, versions_bitmask = 0;
314
315
316
317
318
319
320
321
322
323
324
325
      tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
      versions = smartlist_create();
      smartlist_split_string(versions, line->value, ",",
                             SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
      for (i = 0; i < smartlist_len(versions); i++) {
        version_str = smartlist_get(versions, i);
        if (strlen(version_str) != 1 || strspn(version_str, "02") != 1) {
          log_warn(LD_CONFIG,
                   "HiddenServiceVersion can only be 0 and/or 2.");
          return -1;
        }
        version = atoi(version_str);
326
        versions_bitmask |= 1 << version;
327
      }
Roger Dingledine's avatar
Roger Dingledine committed
328
      /* If exactly one version is set, change descriptor_version to that
Roger Dingledine's avatar
Roger Dingledine committed
329
       * value; otherwise leave it at -1. */
330
331
      if (versions_bitmask == 1 << 0) service->descriptor_version = 0;
      if (versions_bitmask == 1 << 2) service->descriptor_version = 2;
Nick Mathewson's avatar
Nick Mathewson committed
332
333
    }
  }
334
335
336
337
  if (service) {
    if (validate_only)
      rend_service_free(service);
    else
Roger Dingledine's avatar
Roger Dingledine committed
338
      rend_add_service(service);
339
  }
Nick Mathewson's avatar
Nick Mathewson committed
340
341
342
343

  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
344
/** Replace the old value of <b>service</b>-\>desc with one that reflects
Nick Mathewson's avatar
Nick Mathewson committed
345
 * the other fields in service.
Nick Mathewson's avatar
Nick Mathewson committed
346
 */
347
348
static void
rend_service_update_descriptor(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
349
350
{
  rend_service_descriptor_t *d;
351
  origin_circuit_t *circ;
Nick Mathewson's avatar
Nick Mathewson committed
352
  int i,n;
353
  routerinfo_t *router;
Nick Mathewson's avatar
Nick Mathewson committed
354
355
356
357
  if (service->desc) {
    rend_service_descriptor_free(service->desc);
    service->desc = NULL;
  }
358
  d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
Nick Mathewson's avatar
Nick Mathewson committed
359
360
  d->pk = crypto_pk_dup_key(service->private_key);
  d->timestamp = time(NULL);
361
  d->version = service->descriptor_version;
362
363
  n = smartlist_len(service->intro_nodes);
  d->n_intro_points = 0;
364
365
  d->intro_points = tor_malloc_zero(sizeof(char*)*n);
  d->intro_point_extend_info = tor_malloc_zero(sizeof(extend_info_t*)*n);
366
367
368
  /* XXXX020 Why should we support the old intro protocol 0? Whoever
   * understands descriptor version 2 also understands intro protocol 2. */
  d->protocols = 1 << 2; /*< We only support intro protocol 2. */
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385

  if (service->intro_keys) {
    /* We need to copy keys so that they're not deleted when we free the
     * descriptor. */
    strmap_iter_t *iter;
    d->intro_keys = strmap_new();
    for (iter = strmap_iter_init(service->intro_keys); !strmap_iter_done(iter);
         iter = strmap_iter_next(service->intro_keys, iter)) {
      const char *key;
      void *val;
      crypto_pk_env_t *k;
      strmap_iter_get(iter, &key, &val);
      k = val;
      strmap_set(d->intro_keys, key, crypto_pk_dup_key(k));
    }
  }

Nick Mathewson's avatar
Nick Mathewson committed
386
  for (i=0; i < n; ++i) {
387
388
    const char *name = smartlist_get(service->intro_nodes, i);
    router = router_get_by_nickname(name, 1);
389
    if (!router) {
390
      log_info(LD_REND,"Router '%s' not found for intro point %d. Skipping.",
391
               safe_str(name), i);
392
393
      continue;
    }
394
    circ = find_intro_circuit(router, service->pk_digest);
395
    if (circ && circ->_base.purpose == CIRCUIT_PURPOSE_S_INTRO) {
396
      /* We have an entirely established intro circuit. */
397
      d->intro_points[d->n_intro_points] = tor_strdup(name);
398
399
400
      d->intro_point_extend_info[d->n_intro_points] =
        extend_info_from_router(router);
      d->n_intro_points++;
401
    }
Nick Mathewson's avatar
Nick Mathewson committed
402
403
404
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
405
/** Load and/or generate private keys for all hidden services.  Return 0 on
Nick Mathewson's avatar
Nick Mathewson committed
406
407
 * success, -1 on failure.
 */
408
409
int
rend_service_load_keys(void)
Nick Mathewson's avatar
Nick Mathewson committed
410
411
412
413
414
415
{
  int i;
  rend_service_t *s;
  char fname[512];
  char buf[128];

Nick Mathewson's avatar
Nick Mathewson committed
416
417
  for (i=0; i < smartlist_len(rend_service_list); ++i) {
    s = smartlist_get(rend_service_list,i);
Nick Mathewson's avatar
Nick Mathewson committed
418
419
    if (s->private_key)
      continue;
420
421
    log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
             s->directory);
Nick Mathewson's avatar
Nick Mathewson committed
422

Nick Mathewson's avatar
Nick Mathewson committed
423
    /* Check/create directory */
424
    if (check_private_dir(s->directory, CPD_CREATE) < 0)
Nick Mathewson's avatar
Nick Mathewson committed
425
426
427
      return -1;

    /* Load key */
428
    if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
429
430
        strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
                                                  >= sizeof(fname)) {
431
432
      log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
               s->directory);
Nick Mathewson's avatar
Nick Mathewson committed
433
434
      return -1;
    }
435
    s->private_key = init_key_from_file(fname, 1, LOG_ERR);
Nick Mathewson's avatar
Nick Mathewson committed
436
437
438
439
440
    if (!s->private_key)
      return -1;

    /* Create service file */
    if (rend_get_service_id(s->private_key, s->service_id)<0) {
441
      log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
Nick Mathewson's avatar
Nick Mathewson committed
442
443
      return -1;
    }
444
    if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
445
      log_warn(LD_BUG, "Couldn't compute hash of public key.");
446
447
      return -1;
    }
448
    if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
449
450
        strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
                                                  >= sizeof(fname)) {
451
452
      log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
               " \"%s\".", s->directory);
Nick Mathewson's avatar
Nick Mathewson committed
453
454
      return -1;
    }
455
    tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
456
    if (write_str_to_file(fname,buf,0)<0)
Nick Mathewson's avatar
Nick Mathewson committed
457
458
459
460
      return -1;
  }
  return 0;
}
461

462
/** Return the service whose public key has a digest of <b>digest</b> and
463
464
 * which publishes the given descriptor <b>version</b>.  Return NULL if no
 * such service exists.
465
 */
466
static rend_service_t *
467
rend_service_get_by_pk_digest_and_version(const char* digest,
468
                                          uint8_t version)
469
{
Nick Mathewson's avatar
Nick Mathewson committed
470
  SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
471
                    if (!memcmp(s->pk_digest,digest,DIGEST_LEN) &&
472
                        s->descriptor_version == version) return s);
473
474
475
  return NULL;
}

476
477
478
479
/** Return 1 if any virtual port in <b>service</b> wants a circuit
 * to have good uptime. Else return 0.
 */
static int
480
481
rend_service_requires_uptime(rend_service_t *service)
{
482
483
484
485
486
  int i;
  rend_service_port_config_t *p;

  for (i=0; i < smartlist_len(service->ports); ++i) {
    p = smartlist_get(service->ports, i);
487
488
    if (smartlist_string_num_isin(get_options()->LongLivedPorts,
                                  p->virtual_port))
489
490
491
492
493
      return 1;
  }
  return 0;
}

494
495
496
497
/******
 * Handle cells
 ******/

Roger Dingledine's avatar
Roger Dingledine committed
498
/** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
499
 * rendezvous point.
500
 */
501
int
502
rend_service_introduce(origin_circuit_t *circuit, const char *request,
503
                       size_t request_len)
504
{
505
506
  char *ptr, *r_cookie;
  extend_info_t *extend_info = NULL;
507
  char buf[RELAY_PAYLOAD_SIZE];
508
  char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
509
  rend_service_t *service;
510
  int r, i;
511
  size_t len, keylen;
512
  crypto_dh_env_t *dh = NULL;
513
  origin_circuit_t *launched = NULL;
514
  crypt_path_t *cpath = NULL;
515
  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
Nick Mathewson's avatar
Nick Mathewson committed
516
  char hexcookie[9];
517
  int circ_needs_uptime;
518
  int reason = END_CIRC_REASON_TORPROTOCOL;
519
520
  crypto_pk_env_t *intro_key;
  char intro_key_digest[DIGEST_LEN];
Nick Mathewson's avatar
Nick Mathewson committed
521

522
523
  base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
                circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
524
  log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
525
           escaped(serviceid), circuit->_base.n_circ_id);
526

527
  if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
528
529
    log_warn(LD_PROTOCOL,
             "Got an INTRODUCE2 over a non-introduction circuit %d.",
530
             circuit->_base.n_circ_id);
531
532
533
    return -1;
  }

534
  /* min key length plus digest length plus nickname length */
535
  if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
536
      DH_KEY_LEN+42) {
537
    log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
538
             circuit->_base.n_circ_id);
539
540
541
    return -1;
  }

542
543
544
  /* look up service depending on circuit. */
  service = rend_service_get_by_pk_digest_and_version(
              circuit->rend_pk_digest, circuit->rend_desc_version);
545
  if (!service) {
546
    log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
547
             escaped(serviceid));
548
549
    return -1;
  }
550

551
552
  /* if descriptor version is 2, use intro key instead of service key. */
  if (circuit->rend_desc_version == 0) {
553
554
555
556
557
558
559
560
    intro_key = service->private_key;
  } else {
    intro_key = circuit->intro_key;
  }

  /* first DIGEST_LEN bytes of request is intro or service pk digest */
  crypto_pk_get_digest(intro_key, intro_key_digest);
  if (memcmp(intro_key_digest, request, DIGEST_LEN)) {
561
562
    base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
                  request, REND_SERVICE_ID_LEN);
563
    log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
564
             escaped(serviceid));
565
566
567
    return -1;
  }

568
  keylen = crypto_pk_keysize(intro_key);
569
  if (request_len < keylen+DIGEST_LEN) {
570
571
    log_warn(LD_PROTOCOL,
             "PK-encrypted portion of INTRODUCE2 cell was truncated.");
572
573
574
    return -1;
  }
  /* Next N bytes is encrypted with service key */
575
  note_crypto_pk_op(REND_SERVER);
576
  r = crypto_pk_private_hybrid_decrypt(
577
       intro_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
578
       PK_PKCS1_OAEP_PADDING,1);
579
  if (r<0) {
580
    log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
581
582
    return -1;
  }
583
  len = r;
584
585
586
587
588
589
590
591
592
593
594
595
  if (*buf == 2) {
    /* Version 2 INTRODUCE2 cell. */
    int klen;
    extend_info = tor_malloc_zero(sizeof(extend_info_t));
    extend_info->addr = ntohl(get_uint32(buf+1));
    extend_info->port = ntohs(get_uint16(buf+5));
    memcpy(extend_info->identity_digest, buf+7, DIGEST_LEN);
    extend_info->nickname[0] = '$';
    base16_encode(extend_info->nickname+1, sizeof(extend_info->nickname)-1,
                  extend_info->identity_digest, DIGEST_LEN);

    klen = ntohs(get_uint16(buf+7+DIGEST_LEN));
596
    if ((int)len != 7+DIGEST_LEN+2+klen+20+128) {
597
598
      log_warn(LD_PROTOCOL, "Bad length %u for version 2 INTRODUCE2 cell.",
               (int)len);
599
      reason = END_CIRC_REASON_TORPROTOCOL;
600
601
602
603
      goto err;
    }
    extend_info->onion_key = crypto_pk_asn1_decode(buf+7+DIGEST_LEN+2, klen);
    if (!extend_info->onion_key) {
604
605
      log_warn(LD_PROTOCOL,
               "Error decoding onion key in version 2 INTRODUCE2 cell.");
606
      reason = END_CIRC_REASON_TORPROTOCOL;
607
608
609
610
      goto err;
    }
    ptr = buf+7+DIGEST_LEN+2+klen;
    len -= 7+DIGEST_LEN+2+klen;
611
  } else {
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
    char *rp_nickname;
    size_t nickname_field_len;
    routerinfo_t *router;
    int version;
    if (*buf == 1) {
      rp_nickname = buf+1;
      nickname_field_len = MAX_HEX_NICKNAME_LEN+1;
      version = 1;
    } else {
      nickname_field_len = MAX_NICKNAME_LEN+1;
      rp_nickname = buf;
      version = 0;
    }
    ptr=memchr(rp_nickname,0,nickname_field_len);
    if (!ptr || ptr == rp_nickname) {
627
      log_warn(LD_PROTOCOL,
628
               "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
629
630
631
632
      return -1;
    }
    if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
        (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
633
      log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
634
635
636
637
638
      return -1;
    }
    /* Okay, now we know that a nickname is at the start of the buffer. */
    ptr = rp_nickname+nickname_field_len;
    len -= nickname_field_len;
639
640
    len -= rp_nickname - buf; /* also remove header space used by version, if
                               * any */
641
    router = router_get_by_nickname(rp_nickname, 0);
642
    if (!router) {
Roger Dingledine's avatar
Roger Dingledine committed
643
      log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
644
               escaped_safe_str(rp_nickname));
645
646
      /* XXXX Add a no-such-router reason? */
      reason = END_CIRC_REASON_TORPROTOCOL;
647
648
649
650
      goto err;
    }

    extend_info = extend_info_from_router(router);
651
  }
652

653
  if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
654
    log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
655
    reason = END_CIRC_REASON_TORPROTOCOL;
656
657
    return -1;
  }
658

659
  r_cookie = ptr;
660
  base16_encode(hexcookie,9,r_cookie,4);
661

662
663
664
  /* Try DH handshake... */
  dh = crypto_dh_new();
  if (!dh || crypto_dh_generate_public(dh)<0) {
665
666
    log_warn(LD_BUG,"Internal error: couldn't build DH state "
             "or generate public key.");
667
    reason = END_CIRC_REASON_INTERNAL;
668
669
    goto err;
  }
670
671
  if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
                               DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
672
    log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
673
    reason = END_CIRC_REASON_INTERNAL;
674
675
676
    goto err;
  }

677
678
679
  circ_needs_uptime = rend_service_requires_uptime(service);

  /* help predict this next time */
680
  rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
681

682
  /* Launch a circuit to alice's chosen rendezvous point.
683
   */
684
  for (i=0;i<MAX_REND_FAILURES;i++) {
685
    launched = circuit_launch_by_extend_info(
686
          CIRCUIT_PURPOSE_S_CONNECT_REND, 0, extend_info,
687
          circ_needs_uptime, 1, 1);
688

689
690
691
    if (launched)
      break;
  }
692
  if (!launched) { /* give up */
693
    log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
Roger Dingledine's avatar
Roger Dingledine committed
694
             "point %s for service %s.",
695
             escaped_safe_str(extend_info->nickname), serviceid);
696
    reason = END_CIRC_REASON_CONNECTFAILED;
Roger Dingledine's avatar
Roger Dingledine committed
697
    goto err;
698
  }
699
  log_info(LD_REND,
Roger Dingledine's avatar
Roger Dingledine committed
700
           "Accepted intro; launching circuit to %s "
701
           "(cookie %s) for service %s.",
Roger Dingledine's avatar
Roger Dingledine committed
702
           escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
Roger Dingledine's avatar
Roger Dingledine committed
703
  tor_assert(launched->build_state);
704
  /* Fill in the circuit's state. */
705
  memcpy(launched->rend_pk_digest, circuit->rend_pk_digest,
706
         DIGEST_LEN);
707
  memcpy(launched->rend_cookie, r_cookie, REND_COOKIE_LEN);
708
709
  strlcpy(launched->rend_query, service->service_id,
          sizeof(launched->rend_query));
710
  launched->rend_desc_version = service->descriptor_version;
711
712
  launched->build_state->pending_final_cpath = cpath =
    tor_malloc_zero(sizeof(crypt_path_t));
713
  cpath->magic = CRYPT_PATH_MAGIC;
714
  launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
715

716
  cpath->dh_handshake_state = dh;
717
  dh = NULL;
718
  if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
719
    goto err;
720
  memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
721
  if (extend_info) extend_info_free(extend_info);
722
723

  return 0;
724
725
 err:
  if (dh) crypto_dh_free(dh);
726
  if (launched)
727
    circuit_mark_for_close(TO_CIRCUIT(launched), reason);
728
  if (extend_info) extend_info_free(extend_info);
729
  return -1;
730
731
}

Roger Dingledine's avatar
Roger Dingledine committed
732
/** Called when we fail building a rendezvous circuit at some point other
733
734
 * than the last hop: launches a new circuit to the same rendezvous point.
 */
735
void
736
rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
737
{
738
  origin_circuit_t *newcirc;
739
740
  cpath_build_state_t *newstate, *oldstate;

741
  tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
742
743

  if (!oldcirc->build_state ||
744
745
      oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
      oldcirc->build_state->expiry_time < time(NULL)) {
746
747
748
749
750
    log_info(LD_REND,
             "Attempt to build circuit to %s for rendezvous has failed "
             "too many times or expired; giving up.",
             oldcirc->build_state ?
               oldcirc->build_state->chosen_exit->nickname : "*unknown*");
751
752
753
    return;
  }

754
755
756
  oldstate = oldcirc->build_state;
  tor_assert(oldstate);

757
  if (oldstate->pending_final_cpath == NULL) {
758
759
    log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
             "Initiator will retry.");
760
761
762
    return;
  }

763
  log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
764
           oldstate->chosen_exit->nickname);
765

766
  newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND, 0,
767
                               oldstate->chosen_exit, 0, 1, 1);
768
  if (!newcirc) {
769
    log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
770
             oldstate->chosen_exit->nickname);
771
772
773
    return;
  }
  newstate = newcirc->build_state;
774
  tor_assert(newstate);
775
  newstate->failure_count = oldstate->failure_count+1;
776
  newstate->expiry_time = oldstate->expiry_time;
777
778
779
  newstate->pending_final_cpath = oldstate->pending_final_cpath;
  oldstate->pending_final_cpath = NULL;

780
781
  memcpy(newcirc->rend_query, oldcirc->rend_query,
         REND_SERVICE_ID_LEN_BASE32+1);
782
  memcpy(newcirc->rend_pk_digest, oldcirc->rend_pk_digest,
783
         DIGEST_LEN);
784
  memcpy(newcirc->rend_cookie, oldcirc->rend_cookie,
785
         REND_COOKIE_LEN);
786
  newcirc->rend_desc_version = oldcirc->rend_desc_version;
787
788
}

Roger Dingledine's avatar
Roger Dingledine committed
789
/** Launch a circuit to serve as an introduction point for the service
Nick Mathewson's avatar
Nick Mathewson committed
790
 * <b>service</b> at the introduction point <b>nickname</b>
791
792
 */
static int
793
794
rend_service_launch_establish_intro(rend_service_t *service,
                                    const char *nickname)
795
{
796
  origin_circuit_t *launched;
797

798
799
  log_info(LD_REND,
           "Launching circuit to introduction point %s for service %s",
Roger Dingledine's avatar
Roger Dingledine committed
800
           escaped_safe_str(nickname), service->service_id);
Nick Mathewson's avatar
Nick Mathewson committed
801

802
  rep_hist_note_used_internal(time(NULL), 1, 0);
803

804
  ++service->n_intro_circuits_launched;
805
  launched = circuit_launch_by_nickname(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO, 0,
806
                                        nickname, 1, 0, 1);
807
  if (!launched) {
808
    log_info(LD_REND,
Roger Dingledine's avatar
Roger Dingledine committed
809
810
             "Can't launch circuit to establish introduction at %s.",
             escaped_safe_str(nickname));
811
812
    return -1;
  }
813
814
  strlcpy(launched->rend_query, service->service_id,
          sizeof(launched->rend_query));
815
  memcpy(launched->rend_pk_digest, service->pk_digest, DIGEST_LEN);
816
817
  launched->rend_desc_version = service->descriptor_version;
  if (service->descriptor_version == 2) {
818
819
    launched->intro_key = crypto_new_pk_env();
    tor_assert(!crypto_pk_generate_key(launched->intro_key));
820
821
    strmap_set(service->intro_keys, nickname,
               crypto_pk_dup_key(launched->intro_key));
822
  }
823
  if (launched->_base.state == CIRCUIT_STATE_OPEN)
824
    rend_service_intro_has_opened(launched);
825
826
827
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
828
/** Called when we're done building a circuit to an introduction point:
829
830
831
 *  sends a RELAY_ESTABLISH_INTRO cell.
 */
void
832
rend_service_intro_has_opened(origin_circuit_t *circuit)
833
834
{
  rend_service_t *service;
835
836
  size_t len;
  int r;
837
  char buf[RELAY_PAYLOAD_SIZE];
838
  char auth[DIGEST_LEN + 9];
839
  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
840
  int reason = END_CIRC_REASON_TORPROTOCOL;
841
  crypto_pk_env_t *intro_key;
842

843
  tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
844
  tor_assert(circuit->cpath);
Nick Mathewson's avatar
Nick Mathewson committed
845

846
847
  base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
                circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
848

849
850
  service = rend_service_get_by_pk_digest_and_version(
              circuit->rend_pk_digest, circuit->rend_desc_version);
851
  if (!service) {
852
    log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
853
             serviceid, circuit->_base.n_circ_id);
854
    reason = END_CIRC_REASON_NOSUCHSERVICE;