rendservice.c 38.3 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
56
  time_t intro_period_started;
  int n_intro_circuits_launched; /**< count of intro circuits we have
                                  * established in this period. */
Nick Mathewson's avatar
Nick Mathewson committed
57
  rend_service_descriptor_t *desc;
58
  time_t desc_is_dirty;
59
  time_t next_upload_time;
Nick Mathewson's avatar
Nick Mathewson committed
60
61
} rend_service_t;

Roger Dingledine's avatar
Roger Dingledine committed
62
/** A list of rend_service_t's for services run on this OP.
Nick Mathewson's avatar
Nick Mathewson committed
63
64
65
 */
static smartlist_t *rend_service_list = NULL;

66
/** Return the number of rendezvous services we have configured. */
67
68
69
int
num_rend_services(void)
{
70
71
72
73
74
  if (!rend_service_list)
    return 0;
  return smartlist_len(rend_service_list);
}

Nick Mathewson's avatar
Nick Mathewson committed
75
/** Release the storage held by <b>service</b>.
76
 */
77
78
static void
rend_service_free(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
79
{
80
81
82
83
84
85
86
87
88
89
90
91
92
  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);
  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
93
94
}

Roger Dingledine's avatar
Roger Dingledine committed
95
/** Release all the storage held in rend_service_list.
96
 */
97
98
void
rend_service_free_all(void)
Nick Mathewson's avatar
Nick Mathewson committed
99
100
101
102
{
  if (!rend_service_list) {
    return;
  }
Nick Mathewson's avatar
Nick Mathewson committed
103
104
  SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
                    rend_service_free(ptr));
Nick Mathewson's avatar
Nick Mathewson committed
105
  smartlist_free(rend_service_list);
106
  rend_service_list = NULL;
Nick Mathewson's avatar
Nick Mathewson committed
107
108
}

Nick Mathewson's avatar
Nick Mathewson committed
109
/** Validate <b>service</b> and add it to rend_service_list if possible.
110
 */
