rendservice.c 49.6 KB
Newer Older
1
/* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2
 * Copyright (c) 2007-2008, 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
17
static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
                                            const char *pk_digest,
                                            int desc_version);
18

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

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

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

Roger Dingledine's avatar
Roger Dingledine committed
43
/** Represents a single hidden service running at this OP. */
Nick Mathewson's avatar
Nick Mathewson committed
44
typedef struct rend_service_t {
45
  /* Fields specified in config file */
Roger Dingledine's avatar
Roger Dingledine committed
46
47
48
49
  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 */
50
51
  int descriptor_version; /**< Rendezvous descriptor version that will be
                           * published. */
Nick Mathewson's avatar
Nick Mathewson committed
52
  /* Other fields */
53
54
55
56
  crypto_pk_env_t *private_key; /**< Permanent hidden-service key. */
  char service_id[REND_SERVICE_ID_LEN_BASE32+1]; /**< Onion address without
                                                  * '.onion' */
  char pk_digest[DIGEST_LEN]; /**< Hash of permanent hidden-service key. */
57
  smartlist_t *intro_nodes; /**< List of rend_intro_point_t's we have,
58
                             * or are trying to establish. */
59
60
  time_t intro_period_started; /**< Start of the current period to build
                                * introduction points. */
61
62
  int n_intro_circuits_launched; /**< count of intro circuits we have
                                  * established in this period. */
63
64
65
66
67
68
  rend_service_descriptor_t *desc; /**< Current hidden service descriptor. */
  time_t desc_is_dirty; /**< Time at which changes to the hidden service
                         * descriptor content occurred, or 0 if it's
                         * up-to-date. */
  time_t next_upload_time; /**< Scheduled next hidden service descriptor
                            * upload time. */
Nick Mathewson's avatar
Nick Mathewson committed
69
70
} rend_service_t;

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

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

Nick Mathewson's avatar
Nick Mathewson committed
84
/** Release the storage held by <b>service</b>.
85
 */
86
87
static void
rend_service_free(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
88
{
89
90
91
92
93
94
  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);
95
96
97
98
99
  if (service->intro_nodes) {
    SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
      rend_intro_point_free(intro););
    smartlist_free(service->intro_nodes);
  }
100
101
102
103
104
  tor_free(service->intro_prefer_nodes);
  tor_free(service->intro_exclude_nodes);
  if (service->desc)
    rend_service_descriptor_free(service->desc);
  tor_free(service);
Nick Mathewson's avatar
Nick Mathewson committed
105
106
}

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

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

Nick Mathewson's avatar
Nick Mathewson committed
130
131
132
133
  if (!service->intro_prefer_nodes)
    service->intro_prefer_nodes = tor_strdup("");
  if (!service->intro_exclude_nodes)
    service->intro_exclude_nodes = tor_strdup("");
134
  service->intro_nodes = smartlist_create();
Nick Mathewson's avatar
Nick Mathewson committed
135

136
137
  /* If the service is configured to publish unversioned (v0) and versioned
   * descriptors (v2 or higher), split it up into two separate services. */
138
  if (service->descriptor_version == -1) {
139
140
141
142
143
144
145
146
147
148
149
150
    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_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;
151
    v0_service->descriptor_version = 0; /* Unversioned descriptor. */
Roger Dingledine's avatar
Roger Dingledine committed
152
    rend_add_service(v0_service);
153

154
    service->descriptor_version = 2; /* Versioned descriptor. */
155
156
  }

Nick Mathewson's avatar
Nick Mathewson committed
157
  if (!smartlist_len(service->ports)) {
158
    log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
Nick Mathewson's avatar
Nick Mathewson committed
159
160
    rend_service_free(service);
  } else {
Nick Mathewson's avatar
Nick Mathewson committed
161
    smartlist_set_capacity(service->ports, -1);
Nick Mathewson's avatar
Nick Mathewson committed
162
    smartlist_add(rend_service_list, service);
163
164
    log_debug(LD_REND,"Configuring service with directory \"%s\"",
              service->directory);
Nick Mathewson's avatar
Nick Mathewson committed
165
    for (i = 0; i < smartlist_len(service->ports); ++i) {
166
      char addrbuf[INET_NTOA_BUF_LEN];
Nick Mathewson's avatar
Nick Mathewson committed
167
      p = smartlist_get(service->ports, i);
168
      addr.s_addr = htonl(p->real_addr);
169
      tor_inet_ntoa(&addr, addrbuf, sizeof(addrbuf));
170
171
      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
172
173
174
175
    }
  }
}

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

  sl = smartlist_create();
