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

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

#include "or.h"

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

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

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

29
/** If we can't build our intro circuits, don't retry for this long. */
30
#define INTRO_CIRC_RETRY_PERIOD (60*5)
31
32
/** Don't try to build more than this many circuits before giving up
 * for a while.*/
33
#define MAX_INTRO_CIRCS_PER_PERIOD 10
34
35
/** How many times will a hidden service operator attempt to connect to
 * a requested rendezvous point before giving up? */
36
37
38
39
#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
40

Roger Dingledine's avatar
Roger Dingledine committed
41
/** Represents a single hidden service running at this OP. */
Nick Mathewson's avatar
Nick Mathewson committed
42
typedef struct rend_service_t {
Roger Dingledine's avatar
Roger Dingledine committed
43
44
45
46
47
  /** 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
48
49
  /* Other fields */
  crypto_pk_env_t *private_key;
50
  char service_id[REND_SERVICE_ID_LEN_BASE32+1];
51
  char pk_digest[DIGEST_LEN];
Roger Dingledine's avatar
Roger Dingledine committed
52
  smartlist_t *intro_nodes; /**< list of hexdigests for intro points we have,
53
                             * or are trying to establish. */
54
55
  strmap_t *intro_keys; /**< map from intro node hexdigest to key; only
                          * used for versioned hidden service descriptors. */
56
57
58
  time_t intro_period_started;
  int n_intro_circuits_launched; /**< count of intro circuits we have
                                  * established in this period. */
59
  /* DOCDOC undocumented versions */
Nick Mathewson's avatar
Nick Mathewson committed
60
  rend_service_descriptor_t *desc;
61
  time_t desc_is_dirty;
62
  time_t next_upload_time;
63
64
  /* XXXX020 A service never actually has both descriptor versions; perhaps
   * this should be an int rather than in intmax. */
65
66
67
68
69
  /* A service can never publish v0 and v2 descriptors, but maybe it can
   * publish v2 and v3 descriptors in the future. As with origin_circuit_t:
   * Would it be clearer to switch to a single version number for now and
   * switch back to a bitmap, when the above becomes true? -KL */
  /* Yes. s/when/if/.  "YAGNI" -NM. */
70
71
72
  /* Now it's used as version number, not as bitmask. -KL */
  int descriptor_version; /**< rendezvous descriptor version that will be
                           * published. */
Nick Mathewson's avatar
Nick Mathewson committed
73
74
} rend_service_t;

Roger Dingledine's avatar
Roger Dingledine committed
75
/** A list of rend_service_t's for services run on this OP.
Nick Mathewson's avatar
Nick Mathewson committed
76
77
78
 */
static smartlist_t *rend_service_list = NULL;

79
/** Return the number of rendezvous services we have configured. */
80
81
82
int
num_rend_services(void)
{
83
84
85
86
87
  if (!rend_service_list)
    return 0;
  return smartlist_len(rend_service_list);
}

88
/** Helper: Release the storage held by the intro key in <b>_ent</b>.
89
90
91
92
93
94
95
96
 */
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
97
/** Release the storage held by <b>service</b>.
98
 */
99
100
static void
rend_service_free(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
101
{
102
103
104
105
106
107
  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);
108
109
  if (service->intro_keys)
    strmap_free(service->intro_keys, intro_key_free);
110
111
112
113
114
115
116
  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
117
118
}

Roger Dingledine's avatar
Roger Dingledine committed
119
/** Release all the storage held in rend_service_list.
120
 */
121
122
void
rend_service_free_all(void)
Nick Mathewson's avatar
Nick Mathewson committed
123
124
125
126
{
  if (!rend_service_list) {
    return;
  }
Nick Mathewson's avatar
Nick Mathewson committed
127
128
  SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
                    rend_service_free(ptr));
Nick Mathewson's avatar
Nick Mathewson committed
129
  smartlist_free(rend_service_list);
130
  rend_service_list = NULL;
Nick Mathewson's avatar
Nick Mathewson committed
131
132
}