111
112
static void
add_service(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
113
114
115
116
117
{
  int i;
  rend_service_port_config_t *p;
  struct in_addr addr;

Nick Mathewson's avatar
Nick Mathewson committed
118
119
120
121
122
  if (!service->intro_prefer_nodes)
    service->intro_prefer_nodes = tor_strdup("");
  if (!service->intro_exclude_nodes)
    service->intro_exclude_nodes = tor_strdup("");

Nick Mathewson's avatar
Nick Mathewson committed
123
  if (!smartlist_len(service->ports)) {
124
    log_warn(LD_CONFIG, "Hidden service with no ports configured; ignoring.");
Nick Mathewson's avatar
Nick Mathewson committed
125
126
    rend_service_free(service);
  } else {
Nick Mathewson's avatar
Nick Mathewson committed
127
    smartlist_set_capacity(service->ports, -1);
Nick Mathewson's avatar
Nick Mathewson committed
128
    smartlist_add(rend_service_list, service);
129
130
    log_debug(LD_REND,"Configuring service with directory \"%s\"",
              service->directory);
Nick Mathewson's avatar
Nick Mathewson committed
131
    for (i = 0; i < smartlist_len(service->ports); ++i) {
132
      char addrbuf[INET_NTOA_BUF_LEN];
Nick Mathewson's avatar
Nick Mathewson committed
133
      p = smartlist_get(service->ports, i);
134
      addr.s_addr = htonl(p->real_addr);
135
      tor_inet_ntoa(&addr, addrbuf, sizeof(addrbuf));
136
137
      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
138
139
140
141
    }
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
142
/** Parses a real-port to virtual-port mapping and returns a new
143
144
145
 * rend_service_port_config_t.
 *
 * The format is: VirtualPort (IP|RealPort|IP:RealPort)?
Nick Mathewson's avatar
Nick Mathewson committed
146
147
 *
 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
Nick Mathewson's avatar
Nick Mathewson committed
148
 */
149
150
static rend_service_port_config_t *
parse_port_config(const char *string)
Nick Mathewson's avatar
Nick Mathewson committed
151
{
152
  smartlist_t *sl;
153
  int virtport;
154
155
  int realport;
  uint16_t p;
156
  uint32_t addr;
157
158
159
160
  const char *addrport;
  rend_service_port_config_t *result = NULL;

  sl = smartlist_create();
161
162
  smartlist_split_string(sl, string, " ",
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
163
  if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
164
    log_warn(LD_CONFIG, "Bad syntax in hidden service port configuration.");
165
    goto err;
Nick Mathewson's avatar
Nick Mathewson committed
166
  }
167
168

  virtport = atoi(smartlist_get(sl,0));
Nick Mathewson's avatar
Nick Mathewson committed
169
  if (virtport < 1 || virtport > 65535) {
170
171
    log_warn(LD_CONFIG, "Missing or invalid port in hidden service port "
             "configuration.");
172
    goto err;
Nick Mathewson's avatar
Nick Mathewson committed
173
  }
174
175

  if (smartlist_len(sl) == 1) {
Nick Mathewson's avatar
Nick Mathewson committed
176
177
    /* No addr:port part; use default. */
    realport = virtport;
178
179
    addr = 0x7F000001u; /* 127.0.0.1 */
  } else {
180
181
    addrport = smartlist_get(sl,1);
    if (strchr(addrport, ':') || strchr(addrport, '.')) {
182
      if (parse_addr_port(LOG_WARN, addrport, NULL, &addr, &p)<0) {
183
184
        log_warn(LD_CONFIG,"Unparseable address in hidden service port "
                 "configuration.");
185
186
187
188
189
190
191
192
193
        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 */
194
    }
Nick Mathewson's avatar
Nick Mathewson committed
195
196
197
198
199
  }

  result = tor_malloc(sizeof(rend_service_port_config_t));
  result->virtual_port = virtport;
  result->real_port = realport;
200
  result->real_addr = addr;
201
202
203
 err:
  SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  smartlist_free(sl);
Nick Mathewson's avatar
Nick Mathewson committed
204
205
206
  return result;
}

Roger Dingledine's avatar
Roger Dingledine committed
207
/** Set up rend_service_list, based on the values of HiddenServiceDir and
Nick Mathewson's avatar
Nick Mathewson committed
208
 * HiddenServicePort in <b>options</b>.  Return 0 on success and -1 on
209
210
 * 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
211
 */
212
213
int
rend_config_services(or_options_t *options, int validate_only)
Nick Mathewson's avatar
Nick Mathewson committed
214
{
215
  config_line_t *line;
Nick Mathewson's avatar
Nick Mathewson committed
216
217
  rend_service_t *service = NULL;
  rend_service_port_config_t *portcfg;
218

219
  if (!validate_only) {
220
    rend_service_free_all();
221
222
    rend_service_list = smartlist_create();
  }
Nick Mathewson's avatar
Nick Mathewson committed
223
224
225

  for (line = options->RendConfigLines; line; line = line->next) {
    if (!strcasecmp(line->key, "HiddenServiceDir")) {
226
227
228
229
230
231
      if (service) {
        if (validate_only)
          rend_service_free(service);
        else
          add_service(service);
      }
Nick Mathewson's avatar
Nick Mathewson committed
232
233
234
      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
235
      service->intro_nodes = smartlist_create();
236
      service->intro_period_started = time(NULL);
237
238
239
      continue;
    }
    if (!service) {
240
241
      log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
               line->key);
242
243
244
245
      rend_service_free(service);
      return -1;
    }
    if (!strcasecmp(line->key, "HiddenServicePort")) {
Nick Mathewson's avatar
Nick Mathewson committed
246
247
      portcfg = parse_port_config(line->value);
      if (!portcfg) {
Roger Dingledine's avatar
tabs    
Roger Dingledine committed
248
249
        rend_service_free(service);
        return -1;
Nick Mathewson's avatar
Nick Mathewson committed
250
251
      }
      smartlist_add(service->ports, portcfg);
252
    } else if (!strcasecmp(line->key, "HiddenServiceNodes")) {
Nick Mathewson's avatar
Nick Mathewson committed
253
      if (service->intro_prefer_nodes) {
254
255
256
        log_warn(LD_CONFIG,
                 "Got multiple HiddenServiceNodes lines for a single "
                 "service.");
257
258
        return -1;
      }
Nick Mathewson's avatar
Nick Mathewson committed
259
      service->intro_prefer_nodes = tor_strdup(line->value);
260
    } else {
Roger Dingledine's avatar
Roger Dingledine committed
261
      tor_assert(!strcasecmp(line->key, "HiddenServiceExcludeNodes"));
262
      if (service->intro_exclude_nodes) {
263
264
265
        log_warn(LD_CONFIG,
                 "Got multiple HiddenServiceExcludedNodes lines for "
                 "a single service.");
266
267
268
        return -1;
      }
      service->intro_exclude_nodes = tor_strdup(line->value);
Nick Mathewson's avatar
Nick Mathewson committed
269
270
    }
  }
271
272
273
274
275
276
  if (service) {
    if (validate_only)
      rend_service_free(service);
    else
      add_service(service);
  }
Nick Mathewson's avatar
Nick Mathewson committed
277
278
279
280

  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
281
/** Replace the old value of <b>service</b>-\>desc with one that reflects
Nick Mathewson's avatar
Nick Mathewson committed
282
 * the other fields in service.
Nick Mathewson's avatar
Nick Mathewson committed
283
 */
284
285
static void
rend_service_update_descriptor(rend_service_t *service)
Nick Mathewson's avatar
Nick Mathewson committed
286
287
{
  rend_service_descriptor_t *d;
288
  origin_circuit_t *circ;
Nick Mathewson's avatar
Nick Mathewson committed
289
  int i,n;
290
  routerinfo_t *router;
Nick Mathewson's avatar
Nick Mathewson committed
291
292
293
294
295
296
297
298

  if (service->desc) {
    rend_service_descriptor_free(service->desc);
    service->desc = NULL;
  }
  d = service->desc = tor_malloc(sizeof(rend_service_descriptor_t));
  d->pk = crypto_pk_dup_key(service->private_key);
  d->timestamp = time(NULL);
299
  d->version = 1;
300
301
  n = smartlist_len(service->intro_nodes);
  d->n_intro_points = 0;
302
303
304
  d->intro_points = tor_malloc_zero(sizeof(char*)*n);
  d->intro_point_extend_info = tor_malloc_zero(sizeof(extend_info_t*)*n);
  d->protocols = (1<<2) | (1<<0); /* We support protocol 2 and protocol 0. */
Nick Mathewson's avatar
Nick Mathewson committed
305
  for (i=0; i < n; ++i) {
306
    router = router_get_by_nickname(smartlist_get(service->intro_nodes, i),1);
307
    if (!router) {
308
309
      log_info(LD_REND,"Router '%s' not found for intro point %d. Skipping.",
               safe_str((char*)smartlist_get(service->intro_nodes, i)), i);
310
311
      continue;
    }
312
    circ = find_intro_circuit(router, service->pk_digest);
313
    if (circ && circ->_base.purpose == CIRCUIT_PURPOSE_S_INTRO) {
314
      /* We have an entirely established intro circuit. */
315
316
317
318
      d->intro_points[d->n_intro_points] = tor_strdup(router->nickname);
      d->intro_point_extend_info[d->n_intro_points] =
        extend_info_from_router(router);
      d->n_intro_points++;
319
    }
Nick Mathewson's avatar
Nick Mathewson committed
320
321
322
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
323
/** Load and/or generate private keys for all hidden services.  Return 0 on
Nick Mathewson's avatar
Nick Mathewson committed
324
325
 * success, -1 on failure.
 */
326
327
int
rend_service_load_keys(void)
Nick Mathewson's avatar
Nick Mathewson committed
328
329
330
331
332
333
{
  int i;
  rend_service_t *s;
  char fname[512];
  char buf[128];

Nick Mathewson's avatar
Nick Mathewson committed
334
335
  for (i=0; i < smartlist_len(rend_service_list); ++i) {
    s = smartlist_get(rend_service_list,i);
Nick Mathewson's avatar
Nick Mathewson committed
336
337
    if (s->private_key)
      continue;
338
339
    log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
             s->directory);
Nick Mathewson's avatar
Nick Mathewson committed
340

Nick Mathewson's avatar
Nick Mathewson committed
341
    /* Check/create directory */
342
    if (check_private_dir(s->directory, CPD_CREATE) < 0)
Nick Mathewson's avatar
Nick Mathewson committed
343
344
345
      return -1;

    /* Load key */
346
    if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
347
348
        strlcat(fname,PATH_SEPARATOR"private_key",sizeof(fname))
                                                  >= sizeof(fname)) {
349
350
      log_warn(LD_CONFIG, "Directory name too long to store key file: \"%s\".",
               s->directory);
Nick Mathewson's avatar
Nick Mathewson committed
351
352
      return -1;
    }
353
    s->private_key = init_key_from_file(fname, 1, LOG_ERR);
Nick Mathewson's avatar
Nick Mathewson committed
354
355
356
357
358
    if (!s->private_key)
      return -1;

    /* Create service file */
    if (rend_get_service_id(s->private_key, s->service_id)<0) {
359
      log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
Nick Mathewson's avatar
Nick Mathewson committed
360
361
      return -1;
    }
362
    if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
363
      log_warn(LD_BUG, "Couldn't compute hash of public key.");
364
365
      return -1;
    }
366
    if (strlcpy(fname,s->directory,sizeof(fname)) >= sizeof(fname) ||
367
368
        strlcat(fname,PATH_SEPARATOR"hostname",sizeof(fname))
                                                  >= sizeof(fname)) {
369
370
      log_warn(LD_CONFIG, "Directory name too long to store hostname file:"
               " \"%s\".", s->directory);
Nick Mathewson's avatar
Nick Mathewson committed
371
372
      return -1;
    }
373
    tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
374
    if (write_str_to_file(fname,buf,0)<0)
Nick Mathewson's avatar
Nick Mathewson committed
375
376
377
378
      return -1;
  }
  return 0;
}
379

Nick Mathewson's avatar
Nick Mathewson committed
380
/** Return the service whose public key has a digest of <b>digest</b>. Return
381
382
 * NULL if no such service exists.
 */
383
static rend_service_t *
384
385
rend_service_get_by_pk_digest(const char* digest)
{
Nick Mathewson's avatar
Nick Mathewson committed
386
  SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
387
                    if (!memcmp(s->pk_digest,digest,DIGEST_LEN)) return s);
388
389
390
  return NULL;
}

391
392
393
394
/** Return 1 if any virtual port in <b>service</b> wants a circuit
 * to have good uptime. Else return 0.
 */
static int
395
396
rend_service_requires_uptime(rend_service_t *service)
{
397
398
399
400
401
  int i;
  rend_service_port_config_t *p;

  for (i=0; i < smartlist_len(service->ports); ++i) {
    p = smartlist_get(service->ports, i);
402
403
    if (smartlist_string_num_isin(get_options()->LongLivedPorts,
                                  p->virtual_port))
404
405
406
407
408
      return 1;
  }
  return 0;
}

409
410
411
412
/******
 * Handle cells
 ******/

Roger Dingledine's avatar
Roger Dingledine committed
413
/** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
414
 * rendezvous point.
415
 */
416
int
417
rend_service_introduce(origin_circuit_t *circuit, const char *request,
418
                       size_t request_len)
419
{
420
421
  char *ptr, *r_cookie;
  extend_info_t *extend_info = NULL;
422
  char buf[RELAY_PAYLOAD_SIZE];
423
  char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
424
  rend_service_t *service;
425
  int r, i;
426
  size_t len, keylen;
427
  crypto_dh_env_t *dh = NULL;
428
  origin_circuit_t *launched = NULL;
429
  crypt_path_t *cpath = NULL;
430
  char serviceid[REND_SERVICE_ID_LEN+1];
Nick Mathewson's avatar
Nick Mathewson committed
431
  char hexcookie[9];
432
  int circ_needs_uptime;
433
  int reason = END_CIRC_REASON_TORPROTOCOL;
Nick Mathewson's avatar
Nick Mathewson committed
434

435
  base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
436
                circuit->rend_pk_digest,10);
437
  log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %d.",
438
           escaped(serviceid), circuit->_base.n_circ_id);
439

440
  if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_INTRO) {
441
442
    log_warn(LD_PROTOCOL,
             "Got an INTRODUCE2 over a non-introduction circuit %d.",
443
             circuit->_base.n_circ_id);
444
445
446
    return -1;
  }