195
196
  smartlist_split_string(sl, string, " ",
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
197
  if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
198
    log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
199
    goto err;
Nick Mathewson's avatar
Nick Mathewson committed
200
  }
201

202
203
204
205
  virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
  if (!virtport) {
    log_warn(LD_CONFIG, "Missing or invalid port %s in hidden service port "
             "configuration", escaped(smartlist_get(sl,0)));
206
    goto err;
Nick Mathewson's avatar
Nick Mathewson committed
207
  }
208
209

  if (smartlist_len(sl) == 1) {
Nick Mathewson's avatar
Nick Mathewson committed
210
211
    /* No addr:port part; use default. */
    realport = virtport;
212
213
    addr = 0x7F000001u; /* 127.0.0.1 */
  } else {
214
215
    addrport = smartlist_get(sl,1);
    if (strchr(addrport, ':') || strchr(addrport, '.')) {
216
      if (parse_addr_port(LOG_WARN, addrport, NULL, &addr, &p)<0) {
217
218
        log_warn(LD_CONFIG,"Unparseable address in hidden service port "
                 "configuration.");
219
220
221
222
223
        goto err;
      }
      realport = p?p:virtport;
    } else {
      /* No addr:port, no addr -- must be port. */
224
225
226
227
      realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
      if (!realport) {
        log_warn(LD_CONFIG,"Unparseable or out-of-range port %s in hidden "
                 "service port configuration.", escaped(addrport));
228
        goto err;
229
      }
230
      addr = 0x7F000001u; /* Default to 127.0.0.1 */
231
    }
Nick Mathewson's avatar
Nick Mathewson committed
232
233
234
235
236
  }

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

Roger Dingledine's avatar
Roger Dingledine committed
244
/** Set up rend_service_list, based on the values of HiddenServiceDir and
Nick Mathewson's avatar
Nick Mathewson committed
245
 * HiddenServicePort in <b>options</b>.  Return 0 on success and -1 on
246
247
 * 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
248
 */
249
250
int
rend_config_services(or_options_t *options, int validate_only)
Nick Mathewson's avatar
Nick Mathewson committed
251
{
252
  config_line_t *line;
Nick Mathewson's avatar
Nick Mathewson committed
253
254
  rend_service_t *service = NULL;
  rend_service_port_config_t *portcfg;
255

256
  if (!validate_only) {
257
    rend_service_free_all();
258
259
    rend_service_list = smartlist_create();
  }
Nick Mathewson's avatar
Nick Mathewson committed
260
261
262

  for (line = options->RendConfigLines; line; line = line->next) {
    if (!strcasecmp(line->key, "HiddenServiceDir")) {
263
264
265
266
      if (service) {
        if (validate_only)
          rend_service_free(service);
        else
Roger Dingledine's avatar
Roger Dingledine committed
267
          rend_add_service(service);
268
      }
Nick Mathewson's avatar
Nick Mathewson committed
269
270
271
      service = tor_malloc_zero(sizeof(rend_service_t));
      service->directory = tor_strdup(line->value);
      service->ports = smartlist_create();
272
      service->intro_period_started = time(NULL);
273
      service->descriptor_version = -1; /**< All descriptor versions. */
274
275
276
      continue;
    }
    if (!service) {
277
278
      log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
               line->key);
279
280
281
282
      rend_service_free(service);
      return -1;
    }
    if (!strcasecmp(line->key, "HiddenServicePort")) {
Nick Mathewson's avatar
Nick Mathewson committed
283
284
      portcfg = parse_port_config(line->value);
      if (!portcfg) {
Roger Dingledine's avatar
tabs    
Roger Dingledine committed
285
286
        rend_service_free(service);
        return -1;
Nick Mathewson's avatar
Nick Mathewson committed
287
288
      }
      smartlist_add(service->ports, portcfg);
289
    } else if (!strcasecmp(line->key, "HiddenServiceNodes")) {
Nick Mathewson's avatar
Nick Mathewson committed
290
      if (service->intro_prefer_nodes) {
291
292
293
        log_warn(LD_CONFIG,
                 "Got multiple HiddenServiceNodes lines for a single "
                 "service.");
294
        rend_service_free(service);
295
296
        return -1;
      }
Nick Mathewson's avatar
Nick Mathewson committed
297
      service->intro_prefer_nodes = tor_strdup(line->value);
298
    } else if (!strcasecmp(line->key, "HiddenServiceExcludeNodes")) {
299
      if (service->intro_exclude_nodes) {
300
301
302
        log_warn(LD_CONFIG,
                 "Got multiple HiddenServiceExcludedNodes lines for "
                 "a single service.");
303
        rend_service_free(service);
304
305
306
        return -1;
      }
      service->intro_exclude_nodes = tor_strdup(line->value);
307
308
309
    } else {
      smartlist_t *versions;
      char *version_str;
310
      int i, version, ver_ok=1, versions_bitmask = 0;
311
312
313
314
315
316
317
318
319
      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.");
320
321
322
          SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
          smartlist_free(versions);
          rend_service_free(service);
323
324
          return -1;
        }
325
326
327
328
        version = (int)tor_parse_long(version_str, 10, 0, INT_MAX, &ver_ok,
                                      NULL);
        if (!ver_ok)
          continue;
329
        versions_bitmask |= 1 << version;
330
      }