Nick Mathewson's avatar
Nick Mathewson committed
133
/** Validate <b>service</b> and add it to rend_service_list if possible.
134
 */
135
136
static void
add_service(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
137
138
139
140
141
{
  int i;
  rend_service_port_config_t *p;
  struct in_addr addr;

Nick Mathewson's avatar
Nick Mathewson committed
142
143
144
145
  if (!service->intro_prefer_nodes)
    service->intro_prefer_nodes = tor_strdup("");
  if (!service->intro_exclude_nodes)
    service->intro_exclude_nodes = tor_strdup("");
146
  service->intro_nodes = smartlist_create();
147
  service->intro_keys = strmap_new();
Nick Mathewson's avatar
Nick Mathewson committed
148

149
150
  /* If the service is configured to publish unversioned (v0) and versioned
   * descriptors (v2 or higher), split it up into two separate services. */
151
  if (service->descriptor_version == -1) {
152
153
154
155
156
157
158
159
160
161
162
163
164
    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;
165
    v0_service->descriptor_version = 0; /* Unversioned descriptor. */
166
167
    add_service(v0_service);

168
    service->descriptor_version = 2; /* Versioned descriptor. */
169
170
  }

Nick Mathewson's avatar
Nick Mathewson committed
171
  if (!smartlist_len(service->ports)) {
172
    log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
Nick Mathewson's avatar
Nick Mathewson committed
173
174
    rend_service_free(service);
  } else {
Nick Mathewson's avatar
Nick Mathewson committed
175
    smartlist_set_capacity(service->ports, -1);
Nick Mathewson's avatar
Nick Mathewson committed
176
    smartlist_add(rend_service_list, service);
177
178
    log_debug(LD_REND,"Configuring service with directory \"%s\"",
              service->directory);
Nick Mathewson's avatar
Nick Mathewson committed
179
    for (i = 0; i < smartlist_len(service->ports); ++i) {
180
      char addrbuf[INET_NTOA_BUF_LEN];
Nick Mathewson's avatar
Nick Mathewson committed
181
      p = smartlist_get(service->ports, i);
182
      addr.s_addr = htonl(p->real_addr);
183
      tor_inet_ntoa(&addr, addrbuf, sizeof(addrbuf));
184
185
      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
186
187
188
189
    }
  }
}

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

  sl = smartlist_create();
209
210
  smartlist_split_string(sl, string, " ",
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
211
  if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
212
    log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
213
    goto err;
Nick Mathewson's avatar
Nick Mathewson committed
214
  }
215
216

  virtport = atoi(smartlist_get(sl,0));
Nick Mathewson's avatar
Nick Mathewson committed
217
  if (virtport < 1 || virtport > 65535) {
218
219
    log_warn(LD_CONFIG, "Missing or invalid port in hidden service port "
             "configuration.");
220
    goto err;
Nick Mathewson's avatar
Nick Mathewson committed
221
  }
222
223

  if (smartlist_len(sl) == 1) {
Nick Mathewson's avatar
Nick Mathewson committed
224
225
    /* No addr:port part; use default. */
    realport = virtport;
226
227
    addr = 0x7F000001u; /* 127.0.0.1 */
  } else {
228
229
    addrport = smartlist_get(sl,1);
    if (strchr(addrport, ':') || strchr(addrport, '.')) {
230
      if (parse_addr_port(LOG_WARN, addrport, NULL, &addr, &p)<0) {
231
232
        log_warn(LD_CONFIG,"Unparseable address in hidden service port "
                 "configuration.");
233
234
235
236
237
238
239
240
241
        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 */
242
    }
Nick Mathewson's avatar
Nick Mathewson committed
243
244
245
246
247
  }

  result = tor_malloc(sizeof(rend_service_port_config_t));
  result->virtual_port = virtport;
  result->real_port = realport;
248
  result->real_addr = addr;
249
250
251
 err:
  SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  smartlist_free(sl);
Nick Mathewson's avatar
Nick Mathewson committed
252
253
254
  return result;
}

Roger Dingledine's avatar
Roger Dingledine committed
255
/** Set up rend_service_list, based on the values of HiddenServiceDir and
Nick Mathewson's avatar
Nick Mathewson committed
256
 * HiddenServicePort in <b>options</b>.  Return 0 on success and -1 on
257
258
 * 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
259
 */
260
261
int
rend_config_services(or_options_t *options, int validate_only)
Nick Mathewson's avatar
Nick Mathewson committed
262
{
263
  config_line_t *line;
Nick Mathewson's avatar
Nick Mathewson committed
264
265
  rend_service_t *service = NULL;
  rend_service_port_config_t *portcfg;
266

267
  if (!validate_only) {
268
    rend_service_free_all();
269
270
    rend_service_list = smartlist_create();
  }
Nick Mathewson's avatar
Nick Mathewson committed
271
272
273

  for (line = options->RendConfigLines; line; line = line->next) {
    if (!strcasecmp(line->key, "HiddenServiceDir")) {
274
275
276
277
278
279
      if (service) {
        if (validate_only)
          rend_service_free(service);
        else
          add_service(service);
      }
Nick Mathewson's avatar
Nick Mathewson committed
280
281
282
      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
283
      service->intro_nodes = smartlist_create();
284
      service->intro_period_started = time(NULL);
285
      service->descriptor_version = -1; /**< All descriptor versions. */
286
287
288
      continue;
    }
    if (!service) {
289
290
      log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
               line->key);
291
292
293
294
      rend_service_free(service);
      return -1;
    }
    if (!strcasecmp(line->key, "HiddenServicePort")) {
Nick Mathewson's avatar
Nick Mathewson committed
295
296
      portcfg = parse_port_config(line->value);
      if (!portcfg) {
Roger Dingledine's avatar
tabs    
Roger Dingledine committed
297
298
        rend_service_free(service);
        return -1;
Nick Mathewson's avatar
Nick Mathewson committed
299
300
      }
      smartlist_add(service->ports, portcfg);
301
    } else if (!strcasecmp(line->key, "HiddenServiceNodes")) {
Nick Mathewson's avatar
Nick Mathewson committed
302
      if (service->intro_prefer_nodes) {
303
304
305
        log_warn(LD_CONFIG,
                 "Got multiple HiddenServiceNodes lines for a single "
                 "service.");
306
307
        return -1;
      }
Nick Mathewson's avatar
Nick Mathewson committed
308
      service->intro_prefer_nodes = tor_strdup(line->value);
309
    } else if (!strcasecmp(line->key, "HiddenServiceExcludeNodes")) {
310
      if (service->intro_exclude_nodes) {
311
312
313
        log_warn(LD_CONFIG,
                 "Got multiple HiddenServiceExcludedNodes lines for "
                 "a single service.");
314
315
316
        return -1;
      }
      service->intro_exclude_nodes = tor_strdup(line->value);
317
318
319
    } else {
      smartlist_t *versions;
      char *version_str;
320
      int i, version, versions_bitmask = 0;
321
322
323
324
325
326
327
328
329
330
331
332
      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);
333
        versions_bitmask |= 1 << version;
334
      }
335
336
      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
337
338
    }
  }