447
  /* min key length plus digest length plus nickname length */
448
  if (request_len < DIGEST_LEN+REND_COOKIE_LEN+(MAX_NICKNAME_LEN+1)+
449
      DH_KEY_LEN+42) {
450
    log_warn(LD_PROTOCOL, "Got a truncated INTRODUCE2 cell on circ %d.",
451
             circuit->_base.n_circ_id);
452
453
454
    return -1;
  }

455
  /* first DIGEST_LEN bytes of request is service pk digest */
456
457
  service = rend_service_get_by_pk_digest(request);
  if (!service) {
458
    log_warn(LD_REND, "Got an INTRODUCE2 cell for an unrecognized service %s.",
459
             escaped(serviceid));
460
461
    return -1;
  }
462
  if (memcmp(circuit->rend_pk_digest, request, DIGEST_LEN)) {
463
    base32_encode(serviceid, REND_SERVICE_ID_LEN+1, request, 10);
464
    log_warn(LD_REND, "Got an INTRODUCE2 cell for the wrong service (%s).",
465
             escaped(serviceid));
466
467
468
469
    return -1;
  }

  keylen = crypto_pk_keysize(service->private_key);
470
  if (request_len < keylen+DIGEST_LEN) {
471
472
    log_warn(LD_PROTOCOL,
             "PK-encrypted portion of INTRODUCE2 cell was truncated.");
473
474
475
    return -1;
  }
  /* Next N bytes is encrypted with service key */