Roger Dingledine's avatar
Roger Dingledine committed
331
      /* If exactly one version is set, change descriptor_version to that
Roger Dingledine's avatar
Roger Dingledine committed
332
       * value; otherwise leave it at -1. */
333
334
      if (versions_bitmask == 1 << 0) service->descriptor_version = 0;
      if (versions_bitmask == 1 << 2) service->descriptor_version = 2;
335
336
      SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
      smartlist_free(versions);
Nick Mathewson's avatar
Nick Mathewson committed
337
338
    }
  }
339
340
341
342
  if (service) {
    if (validate_only)
      rend_service_free(service);
    else
Roger Dingledine's avatar
Roger Dingledine committed
343
      rend_add_service(service);
344
  }
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;
357
  int i;
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
  d->version = service->descriptor_version;
366
  d->intro_nodes = smartlist_create();
Roger Dingledine's avatar
Roger Dingledine committed
367
368
369
  /* Whoever understands descriptor version 2 also understands intro
   * protocol 2. So we only support 2. */
  d->protocols = 1 << 2;
370

371
372
373
374
375
  for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
    rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
    rend_intro_point_t *intro_desc;
    circ = find_intro_circuit(intro_svc, service->pk_digest, d->version);
    if (!circ || circ->_base.purpose != CIRCUIT_PURPOSE_S_INTRO)
376
      continue;
377
378
379
380
381
382
383

    /* We have an entirely established intro circuit. */
    intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
    intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
    if (intro_svc->intro_key)
      intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
    smartlist_add(d->intro_nodes, intro_desc);
Nick Mathewson's avatar
Nick Mathewson committed
384
385
386
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
387
/** Load and/or generate private keys for all hidden services.  Return 0 on
Nick Mathewson's avatar
Nick Mathewson committed
388
389
 * success, -1 on failure.
 */
390
391
int
rend_service_load_keys(void)
Nick Mathewson's avatar
Nick Mathewson committed
392
393
394
395
396
397
{
  int i;
  rend_service_t *s;
  char fname[512];
  char buf[128];

Nick Mathewson's avatar
Nick Mathewson committed
398
399
  for (i=0; i < smartlist_len(rend_service_list); ++i) {
    s = smartlist_get(rend_service_list,i);
Nick Mathewson's avatar
Nick Mathewson committed
400
401
    if (s->private_key)
      continue;
402
403
    log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
             s->directory);
Nick Mathewson's avatar
Nick Mathewson committed
404

Nick Mathewson's avatar
Nick Mathewson committed
405
    /* Check/create directory */
406
    if (check_private_dir(s->directory, CPD_CREATE) < 0)
Nick Mathewson's avatar
Nick Mathewson committed
407
408
409
      return -1;

    /* Load key */
410
    if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
411
412
        strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
                                                  >= sizeof(fname)) {
413
414
      log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
               s->directory);
Nick Mathewson's avatar
Nick Mathewson committed
415
416
      return -1;
    }
417
    s->private_key = init_key_from_file(fname, 1, LOG_ERR);
