routerparse.c 131 KB
Newer Older
1
/* Copyright (c) 2001 Matej Pfajfar.
Roger Dingledine's avatar
Roger Dingledine committed
2
 * Copyright (c) 2001-2004, Roger Dingledine.
3
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4
 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5
6
/* See LICENSE for licensing information */
/* $Id$ */
7
8
const char routerparse_c_id[] =
  "$Id$";
9
10
11
12
13
14
15

/**
 * \file routerparse.c
 * \brief Code to parse and validate router descriptors and directories.
 **/

#include "or.h"
16
#include "memarea.h"
17
18
19

/****************************************************************************/

20
21
22
/** Enumeration of possible token types.  The ones starting with K_ correspond
 * to directory 'keywords'. _ERR is an error in the tokenizing process, _EOF
 * is an end-of-file marker, and _NIL is used to encode not-a-token.
23
24
 */
typedef enum {
25
  K_ACCEPT = 0,
26
  K_ACCEPT6,
27
28
29
  K_DIRECTORY_SIGNATURE,
  K_RECOMMENDED_SOFTWARE,
  K_REJECT,
30
  K_REJECT6,
31
32
33
34
35
36
37
  K_ROUTER,
  K_SIGNED_DIRECTORY,
  K_SIGNING_KEY,
  K_ONION_KEY,
  K_ROUTER_SIGNATURE,
  K_PUBLISHED,
  K_RUNNING_ROUTERS,
38
  K_ROUTER_STATUS,
39
40
41
  K_PLATFORM,
  K_OPT,
  K_BANDWIDTH,
42
  K_CONTACT,
43
  K_NETWORK_STATUS,
Nick Mathewson's avatar
Nick Mathewson committed
44
  K_UPTIME,
45
  K_DIR_SIGNING_KEY,
46
  K_FAMILY,
47
48
49
50
  K_FINGERPRINT,
  K_HIBERNATING,
  K_READ_HISTORY,
  K_WRITE_HISTORY,
51
52
53
54
55
  K_NETWORK_STATUS_VERSION,
  K_DIR_SOURCE,
  K_DIR_OPTIONS,
  K_CLIENT_VERSIONS,
  K_SERVER_VERSIONS,
56
  K_P,
57
58
  K_R,
  K_S,
59
  K_V,
60
  K_W,
61
  K_EVENTDNS,
62
63
64
  K_EXTRA_INFO,
  K_EXTRA_INFO_DIGEST,
  K_CACHES_EXTRA_INFO,
65
  K_HIDDEN_SERVICE_DIR,
66
  K_ALLOW_SINGLE_HOP_EXITS,
67
68
69
70
71
72

  K_DIR_KEY_CERTIFICATE_VERSION,
  K_DIR_IDENTITY_KEY,
  K_DIR_KEY_PUBLISHED,
  K_DIR_KEY_EXPIRES,
  K_DIR_KEY_CERTIFICATION,
73
  K_DIR_KEY_CROSSCERT,
74
  K_DIR_ADDRESS,
75
76

  K_VOTE_STATUS,
77
78
  K_VALID_AFTER,
  K_FRESH_UNTIL,
79
  K_VALID_UNTIL,
80
81
  K_VOTING_DELAY,

82
83
84
  K_KNOWN_FLAGS,
  K_VOTE_DIGEST,
  K_CONSENSUS_DIGEST,
85
  K_CONSENSUS_METHODS,
86
  K_CONSENSUS_METHOD,
87
  K_LEGACY_DIR_KEY,
88

89
90
91
  A_PURPOSE,
  _A_UNKNOWN,

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
  R_RENDEZVOUS_SERVICE_DESCRIPTOR,
  R_VERSION,
  R_PERMANENT_KEY,
  R_SECRET_ID_PART,
  R_PUBLICATION_TIME,
  R_PROTOCOL_VERSIONS,
  R_INTRODUCTION_POINTS,
  R_SIGNATURE,

  R_IPO_IDENTIFIER,
  R_IPO_IP_ADDRESS,
  R_IPO_ONION_PORT,
  R_IPO_ONION_KEY,
  R_IPO_SERVICE_KEY,

107
108
109
110
  C_CLIENT_NAME,
  C_DESCRIPTOR_COOKIE,
  C_CLIENT_KEY,

111
112
113
114
115
116
  _UNRECOGNIZED,
  _ERR,
  _EOF,
  _NIL
} directory_keyword;

117
118
119
#define MIN_ANNOTATION A_PURPOSE
#define MAX_ANNOTATION _A_UNKNOWN

120
121
122
123
124
125
/** Structure to hold a single directory token.
 *
 * We parse a directory by breaking it into "tokens", each consisting
 * of a keyword, a line full of arguments, and a binary object.  The
 * arguments and object are both optional, depending on the keyword
 * type.
126
127
128
 *
 * This structure is only allocated in memareas; do not allocate it on
 * the heap, or token_free() won't work.
129
130
131
 */
typedef struct directory_token_t {
  directory_keyword tp;        /**< Type of the token. */
132
  int n_args:30;               /**< Number of elements in args */
133
  char **args;                 /**< Array of arguments from keyword line. */
134

135
  char *object_type;           /**< -----BEGIN [object_type]-----*/
136
  size_t object_size;          /**< Bytes in object_body */
137
  char *object_body;           /**< Contents of object, base64-decoded. */
138
139
140

  crypto_pk_env_t *key;        /**< For public keys only.  Heap-allocated. */

141
  char *error;                 /**< For _ERR tokens only. */
142
143
144
145
146
147
148
149
} directory_token_t;