476
  note_crypto_pk_op(REND_SERVER);
477
  r = crypto_pk_private_hybrid_decrypt(
478
       service->private_key,buf,request+DIGEST_LEN,request_len-DIGEST_LEN,
479
       PK_PKCS1_OAEP_PADDING,1);
480
  if (r<0) {
481
    log_warn(LD_PROTOCOL, "Couldn't decrypt INTRODUCE2 cell.");
482
483
    return -1;
  }
484
  len = r;
485
486
487
488
489
490
491
492
493
494
495
496
  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));
497
    if ((int)len != 7+DIGEST_LEN+2+klen+20+128) {
498
499
      log_warn(LD_PROTOCOL, "Bad length %u for version 2 INTRODUCE2 cell.",
               (int)len);
500
      reason = END_CIRC_REASON_TORPROTOCOL;
501
502
503
504
      goto err;
    }
    extend_info->onion_key = crypto_pk_asn1_decode(buf+7+DIGEST_LEN+2, klen);
    if (!extend_info->onion_key) {
505
506
      log_warn(LD_PROTOCOL,
               "Error decoding onion key in version 2 INTRODUCE2 cell.");
507
      reason = END_CIRC_REASON_TORPROTOCOL;
508
509
510
511
      goto err;
    }
    ptr = buf+7+DIGEST_LEN+2+klen;
    len -= 7+DIGEST_LEN+2+klen;