Nick Mathewson's avatar
Nick Mathewson committed
418
419
420
421
422
    if (!s->private_key)
      return -1;

    /* Create service file */
    if (rend_get_service_id(s->private_key, s->service_id)<0) {
423
      log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
Nick Mathewson's avatar
Nick Mathewson committed
424
425
      return -1;
    }
426
    if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
427
      log_warn(LD_BUG, "Couldn't compute hash of public key.");
428
429
      return -1;
    }
430
    if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
431
432
        strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
                                                  >= sizeof(fname)) {
433
434
      log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
               " \"%s\".", s->directory);
Nick Mathewson's avatar
Nick Mathewson committed
435
436
      return -1;
    }
437
    tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
438
    if (write_str_to_file(fname,buf,0)<0)
Nick Mathewson's avatar
Nick Mathewson committed
439
440
441
442
      return -1;
  }
  return 0;
}
443

444
/** Return the service whose public key has a digest of <b>digest</b> and
445
446
 * which publishes the given descriptor <b>version</b>.  Return NULL if no
 * such service exists.
447
 */
448
static rend_service_t *
449
rend_service_get_by_pk_digest_and_version(const char* digest,
450
                                          uint8_t version)
451
{
Nick Mathewson's avatar
Nick Mathewson committed
452
  SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
453
                    if (!memcmp(s->pk_digest,digest,DIGEST_LEN) &&
454
                        s->descriptor_version == version) return s);
455
456
457
  return NULL;
}

458
459
460
461
/** Return 1 if any virtual port in <b>service</b> wants a circuit
 * to have good uptime. Else return 0.
 */
static int
462
463
rend_service_requires_uptime(rend_service_t *service)
{
464
465
466
467
468
  int i;
  rend_service_port_config_t *p;

  for (i=0; i < smartlist_len(service->ports); ++i) {
    p = smartlist_get(service->ports, i);
469
470
    if (smartlist_string_num_isin(get_options()->LongLivedPorts,
                                  p->virtual_port))
471
472
473
474
475
      return 1;
  }
  return 0;
}

476
477
478
479
/******
 * Handle cells
 ******/

Roger Dingledine's avatar
Roger Dingledine committed
480
/** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
481
 * rendezvous point.
482
 */
483
int
484
rend_service_introduce(origin_circuit_t *circuit, const char *request,
485
                       size_t request_len)
486
{
487
488
  char *ptr, *r_cookie;
  extend_info_t *extend_info = NULL;
489
  char buf[RELAY_PAYLOAD_SIZE];
490
  char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
491
  rend_service_t *service;
492
  int r, i;
493
  size_t len, keylen;
494
  crypto_dh_env_t *dh = NULL;
495
  origin_circuit_t *launched = NULL;
496
  crypt_path_t *cpath = NULL;
497
  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
Nick Mathewson's avatar
Nick Mathewson committed
498
  char hexcookie[9];
499
  int circ_needs_uptime;
500
  int reason = END_CIRC_REASON_TORPROTOCOL;
501
502
  crypto_pk_env_t *intro_key;
  char intro_key_digest[DIGEST_LEN];
Nick Mathewson's avatar
Nick Mathewson committed
503

504
505
  base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
                circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
506
  log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
507
           escaped(serviceid), circuit->_base.n_circ_id);
508

509
  if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
510
511
    log_warn(LD_PROTOCOL,
             "Got an INTRODUCE2 over a non-introduction circuit %d.",
512
             circuit->_base.n_circ_id);
513
514
515
    return -1;
  }

516
  /* min key length plus digest length plus nickname length */
517
  if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
518
      DH_KEY_LEN+42) {
519
    log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
520
             circuit->_base.n_circ_id);
521
522
523
    return -1;
  }

524
525
526
  /* look up service depending on circuit. */
  service = rend_service_get_by_pk_digest_and_version(
              circuit->rend_pk_digest, circuit->rend_desc_version);
527
  if (!service) {
528
    log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
529
             escaped(serviceid));
530
531
    return -1;
  }
532

533
534
  /* if descriptor version is 2, use intro key instead of service key. */
  if (circuit->rend_desc_version == 0) {
535
536
537
538
539
540
541
542
    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)) {
543
544
    base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
                  request, REND_SERVICE_ID_LEN);
545
    log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
546
             escaped(serviceid));