/* ********************************************************************** */

/** We use a table of rules to decide how to parse each token type. */

/** Rules for whether the keyword needs an object. */
typedef enum {
150
151
  NO_OBJ,        /**< No object, ever. */
  NEED_OBJ,      /**< Object is required. */
152
  NEED_SKEY_1024,/**< Object is required, and must be a 1024 bit private key */
153
154
155
  NEED_KEY_1024, /**< Object is required, and must be a 1024 bit public key */
  NEED_KEY,      /**< Object is required, and must be a public key. */
  OBJ_OK,        /**< Object is optional. */
156
157
} obj_syntax;

158
#define AT_START 1
159
#define AT_END 2
160
161

/** Determines the parsing rules for a single token type. */
162
typedef struct token_rule_t {
163
164
165
166
167
168
169
170
171
172
173
174
  /** The string value of the keyword identifying the type of item. */
  const char *t;
  /** The corresponding directory_keyword enum. */
  directory_keyword v;
  /** Minimum number of arguments for this item */
  int min_args;
  /** Maximum number of arguments for this item */
  int max_args;
  /** If true, we concatenate all arguments for this item into a single
   * string. */
  int concat_args;
  /** Requirments on object syntax for this item. */
175
  obj_syntax os;
176
177
178
179
180
181
182
  /** Lowest number of times this item may appear in a document. */
  int min_cnt;
  /** Highest number of times this item may appear in a document. */
  int max_cnt;
  /** One or more of AT_START/AT_END to limit where the item may appear in a
   * document. */
  int pos;
183
  /** True iff this token is an annotation. */
184
  int is_annotation;
185
186
} token_rule_t;

187
188
189
190
191
192
/*
 * Helper macros to define token tables.  's' is a string, 't' is a
 * directory_keyword, 'a' is a trio of argument multiplicities, and 'o' is an
 * object syntax.
 *
 */
193

194
/** Appears to indicate the end of a table. */
195
#define END_OF_TABLE { NULL, _NIL, 0,0,0, NO_OBJ, 0, INT_MAX, 0, 0 }
196
/** An item with no restrictions: used for obsolete document types */
197
#define T(s,t,a,o)    { s, t, a, o, 0, INT_MAX, 0, 0 }
198
/** An item with no restrictions on multiplicity or location. */
199
#define T0N(s,t,a,o)  { s, t, a, o, 0, INT_MAX, 0, 0 }
200
/** An item that must appear exactly once */
201
#define T1(s,t,a,o)   { s, t, a, o, 1, 1, 0, 0 }
202
/** An item that must appear exactly once, at the start of the document */
203
#define T1_START(s,t,a,o)   { s, t, a, o, 1, 1, AT_START, 0 }
204
/** An item that must appear exactly once, at the end of the document */
205
#define T1_END(s,t,a,o)   { s, t, a, o, 1, 1, AT_END, 0 }
206
/** An item that must appear one or more times */
207
#define T1N(s,t,a,o)  { s, t, a, o, 1, INT_MAX, 0, 0 }
208
/** An item that must appear no more than once */
209
210
211
#define T01(s,t,a,o)  { s, t, a, o, 0, 1, 0, 0 }
/** An annotation that must appear no more than once */
#define A01(s,t,a,o)  { s, t, a, o, 0, 1, 0, 0 }
212
213

/* Argument multiplicity: any number of arguments. */
214
#define ARGS        0,INT_MAX,0
215
/* Argument multiplicity: no arguments. */
216
#define NO_ARGS     0,0,0
217
/* Argument multiplicity: concatenate all arguments. */
218
#define CONCAT_ARGS 1,1,1
219
/* Argument multiplicity: at least <b>n</b> arguments. */
220
#define GE(n)       n,INT_MAX,0
221
/* Argument multiplicity: exactly <b>n</b> arguments. */
222
223
#define EQ(n)       n,n,0

224
/** List of tokens allowable in router derscriptors */
225
226
static token_rule_t routerdesc_token_table[] = {
  T0N("reject",              K_REJECT,              ARGS,    NO_OBJ ),
227
  T0N("accept",              K_ACCEPT,              ARGS,    NO_OBJ ),
228
229
230
  T0N("reject6",             K_REJECT6,             ARGS,    NO_OBJ ),
  T0N("accept6",             K_ACCEPT6,             ARGS,    NO_OBJ ),
  T1_START( "router",        K_ROUTER,              GE(5),   NO_OBJ ),
231
232
  T1( "signing-key",         K_SIGNING_KEY,         NO_ARGS, NEED_KEY_1024 ),
  T1( "onion-key",           K_ONION_KEY,           NO_ARGS, NEED_KEY_1024 ),
233
  T1_END( "router-signature",    K_ROUTER_SIGNATURE,    NO_ARGS, NEED_OBJ ),
234
  T1( "published",           K_PUBLISHED,       CONCAT_ARGS, NO_OBJ ),
235
  T01("uptime",              K_UPTIME,              GE(1),   NO_OBJ ),
236
  T01("fingerprint",         K_FINGERPRINT,     CONCAT_ARGS, NO_OBJ ),
237
  T01("hibernating",         K_HIBERNATING,         GE(1),   NO_OBJ ),
238
239
  T01("platform",            K_PLATFORM,        CONCAT_ARGS, NO_OBJ ),
  T01("contact",             K_CONTACT,         CONCAT_ARGS, NO_OBJ ),
240
241
  T01("read-history",        K_READ_HISTORY,        ARGS,    NO_OBJ ),
  T01("write-history",       K_WRITE_HISTORY,       ARGS,    NO_OBJ ),
242
  T01("extra-info-digest",   K_EXTRA_INFO_DIGEST,   GE(1),   NO_OBJ ),
243
  T01("hidden-service-dir",  K_HIDDEN_SERVICE_DIR,  NO_ARGS, NO_OBJ ),
244
  T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS,    NO_ARGS, NO_OBJ ),