512
  } else {
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
    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) {
528
      log_warn(LD_PROTOCOL,
529
               "Couldn't find a nul-padded nickname in INTRODUCE2 cell.");
530
531
532
533
      return -1;
    }
    if ((version == 0 && !is_legal_nickname(rp_nickname)) ||
        (version == 1 && !is_legal_nickname_or_hexdigest(rp_nickname))) {
534
      log_warn(LD_PROTOCOL, "Bad nickname in INTRODUCE2 cell.");
535
536
537
538
539
      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;
540
541
    len -= rp_nickname - buf; /* also remove header space used by version, if
                               * any */
542
    router = router_get_by_nickname(rp_nickname, 0);
543
    if (!router) {
544
      log_info(LD_REND, "Couldn't find router %s named in rendezvous cell.",
545
               escaped_safe_str(rp_nickname));
546
547
      /* XXXX Add a no-such-router reason? */
      reason = END_CIRC_REASON_TORPROTOCOL;
548
549
550
551
      goto err;
    }

    extend_info = extend_info_from_router(router);
552
  }
553

554
  if (len != REND_COOKIE_LEN+DH_KEY_LEN) {
555
    log_warn(LD_PROTOCOL, "Bad length %u for INTRODUCE2 cell.", (int)len);
556
    reason = END_CIRC_REASON_TORPROTOCOL;
557
558
    return -1;
  }