547
548
549
    return -1;
  }

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

    extend_info = extend_info_from_router(router);
633
  }
634

635
  if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
636
    log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
637
    reason = END_CIRC_REASON_TORPROTOCOL;
638
    goto err;
639
  }
640

641
  r_cookie = ptr;
642
  base16_encode(hexcookie,9,r_cookie,4);
643

644
645
646
  /* Try DH handshake... */
  dh = crypto_dh_new();
  if (!dh || crypto_dh_generate_public(dh)<0) {
647
648
    log_warn(LD_BUG,"Internal error: couldn't build DH state "
             "or generate public key.");
649
    reason = END_CIRC_REASON_INTERNAL;
650
651
    goto err;
  }
652
653
  if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
                               DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
654
    log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
655
    reason = END_CIRC_REASON_INTERNAL;
656
657
658
    goto err;
  }

659
660
661
  circ_needs_uptime = rend_service_requires_uptime(service);

  /* help predict this next time */
662
  rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
663

664
  /* Launch a circuit to alice's chosen rendezvous point.
665
   */
666
  for (i=0;i<MAX_REND_FAILURES;i++) {
667
668
    int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
    if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
669
    launched = circuit_launch_by_extend_info(
670
                        CIRCUIT_PURPOSE_S_CONNECT_REND, extend_info, flags);
671

672
673
674
    if (launched)
      break;
  }
675
  if (!launched) { /* give up */
676
    log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
Roger Dingledine's avatar
Roger Dingledine committed
677
             "point %s for service %s.",
678
             escaped_safe_str(extend_info->nickname), serviceid);
679
    reason = END_CIRC_REASON_CONNECTFAILED;
Roger Dingledine's avatar
Roger Dingledine committed
680
    goto err;
681
  }
682
  log_info(LD_REND,
Roger Dingledine's avatar
Roger Dingledine committed
683
           "Accepted intro; launching circuit to %s "
684
           "(cookie %s) for service %s.",
Roger Dingledine's avatar
Roger Dingledine committed
685
           escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
Roger Dingledine's avatar
Roger Dingledine committed
686
  tor_assert(launched->build_state);
687
  /* Fill in the circuit's state. */
688
  memcpy(launched->rend_pk_digest, circuit->rend_pk_digest,
689
         DIGEST_LEN);
690
  memcpy(launched->rend_cookie, r_cookie, REND_COOKIE_LEN);
691
692
  strlcpy(launched->rend_query, service->service_id,
          sizeof(launched->rend_query));
693
  launched->rend_desc_version = service->descriptor_version;
694
695
  launched->build_state->pending_final_cpath = cpath =
    tor_malloc_zero(sizeof(crypt_path_t));
696
  cpath->magic = CRYPT_PATH_MAGIC;
697
  launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
698

699
  cpath->dh_handshake_state = dh;
700
  dh = NULL;
701
  if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
702
    goto err;
703
  memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
704
  if (extend_info) extend_info_free(extend_info);
705
706

  return 0;
707
708
 err:
  if (dh) crypto_dh_free(dh);
709
  if (launched)
710
    circuit_mark_for_close(TO_CIRCUIT(launched), reason);
711
  if (extend_info) extend_info_free(extend_info);
712
  return -1;
713
714
}

Roger Dingledine's avatar
Roger Dingledine committed
715
/** Called when we fail building a rendezvous circuit at some point other
716
717
 * than the last hop: launches a new circuit to the same rendezvous point.
 */
718
void
719
rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
720
{
721
  origin_circuit_t *newcirc;
722
723
  cpath_build_state_t *newstate, *oldstate;

724
  tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
725
726

  if (!oldcirc->build_state ||
727
728
      oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
      oldcirc->build_state->expiry_time < time(NULL)) {
729
730
731
732
733
    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*");
734
735
736
    return;
  }

737
738
739
  oldstate = oldcirc->build_state;
  tor_assert(oldstate);

740
  if (oldstate->pending_final_cpath == NULL) {
741
742
    log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
             "Initiator will retry.");
743
744
745
    return;
  }

746
  log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
747
           oldstate->chosen_exit->nickname);
748

749
750
751
752
  newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
                            oldstate->chosen_exit,
                            CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);

753
  if (!newcirc) {
754
    log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
755
             oldstate->chosen_exit->nickname);