339
340
341
342
343
344
  if (service) {
    if (validate_only)
      rend_service_free(service);
    else
      add_service(service);
  }
Nick Mathewson's avatar
Nick Mathewson committed
345
346
347
348

  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
349
/** Replace the old value of <b>service</b>-\>desc with one that reflects
Nick Mathewson's avatar
Nick Mathewson committed
350
 * the other fields in service.
Nick Mathewson's avatar
Nick Mathewson committed
351
 */
352
353
static void
rend_service_update_descriptor(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
354
355
{
  rend_service_descriptor_t *d;
356
  origin_circuit_t *circ;
Nick Mathewson's avatar
Nick Mathewson committed
357
  int i,n;
358
  routerinfo_t *router;
Nick Mathewson's avatar
Nick Mathewson committed
359
360
361
362
  if (service->desc) {
    rend_service_descriptor_free(service->desc);
    service->desc = NULL;
  }
363
  d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
Nick Mathewson's avatar
Nick Mathewson committed
364
365
  d->pk = crypto_pk_dup_key(service->private_key);
  d->timestamp = time(NULL);
366
  d->version = service->descriptor_version;
367
368
  n = smartlist_len(service->intro_nodes);
  d->n_intro_points = 0;
369
370
  d->intro_points = tor_malloc_zero(sizeof(char*)*n);
  d->intro_point_extend_info = tor_malloc_zero(sizeof(extend_info_t*)*n);
371
372
373
  /* 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. */
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390

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

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

Nick Mathewson's avatar
Nick Mathewson committed
421
422
  for (i=0; i < smartlist_len(rend_service_list); ++i) {
    s = smartlist_get(rend_service_list,i);
Nick Mathewson's avatar
Nick Mathewson committed
423
424
    if (s->private_key)
      continue;
425
426
    log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
             s->directory);
Nick Mathewson's avatar
Nick Mathewson committed
427

Nick Mathewson's avatar
Nick Mathewson committed
428
    /* Check/create directory */
429
    if (check_private_dir(s->directory, CPD_CREATE) < 0)
Nick Mathewson's avatar
Nick Mathewson committed
430
431
432
      return -1;

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

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

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

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

  for (i=0; i < smartlist_len(service->ports); ++i) {
    p = smartlist_get(service->ports, i);
492
493
    if (smartlist_string_num_isin(get_options()->LongLivedPorts,
                                  p->virtual_port))
494
495
496
497
498
      return 1;
  }
  return 0;
}

499
500
501
502
/******
 * Handle cells
 ******/

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

527
528
  base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
                circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
529
  log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
530
           escaped(serviceid), circuit->_base.n_circ_id);