559

560
  r_cookie = ptr;
561
  base16_encode(hexcookie,9,r_cookie,4);
562

563
564
565
  /* Try DH handshake... */
  dh = crypto_dh_new();
  if (!dh || crypto_dh_generate_public(dh)<0) {
566
567
    log_warn(LD_BUG,"Internal error: couldn't build DH state "
             "or generate public key.");
568
    reason = END_CIRC_REASON_INTERNAL;
569
570
    goto err;
  }
571
572
  if (crypto_dh_compute_secret(dh, ptr+REND_COOKIE_LEN, DH_KEY_LEN, keys,
                               DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
573
    log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
574
    reason = END_CIRC_REASON_INTERNAL;
575
576
577
    goto err;
  }

578
579
580
  circ_needs_uptime = rend_service_requires_uptime(service);

  /* help predict this next time */
581
  rep_hist_note_used_internal(time(NULL), circ_needs_uptime, 1);
582

583
  /* Launch a circuit to alice's chosen rendezvous point.
584
   */
585
  for (i=0;i<MAX_REND_FAILURES;i++) {
586
    launched = circuit_launch_by_extend_info(
587
          CIRCUIT_PURPOSE_S_CONNECT_REND, 0, extend_info,
588
          circ_needs_uptime, 1, 1);
589

590
591
592
    if (launched)
      break;
  }
593
  if (!launched) { /* give up */
594
    log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
Roger Dingledine's avatar
Roger Dingledine committed
595
             "point %s for service %s.",
596
             escaped_safe_str(extend_info->nickname), serviceid);
597
    reason = END_CIRC_REASON_CONNECTFAILED;
Roger Dingledine's avatar
Roger Dingledine committed
598
    goto err;
599
  }
600
  log_info(LD_REND,
Roger Dingledine's avatar
Roger Dingledine committed
601
           "Accepted intro; launching circuit to %s "
602
           "(cookie %s) for service %s.",
Roger Dingledine's avatar
Roger Dingledine committed
603
           escaped_safe_str(extend_info->nickname), hexcookie, serviceid);
Roger Dingledine's avatar
Roger Dingledine committed
604
  tor_assert(launched->build_state);
605
  /* Fill in the circuit's state. */
606
  memcpy(launched->rend_pk_digest, circuit->rend_pk_digest,
607
         DIGEST_LEN);
608
  memcpy(launched->rend_cookie, r_cookie, REND_COOKIE_LEN);
609
610
  strlcpy(launched->rend_query, service->service_id,
          sizeof(launched->rend_query));
611
612
  launched->build_state->pending_final_cpath = cpath =
    tor_malloc_zero(sizeof(crypt_path_t));
613
  cpath->magic = CRYPT_PATH_MAGIC;
614
  launched->build_state->expiry_time = time(NULL) + MAX_REND_TIMEOUT;
615

616
  cpath->dh_handshake_state = dh;
617
  dh = NULL;
618
  if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
619
    goto err;
620
  memcpy(cpath->handshake_digest, keys, DIGEST_LEN);
621
  if (extend_info) extend_info_free(extend_info);
622
623

  return 0;
624
625
 err:
  if (dh) crypto_dh_free(dh);
626
  if (launched)
627
    circuit_mark_for_close(TO_CIRCUIT(launched), reason);
628
  if (extend_info) extend_info_free(extend_info);
629
  return -1;
630
631
}