756
757
758
    return;
  }
  newstate = newcirc->build_state;
759
  tor_assert(newstate);
760
  newstate->failure_count = oldstate->failure_count+1;
761
  newstate->expiry_time = oldstate->expiry_time;
762
763
764
  newstate->pending_final_cpath = oldstate->pending_final_cpath;
  oldstate->pending_final_cpath = NULL;

765
766
  memcpy(newcirc->rend_query, oldcirc->rend_query,
         REND_SERVICE_ID_LEN_BASE32+1);
767
  memcpy(newcirc->rend_pk_digest, oldcirc->rend_pk_digest,
768
         DIGEST_LEN);
769
  memcpy(newcirc->rend_cookie, oldcirc->rend_cookie,
770
         REND_COOKIE_LEN);
771
  newcirc->rend_desc_version = oldcirc->rend_desc_version;
772
773
}

Roger Dingledine's avatar
Roger Dingledine committed
774
/** Launch a circuit to serve as an introduction point for the service
Nick Mathewson's avatar
Nick Mathewson committed
775
 * <b>service</b> at the introduction point <b>nickname</b>
776
777
 */
static int
778
rend_service_launch_establish_intro(rend_service_t *service,
779
                                    rend_intro_point_t *intro)
780
{
781
  origin_circuit_t *launched;
782

783
784
  log_info(LD_REND,
           "Launching circuit to introduction point %s for service %s",
785
786
           escaped_safe_str(intro->extend_info->nickname),
           service->service_id);
Nick Mathewson's avatar
Nick Mathewson committed
787

788
  rep_hist_note_used_internal(time(NULL), 1, 0);
789

790
  ++service->n_intro_circuits_launched;
791
  launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
792
793
794
                             intro->extend_info,
                             CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL);

795
  if (!launched) {
796
    log_info(LD_REND,
Roger Dingledine's avatar
Roger Dingledine committed
797
             "Can't launch circuit to establish introduction at %s.",
798
             escaped_safe_str(intro->extend_info->nickname));
799
800
    return -1;
  }
801
802
  strlcpy(launched->rend_query, service->service_id,
          sizeof(launched->rend_query));
803
  memcpy(launched->rend_pk_digest, service->pk_digest, DIGEST_LEN);
804
  launched->rend_desc_version = service->descriptor_version;
805
806
  if (service->descriptor_version == 2)
    launched->intro_key = crypto_pk_dup_key(intro->intro_key);
807
  if (launched->_base.state == CIRCUIT_STATE_OPEN)
808
    rend_service_intro_has_opened(launched);
809
810
811
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
812
/** Called when we're done building a circuit to an introduction point:
813
814
815
 *  sends a RELAY_ESTABLISH_INTRO cell.
 */
void
816
rend_service_intro_has_opened(origin_circuit_t *circuit)
817
818
{
  rend_service_t *service;
819
820
  size_t len;
  int r;
821
  char buf[RELAY_PAYLOAD_SIZE];
822
  char auth[DIGEST_LEN + 9];
823
  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
824
  int reason = END_CIRC_REASON_TORPROTOCOL;
825
  crypto_pk_env_t *intro_key;
826

827
  tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
828
  tor_assert(circuit->cpath);
Nick Mathewson's avatar
Nick Mathewson committed
829

830
831
  base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
                circuit->rend_pk_digest, REND_SERVICE_ID_LEN);
832

833
834
  service = rend_service_get_by_pk_digest_and_version(
              circuit->rend_pk_digest, circuit->rend_desc_version);
835
  if (!service) {
836
    log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
837
             serviceid, circuit->_base.n_circ_id);
838
    reason = END_CIRC_REASON_NOSUCHSERVICE;
839
840
841
    goto err;
  }

842
843
  log_info(LD_REND,
           "Established circuit %d as introduction point for service %s",
844
           circuit->_base.n_circ_id, serviceid);
Nick Mathewson's avatar
Nick Mathewson committed
845

846
847
848
  /* If the introduction point will not be used in an unversioned
   * descriptor, use the intro key instead of the service key in
   * ESTABLISH_INTRO. */
849
  if (service->descriptor_version == 0)
850
851
852
    intro_key = service->private_key;
  else
    intro_key = circuit->intro_key;
853
  /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
854
  len = crypto_pk_asn1_encode(intro_key, buf+2,