rendservice.c 47.7 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
50
  /* Other fields */
  crypto_pk_env_t *private_key;
  char service_id[REND_SERVICE_ID_LEN+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
  int descriptor_versions; /**< bitmask of rendezvous descriptor versions
71
                            * that will be published. "0" means "default." */
Nick Mathewson's avatar
Nick Mathewson committed
72
73
} rend_service_t;

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

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

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

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

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

Nick Mathewson's avatar
Nick Mathewson committed
141
142
143
144
  if (!service->intro_prefer_nodes)
    service->intro_prefer_nodes = tor_strdup("");
  if (!service->intro_exclude_nodes)
    service->intro_exclude_nodes = tor_strdup("");
145
  if (service->descriptor_versions == 0)
146
147
    service->descriptor_versions = 1 + (1<<2); /**< Default is v0 and v2 in
                                                * parallel. */
148
  service->intro_keys = strmap_new();
Nick Mathewson's avatar
Nick Mathewson committed
149

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

    service->descriptor_versions -= 1; /* Versioned descriptor. */
  }

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

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

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

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

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

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

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

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

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

  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
348
/** Replace the old value of <b>service</b>-\>desc with one that reflects
Nick Mathewson's avatar
Nick Mathewson committed
349
 * the other fields in service.
Nick Mathewson's avatar
Nick Mathewson committed
350
 */
351
352
static void
rend_service_update_descriptor(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
353
354
{
  rend_service_descriptor_t *d;
355
  origin_circuit_t *circ;
Nick Mathewson's avatar
Nick Mathewson committed
356
  int i,n;
357
  routerinfo_t *router;
Nick Mathewson's avatar
Nick Mathewson committed
358
359
360
361
  if (service->desc) {
    rend_service_descriptor_free(service->desc);
    service->desc = NULL;
  }
362
  d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
Nick Mathewson's avatar
Nick Mathewson committed
363
364
  d->pk = crypto_pk_dup_key(service->private_key);
  d->timestamp = time(NULL);
365
366
  d->version = 1; /*< XXXX020 this value is ignored by the
                   * encode functions; do we need to set it at all? */
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);
Roger Dingledine's avatar
Roger Dingledine committed
371
372
  /* We support intro protocol 2 and protocol 0. */
  d->protocols = (1<<2) | (1<<0);
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389

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

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

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

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

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

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

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

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

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

498
499
500
501
/******
 * Handle cells
 ******/

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

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

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

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

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

  /* if descriptor is versioned, use intro key instead of service key. */
  if (circuit->rend_desc_version & 1) {
    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)) {
565
    base32_encode(serviceid, REND_SERVICE_ID_LEN+1, request, 10);
566
    log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
567
             escaped(serviceid));
568
569
570
    return -1;
  }

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

    extend_info = extend_info_from_router(router);
654
  }
655

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

662
  r_cookie = ptr;
663
  base16_encode(hexcookie,9,r_cookie,4);
664

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

680
681
682
  circ_needs_uptime = rend_service_requires_uptime(service);

  /* help predict this next time */
683
  rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
684

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

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

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

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

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

744
  tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
745
746

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

757
758
759
  oldstate = oldcirc->build_state;
  tor_assert(oldstate);

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

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

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

783
  memcpy(newcirc->rend_query, oldcirc->rend_query, REND_SERVICE_ID_LEN+1);
784
  memcpy(newcirc->rend_pk_digest, oldcirc->rend_pk_digest,
785
         DIGEST_LEN);
786
  memcpy(newcirc->rend_cookie, oldcirc->rend_cookie,
787
         REND_COOKIE_LEN);
788
  newcirc->rend_desc_version = oldcirc->rend_desc_version;
789
790
}

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

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

804
  rep_hist_note_used_internal(time(NULL), 1, 0);
805

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

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

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

848
  base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
849
                circuit->rend_pk_digest,10);
850

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

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

864
865
866
867
868
869
870
  /* If the introduction point will not be used in an unversioned
   * descriptor, use the intro key instead of the service key in
   * ESTABLISH_INTRO. */
  if (service->descriptor_versions & 1)
    intro_key = service->private_key;
  else
    intro_key = circuit->intro_key;
871
  /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
872
  len = crypto_pk_asn1_encode(intro_key, buf+2,
873
                              RELAY_PAYLOAD_SIZE-2);
874
  set_uint16(buf, htons((uint16_t)len));
875
  len += 2;
876
877
  memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
  memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
878
  if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
879
880
    goto err;
  len += 20;
881
  note_crypto_pk_op(REND_SERVER);