245
246

  T01("family",              K_FAMILY,              ARGS,    NO_OBJ ),
247
  T01("caches-extra-info",   K_CACHES_EXTRA_INFO,   NO_ARGS, NO_OBJ ),
248
249
250
  T01("eventdns",            K_EVENTDNS,            ARGS,    NO_OBJ ),

  T0N("opt",                 K_OPT,             CONCAT_ARGS, OBJ_OK ),
251
  T1( "bandwidth",           K_BANDWIDTH,           GE(3),   NO_OBJ ),
252
  A01("@purpose",            A_PURPOSE,             GE(1),   NO_OBJ ),
253
254
255
256

  END_OF_TABLE
};

257
/** List of tokens allowable in extra-info documents. */
258
static token_rule_t extrainfo_token_table[] = {
259
  T1_END( "router-signature",    K_ROUTER_SIGNATURE,    NO_ARGS, NEED_OBJ ),
260
261
262
263
  T1( "published",           K_PUBLISHED,       CONCAT_ARGS, NO_OBJ ),
  T0N("opt",                 K_OPT,             CONCAT_ARGS, OBJ_OK ),
  T01("read-history",        K_READ_HISTORY,        ARGS,    NO_OBJ ),
  T01("write-history",       K_WRITE_HISTORY,       ARGS,    NO_OBJ ),
264
  T1_START( "extra-info",          K_EXTRA_INFO,          GE(2),   NO_OBJ ),
265
266
267
268

  END_OF_TABLE
};

269
270
/** List of tokens allowable in the body part of v2 and v3 networkstatus
 * documents. */
271
static token_rule_t rtrstatus_token_table[] = {
272
  T01("p",                   K_P,               CONCAT_ARGS, NO_OBJ ),
Roger Dingledine's avatar
Roger Dingledine committed
273
  T1( "r",                   K_R,                   GE(8),   NO_OBJ ),
274
275
  T1( "s",                   K_S,                   ARGS,    NO_OBJ ),
  T01("v",                   K_V,               CONCAT_ARGS, NO_OBJ ),
276
  T01("w",                   K_W,                   ARGS,    NO_OBJ ),
277
278
279
280
  T0N("opt",                 K_OPT,             CONCAT_ARGS, OBJ_OK ),
  END_OF_TABLE
};

281
282
/** List of tokens allowable in the header part of v2 networkstatus documents.
 */
283
284
285
286
static token_rule_t netstatus_token_table[] = {
  T1( "published",           K_PUBLISHED,       CONCAT_ARGS, NO_OBJ ),
  T0N("opt",                 K_OPT,             CONCAT_ARGS, OBJ_OK ),
  T1( "contact",             K_CONTACT,         CONCAT_ARGS, NO_OBJ ),
287
  T1( "dir-signing-key",     K_DIR_SIGNING_KEY,  NO_ARGS,    NEED_KEY_1024 ),
288
  T1( "fingerprint",         K_FINGERPRINT,     CONCAT_ARGS, NO_OBJ ),
289
  T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
290
291
                                                    GE(1),   NO_OBJ ),
  T1( "dir-source",          K_DIR_SOURCE,          GE(3),   NO_OBJ ),
292
  T01("dir-options",         K_DIR_OPTIONS,         ARGS,    NO_OBJ ),
