summaryrefslogtreecommitdiff
path: root/src/or/rendclient.c
blob: 7af0a03a73f63409dc388b6666c5b914e1011ebe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/* Copyright 2004 Roger Dingledine */
/* See LICENSE for licensing information */
/* $Id$ */

#include "or.h"

/* send the introduce cell */
void
rend_client_introcirc_is_open(circuit_t *circ)
{
  assert(circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  assert(CIRCUIT_IS_ORIGIN(circ) && circ->cpath);

  log_fn(LOG_INFO,"introcirc is open");
  connection_ap_attach_pending();
}

/* send the establish-rendezvous cell. if it fails, mark
 * the circ for close and return -1. else return 0.
 */
int
rend_client_send_establish_rendezvous(circuit_t *circ)
{
  assert(circ->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  log_fn(LOG_INFO, "Sending an ESTABLISH_RENDEZVOUS cell");

  if (crypto_rand(REND_COOKIE_LEN, circ->rend_cookie)<0) {
    log_fn(LOG_WARN, "Couldn't get random cookie");
    circuit_mark_for_close(circ);
    return -1;
  }
  if (connection_edge_send_command(NULL,circ,
                                   RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
                                   circ->rend_cookie, REND_COOKIE_LEN,
                                   circ->cpath->prev)<0) {
    /* circ is already marked for close */
    log_fn(LOG_WARN, "Couldn't send ESTABLISH_RENDEZVOUS cell");
    return -1;
  }

  return 0;
}

/* Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
 * down introcirc if possible.
 */
int
rend_client_send_introduction(circuit_t *introcirc, circuit_t *rendcirc) {
  int payload_len, r;
  char payload[RELAY_PAYLOAD_SIZE];
  char tmp[(MAX_NICKNAME_LEN+1)+REND_COOKIE_LEN+DH_KEY_LEN];
  rend_cache_entry_t *entry;
  crypt_path_t *cpath;

  assert(introcirc->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  assert(rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY);
  assert(!rend_cmp_service_ids(introcirc->rend_query, rendcirc->rend_query));

  if(rend_cache_lookup_entry(introcirc->rend_query, &entry) < 1) {
    log_fn(LOG_WARN,"query '%s' didn't have valid rend desc in cache. Failing.",
           introcirc->rend_query);
    goto err;
  }

  /* first 20 bytes of payload are the hash of bob's pk */
  if (crypto_pk_get_digest(entry->parsed->pk, payload)<0) {
    log_fn(LOG_WARN, "Couldn't hash public key.");
    goto err;
  }

  /* Initialize the pending_final_cpath and start the DH handshake. */
  cpath = rendcirc->build_state->pending_final_cpath;
  if (!cpath) {
    cpath = rendcirc->build_state->pending_final_cpath =
      tor_malloc_zero(sizeof(crypt_path_t));
    if (!(cpath->handshake_state = crypto_dh_new())) {
      log_fn(LOG_WARN, "Couldn't allocate DH");
      goto err;
    }
    if (crypto_dh_generate_public(cpath->handshake_state)<0) {
      log_fn(LOG_WARN, "Couldn't generate g^x");
      goto err;
    }
  }

  /* write the remaining items into tmp */
  strncpy(tmp, rendcirc->build_state->chosen_exit, (MAX_NICKNAME_LEN+1)); /* nul pads */
  memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_cookie, REND_COOKIE_LEN);
  if (crypto_dh_get_public(cpath->handshake_state,
                           tmp+MAX_NICKNAME_LEN+1+REND_COOKIE_LEN,
                           DH_KEY_LEN)<0) {
    log_fn(LOG_WARN, "Couldn't extract g^x");
    goto err;
  }

  r = crypto_pk_public_hybrid_encrypt(entry->parsed->pk, tmp,
                           MAX_NICKNAME_LEN+1+REND_COOKIE_LEN+DH_KEY_LEN,
                                      payload+DIGEST_LEN,
                                      PK_PKCS1_OAEP_PADDING, 0);
  if (r<0) {
    log_fn(LOG_WARN,"hybrid pk encrypt failed.");
    goto err;
  }

  assert(DIGEST_LEN + r <= RELAY_PAYLOAD_SIZE); /* we overran something */
  payload_len = DIGEST_LEN + r;

  if (connection_edge_send_command(NULL, introcirc,
                                   RELAY_COMMAND_INTRODUCE1,
                                   payload, payload_len,
                                   introcirc->cpath->prev)<0) {
    /* introcirc is already marked for close. leave rendcirc alone. */
    log_fn(LOG_WARN, "Couldn't send INTRODUCE1 cell");
    return -1;
  }

  /* Now, we wait for an ACK or NAK on this circuit. */
  introcirc->purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT;

  return 0;
err:
  circuit_mark_for_close(introcirc);
  circuit_mark_for_close(rendcirc);
  return -1;
}

/* send the rendezvous cell */
void
rend_client_rendcirc_is_open(circuit_t *circ)
{
  assert(circ->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  assert(CIRCUIT_IS_ORIGIN(circ));

  log_fn(LOG_INFO,"rendcirc is open");

  /* generate a rendezvous cookie, store it in circ */
  if (rend_client_send_establish_rendezvous(circ) < 0) {
    return;
  }

  connection_ap_attach_pending();
}

/* Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
 */
int
rend_client_introduction_acked(circuit_t *circ,
                               const char *request, int request_len)
{
  int i, r;
  rend_cache_entry_t *ent;
  char *nickname;
  circuit_t *rendcirc;

  if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
    log_fn(LOG_WARN, "Received REND_INTRODUCE_ACK on unexpected circuit %d",
           circ->n_circ_id);
    circuit_mark_for_close(circ);
    return -1;
  }

  assert(circ->build_state->chosen_exit);

  if (request_len == 0) {
    /* It's an ACK; the introduction point relayed our introduction request. */
    /* Locate the rend circ which is waiting to hear about this ack,
     * and tell it.
     */
    log_fn(LOG_INFO,"Received ack. Telling rend circ.");
    rendcirc = circuit_get_by_rend_query_and_purpose(
               circ->rend_query, CIRCUIT_PURPOSE_C_REND_READY);
    if(rendcirc) { /* remember the ack */
      rendcirc->purpose = CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED;
    }
    /* close the circuit: we won't need it anymore. */
    circuit_mark_for_close(circ);
  } else {
    /* It's a NAK; the introduction point didn't relay our request. */
    circ->purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
    /* XXXX
     * Now become non-open, extend to another one of Bob's
     * introduction points, and try again.  Maybe mark the service as
     * non-functional at the first intro point somehow?
     *
     * Or re-fetch the service descriptor? Hm....
     */
    r = rend_cache_lookup_entry(circ->rend_query, &ent);
    if (r<0) {
      log_fn(LOG_WARN, "Malformed service ID '%s'", circ->rend_query);
      return -1;
    }
    if (r>0) {
      /* Okay, we found the right service desc.  First, remove this intro point
       * from the parsed descriptor (if it's still there!)
       */
      for (i=0; i < ent->parsed->n_intro_points; ++i) {
        if (!strcasecmp(ent->parsed->intro_points[i],
                        circ->build_state->chosen_exit)) {
          tor_free(ent->parsed->intro_points[i]);
          ent->parsed->intro_points[i] =
            ent->parsed->intro_points[--ent->parsed->n_intro_points];
          break;
        }
      }
      /* If there are any introduction points left, re-extend the circuit to
       * another intro point and try again. */
      if (ent->parsed->n_intro_points) {
        nickname = rend_client_get_random_intro(circ->rend_query);
        assert(nickname);
        if (!router_get_by_nickname(nickname)) {
          log_fn(LOG_WARN, "Advertised intro point '%s' for %s is not known. Closing.",
                 nickname, circ->rend_query);
          circuit_mark_for_close(circ);
          return -1;
        }
        log_fn(LOG_INFO, "Chose new intro point %s for %s (circ %d, %d choices left)",
               nickname, circ->rend_query, circ->n_circ_id, ent->parsed->n_intro_points);
        circ->state = CIRCUIT_STATE_BUILDING;
        tor_free(circ->build_state->chosen_exit);
        circ->build_state->chosen_exit = tor_strdup(nickname);
        ++circ->build_state->desired_path_len;
        if (circuit_send_next_onion_skin(circ)<0) {
          log_fn(LOG_WARN, "Couldn't extend circuit to new intro point.");
          circuit_mark_for_close(circ);
          return -1;
        }
        return 0;
      }
    }
    /* Either we have no service desc, or all the intro points in that
     * descriptor failed. So re-fetch the descriptor and try again. */
    circ->purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
    /* XXX anything else we need to do to circ? */
    /* Refetch descriptor */
    if(!connection_get_by_type_rendquery(CONN_TYPE_DIR, circ->rend_query)) {
      /* not one already; initiate a dir rend desc lookup */
      directory_initiate_command(router_pick_directory_server(),
                                 DIR_PURPOSE_FETCH_RENDDESC,
                                 circ->rend_query, strlen(circ->rend_query));
    }
  }
  return 0;
}

/* Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
 * the circuit to C_REND_READY.
 */
int
rend_client_rendezvous_acked(circuit_t *circ, const char *request, int request_len)
{
  /* we just got an ack for our establish-rendezvous. switch purposes. */
  if(circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
    log_fn(LOG_WARN,"Got a rendezvous ack when we weren't expecting one. Closing circ.");
    circuit_mark_for_close(circ);
    return -1;
  }
  log_fn(LOG_INFO,"Got rendezvous ack. This circuit is now ready for rendezvous.");
  circ->purpose = CIRCUIT_PURPOSE_C_REND_READY;
  return 0;
}

/* bob sent us a rendezvous cell, join the circs. */
int
rend_client_receive_rendezvous(circuit_t *circ, const char *request, int request_len)
{
  crypt_path_t *hop;
  char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];

  if( (circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
       circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
      || !circ->build_state->pending_final_cpath) {
    log_fn(LOG_WARN,"Got rendezvous2 cell from Bob, but not expecting it. Closing.");
    circuit_mark_for_close(circ);
    return -1;
  }

  if (request_len != DH_KEY_LEN+DIGEST_LEN) {
    log_fn(LOG_WARN,"Incorrect length (%d) on RENDEZVOUS2 cell.",request_len);
    goto err;
  }

  /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
  assert(circ->build_state && circ->build_state->pending_final_cpath);
  hop = circ->build_state->pending_final_cpath;
  assert(hop->handshake_state);
  if (crypto_dh_compute_secret(hop->handshake_state, request, DH_KEY_LEN,
                               keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
    log_fn(LOG_WARN, "Couldn't complete DH handshake");
    goto err;
  }
  /* ... and set up cpath. */
  if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
    goto err;

  /* Check whether the digest is right... */
  if (memcmp(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
    log_fn(LOG_WARN, "Incorrect digest of key material");
    goto err;
  }

  crypto_dh_free(hop->handshake_state);
  hop->handshake_state = NULL;

  /* All is well. Extend the circuit. */
  circ->purpose = CIRCUIT_PURPOSE_C_REND_JOINED;
  hop->state = CPATH_STATE_OPEN;
  /* set the windows to default. these are the windows
   * that alice thinks bob has.
   */
  hop->package_window = CIRCWINDOW_START;
  hop->deliver_window = CIRCWINDOW_START;

  onion_append_to_cpath(&circ->cpath, hop);
  circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
  return 0;
 err:
  circuit_mark_for_close(circ);
  return -1;
}

/* Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that
 * are waiting on query. If success==1, move them to the next state.
 * If success==0, fail them.
 */
void rend_client_desc_fetched(char *query, int success) {
  connection_t **carray;
  connection_t *conn;
  int n, i;
  rend_cache_entry_t *entry;

  get_connection_array(&carray, &n);

  for (i = 0; i < n; ++i) {
    conn = carray[i];
    if (conn->type != CONN_TYPE_AP ||
        conn->state != AP_CONN_STATE_RENDDESC_WAIT)
      continue;
    if (rend_cmp_service_ids(conn->rend_query, query))
      continue;
    /* great, this guy was waiting */
    if(success ||
       rend_cache_lookup_entry(conn->rend_query, &entry) == 1) {
      /* either this fetch worked, or it failed but there was a
       * valid entry from before which we should reuse */
      log_fn(LOG_INFO,"Rend desc retrieved. Launching circuits.");
      conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
      if (connection_ap_handshake_attach_circuit(conn) < 0) {
        /* it will never work */
        log_fn(LOG_WARN,"attaching to a rend circ failed. Closing conn.");
        connection_mark_for_close(conn,0);
      }
    } else { /* 404, or fetch didn't get that far */
      log_fn(LOG_WARN,"service id '%s' fetched failed, and not in cache. Closing conn.", query);
      connection_mark_for_close(conn,0);
    }
  }
}

int rend_cmp_service_ids(const char *one, const char *two) {
  return strcasecmp(one,two);
}

/* strdup a nickname for a random introduction
 * point of query. return NULL if error.
 */
char *rend_client_get_random_intro(char *query) {
  int i;
  smartlist_t *sl;
  char *choice;
  char *nickname;
  rend_cache_entry_t *entry;

  if(rend_cache_lookup_entry(query, &entry) < 1) {
    log_fn(LOG_WARN,"query '%s' didn't have valid rend desc in cache. Failing.", query);
    return NULL;
  }

  sl = smartlist_create();

  /* add the intro point nicknames */
  for(i=0;i<entry->parsed->n_intro_points;i++)
    smartlist_add(sl,entry->parsed->intro_points[i]);

  choice = smartlist_choose(sl);
  if(!choice) {
    smartlist_free(sl);
    return NULL;
  }
  nickname = tor_strdup(choice);
  smartlist_free(sl);
  return nickname;
}

/* If address is of the form "y.onion" with a well-formed handle y,
 * then put a '\0' after y, lower-case it, and return 0.
 * Else return -1 and change nothing.
 */
int rend_parse_rendezvous_address(char *address) {
  char *s;
  char query[REND_SERVICE_ID_LEN+1];

  s = strrchr(address,'.');
  if(!s) return -1; /* no dot */
  if (strcasecmp(s+1,"onion"))
    return -1; /* not .onion */

  *s = 0; /* null terminate it */
  if(strlcpy(query, address, REND_SERVICE_ID_LEN+1) >= REND_SERVICE_ID_LEN+1)
    goto failed;
  tor_strlower(query);
  if(rend_valid_service_id(query)) {
    tor_strlower(address);
    return 0; /* success */
  }
failed:
  /* otherwise, return to previous state and return -1 */
  *s = '.';
  return -1;
}

/*
  Local Variables:
  mode:c
  indent-tabs-mode:nil
  c-basic-offset:2
  End:
*/