Roger Dingledine's avatar
Roger Dingledine committed
632
/** Called when we fail building a rendezvous circuit at some point other
633
634
 * than the last hop: launches a new circuit to the same rendezvous point.
 */
635
void
636
rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
637
{
638
  origin_circuit_t *newcirc;
639
640
  cpath_build_state_t *newstate, *oldstate;

641
  tor_assert(oldcirc->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
642
643

  if (!oldcirc->build_state ||
644
645
      oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
      oldcirc->build_state->expiry_time < time(NULL)) {
646
647
648
649
650
    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*");
651
652
653
    return;
  }

654
655
656
  oldstate = oldcirc->build_state;
  tor_assert(oldstate);

657
  if (oldstate->pending_final_cpath == NULL) {
658
659
    log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
             "Initiator will retry.");
660
661
662
    return;
  }

663
  log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
664
           oldstate->chosen_exit->nickname);
665

666
  newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND, 0,
667
                               oldstate->chosen_exit, 0, 1, 1);
668
  if (!newcirc) {
669
    log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
670
             oldstate->chosen_exit->nickname);
671
672
673
    return;
  }
  newstate = newcirc->build_state;
674
  tor_assert(newstate);
675
  newstate->failure_count = oldstate->failure_count+1;
676
  newstate->expiry_time = oldstate->expiry_time;
677
678
679
  newstate->pending_final_cpath = oldstate->pending_final_cpath;
  oldstate->pending_final_cpath = NULL;

680
  memcpy(newcirc->rend_query, oldcirc->rend_query, REND_SERVICE_ID_LEN+1);
681
  memcpy(newcirc->rend_pk_digest, oldcirc->rend_pk_digest,
682
         DIGEST_LEN);
683
  memcpy(newcirc->rend_cookie, oldcirc->rend_cookie,
684
         REND_COOKIE_LEN);
685
686
}

Roger Dingledine's avatar
Roger Dingledine committed
687
/** Launch a circuit to serve as an introduction point for the service
Nick Mathewson's avatar
Nick Mathewson committed
688
 * <b>service</b> at the introduction point <b>nickname</b>
689
690
 */
static int
691
692
rend_service_launch_establish_intro(rend_service_t *service,
                                    const char *nickname)