293
  T01("client-versions",     K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
Roger Dingledine's avatar
Roger Dingledine committed
294
  T01("server-versions",     K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
295
296
297
298

  END_OF_TABLE
};

299
300
/** List of tokens allowable in the footer of v1/v2 directory/networkstatus
 * footers. */
301
static token_rule_t dir_footer_token_table[] = {
302
  T1("directory-signature", K_DIRECTORY_SIGNATURE, EQ(1), NEED_OBJ ),
303
304
305
  END_OF_TABLE
};

306
/** List of tokens allowable in v1 directory headers/footers. */
307
308
309
310
static token_rule_t dir_token_table[] = {
  /* don't enforce counts; this is obsolete. */
  T( "network-status",      K_NETWORK_STATUS,      NO_ARGS, NO_OBJ ),
  T( "directory-signature", K_DIRECTORY_SIGNATURE, ARGS,    NEED_OBJ ),
311
  T( "recommended-software",K_RECOMMENDED_SOFTWARE,CONCAT_ARGS, NO_OBJ ),
312
313
314
315
  T( "signed-directory",    K_SIGNED_DIRECTORY,    NO_ARGS, NO_OBJ ),

  T( "running-routers",     K_RUNNING_ROUTERS,     ARGS,    NO_OBJ ),
  T( "router-status",       K_ROUTER_STATUS,       ARGS,    NO_OBJ ),
316
  T( "published",           K_PUBLISHED,       CONCAT_ARGS, NO_OBJ ),
317
318
319
320
321
322
  T( "opt",                 K_OPT,             CONCAT_ARGS, OBJ_OK ),
  T( "contact",             K_CONTACT,         CONCAT_ARGS, NO_OBJ ),
  T( "dir-signing-key",     K_DIR_SIGNING_KEY,     ARGS,    OBJ_OK ),
  T( "fingerprint",         K_FINGERPRINT,     CONCAT_ARGS, NO_OBJ ),

  END_OF_TABLE
323
324
};

325
326
#define CERTIFICATE_MEMBERS                                                  \
  T1("dir-key-certificate-version", K_DIR_KEY_CERTIFICATE_VERSION,           \
Roger Dingledine's avatar
Roger Dingledine committed
327
                                                     GE(1),       NO_OBJ ),  \
328
329
330
331
  T1("dir-identity-key", K_DIR_IDENTITY_KEY,         NO_ARGS,     NEED_KEY ),\
  T1("dir-key-published",K_DIR_KEY_PUBLISHED,        CONCAT_ARGS, NO_OBJ),   \
  T1("dir-key-expires",  K_DIR_KEY_EXPIRES,          CONCAT_ARGS, NO_OBJ),   \
  T1("dir-signing-key",  K_DIR_SIGNING_KEY,          NO_ARGS,     NEED_KEY ),\
332
  T01("dir-key-crosscert", K_DIR_KEY_CROSSCERT,       NO_ARGS,    NEED_OBJ ),\
333
  T1("dir-key-certification", K_DIR_KEY_CERTIFICATION,                       \
334
335
                                                     NO_ARGS,     NEED_OBJ), \
  T01("dir-address",     K_DIR_ADDRESS,              GE(1),       NO_OBJ),
336
337
338
339
340
341
342

static token_rule_t dir_key_certificate_table[] = {
  CERTIFICATE_MEMBERS
  T1("fingerprint",      K_FINGERPRINT,              CONCAT_ARGS, NO_OBJ ),
  END_OF_TABLE
};

343
344
/** List of tokens allowable in rendezvous service descriptors */
static token_rule_t desc_token_table[] = {
345
346
  T1_START("rendezvous-service-descriptor", R_RENDEZVOUS_SERVICE_DESCRIPTOR,
           EQ(1), NO_OBJ),
347
348
349
350
351
  T1("version", R_VERSION, EQ(1), NO_OBJ),
  T1("permanent-key", R_PERMANENT_KEY, NO_ARGS, NEED_KEY_1024),
  T1("secret-id-part", R_SECRET_ID_PART, EQ(1), NO_OBJ),
  T1("publication-time", R_PUBLICATION_TIME, CONCAT_ARGS, NO_OBJ),
  T1("protocol-versions", R_PROTOCOL_VERSIONS, EQ(1), NO_OBJ),
352
  T01("introduction-points", R_INTRODUCTION_POINTS, NO_ARGS, NEED_OBJ),
353
  T1_END("signature", R_SIGNATURE, NO_ARGS, NEED_OBJ),
354
355
356
357
358
359
  END_OF_TABLE
};

/** List of tokens allowed in the (encrypted) list of introduction points of
 * rendezvous service descriptors */
static token_rule_t ipo_token_table[] = {
360
  T1_START("introduction-point", R_IPO_IDENTIFIER, EQ(1), NO_OBJ),
361
362
363
364
365
366
367
  T1("ip-address", R_IPO_IP_ADDRESS, EQ(1), NO_OBJ),
  T1("onion-port", R_IPO_ONION_PORT, EQ(1), NO_OBJ),
  T1("onion-key", R_IPO_ONION_KEY, NO_ARGS, NEED_KEY_1024),
  T1("service-key", R_IPO_SERVICE_KEY, NO_ARGS, NEED_KEY_1024),
  END_OF_TABLE
};

368
369
370
371
372
373
374
375
376
/** List of tokens allowed in the (possibly encrypted) list of introduction
 * points of rendezvous service descriptors */
static token_rule_t client_keys_token_table[] = {
  T1_START("client-name", C_CLIENT_NAME, CONCAT_ARGS, NO_OBJ),
  T1("descriptor-cookie", C_DESCRIPTOR_COOKIE, EQ(1), NO_OBJ),
  T01("client-key", C_CLIENT_KEY, NO_ARGS, NEED_SKEY_1024),
  END_OF_TABLE
};

377
static token_rule_t networkstatus_token_table[] = {
378
379
380
381
  T1("network-status-version", K_NETWORK_STATUS_VERSION,
                                                   GE(1),       NO_OBJ ),
  T1("vote-status",            K_VOTE_STATUS,      GE(1),       NO_OBJ ),
  T1("published",              K_PUBLISHED,        CONCAT_ARGS, NO_OBJ ),
382
383
  T1("valid-after",            K_VALID_AFTER,      CONCAT_ARGS, NO_OBJ ),
  T1("fresh-until",            K_FRESH_UNTIL,      CONCAT_ARGS, NO_OBJ ),
384
  T1("valid-until",            K_VALID_UNTIL,      CONCAT_ARGS, NO_OBJ ),
385
  T1("voting-delay",           K_VOTING_DELAY,     GE(2),       NO_OBJ ),
386
  T1("known-flags",            K_KNOWN_FLAGS,      ARGS,        NO_OBJ ),
387
388
389
390
391
392
  T( "fingerprint",            K_FINGERPRINT,      CONCAT_ARGS, NO_OBJ ),

  CERTIFICATE_MEMBERS

  T0N("opt",                 K_OPT,             CONCAT_ARGS, OBJ_OK ),
  T1( "contact",             K_CONTACT,         CONCAT_ARGS, NO_OBJ ),
393
  T1( "dir-source",          K_DIR_SOURCE,      GE(6),       NO_OBJ ),
394
  T01("legacy-dir-key",      K_LEGACY_DIR_KEY,  GE(1),       NO_OBJ ),
395
396
397
  T1( "known-flags",         K_KNOWN_FLAGS,     CONCAT_ARGS, NO_OBJ ),
  T01("client-versions",     K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  T01("server-versions",     K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
398
  T1( "consensus-methods",   K_CONSENSUS_METHODS, GE(1),     NO_OBJ ),
399
400
401

  END_OF_TABLE
};
402
static token_rule_t networkstatus_consensus_token_table[] = {
403
404
405
  T1("network-status-version", K_NETWORK_STATUS_VERSION,
                                                   GE(1),       NO_OBJ ),
  T1("vote-status",            K_VOTE_STATUS,      GE(1),       NO_OBJ ),
406
407
  T1("valid-after",            K_VALID_AFTER,      CONCAT_ARGS, NO_OBJ ),
  T1("fresh-until",            K_FRESH_UNTIL,      CONCAT_ARGS, NO_OBJ ),
408
  T1("valid-until",            K_VALID_UNTIL,      CONCAT_ARGS, NO_OBJ ),
409
  T1("voting-delay",           K_VOTING_DELAY,     GE(2),       NO_OBJ ),
410
411
412
413
414
415
416
417
418
419

  T0N("opt",                 K_OPT,             CONCAT_ARGS, OBJ_OK ),

  T1N("dir-source",          K_DIR_SOURCE,          GE(3),   NO_OBJ ),
  T1N("contact",             K_CONTACT,         CONCAT_ARGS, NO_OBJ ),
  T1N("vote-digest",         K_VOTE_DIGEST,         GE(1),   NO_OBJ ),

  T1( "known-flags",         K_KNOWN_FLAGS,     CONCAT_ARGS, NO_OBJ ),

  T01("client-versions",     K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
420
421
  T01("server-versions",     K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  T01("consensus-method",    K_CONSENSUS_METHOD,    EQ(1),   NO_OBJ),
422
423
424
425

  END_OF_TABLE
};

426
427
/** List of tokens allowable in the footer of v1/v2 directory/networkstatus
 * footers. */
428
static token_rule_t networkstatus_vote_footer_token_table[] = {
429
430
431
  T(  "directory-signature", K_DIRECTORY_SIGNATURE, GE(2),   NEED_OBJ ),
  END_OF_TABLE
};
432

433
434
435
436
437
static token_rule_t networkstatus_detached_signature_token_table[] = {
  T1_START("consensus-digest", K_CONSENSUS_DIGEST, GE(1),       NO_OBJ ),
  T1("valid-after",            K_VALID_AFTER,      CONCAT_ARGS, NO_OBJ ),
  T1("fresh-until",            K_FRESH_UNTIL,      CONCAT_ARGS, NO_OBJ ),
  T1("valid-until",            K_VALID_UNTIL,      CONCAT_ARGS, NO_OBJ ),
438
  T1N("directory-signature", K_DIRECTORY_SIGNATURE, GE(2),   NEED_OBJ ),
439
440
441
  END_OF_TABLE
};

442
443
#undef T

444
445
/* static function prototypes */
static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
446
static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
447
448
static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);

449
static int router_get_hash_impl(const char *s, char *digest,
450
451
                                const char *start_str, const char *end_str,
                                char end_char);
452
453
static void token_free(directory_token_t *tok);
static smartlist_t *find_all_exitpolicy(smartlist_t *s);
454
455
456
457
458
459
460
static directory_token_t *_find_by_keyword(smartlist_t *s,
                                           directory_keyword keyword,
                                           const char *keyword_str);
#define find_by_keyword(s, keyword) _find_by_keyword((s), (keyword), #keyword)
static directory_token_t *find_opt_by_keyword(smartlist_t *s,
                                              directory_keyword keyword);

461
462
463
#define TS_ANNOTATIONS_OK 1
#define TS_NOCHECK 2
#define TS_NO_NEW_ANNOTATIONS 4
464
465
static int tokenize_string(memarea_t *area,
                           const char *start, const char *end,
466
                           smartlist_t *out,
467
                           token_rule_t *table,
468
                           int flags);
469
470
static directory_token_t *get_next_token(memarea_t *area,
                                         const char **s,
471
                                         const char *eos,
472
                                         token_rule_t *table);
473
474
#define CST_CHECK_AUTHORITY   (1<<0)
#define CST_NO_CHECK_OBJTYPE  (1<<1)
475
476
477
static int check_signature_token(const char *digest,
                                 directory_token_t *tok,
                                 crypto_pk_env_t *pkey,
478
                                 int flags,
479
                                 const char *doctype);
480
static crypto_pk_env_t *find_dir_signing_key(const char *str, const char *eos);
481
static int tor_version_same_series(tor_version_t *a, tor_version_t *b);
482

483
484
485
486
487
488
489
490
491
492
493
494
495
#undef DEBUG_AREA_ALLOC

#ifdef DEBUG_AREA_ALLOC
#define DUMP_AREA(a,name) STMT_BEGIN                              \
  size_t alloc=0, used=0;                                         \
  memarea_get_stats((a),&alloc,&used);                            \
  log_debug(LD_MM, "Area for %s has %lu allocated; using %lu.",   \
            name, (unsigned long)alloc, (unsigned long)used);     \
  STMT_END
#else
#define DUMP_AREA(a,name) STMT_NIL
#endif

496
/** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
497
 * <b>s</b>.  Return 0 on success, -1 on failure.
498
 */
499
500
int
router_get_dir_hash(const char *s, char *digest)
501
502
{
  return router_get_hash_impl(s,digest,
503
                              "signed-directory","\ndirectory-signature",'\n');
504
505
506
}

/** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
507
 * <b>s</b>. Return 0 on success, -1 on failure.
508
 */
509
510
int
router_get_router_hash(const char *s, char *digest)
511
512
{
  return router_get_hash_impl(s,digest,
513
                              "router ","\nrouter-signature", '\n');
514
515
}

Nick Mathewson's avatar
Nick Mathewson committed
516
/** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
517
 * string in <b>s</b>. Return 0 on success, -1 on failure.
Nick Mathewson's avatar
Nick Mathewson committed
518
 */
519
520
int
router_get_runningrouters_hash(const char *s, char *digest)
521
522
{
  return router_get_hash_impl(s,digest,
523
                              "network-status","\ndirectory-signature", '\n');
524
525
}

526
527
/** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
 * string in <b>s</b>.  Return 0 on success, -1 on failure. */
528
529
530
531
int
router_get_networkstatus_v2_hash(const char *s, char *digest)
{
  return router_get_hash_impl(s,digest,
532
533
534
535
536
537
538
539
540
541
542
543
                              "network-status-version","\ndirectory-signature",
                              '\n');
}

/** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
 * string in <b>s</b>.  Return 0 on success, -1 on failure. */
int
router_get_networkstatus_v3_hash(const char *s, char *digest)
{
  return router_get_hash_impl(s,digest,
                              "network-status-version","\ndirectory-signature",
                              ' ');
544
545
}

546
547
/** Set <b>digest</b> to the SHA-1 digest of the hash of the extrainfo
 * string in <b>s</b>.  Return 0 on success, -1 on failure. */
548
549
550
int
router_get_extrainfo_hash(const char *s, char *digest)
{
551
  return router_get_hash_impl(s,digest,"extra-info","\nrouter-signature",'\n');
552
553
}

554
555
556
557
558
559
560
561
562
563
564
/** Helper: used to generate signatures for routers, directories and
 * network-status objects.  Given a digest in <b>digest</b> and a secret
 * <b>private_key</b>, generate an PKCS1-padded signature, BASE64-encode it,
 * surround it with -----BEGIN/END----- pairs, and write it to the
 * <b>buf_len</b>-byte buffer at <b>buf</b>.  Return 0 on success, -1 on
 * failure.
 */
int
router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
                               crypto_pk_env_t *private_key)
{
565
  char *signature;
566
  size_t i;
567

568
  signature = tor_malloc(crypto_pk_keysize(private_key));
569
570
  if (crypto_pk_private_sign(private_key, signature, digest, DIGEST_LEN) < 0) {

571
    log_warn(LD_BUG,"Couldn't sign digest.");
572
    goto err;
573
574
575
576
577
578
  }
  if (strlcat(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
    goto truncated;

  i = strlen(buf);
  if (base64_encode(buf+i, buf_len-i, signature, 128) < 0) {
579
    log_warn(LD_BUG,"couldn't base64-encode signature");
580
    goto err;
581
582
583
584
585
  }

  if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
    goto truncated;

586
  tor_free(signature);
587
  return 0;
588

589
 truncated:
590
  log_warn(LD_BUG,"tried to exceed string length.");
591
592
 err:
  tor_free(signature);
593
594
595
  return -1;
}

596
/** Return VS_RECOMMENDED if <b>myversion</b> is contained in
597
598
 * <b>versionlist</b>.  Else, return VS_EMPTY if versionlist has no
 * entries. Else, return VS_OLD if every member of
599
600
601
602
603
604
 * <b>versionlist</b> is newer than <b>myversion</b>.  Else, return
 * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
 * the same series (major.minor.micro) as <b>myversion</b>, but no such member
 * is newer than <b>myversion.</b>.  Else, return VS_NEW if every memeber of
 * <b>versionlist</b> is older than <b>myversion</b>.  Else, return
 * VS_UNRECOMMENDED.
605
 *
606
607
 * (versionlist is a comma-separated list of version strings,
 * optionally prefixed with "Tor".  Versions that can't be parsed are
608
 * ignored.)
609
 */
610
611
612
version_status_t
tor_version_is_obsolete(const char *myversion, const char *versionlist)
{
613
  tor_version_t mine, other;
614
615
616
  int found_newer = 0, found_older = 0, found_newer_in_series = 0,
    found_any_in_series = 0, r, same;
  version_status_t ret = VS_UNRECOMMENDED;
617
  smartlist_t *version_sl;
618

619
620
  log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
            myversion, versionlist);
621

622
  if (tor_version_parse(myversion, &mine)) {
623
    log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
624
625
    tor_assert(0);
  }
626
627
  version_sl = smartlist_create();
  smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
628

629
630
631
632
633
  if (!strlen(versionlist)) { /* no authorities cared or agreed */
    ret = VS_EMPTY;
    goto done;
  }

634
635
  SMARTLIST_FOREACH(version_sl, const char *, cp, {
    if (!strcmpstart(cp, "Tor "))
636
637
638
639
640
      cp += 4;

    if (tor_version_parse(cp, &other)) {
      /* Couldn't parse other; it can't be a match. */
    } else {
641
642
643
      same = tor_version_same_series(&mine, &other);
      if (same)
        found_any_in_series = 1;
644
645
      r = tor_version_compare(&mine, &other);
      if (r==0) {
646
        ret = VS_RECOMMENDED;
647
        goto done;
648
649
      } else if (r<0) {
        found_newer = 1;
650
651
        if (same)
          found_newer_in_series = 1;
652
653
      } else if (r>0) {
        found_older = 1;
654
655
      }
    }
656
657
  });

658
  /* We didn't find the listed version. Is it new or old? */
659
  if (found_any_in_series && !found_newer_in_series && found_newer) {
660
661
662
663
664
    ret = VS_NEW_IN_SERIES;
  } else if (found_newer && !found_older) {
    ret = VS_OLD;
  } else if (found_older && !found_newer) {
    ret = VS_NEW;
665
  } else {
666
    ret = VS_UNRECOMMENDED;
667
  }
668
669
670
671
672

 done:
  SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  smartlist_free(version_sl);
  return ret;
673
674
}

675
676
/** Read a signed directory from <b>str</b>.  If it's well-formed, return 0.
 * Otherwise, return -1.  If we're a directory cache, cache it.
677
 */
678
679
int
router_parse_directory(const char *str)
680
681
{
  directory_token_t *tok;
682
683
  char digest[DIGEST_LEN];
  time_t published_on;
684
  int r;
685
  const char *end, *cp;
686
  smartlist_t *tokens = NULL;
687
  crypto_pk_env_t *declared_key = NULL;
688
  memarea_t *area = memarea_new();
689

690
691
  /* XXXX This could be simplified a lot, but it will all go away
   * once pre-0.1.1.8 is obsolete, and for now it's better not to
Roger Dingledine's avatar
Roger Dingledine committed
692
   * touch it. */
693

694
  if (router_get_dir_hash(str, digest)) {
695
    log_warn(LD_DIR, "Unable to compute digest of directory");
696
697
    goto err;
  }
698
  log_debug(LD_DIR,"Received directory hashes to %s",hex_str(digest,4));
699

700
701
702
703
704
  /* Check signature first, before we try to tokenize. */
  cp = str;
  while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
    cp = end;
  if (cp == str || !cp) {
705
    log_warn(LD_DIR, "No signature found on directory."); goto err;
706
707
708
  }
  ++cp;
  tokens = smartlist_create();
709
  if (tokenize_string(area,cp,strchr(cp,'\0'),tokens,dir_token_table,0)) {
710
    log_warn(LD_DIR, "Error tokenizing directory signature"); goto err;
711
712
  }
  if (smartlist_len(tokens) != 1) {
713
    log_warn(LD_DIR, "Unexpected number of tokens in signature"); goto err;
714
  }
715
  tok=smartlist_get(tokens,0);
716
  if (tok->tp != K_DIRECTORY_SIGNATURE) {
717
    log_warn(LD_DIR,"Expected a single directory signature"); goto err;
718
  }
719
  declared_key = find_dir_signing_key(str, str+strlen(str));
720
  note_crypto_pk_op(VERIFY_DIR);
721
722
  if (check_signature_token(digest, tok, declared_key,
                            CST_CHECK_AUTHORITY, "directory")<0)
723
    goto err;
724

725
  SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
726
727
  smartlist_clear(tokens);
  memarea_clear(area);
728
729

  /* Now try to parse the first part of the directory. */
730
731
732
733
734
735
736
737
  if ((end = strstr(str,"\nrouter "))) {
    ++end;
  } else if ((end = strstr(str, "\ndirectory-signature"))) {
    ++end;
  } else {
    end = str + strlen(str);
  }

738
  if (tokenize_string(area,str,end,tokens,dir_token_table,0)) {
739
    log_warn(LD_DIR, "Error tokenizing directory"); goto err;
740
741
  }

742
  tok = find_by_keyword(tokens, K_PUBLISHED);
743
744
  tor_assert(tok->n_args == 1);

745
  if (parse_iso_time(tok->args[0], &published_on) < 0) {
746
747
748
     goto err;
  }

749
750
  /* Now that we know the signature is okay, and we have a
   * publication time, cache the directory. */
751
  if (directory_caches_v1_dir_info(get_options()) &&
752
      !authdir_mode_v1(get_options()))
753
    dirserv_set_cached_directory(str, published_on, 0);
754

755
756
757
758
759
  r = 0;
  goto done;
 err:
  r = -1;
 done:
760
  if (declared_key) crypto_free_pk_env(declared_key);
761
  if (tokens) {
762
    SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
763
764
    smartlist_free(tokens);
  }
765
766
  if (area) {
    DUMP_AREA(area, "v1 directory");
767
    memarea_drop_all(area);
768
  }
769
770
771
  return r;
}

772
773
774
/** Read a signed router status statement from <b>str</b>.  If it's
 * well-formed, return 0.  Otherwise, return -1.  If we're a directory cache,
 * cache it.*/
775
776
int
router_parse_runningrouters(const char *str)
777
778
779
780
{
  char digest[DIGEST_LEN];
  directory_token_t *tok;
  time_t published_on;
781
  int r = -1;
782
  crypto_pk_env_t *declared_key = NULL;
783
  smartlist_t *tokens = NULL;
784
  const char *eos = str + strlen(str);
785
  memarea_t *area = NULL;
786
787

  if (router_get_runningrouters_hash(str, digest)) {
788
    log_warn(LD_DIR, "Unable to compute digest of running-routers");
789
790
    goto err;
  }
791
  area = memarea_new();
792
  tokens = smartlist_create();
793
  if (tokenize_string(area,str,eos,tokens,dir_token_table,0)) {
794
    log_warn(LD_DIR, "Error tokenizing running-routers"); goto err;
795
796
797
  }
  tok = smartlist_get(tokens,0);
  if (tok->tp != K_NETWORK_STATUS) {
798
    log_warn(LD_DIR, "Network-status starts with wrong token");
799
800
801
    goto err;
  }

802
  tok = find_by_keyword(tokens, K_PUBLISHED);
803
  tor_assert(tok->n_args == 1);
804
  if (parse_iso_time(tok->args[0], &published_on) < 0) {
805
806
     goto err;
  }
807
  if (!(tok = find_opt_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
808
    log_warn(LD_DIR, "Missing signature on running-routers");
809
810
    goto err;
  }
811
  declared_key = find_dir_signing_key(str, eos);
812
  note_crypto_pk_op(VERIFY_DIR);
813
814
  if (check_signature_token(digest, tok, declared_key,
                            CST_CHECK_AUTHORITY, "running-routers")
815
      < 0)
816
817
    goto err;

818
819
  /* Now that we know the signature is okay, and we have a
   * publication time, cache the list. */
820
  if (get_options()->DirPort && !authdir_mode_v1(get_options()))
821
822
823
    dirserv_set_cached_directory(str, published_on, 1);

  r = 0;
824
 err:
825
  if (declared_key) crypto_free_pk_env(declared_key);
826
  if (tokens) {
827
    SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
828
829
    smartlist_free(tokens);
  }
830
831
  if (area) {
    DUMP_AREA(area, "v1 running-routers");
832
    memarea_drop_all(area);
833
  }
834
  return r;
835
836
}

837
838
839
/** Given a directory or running-routers string in <b>str</b>, try to
 * find the its dir-signing-key token (if any).  If this token is
 * present, extract and return the key.  Return NULL on failure. */
840
static crypto_pk_env_t *
841
find_dir_signing_key(const char *str, const char *eos)
842
843
844
845
{
  const char *cp;
  directory_token_t *tok;
  crypto_pk_env_t *key = NULL;
846
  memarea_t *area = NULL;
847
848
  tor_assert(str);
  tor_assert(eos);
849
850

  /* Is there a dir-signing-key in the directory? */
851
  cp = tor_memstr(str, eos-str, "\nopt dir-signing-key");
852
  if (!cp)
853
    cp = tor_memstr(str, eos-str, "\ndir-signing-key");
854
855
856
857
  if (!cp)
    return NULL;
  ++cp; /* Now cp points to the start of the token. */

858
  area = memarea_new();
859
  tok = get_next_token(area, &cp, eos, dir_token_table);
860
  if (!tok) {
861
    log_warn(LD_DIR, "Unparseable dir-signing-key token");
862
    goto done;
863
864
  }
  if (tok->tp != K_DIR_SIGNING_KEY) {
865
    log_warn(LD_DIR, "Dir-signing-key token did not parse as expected");
866
    goto done;
867
868
869
870
871
872
  }

  if (tok->key) {
    key = tok->key;
    tok->key = NULL; /* steal reference. */
  } else {
873
    log_warn(LD_DIR, "Dir-signing-key token contained no key");
874
875
  }

876
877
 done:
  if (tok) token_free(tok);
878
879
880
881
  if (area) {
    DUMP_AREA(area, "dir-signing-key token");
    memarea_drop_all(area);
  }
882
883
884
885
886
  return key;
}

/** Return true iff <b>key</b> is allowed to sign directories.
 */
887
888
static int
dir_signing_key_is_trusted(crypto_pk_env_t *key)
889
890
891
892
{
  char digest[DIGEST_LEN];
  if (!key) return 0;
  if (crypto_pk_get_digest(key, digest) < 0) {
893
    log_warn(LD_DIR, "Error computing dir-signing-key digest");
894
895
    return 0;
  }
896
  if (!router_digest_is_trusted_dir(digest)) {
897
    log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
898
899
900
901
902
    return 0;
  }
  return 1;
}

903
904
/** Check whether the object body of the token in <b>tok</b> has a good
 * signature for <b>digest</b> using key <b>pkey</b>.  If
905
906
907
908
909
 * <b>CST_CHECK_AUTHORITY</b> is set, make sure that <b>pkey</b> is the key of
 * a directory authority.  If <b>CST_NO_CHECK_OBJTYPE</b> is set, do not check
 * the object type of the signature object. Use <b>doctype</b> as the type of
 * the document when generating log messages.  Return 0 on success, negative
 * on failure.
910
 */
911
static int
912
913
914
check_signature_token(const char *digest,
                      directory_token_t *tok,
                      crypto_pk_env_t *pkey,
915
                      int flags,
916
                      const char *doctype)
917
{
918
  char *signed_digest;
919
920
  const int check_authority = (flags & CST_CHECK_AUTHORITY);
  const int check_objtype = ! (flags & CST_NO_CHECK_OBJTYPE);