531

532
  if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
533
534
    log_warn(LD_PROTOCOL,
             "Got an INTRODUCE2 over a non-introduction circuit %d.",
535
             circuit->_base.n_circ_id);
536
537
538
    return -1;
  }

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

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

556
557
  /* if descriptor version is 2, use intro key instead of service key. */
  if (circuit->rend_desc_version == 0) {
558
559
560
561
562
563
564
565
    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)) {
566
567
    base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
                  request, REND_SERVICE_ID_LEN);
568
    log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
569
             escaped(serviceid));
570
571
572
    return -1;
  }

573
  keylen = crypto_pk_keysize(intro_key);
574
  if (request_len < keylen+DIGEST_LEN) {
575
576
    log_warn(LD_PROTOCOL,
             "PK-encrypted portion of INTRODUCE2 cell was truncated.");
577
578
579
    return -1;
  }
  /* Next N bytes is encrypted with service key */
580
  note_crypto_pk_op(REND_SERVER);
581
  r = crypto_pk_private_hybrid_decrypt(
582
       intro_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
583
       PK_PKCS1_OAEP_PADDING,1);
584
  if (r<0) {
585
    log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
586
587
    return -1;
  }
588
  len = r;
589
590
591
592
593
594
595
596
597
598
599
600
  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));
601
    if ((int)len != 7+DIGEST_LEN+2+klen+20+128) {
602
603
      log_warn(LD_PROTOCOL, "Bad length %u for version 2 INTRODUCE2 cell.",
               (int)len);
604
      reason = END_CIRC_REASON_TORPROTOCOL;
605
606
607
608
      goto err;
    }
    extend_info->onion_key = crypto_pk_asn1_decode(buf+7+DIGEST_LEN+2, klen);
    if (!extend_info->onion_key) {
609
610
      log_warn(LD_PROTOCOL,
               "Error decoding onion key in version 2 INTRODUCE2 cell.");
611
      reason = END_CIRC_REASON_TORPROTOCOL;
612
613
614
615
      goto err;
    }
    ptr = buf+7+DIGEST_LEN+2+klen;
    len -= 7+DIGEST_LEN+2+klen;