693
{
694
  origin_circuit_t *launched;
695

696
697
  log_info(LD_REND,
           "Launching circuit to introduction point %s for service %s",
Roger Dingledine's avatar
Roger Dingledine committed
698
           escaped_safe_str(nickname), service->service_id);
Nick Mathewson's avatar
Nick Mathewson committed
699

700
  rep_hist_note_used_internal(time(NULL), 1, 0);
701

702
  ++service->n_intro_circuits_launched;
703
  launched = circuit_launch_by_nickname(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO, 0,
704
                                        nickname, 1, 0, 1);
705
  if (!launched) {
706
    log_info(LD_REND,
Roger Dingledine's avatar
Roger Dingledine committed
707
708
             "Can't launch circuit to establish introduction at %s.",
             escaped_safe_str(nickname));
709
710
    return -1;
  }
711
712
  strlcpy(launched->rend_query, service->service_id,
          sizeof(launched->rend_query));
713
  memcpy(launched->rend_pk_digest, service->pk_digest, DIGEST_LEN);
714

715
  if (launched->_base.state == CIRCUIT_STATE_OPEN)
716
    rend_service_intro_has_opened(launched);
717
718
719
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
720
/** Called when we're done building a circuit to an introduction point:
721
722
723
 *  sends a RELAY_ESTABLISH_INTRO cell.
 */
void
724
rend_service_intro_has_opened(origin_circuit_t *circuit)
725
726
{
  rend_service_t *service;
727
728
  size_t len;
  int r;
729
  char buf[RELAY_PAYLOAD_SIZE];
730
  char auth[DIGEST_LEN + 9];
731
  char serviceid[REND_SERVICE_ID_LEN+1];
732
  int reason = END_CIRC_REASON_TORPROTOCOL;
733

734
  tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
735
  tor_assert(circuit->cpath);
Nick Mathewson's avatar
Nick Mathewson committed
736

737
  base32_encode(serviceid, REND_SERVICE_ID_LEN+1,
738
                circuit->rend_pk_digest,10);
739

740
  service = rend_service_get_by_pk_digest(circuit->rend_pk_digest);
741
  if (!service) {
742
    log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %d.",
743
             serviceid, circuit->_base.n_circ_id);
744
    reason = END_CIRC_REASON_NOSUCHSERVICE;
745
746
747
    goto err;
  }

748
749
  log_info(LD_REND,
           "Established circuit %d as introduction point for service %s",
750
           circuit->_base.n_circ_id, serviceid);
Nick Mathewson's avatar
Nick Mathewson committed
751

752
753
754
  /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
  len = crypto_pk_asn1_encode(service->private_key, buf+2,
                              RELAY_PAYLOAD_SIZE-2);
755
  set_uint16(buf, htons((uint16_t)len));
756
  len += 2;
757
758
  memcpy(auth, circuit->cpath->prev->handshake_digest, DIGEST_LEN);
  memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
759
  if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
760
761
    goto err;
  len += 20;
762
  note_crypto_pk_op(REND_SERVER);
763
  r = crypto_pk_private_sign_digest(service->private_key, buf+len, buf, len);
764
  if (r<0) {
765
    log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
766
    reason = END_CIRC_REASON_INTERNAL;
767
768
769
770
    goto err;
  }
  len += r;

771
  if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
772
                                   RELAY_COMMAND_ESTABLISH_INTRO,
773
                                   buf, len, circuit->cpath->prev)<0) {
774
775
    log_info(LD_GENERAL,
             "Couldn't send introduction request for service %s on circuit %d",
776
             serviceid, circuit->_base.n_circ_id);
777
    reason = END_CIRC_REASON_INTERNAL;
778
779
780
781
782
    goto err;
  }

  return;
 err:
783
  circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
784
785
}

Roger Dingledine's avatar
Roger Dingledine committed
786
/** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
787
788
 * live introduction point, and note that the service descriptor is
 * now out-of-date.*/
Nick Mathewson's avatar
Nick Mathewson committed
789
int
790
rend_service_intro_established(origin_circuit_t *circuit, const char *request,
791
                               size_t request_len)
Nick Mathewson's avatar
Nick Mathewson committed
792
{
793
  rend_service_t *service;
794
795
  (void) request;
  (void) request_len;
796

797
  if (circuit->_base.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
798
799
    log_warn(LD_PROTOCOL,
             "received INTRO_ESTABLISHED cell on non-intro circuit.");
Nick Mathewson's avatar
Nick Mathewson committed
800
801
    goto err;
  }
802
  service = rend_service_get_by_pk_digest(circuit->rend_pk_digest);
803
  if (!service) {
804
    log_warn(LD_REND, "Unknown service on introduction circuit %d.",
805
             circuit->_base.n_circ_id);
806
807
    goto err;
  }
808
  service->desc_is_dirty = time(NULL);
809
  circuit->_base.purpose = CIRCUIT_PURPOSE_S_INTRO;
Nick Mathewson's avatar
Nick Mathewson committed
810
811
812

  return 0;
 err:
813
  circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
Nick Mathewson's avatar
Nick Mathewson committed
814
815
816
  return -1;
}

Roger Dingledine's avatar
Roger Dingledine committed
817
/** Called once a circuit to a rendezvous point is established: sends a
818
819
820
 *  RELAY_COMMAND_RENDEZVOUS1 cell.
 */
void
821
rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
822
823
824
825
{
  rend_service_t *service;
  char buf[RELAY_PAYLOAD_SIZE];
  crypt_path_t *hop;
826
  char serviceid[REND_SERVICE_ID_LEN+1];
Nick Mathewson's avatar
Nick Mathewson committed
827
  char hexcookie[9];
828
  int reason;
829

830
  tor_assert(circuit->_base.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
Roger Dingledine's avatar
Roger Dingledine committed
831
832
  tor_assert(circuit->cpath);
  tor_assert(circuit->build_state);