616
  } else {
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
    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) {
632
      log_warn(LD_PROTOCOL,
633
               "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
634
635
636
637
      return -1;
    }
    if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
        (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
638
      log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
639
640
641
642
643
      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;
644
645
    len -= rp_nickname - buf; /* also remove header space used by version, if
                               * any */
646
    router = router_get_by_nickname(rp_nickname, 0);
647
    if (!router) {
Roger Dingledine's avatar
Roger Dingledine committed
648
      log_info(LD_REND, "Couldn't find router %s named in introduce2 cell.",
649
               escaped_safe_str(rp_nickname));
650
651
      /* XXXX Add a no-such-router reason? */
      reason = END_CIRC_REASON_TORPROTOCOL;
652
653
654
655
      goto err;
    }

    extend_info = extend_info_from_router(router);
656
  }
657

658
  if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
659
    log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
660
    reason = END_CIRC_REASON_TORPROTOCOL;
661
662
    return -1;
  }
663

664
  r_cookie = ptr;
665
  base16_encode(hexcookie,9,r_cookie,4);
666

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

682
683
684
  circ_needs_uptime = rend_service_requires_uptime(service);

  /* help predict this next time */
685
  rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
686

687
  /* Launch a circuit to alice's chosen rendezvous point.
688
   */
689
  for (i=0;i<MAX_REND_FAILURES;i++) {
690
    launched = circuit_launch_by_extend_info(
691
          CIRCUIT_PURPOSE_S_CONNECT_REND, 0, extend_info,
692
          circ_needs_uptime, 1, 1);
693

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

721
  cpath->dh_handshake_state = dh;
722
  dh = NULL;
723
  if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
724
    goto err;
725
  memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
726
  if (extend_info) extend_info_free(extend_info);
727
728

  return 0;
729
730
 err:
  if (dh) crypto_dh_free(dh);
731
  if (launched)
732
    circuit_mark_for_close(TO_CIRCUIT(launched), reason);
733
  if (extend_info) extend_info_free(extend_info);
734
  return -1;
735
736
}

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

746
  tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
747
748

  if (!oldcirc->build_state ||
749
750
      oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
      oldcirc->build_state->expiry_time < time(NULL)) {
751
752
753
754
755
    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*");
756
757
758
    return;
  }

759
760
761
  oldstate = oldcirc->build_state;
  tor_assert(oldstate);

762
  if (oldstate->pending_final_cpath == NULL) {
763
764
    log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
             "Initiator will retry.");
765
766
767
    return;
  }

768
  log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
769
           oldstate->chosen_exit->nickname);
770

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

785
786
  memcpy(newcirc->rend_query, oldcirc->rend_query,
         REND_SERVICE_ID_LEN_BASE32+1);
787
  memcpy(newcirc->rend_pk_digest, oldcirc->rend_pk_digest,
788
         DIGEST_LEN);
789
  memcpy(newcirc->rend_cookie, oldcirc->rend_cookie,
790
         REND_COOKIE_LEN);
791
  newcirc->rend_desc_version = oldcirc->rend_desc_version;
792
793
}

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

803
804
  log_info(LD_REND,
           "Launching circuit to introduction point %s for service %s",
Roger Dingledine's avatar
Roger Dingledine committed
805
           escaped_safe_str(nickname), service->service_id);
Nick Mathewson's avatar
Nick Mathewson committed
806

807
  rep_hist_note_used_internal(time(NULL), 1, 0);
808

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

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

848
  tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
849
  tor_assert(circuit->cpath);
Nick Mathewson's avatar
Nick Mathewson committed
850

851
852
  base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
                circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
853

854
855
  service = rend_service_get_by_pk_digest_and_version(
              circuit->rend_pk_digest, circuit->rend_desc_version);
856
  if (!service) {
857
    log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
858
             serviceid, circuit->_base.n_circ_id);
859
    reason = END_CIRC_REASON_NOSUCHSERVICE;
860
861
862
    goto err;
  }

863
864
  log_info(LD_REND,
           "Established circuit %d as introduction point for service %s",
865
           circuit->_base.n_circ_id, serviceid);
Nick Mathewson's avatar
Nick Mathewson committed
866

867
868
869
  /* If the introduction point will not be used in an unversioned