catch another overlong malloc possibility. found by cypherpunks
[tor/rransom.git] / src / or / routerparse.c
blob3aaefec681ddb052e1e1e37c2809c6aace029d65
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2011, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file routerparse.c
9 * \brief Code to parse and validate router descriptors and directories.
10 **/
12 #include "or.h"
13 #include "memarea.h"
15 /****************************************************************************/
17 /** Enumeration of possible token types. The ones starting with K_ correspond
18 * to directory 'keywords'. _ERR is an error in the tokenizing process, _EOF
19 * is an end-of-file marker, and _NIL is used to encode not-a-token.
21 typedef enum {
22 K_ACCEPT = 0,
23 K_ACCEPT6,
24 K_DIRECTORY_SIGNATURE,
25 K_RECOMMENDED_SOFTWARE,
26 K_REJECT,
27 K_REJECT6,
28 K_ROUTER,
29 K_SIGNED_DIRECTORY,
30 K_SIGNING_KEY,
31 K_ONION_KEY,
32 K_ROUTER_SIGNATURE,
33 K_PUBLISHED,
34 K_RUNNING_ROUTERS,
35 K_ROUTER_STATUS,
36 K_PLATFORM,
37 K_OPT,
38 K_BANDWIDTH,
39 K_CONTACT,
40 K_NETWORK_STATUS,
41 K_UPTIME,
42 K_DIR_SIGNING_KEY,
43 K_FAMILY,
44 K_FINGERPRINT,
45 K_HIBERNATING,
46 K_READ_HISTORY,
47 K_WRITE_HISTORY,
48 K_NETWORK_STATUS_VERSION,
49 K_DIR_SOURCE,
50 K_DIR_OPTIONS,
51 K_CLIENT_VERSIONS,
52 K_SERVER_VERSIONS,
53 K_P,
54 K_R,
55 K_S,
56 K_V,
57 K_W,
58 K_EVENTDNS,
59 K_EXTRA_INFO,
60 K_EXTRA_INFO_DIGEST,
61 K_CACHES_EXTRA_INFO,
62 K_HIDDEN_SERVICE_DIR,
63 K_ALLOW_SINGLE_HOP_EXITS,
65 K_DIR_KEY_CERTIFICATE_VERSION,
66 K_DIR_IDENTITY_KEY,
67 K_DIR_KEY_PUBLISHED,
68 K_DIR_KEY_EXPIRES,
69 K_DIR_KEY_CERTIFICATION,
70 K_DIR_KEY_CROSSCERT,
71 K_DIR_ADDRESS,
73 K_VOTE_STATUS,
74 K_VALID_AFTER,
75 K_FRESH_UNTIL,
76 K_VALID_UNTIL,
77 K_VOTING_DELAY,
79 K_KNOWN_FLAGS,
80 K_PARAMS,
81 K_VOTE_DIGEST,
82 K_CONSENSUS_DIGEST,
83 K_CONSENSUS_METHODS,
84 K_CONSENSUS_METHOD,
85 K_LEGACY_DIR_KEY,
87 A_PURPOSE,
88 _A_UNKNOWN,
90 R_RENDEZVOUS_SERVICE_DESCRIPTOR,
91 R_VERSION,
92 R_PERMANENT_KEY,
93 R_SECRET_ID_PART,
94 R_PUBLICATION_TIME,
95 R_PROTOCOL_VERSIONS,
96 R_INTRODUCTION_POINTS,
97 R_SIGNATURE,
99 R_IPO_IDENTIFIER,
100 R_IPO_IP_ADDRESS,
101 R_IPO_ONION_PORT,
102 R_IPO_ONION_KEY,
103 R_IPO_SERVICE_KEY,
105 C_CLIENT_NAME,
106 C_DESCRIPTOR_COOKIE,
107 C_CLIENT_KEY,
109 _ERR,
110 _EOF,
111 _NIL
112 } directory_keyword;
114 #define MIN_ANNOTATION A_PURPOSE
115 #define MAX_ANNOTATION _A_UNKNOWN
117 /** Structure to hold a single directory token.
119 * We parse a directory by breaking it into "tokens", each consisting
120 * of a keyword, a line full of arguments, and a binary object. The
121 * arguments and object are both optional, depending on the keyword
122 * type.
124 * This structure is only allocated in memareas; do not allocate it on
125 * the heap, or token_free() won't work.
127 typedef struct directory_token_t {
128 directory_keyword tp; /**< Type of the token. */
129 int n_args:30; /**< Number of elements in args */
130 char **args; /**< Array of arguments from keyword line. */
132 char *object_type; /**< -----BEGIN [object_type]-----*/
133 size_t object_size; /**< Bytes in object_body */
134 char *object_body; /**< Contents of object, base64-decoded. */
136 crypto_pk_env_t *key; /**< For public keys only. Heap-allocated. */
138 char *error; /**< For _ERR tokens only. */
139 } directory_token_t;
141 /* ********************************************************************** */
143 /** We use a table of rules to decide how to parse each token type. */
145 /** Rules for whether the keyword needs an object. */
146 typedef enum {
147 NO_OBJ, /**< No object, ever. */
148 NEED_OBJ, /**< Object is required. */
149 NEED_SKEY_1024,/**< Object is required, and must be a 1024 bit private key */
150 NEED_KEY_1024, /**< Object is required, and must be a 1024 bit public key */
151 NEED_KEY, /**< Object is required, and must be a public key. */
152 OBJ_OK, /**< Object is optional. */
153 } obj_syntax;
155 #define AT_START 1
156 #define AT_END 2
158 /** Determines the parsing rules for a single token type. */
159 typedef struct token_rule_t {
160 /** The string value of the keyword identifying the type of item. */
161 const char *t;
162 /** The corresponding directory_keyword enum. */
163 directory_keyword v;
164 /** Minimum number of arguments for this item */
165 int min_args;
166 /** Maximum number of arguments for this item */
167 int max_args;
168 /** If true, we concatenate all arguments for this item into a single
169 * string. */
170 int concat_args;
171 /** Requirements on object syntax for this item. */
172 obj_syntax os;
173 /** Lowest number of times this item may appear in a document. */
174 int min_cnt;
175 /** Highest number of times this item may appear in a document. */
176 int max_cnt;
177 /** One or more of AT_START/AT_END to limit where the item may appear in a
178 * document. */
179 int pos;
180 /** True iff this token is an annotation. */
181 int is_annotation;
182 } token_rule_t;
185 * Helper macros to define token tables. 's' is a string, 't' is a
186 * directory_keyword, 'a' is a trio of argument multiplicities, and 'o' is an
187 * object syntax.
191 /** Appears to indicate the end of a table. */
192 #define END_OF_TABLE { NULL, _NIL, 0,0,0, NO_OBJ, 0, INT_MAX, 0, 0 }
193 /** An item with no restrictions: used for obsolete document types */
194 #define T(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0, 0 }
195 /** An item with no restrictions on multiplicity or location. */
196 #define T0N(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0, 0 }
197 /** An item that must appear exactly once */
198 #define T1(s,t,a,o) { s, t, a, o, 1, 1, 0, 0 }
199 /** An item that must appear exactly once, at the start of the document */
200 #define T1_START(s,t,a,o) { s, t, a, o, 1, 1, AT_START, 0 }
201 /** An item that must appear exactly once, at the end of the document */
202 #define T1_END(s,t,a,o) { s, t, a, o, 1, 1, AT_END, 0 }
203 /** An item that must appear one or more times */
204 #define T1N(s,t,a,o) { s, t, a, o, 1, INT_MAX, 0, 0 }
205 /** An item that must appear no more than once */
206 #define T01(s,t,a,o) { s, t, a, o, 0, 1, 0, 0 }
207 /** An annotation that must appear no more than once */
208 #define A01(s,t,a,o) { s, t, a, o, 0, 1, 0, 1 }
210 /* Argument multiplicity: any number of arguments. */
211 #define ARGS 0,INT_MAX,0
212 /* Argument multiplicity: no arguments. */
213 #define NO_ARGS 0,0,0
214 /* Argument multiplicity: concatenate all arguments. */
215 #define CONCAT_ARGS 1,1,1
216 /* Argument multiplicity: at least <b>n</b> arguments. */
217 #define GE(n) n,INT_MAX,0
218 /* Argument multiplicity: exactly <b>n</b> arguments. */
219 #define EQ(n) n,n,0
221 /** List of tokens allowable in router descriptors */
222 static token_rule_t routerdesc_token_table[] = {
223 T0N("reject", K_REJECT, ARGS, NO_OBJ ),
224 T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
225 T0N("reject6", K_REJECT6, ARGS, NO_OBJ ),
226 T0N("accept6", K_ACCEPT6, ARGS, NO_OBJ ),
227 T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
228 T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
229 T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
230 T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
231 T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
232 T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
233 T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
234 T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
235 T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
236 T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
237 T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
238 T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
239 T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
240 T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
241 T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
243 T01("family", K_FAMILY, ARGS, NO_OBJ ),
244 T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
245 T01("eventdns", K_EVENTDNS, ARGS, NO_OBJ ),
247 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
248 T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
249 A01("@purpose", A_PURPOSE, GE(1), NO_OBJ ),
251 END_OF_TABLE
254 /** List of tokens allowable in extra-info documents. */
255 static token_rule_t extrainfo_token_table[] = {
256 T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
257 T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
258 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
259 T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
260 T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
261 T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
263 END_OF_TABLE
266 /** List of tokens allowable in the body part of v2 and v3 networkstatus
267 * documents. */
268 static token_rule_t rtrstatus_token_table[] = {
269 T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
270 T1( "r", K_R, GE(8), NO_OBJ ),
271 T1( "s", K_S, ARGS, NO_OBJ ),
272 T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
273 T01("w", K_W, ARGS, NO_OBJ ),
274 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
275 END_OF_TABLE
278 /** List of tokens allowable in the header part of v2 networkstatus documents.
280 static token_rule_t netstatus_token_table[] = {
281 T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
282 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
283 T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
284 T1( "dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
285 T1( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
286 T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
287 GE(1), NO_OBJ ),
288 T1( "dir-source", K_DIR_SOURCE, GE(3), NO_OBJ ),
289 T01("dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ ),
290 T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
291 T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
293 END_OF_TABLE
296 /** List of tokens allowable in the footer of v1/v2 directory/networkstatus
297 * footers. */
298 static token_rule_t dir_footer_token_table[] = {
299 T1("directory-signature", K_DIRECTORY_SIGNATURE, EQ(1), NEED_OBJ ),
300 END_OF_TABLE
303 /** List of tokens allowable in v1 directory headers/footers. */
304 static token_rule_t dir_token_table[] = {
305 /* don't enforce counts; this is obsolete. */
306 T( "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ ),
307 T( "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ ),
308 T( "recommended-software",K_RECOMMENDED_SOFTWARE,CONCAT_ARGS, NO_OBJ ),
309 T( "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ ),
311 T( "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ ),
312 T( "router-status", K_ROUTER_STATUS, ARGS, NO_OBJ ),
313 T( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
314 T( "opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
315 T( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
316 T( "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK ),
317 T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
319 END_OF_TABLE
322 /** List of tokens common to V3 authority certificates and V3 consensuses. */
323 #define CERTIFICATE_MEMBERS \
324 T1("dir-key-certificate-version", K_DIR_KEY_CERTIFICATE_VERSION, \
325 GE(1), NO_OBJ ), \
326 T1("dir-identity-key", K_DIR_IDENTITY_KEY, NO_ARGS, NEED_KEY ),\
327 T1("dir-key-published",K_DIR_KEY_PUBLISHED, CONCAT_ARGS, NO_OBJ), \
328 T1("dir-key-expires", K_DIR_KEY_EXPIRES, CONCAT_ARGS, NO_OBJ), \
329 T1("dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY ),\
330 T01("dir-key-crosscert", K_DIR_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),\
331 T1("dir-key-certification", K_DIR_KEY_CERTIFICATION, \
332 NO_ARGS, NEED_OBJ), \
333 T01("dir-address", K_DIR_ADDRESS, GE(1), NO_OBJ),
335 /** List of tokens allowable in V3 authority certificates. */
336 static token_rule_t dir_key_certificate_table[] = {
337 CERTIFICATE_MEMBERS
338 T1("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
339 END_OF_TABLE
342 /** List of tokens allowable in rendezvous service descriptors */
343 static token_rule_t desc_token_table[] = {
344 T1_START("rendezvous-service-descriptor", R_RENDEZVOUS_SERVICE_DESCRIPTOR,
345 EQ(1), NO_OBJ),
346 T1("version", R_VERSION, EQ(1), NO_OBJ),
347 T1("permanent-key", R_PERMANENT_KEY, NO_ARGS, NEED_KEY_1024),
348 T1("secret-id-part", R_SECRET_ID_PART, EQ(1), NO_OBJ),
349 T1("publication-time", R_PUBLICATION_TIME, CONCAT_ARGS, NO_OBJ),
350 T1("protocol-versions", R_PROTOCOL_VERSIONS, EQ(1), NO_OBJ),
351 T01("introduction-points", R_INTRODUCTION_POINTS, NO_ARGS, NEED_OBJ),
352 T1_END("signature", R_SIGNATURE, NO_ARGS, NEED_OBJ),
353 END_OF_TABLE
356 /** List of tokens allowed in the (encrypted) list of introduction points of
357 * rendezvous service descriptors */
358 static token_rule_t ipo_token_table[] = {
359 T1_START("introduction-point", R_IPO_IDENTIFIER, EQ(1), NO_OBJ),
360 T1("ip-address", R_IPO_IP_ADDRESS, EQ(1), NO_OBJ),
361 T1("onion-port", R_IPO_ONION_PORT, EQ(1), NO_OBJ),
362 T1("onion-key", R_IPO_ONION_KEY, NO_ARGS, NEED_KEY_1024),
363 T1("service-key", R_IPO_SERVICE_KEY, NO_ARGS, NEED_KEY_1024),
364 END_OF_TABLE
367 /** List of tokens allowed in the (possibly encrypted) list of introduction
368 * points of rendezvous service descriptors */
369 static token_rule_t client_keys_token_table[] = {
370 T1_START("client-name", C_CLIENT_NAME, CONCAT_ARGS, NO_OBJ),
371 T1("descriptor-cookie", C_DESCRIPTOR_COOKIE, EQ(1), NO_OBJ),
372 T01("client-key", C_CLIENT_KEY, NO_ARGS, NEED_SKEY_1024),
373 END_OF_TABLE
376 /** List of tokens allowed in V3 networkstatus votes. */
377 static token_rule_t networkstatus_token_table[] = {
378 T1("network-status-version", K_NETWORK_STATUS_VERSION,
379 GE(1), NO_OBJ ),
380 T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
381 T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
382 T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
383 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 T01("params", K_PARAMS, ARGS, NO_OBJ ),
388 T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
390 CERTIFICATE_MEMBERS
392 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
393 T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
394 T1( "dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
395 T01("legacy-dir-key", K_LEGACY_DIR_KEY, GE(1), NO_OBJ ),
396 T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
397 T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
398 T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
399 T1( "consensus-methods", K_CONSENSUS_METHODS, GE(1), NO_OBJ ),
401 END_OF_TABLE
404 /** List of tokens allowed in V3 networkstatus consensuses. */
405 static token_rule_t networkstatus_consensus_token_table[] = {
406 T1("network-status-version", K_NETWORK_STATUS_VERSION,
407 GE(1), NO_OBJ ),
408 T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
409 T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
410 T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
411 T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
412 T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
414 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
416 T1N("dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
417 T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
418 T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
420 T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
422 T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
423 T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
424 T01("consensus-method", K_CONSENSUS_METHOD, EQ(1), NO_OBJ),
425 T01("params", K_PARAMS, ARGS, NO_OBJ ),
427 END_OF_TABLE
430 /** List of tokens allowable in the footer of v1/v2 directory/networkstatus
431 * footers. */
432 static token_rule_t networkstatus_vote_footer_token_table[] = {
433 T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
434 END_OF_TABLE
437 /** List of tokens allowable in detached networkstatus signature documents. */
438 static token_rule_t networkstatus_detached_signature_token_table[] = {
439 T1_START("consensus-digest", K_CONSENSUS_DIGEST, GE(1), NO_OBJ ),
440 T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
441 T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
442 T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
443 T1N("directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
444 END_OF_TABLE
447 #undef T
449 /* static function prototypes */
450 static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
451 static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
452 static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
454 static int router_get_hash_impl(const char *s, size_t s_len, char *digest,
455 const char *start_str, const char *end_str,
456 char end_char);
458 static void token_free(directory_token_t *tok);
459 static smartlist_t *find_all_exitpolicy(smartlist_t *s);
460 static directory_token_t *_find_by_keyword(smartlist_t *s,
461 directory_keyword keyword,
462 const char *keyword_str);
463 #define find_by_keyword(s, keyword) _find_by_keyword((s), (keyword), #keyword)
464 static directory_token_t *find_opt_by_keyword(smartlist_t *s,
465 directory_keyword keyword);
467 #define TS_ANNOTATIONS_OK 1
468 #define TS_NOCHECK 2
469 #define TS_NO_NEW_ANNOTATIONS 4
470 static int tokenize_string(memarea_t *area,
471 const char *start, const char *end,
472 smartlist_t *out,
473 token_rule_t *table,
474 int flags);
475 static directory_token_t *get_next_token(memarea_t *area,
476 const char **s,
477 const char *eos,
478 token_rule_t *table);
479 #define CST_CHECK_AUTHORITY (1<<0)
480 #define CST_NO_CHECK_OBJTYPE (1<<1)
481 static int check_signature_token(const char *digest,
482 directory_token_t *tok,
483 crypto_pk_env_t *pkey,
484 int flags,
485 const char *doctype);
486 static crypto_pk_env_t *find_dir_signing_key(const char *str, const char *eos);
487 static int tor_version_same_series(tor_version_t *a, tor_version_t *b);
489 #undef DEBUG_AREA_ALLOC
491 #ifdef DEBUG_AREA_ALLOC
492 #define DUMP_AREA(a,name) STMT_BEGIN \
493 size_t alloc=0, used=0; \
494 memarea_get_stats((a),&alloc,&used); \
495 log_debug(LD_MM, "Area for %s has %lu allocated; using %lu.", \
496 name, (unsigned long)alloc, (unsigned long)used); \
497 STMT_END
498 #else
499 #define DUMP_AREA(a,name) STMT_NIL
500 #endif
502 /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
503 * <b>s</b>. Return 0 on success, -1 on failure.
506 router_get_dir_hash(const char *s, char *digest)
508 return router_get_hash_impl(s, strlen(s), digest,
509 "signed-directory","\ndirectory-signature",'\n');
512 /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
513 * <b>s</b>. Return 0 on success, -1 on failure.
516 router_get_router_hash(const char *s, size_t s_len, char *digest)
518 return router_get_hash_impl(s, s_len, digest,
519 "router ","\nrouter-signature", '\n');
522 /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
523 * string in <b>s</b>. Return 0 on success, -1 on failure.
526 router_get_runningrouters_hash(const char *s, char *digest)
528 return router_get_hash_impl(s, strlen(s), digest,
529 "network-status","\ndirectory-signature", '\n');
532 /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
533 * string in <b>s</b>. Return 0 on success, -1 on failure. */
535 router_get_networkstatus_v2_hash(const char *s, char *digest)
537 return router_get_hash_impl(s, strlen(s), digest,
538 "network-status-version","\ndirectory-signature",
539 '\n');
542 /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
543 * string in <b>s</b>. Return 0 on success, -1 on failure. */
545 router_get_networkstatus_v3_hash(const char *s, char *digest)
547 return router_get_hash_impl(s, strlen(s), digest,
548 "network-status-version",
549 "\ndirectory-signature",
550 ' ');
553 /** Set <b>digest</b> to the SHA-1 digest of the hash of the extrainfo
554 * string in <b>s</b>. Return 0 on success, -1 on failure. */
556 router_get_extrainfo_hash(const char *s, char *digest)
558 return router_get_hash_impl(s, strlen(s), digest, "extra-info",
559 "\nrouter-signature",'\n');
562 /** Helper: used to generate signatures for routers, directories and
563 * network-status objects. Given a digest in <b>digest</b> and a secret
564 * <b>private_key</b>, generate an PKCS1-padded signature, BASE64-encode it,
565 * surround it with -----BEGIN/END----- pairs, and write it to the
566 * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
567 * failure.
570 router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
571 crypto_pk_env_t *private_key)
573 char *signature;
574 size_t i;
576 signature = tor_malloc(crypto_pk_keysize(private_key));
577 if (crypto_pk_private_sign(private_key, signature, digest, DIGEST_LEN) < 0) {
579 log_warn(LD_BUG,"Couldn't sign digest.");
580 goto err;
582 if (strlcat(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
583 goto truncated;
585 i = strlen(buf);
586 if (base64_encode(buf+i, buf_len-i, signature, 128) < 0) {
587 log_warn(LD_BUG,"couldn't base64-encode signature");
588 goto err;
591 if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
592 goto truncated;
594 tor_free(signature);
595 return 0;
597 truncated:
598 log_warn(LD_BUG,"tried to exceed string length.");
599 err:
600 tor_free(signature);
601 return -1;
604 /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
605 * <b>versionlist</b>. Else, return VS_EMPTY if versionlist has no
606 * entries. Else, return VS_OLD if every member of
607 * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
608 * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
609 * the same series (major.minor.micro) as <b>myversion</b>, but no such member
610 * is newer than <b>myversion.</b>. Else, return VS_NEW if every member of
611 * <b>versionlist</b> is older than <b>myversion</b>. Else, return
612 * VS_UNRECOMMENDED.
614 * (versionlist is a comma-separated list of version strings,
615 * optionally prefixed with "Tor". Versions that can't be parsed are
616 * ignored.)
618 version_status_t
619 tor_version_is_obsolete(const char *myversion, const char *versionlist)
621 tor_version_t mine, other;
622 int found_newer = 0, found_older = 0, found_newer_in_series = 0,
623 found_any_in_series = 0, r, same;
624 version_status_t ret = VS_UNRECOMMENDED;
625 smartlist_t *version_sl;
627 log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
628 myversion, versionlist);
630 if (tor_version_parse(myversion, &mine)) {
631 log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
632 tor_assert(0);
634 version_sl = smartlist_create();
635 smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
637 if (!strlen(versionlist)) { /* no authorities cared or agreed */
638 ret = VS_EMPTY;
639 goto done;
642 SMARTLIST_FOREACH(version_sl, const char *, cp, {
643 if (!strcmpstart(cp, "Tor "))
644 cp += 4;
646 if (tor_version_parse(cp, &other)) {
647 /* Couldn't parse other; it can't be a match. */
648 } else {
649 same = tor_version_same_series(&mine, &other);
650 if (same)
651 found_any_in_series = 1;
652 r = tor_version_compare(&mine, &other);
653 if (r==0) {
654 ret = VS_RECOMMENDED;
655 goto done;
656 } else if (r<0) {
657 found_newer = 1;
658 if (same)
659 found_newer_in_series = 1;
660 } else if (r>0) {
661 found_older = 1;
666 /* We didn't find the listed version. Is it new or old? */
667 if (found_any_in_series && !found_newer_in_series && found_newer) {
668 ret = VS_NEW_IN_SERIES;
669 } else if (found_newer && !found_older) {
670 ret = VS_OLD;
671 } else if (found_older && !found_newer) {
672 ret = VS_NEW;
673 } else {
674 ret = VS_UNRECOMMENDED;
677 done:
678 SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
679 smartlist_free(version_sl);
680 return ret;
683 /** Read a signed directory from <b>str</b>. If it's well-formed, return 0.
684 * Otherwise, return -1. If we're a directory cache, cache it.
687 router_parse_directory(const char *str)
689 directory_token_t *tok;
690 char digest[DIGEST_LEN];
691 time_t published_on;
692 int r;
693 const char *end, *cp;
694 smartlist_t *tokens = NULL;
695 crypto_pk_env_t *declared_key = NULL;
696 memarea_t *area = memarea_new();
698 /* XXXX This could be simplified a lot, but it will all go away
699 * once pre-0.1.1.8 is obsolete, and for now it's better not to
700 * touch it. */
702 if (router_get_dir_hash(str, digest)) {
703 log_warn(LD_DIR, "Unable to compute digest of directory");
704 goto err;
706 log_debug(LD_DIR,"Received directory hashes to %s",hex_str(digest,4));
708 /* Check signature first, before we try to tokenize. */
709 cp = str;
710 while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
711 cp = end;
712 if (cp == str || !cp) {
713 log_warn(LD_DIR, "No signature found on directory."); goto err;
715 ++cp;
716 tokens = smartlist_create();
717 if (tokenize_string(area,cp,strchr(cp,'\0'),tokens,dir_token_table,0)) {
718 log_warn(LD_DIR, "Error tokenizing directory signature"); goto err;
720 if (smartlist_len(tokens) != 1) {
721 log_warn(LD_DIR, "Unexpected number of tokens in signature"); goto err;
723 tok=smartlist_get(tokens,0);
724 if (tok->tp != K_DIRECTORY_SIGNATURE) {
725 log_warn(LD_DIR,"Expected a single directory signature"); goto err;
727 declared_key = find_dir_signing_key(str, str+strlen(str));
728 note_crypto_pk_op(VERIFY_DIR);
729 if (check_signature_token(digest, tok, declared_key,
730 CST_CHECK_AUTHORITY, "directory")<0)
731 goto err;
733 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
734 smartlist_clear(tokens);
735 memarea_clear(area);
737 /* Now try to parse the first part of the directory. */
738 if ((end = strstr(str,"\nrouter "))) {
739 ++end;
740 } else if ((end = strstr(str, "\ndirectory-signature"))) {
741 ++end;
742 } else {
743 end = str + strlen(str);
746 if (tokenize_string(area,str,end,tokens,dir_token_table,0)) {
747 log_warn(LD_DIR, "Error tokenizing directory"); goto err;
750 tok = find_by_keyword(tokens, K_PUBLISHED);
751 tor_assert(tok->n_args == 1);
753 if (parse_iso_time(tok->args[0], &published_on) < 0) {
754 goto err;
757 /* Now that we know the signature is okay, and we have a
758 * publication time, cache the directory. */
759 if (directory_caches_v1_dir_info(get_options()) &&
760 !authdir_mode_v1(get_options()))
761 dirserv_set_cached_directory(str, published_on, 0);
763 r = 0;
764 goto done;
765 err:
766 r = -1;
767 done:
768 if (declared_key) crypto_free_pk_env(declared_key);
769 if (tokens) {
770 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
771 smartlist_free(tokens);
773 if (area) {
774 DUMP_AREA(area, "v1 directory");
775 memarea_drop_all(area);
777 return r;
780 /** Read a signed router status statement from <b>str</b>. If it's
781 * well-formed, return 0. Otherwise, return -1. If we're a directory cache,
782 * cache it.*/
784 router_parse_runningrouters(const char *str)
786 char digest[DIGEST_LEN];
787 directory_token_t *tok;
788 time_t published_on;
789 int r = -1;
790 crypto_pk_env_t *declared_key = NULL;
791 smartlist_t *tokens = NULL;
792 const char *eos = str + strlen(str);
793 memarea_t *area = NULL;
795 if (router_get_runningrouters_hash(str, digest)) {
796 log_warn(LD_DIR, "Unable to compute digest of running-routers");
797 goto err;
799 area = memarea_new();
800 tokens = smartlist_create();
801 if (tokenize_string(area,str,eos,tokens,dir_token_table,0)) {
802 log_warn(LD_DIR, "Error tokenizing running-routers"); goto err;
804 tok = smartlist_get(tokens,0);
805 if (tok->tp != K_NETWORK_STATUS) {
806 log_warn(LD_DIR, "Network-status starts with wrong token");
807 goto err;
810 tok = find_by_keyword(tokens, K_PUBLISHED);
811 tor_assert(tok->n_args == 1);
812 if (parse_iso_time(tok->args[0], &published_on) < 0) {
813 goto err;
815 if (!(tok = find_opt_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
816 log_warn(LD_DIR, "Missing signature on running-routers");
817 goto err;
819 declared_key = find_dir_signing_key(str, eos);
820 note_crypto_pk_op(VERIFY_DIR);
821 if (check_signature_token(digest, tok, declared_key,
822 CST_CHECK_AUTHORITY, "running-routers")
823 < 0)
824 goto err;
826 /* Now that we know the signature is okay, and we have a
827 * publication time, cache the list. */
828 if (get_options()->DirPort && !authdir_mode_v1(get_options()))
829 dirserv_set_cached_directory(str, published_on, 1);
831 r = 0;
832 err:
833 if (declared_key) crypto_free_pk_env(declared_key);
834 if (tokens) {
835 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
836 smartlist_free(tokens);
838 if (area) {
839 DUMP_AREA(area, "v1 running-routers");
840 memarea_drop_all(area);
842 return r;
845 /** Given a directory or running-routers string in <b>str</b>, try to
846 * find the its dir-signing-key token (if any). If this token is
847 * present, extract and return the key. Return NULL on failure. */
848 static crypto_pk_env_t *
849 find_dir_signing_key(const char *str, const char *eos)
851 const char *cp;
852 directory_token_t *tok;
853 crypto_pk_env_t *key = NULL;
854 memarea_t *area = NULL;
855 tor_assert(str);
856 tor_assert(eos);
858 /* Is there a dir-signing-key in the directory? */
859 cp = tor_memstr(str, eos-str, "\nopt dir-signing-key");
860 if (!cp)
861 cp = tor_memstr(str, eos-str, "\ndir-signing-key");
862 if (!cp)
863 return NULL;
864 ++cp; /* Now cp points to the start of the token. */
866 area = memarea_new();
867 tok = get_next_token(area, &cp, eos, dir_token_table);
868 if (!tok) {
869 log_warn(LD_DIR, "Unparseable dir-signing-key token");
870 goto done;
872 if (tok->tp != K_DIR_SIGNING_KEY) {
873 log_warn(LD_DIR, "Dir-signing-key token did not parse as expected");
874 goto done;
877 if (tok->key) {
878 key = tok->key;
879 tok->key = NULL; /* steal reference. */
880 } else {
881 log_warn(LD_DIR, "Dir-signing-key token contained no key");
884 done:
885 if (tok) token_free(tok);
886 if (area) {
887 DUMP_AREA(area, "dir-signing-key token");
888 memarea_drop_all(area);
890 return key;
893 /** Return true iff <b>key</b> is allowed to sign directories.
895 static int
896 dir_signing_key_is_trusted(crypto_pk_env_t *key)
898 char digest[DIGEST_LEN];
899 if (!key) return 0;
900 if (crypto_pk_get_digest(key, digest) < 0) {
901 log_warn(LD_DIR, "Error computing dir-signing-key digest");
902 return 0;
904 if (!router_digest_is_trusted_dir(digest)) {
905 log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
906 return 0;
908 return 1;
911 /** Check whether the object body of the token in <b>tok</b> has a good
912 * signature for <b>digest</b> using key <b>pkey</b>. If
913 * <b>CST_CHECK_AUTHORITY</b> is set, make sure that <b>pkey</b> is the key of
914 * a directory authority. If <b>CST_NO_CHECK_OBJTYPE</b> is set, do not check
915 * the object type of the signature object. Use <b>doctype</b> as the type of
916 * the document when generating log messages. Return 0 on success, negative
917 * on failure.
919 static int
920 check_signature_token(const char *digest,
921 directory_token_t *tok,
922 crypto_pk_env_t *pkey,
923 int flags,
924 const char *doctype)
926 char *signed_digest;
927 const int check_authority = (flags & CST_CHECK_AUTHORITY);
928 const int check_objtype = ! (flags & CST_NO_CHECK_OBJTYPE);
930 tor_assert(pkey);
931 tor_assert(tok);
932 tor_assert(digest);
933 tor_assert(doctype);
935 if (check_authority && !dir_signing_key_is_trusted(pkey)) {
936 log_warn(LD_DIR, "Key on %s did not come from an authority; rejecting",
937 doctype);
938 return -1;
941 if (check_objtype) {
942 if (strcmp(tok->object_type, "SIGNATURE")) {
943 log_warn(LD_DIR, "Bad object type on %s signature", doctype);
944 return -1;
948 signed_digest = tor_malloc(tok->object_size);
949 if (crypto_pk_public_checksig(pkey, signed_digest, tok->object_body,
950 tok->object_size)
951 != DIGEST_LEN) {
952 log_warn(LD_DIR, "Error reading %s: invalid signature.", doctype);
953 tor_free(signed_digest);
954 return -1;
956 // log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
957 // hex_str(signed_digest,4));
958 if (memcmp(digest, signed_digest, DIGEST_LEN)) {
959 log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
960 tor_free(signed_digest);
961 return -1;
963 tor_free(signed_digest);
964 return 0;
967 /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
968 * or to the first of the annotations proceeding the next router or
969 * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
970 * we found an extrainfo, or false if found a router. Do not scan beyond
971 * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
972 static int
973 find_start_of_next_router_or_extrainfo(const char **s_ptr,
974 const char *eos,
975 int *is_extrainfo_out)
977 const char *annotations = NULL;
978 const char *s = *s_ptr;
980 s = eat_whitespace_eos(s, eos);
982 while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
983 /* We're at the start of a line. */
984 tor_assert(*s != '\n');
986 if (*s == '@' && !annotations) {
987 annotations = s;
988 } else if (*s == 'r' && !strcmpstart(s, "router ")) {
989 *s_ptr = annotations ? annotations : s;
990 *is_extrainfo_out = 0;
991 return 0;
992 } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
993 *s_ptr = annotations ? annotations : s;
994 *is_extrainfo_out = 1;
995 return 0;
998 if (!(s = memchr(s+1, '\n', eos-(s+1))))
999 break;
1000 s = eat_whitespace_eos(s, eos);
1002 return -1;
1005 /** Given a string *<b>s</b> containing a concatenated sequence of router
1006 * descriptors (or extra-info documents if <b>is_extrainfo</b> is set), parses
1007 * them and stores the result in <b>dest</b>. All routers are marked running
1008 * and valid. Advances *s to a point immediately following the last router
1009 * entry. Ignore any trailing router entries that are not complete.
1011 * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
1012 * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
1013 * isn't SAVED_NOWHERE, remember the offset of each descriptor.
1015 * Returns 0 on success and -1 on failure.
1018 router_parse_list_from_string(const char **s, const char *eos,
1019 smartlist_t *dest,
1020 saved_location_t saved_location,
1021 int want_extrainfo,
1022 int allow_annotations,
1023 const char *prepend_annotations)
1025 routerinfo_t *router;
1026 extrainfo_t *extrainfo;
1027 signed_descriptor_t *signed_desc;
1028 void *elt;
1029 const char *end, *start;
1030 int have_extrainfo;
1032 tor_assert(s);
1033 tor_assert(*s);
1034 tor_assert(dest);
1036 start = *s;
1037 if (!eos)
1038 eos = *s + strlen(*s);
1040 tor_assert(eos >= *s);
1042 while (1) {
1043 if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
1044 break;
1046 end = tor_memstr(*s, eos-*s, "\nrouter-signature");
1047 if (end)
1048 end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
1049 if (end)
1050 end += strlen("\n-----END SIGNATURE-----\n");
1052 if (!end)
1053 break;
1055 elt = NULL;
1057 if (have_extrainfo && want_extrainfo) {
1058 routerlist_t *rl = router_get_routerlist();
1059 extrainfo = extrainfo_parse_entry_from_string(*s, end,
1060 saved_location != SAVED_IN_CACHE,
1061 rl->identity_map);
1062 if (extrainfo) {
1063 signed_desc = &extrainfo->cache_info;
1064 elt = extrainfo;
1066 } else if (!have_extrainfo && !want_extrainfo) {
1067 router = router_parse_entry_from_string(*s, end,
1068 saved_location != SAVED_IN_CACHE,
1069 allow_annotations,
1070 prepend_annotations);
1071 if (router) {
1072 log_debug(LD_DIR, "Read router '%s', purpose '%s'",
1073 router->nickname, router_purpose_to_string(router->purpose));
1074 signed_desc = &router->cache_info;
1075 elt = router;
1078 if (!elt) {
1079 *s = end;
1080 continue;
1082 if (saved_location != SAVED_NOWHERE) {
1083 signed_desc->saved_location = saved_location;
1084 signed_desc->saved_offset = *s - start;
1086 *s = end;
1087 smartlist_add(dest, elt);
1090 return 0;
1093 /* For debugging: define to count every descriptor digest we've seen so we
1094 * know if we need to try harder to avoid duplicate verifies. */
1095 #undef COUNT_DISTINCT_DIGESTS
1097 #ifdef COUNT_DISTINCT_DIGESTS
1098 static digestmap_t *verified_digests = NULL;
1099 #endif
1101 /** Log the total count of the number of distinct router digests we've ever
1102 * verified. When compared to the number of times we've verified routerdesc
1103 * signatures <i>in toto</i>, this will tell us if we're doing too much
1104 * multiple-verification. */
1105 void
1106 dump_distinct_digest_count(int severity)
1108 #ifdef COUNT_DISTINCT_DIGESTS
1109 if (!verified_digests)
1110 verified_digests = digestmap_new();
1111 log(severity, LD_GENERAL, "%d *distinct* router digests verified",
1112 digestmap_size(verified_digests));
1113 #else
1114 (void)severity; /* suppress "unused parameter" warning */
1115 #endif
1118 /** Helper function: reads a single router entry from *<b>s</b> ...
1119 * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
1120 * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
1121 * s through end into the signed_descriptor_body of the resulting
1122 * routerinfo_t.
1124 * If <b>end</b> is NULL, <b>s</b> must be properly NULL-terminated.
1126 * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
1127 * before the router; if it's false, reject the router if it's annotated. If
1128 * <b>prepend_annotations</b> is set, it should contain some annotations:
1129 * append them to the front of the router before parsing it, and keep them
1130 * around when caching the router.
1132 * Only one of allow_annotations and prepend_annotations may be set.
1134 routerinfo_t *
1135 router_parse_entry_from_string(const char *s, const char *end,
1136 int cache_copy, int allow_annotations,
1137 const char *prepend_annotations)
1139 routerinfo_t *router = NULL;
1140 char digest[128];
1141 smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
1142 directory_token_t *tok;
1143 struct in_addr in;
1144 const char *start_of_annotations, *cp;
1145 size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
1146 int ok = 1;
1147 memarea_t *area = NULL;
1149 tor_assert(!allow_annotations || !prepend_annotations);
1151 if (!end) {
1152 end = s + strlen(s);
1155 /* point 'end' to a point immediately after the final newline. */
1156 while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
1157 --end;
1159 area = memarea_new();
1160 tokens = smartlist_create();
1161 if (prepend_annotations) {
1162 if (tokenize_string(area,prepend_annotations,NULL,tokens,
1163 routerdesc_token_table,TS_NOCHECK)) {
1164 log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
1165 goto err;
1169 start_of_annotations = s;
1170 cp = tor_memstr(s, end-s, "\nrouter ");
1171 if (!cp) {
1172 if (end-s < 7 || strcmpstart(s, "router ")) {
1173 log_warn(LD_DIR, "No router keyword found.");
1174 goto err;
1176 } else {
1177 s = cp+1;
1180 if (start_of_annotations != s) { /* We have annotations */
1181 if (allow_annotations) {
1182 if (tokenize_string(area,start_of_annotations,s,tokens,
1183 routerdesc_token_table,TS_NOCHECK)) {
1184 log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
1185 goto err;
1187 } else {
1188 log_warn(LD_DIR, "Found unexpected annotations on router descriptor not "
1189 "loaded from disk. Dropping it.");
1190 goto err;
1194 if (router_get_router_hash(s, end - s, digest) < 0) {
1195 log_warn(LD_DIR, "Couldn't compute router hash.");
1196 goto err;
1199 int flags = 0;
1200 if (allow_annotations)
1201 flags |= TS_ANNOTATIONS_OK;
1202 if (prepend_annotations)
1203 flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
1205 if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
1206 log_warn(LD_DIR, "Error tokenizing router descriptor.");
1207 goto err;
1211 if (smartlist_len(tokens) < 2) {
1212 log_warn(LD_DIR, "Impossibly short router descriptor.");
1213 goto err;
1216 tok = find_by_keyword(tokens, K_ROUTER);
1217 tor_assert(tok->n_args >= 5);
1219 router = tor_malloc_zero(sizeof(routerinfo_t));
1220 router->country = -1;
1221 router->cache_info.routerlist_index = -1;
1222 router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
1223 router->cache_info.signed_descriptor_len = end-s;
1224 if (cache_copy) {
1225 size_t len = router->cache_info.signed_descriptor_len +
1226 router->cache_info.annotations_len;
1227 char *cp =
1228 router->cache_info.signed_descriptor_body = tor_malloc(len+1);
1229 if (prepend_annotations) {
1230 memcpy(cp, prepend_annotations, prepend_len);
1231 cp += prepend_len;
1233 /* This assertion will always succeed.
1234 * len == signed_desc_len + annotations_len
1235 * == end-s + s-start_of_annotations + prepend_len
1236 * == end-start_of_annotations + prepend_len
1237 * We already wrote prepend_len bytes into the buffer; now we're
1238 * writing end-start_of_annotations -NM. */
1239 tor_assert(cp+(end-start_of_annotations) ==
1240 router->cache_info.signed_descriptor_body+len);
1241 memcpy(cp, start_of_annotations, end-start_of_annotations);
1242 router->cache_info.signed_descriptor_body[len] = '\0';
1243 tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
1245 memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
1247 router->nickname = tor_strdup(tok->args[0]);
1248 if (!is_legal_nickname(router->nickname)) {
1249 log_warn(LD_DIR,"Router nickname is invalid");
1250 goto err;
1252 router->address = tor_strdup(tok->args[1]);
1253 if (!tor_inet_aton(router->address, &in)) {
1254 log_warn(LD_DIR,"Router address is not an IP address.");
1255 goto err;
1257 router->addr = ntohl(in.s_addr);
1259 router->or_port =
1260 (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
1261 if (!ok) {
1262 log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
1263 goto err;
1265 router->dir_port =
1266 (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
1267 if (!ok) {
1268 log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
1269 goto err;
1272 tok = find_by_keyword(tokens, K_BANDWIDTH);
1273 tor_assert(tok->n_args >= 3);
1274 router->bandwidthrate = (int)
1275 tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
1277 if (!ok) {
1278 log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
1279 escaped(tok->args[0]));
1280 goto err;
1282 router->bandwidthburst =
1283 (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
1284 if (!ok) {
1285 log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
1286 goto err;
1288 router->bandwidthcapacity = (int)
1289 tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
1290 if (!ok) {
1291 log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
1292 goto err;
1295 if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
1296 tor_assert(tok->n_args);
1297 router->purpose = router_purpose_from_string(tok->args[0]);
1298 } else {
1299 router->purpose = ROUTER_PURPOSE_GENERAL;
1301 router->cache_info.send_unencrypted =
1302 (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
1304 if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
1305 tor_assert(tok->n_args >= 1);
1306 router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
1307 if (!ok) {
1308 log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
1309 goto err;
1313 if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
1314 tor_assert(tok->n_args >= 1);
1315 router->is_hibernating
1316 = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
1319 tok = find_by_keyword(tokens, K_PUBLISHED);
1320 tor_assert(tok->n_args == 1);
1321 if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
1322 goto err;
1324 tok = find_by_keyword(tokens, K_ONION_KEY);
1325 router->onion_pkey = tok->key;
1326 tok->key = NULL; /* Prevent free */
1328 tok = find_by_keyword(tokens, K_SIGNING_KEY);
1329 router->identity_pkey = tok->key;
1330 tok->key = NULL; /* Prevent free */
1331 if (crypto_pk_get_digest(router->identity_pkey,
1332 router->cache_info.identity_digest)) {
1333 log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
1336 if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
1337 /* If there's a fingerprint line, it must match the identity digest. */
1338 char d[DIGEST_LEN];
1339 tor_assert(tok->n_args == 1);
1340 tor_strstrip(tok->args[0], " ");
1341 if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
1342 log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
1343 escaped(tok->args[0]));
1344 goto err;
1346 if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
1347 log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
1348 tok->args[0]);
1349 goto err;
1353 if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
1354 router->platform = tor_strdup(tok->args[0]);
1357 if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
1358 router->contact_info = tor_strdup(tok->args[0]);
1361 if ((tok = find_opt_by_keyword(tokens, K_EVENTDNS))) {
1362 router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
1363 } else if (router->platform) {
1364 if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
1365 router->has_old_dnsworkers = 1;
1368 exit_policy_tokens = find_all_exitpolicy(tokens);
1369 if (!smartlist_len(exit_policy_tokens)) {
1370 log_warn(LD_DIR, "No exit policy tokens in descriptor.");
1371 goto err;
1373 SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
1374 if (router_add_exit_policy(router,t)<0) {
1375 log_warn(LD_DIR,"Error in exit policy");
1376 goto err;
1378 policy_expand_private(&router->exit_policy);
1379 if (policy_is_reject_star(router->exit_policy))
1380 router->policy_is_reject_star = 1;
1382 if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
1383 int i;
1384 router->declared_family = smartlist_create();
1385 for (i=0;i<tok->n_args;++i) {
1386 if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
1387 log_warn(LD_DIR, "Illegal nickname %s in family line",
1388 escaped(tok->args[i]));
1389 goto err;
1391 smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
1395 if ((tok = find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO)))
1396 router->caches_extra_info = 1;
1398 if ((tok = find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS)))
1399 router->allow_single_hop_exits = 1;
1401 if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
1402 tor_assert(tok->n_args >= 1);
1403 if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
1404 base16_decode(router->cache_info.extra_info_digest,
1405 DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
1406 } else {
1407 log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
1411 if ((tok = find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR))) {
1412 router->wants_to_be_hs_dir = 1;
1415 tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
1416 note_crypto_pk_op(VERIFY_RTR);
1417 #ifdef COUNT_DISTINCT_DIGESTS
1418 if (!verified_digests)
1419 verified_digests = digestmap_new();
1420 digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
1421 #endif
1422 if (check_signature_token(digest, tok, router->identity_pkey, 0,
1423 "router descriptor") < 0)
1424 goto err;
1426 routerinfo_set_country(router);
1428 if (!router->or_port) {
1429 log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
1430 goto err;
1433 if (!router->platform) {
1434 router->platform = tor_strdup("<unknown>");
1437 goto done;
1439 err:
1440 routerinfo_free(router);
1441 router = NULL;
1442 done:
1443 if (tokens) {
1444 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
1445 smartlist_free(tokens);
1447 if (exit_policy_tokens) {
1448 smartlist_free(exit_policy_tokens);
1450 if (area) {
1451 DUMP_AREA(area, "routerinfo");
1452 memarea_drop_all(area);
1454 return router;
1457 /** Parse a single extrainfo entry from the string <b>s</b>, ending at
1458 * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
1459 * <b>cache_copy</b> is true, make a copy of the extra-info document in the
1460 * cache_info fields of the result. If <b>routermap</b> is provided, use it
1461 * as a map from router identity to routerinfo_t when looking up signing keys.
1463 extrainfo_t *
1464 extrainfo_parse_entry_from_string(const char *s, const char *end,
1465 int cache_copy, struct digest_ri_map_t *routermap)
1467 extrainfo_t *extrainfo = NULL;
1468 char digest[128];
1469 smartlist_t *tokens = NULL;
1470 directory_token_t *tok;
1471 crypto_pk_env_t *key = NULL;
1472 routerinfo_t *router = NULL;
1473 memarea_t *area = NULL;
1475 if (!end) {
1476 end = s + strlen(s);
1479 /* point 'end' to a point immediately after the final newline. */
1480 while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
1481 --end;
1483 if (router_get_extrainfo_hash(s, digest) < 0) {
1484 log_warn(LD_DIR, "Couldn't compute router hash.");
1485 goto err;
1487 tokens = smartlist_create();
1488 area = memarea_new();
1489 if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
1490 log_warn(LD_DIR, "Error tokenizing extra-info document.");
1491 goto err;
1494 if (smartlist_len(tokens) < 2) {
1495 log_warn(LD_DIR, "Impossibly short extra-info document.");
1496 goto err;
1499 tok = smartlist_get(tokens,0);
1500 if (tok->tp != K_EXTRA_INFO) {
1501 log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
1502 goto err;
1505 extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
1506 extrainfo->cache_info.is_extrainfo = 1;
1507 if (cache_copy)
1508 extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
1509 extrainfo->cache_info.signed_descriptor_len = end-s;
1510 memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
1512 tor_assert(tok->n_args >= 2);
1513 if (!is_legal_nickname(tok->args[0])) {
1514 log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
1515 goto err;
1517 strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
1518 if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
1519 base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
1520 tok->args[1], HEX_DIGEST_LEN)) {
1521 log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
1522 escaped(tok->args[1]));
1523 goto err;
1526 tok = find_by_keyword(tokens, K_PUBLISHED);
1527 if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
1528 log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
1529 escaped(tok->args[0]));
1530 goto err;
1533 if (routermap &&
1534 (router = digestmap_get((digestmap_t*)routermap,
1535 extrainfo->cache_info.identity_digest))) {
1536 key = router->identity_pkey;
1539 tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
1540 if (strcmp(tok->object_type, "SIGNATURE") ||
1541 tok->object_size < 128 || tok->object_size > 512) {
1542 log_warn(LD_DIR, "Bad object type or length on extra-info signature");
1543 goto err;
1546 if (key) {
1547 note_crypto_pk_op(VERIFY_RTR);
1548 if (check_signature_token(digest, tok, key, 0, "extra-info") < 0)
1549 goto err;
1551 if (router)
1552 extrainfo->cache_info.send_unencrypted =
1553 router->cache_info.send_unencrypted;
1554 } else {
1555 extrainfo->pending_sig = tor_memdup(tok->object_body,
1556 tok->object_size);
1557 extrainfo->pending_sig_len = tok->object_size;
1560 goto done;
1561 err:
1562 if (extrainfo)
1563 extrainfo_free(extrainfo);
1564 extrainfo = NULL;
1565 done:
1566 if (tokens) {
1567 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
1568 smartlist_free(tokens);
1570 if (area) {
1571 DUMP_AREA(area, "extrainfo");
1572 memarea_drop_all(area);
1574 return extrainfo;
1577 /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
1578 * the first character after the certificate. */
1579 authority_cert_t *
1580 authority_cert_parse_from_string(const char *s, const char **end_of_string)
1582 authority_cert_t *cert = NULL, *old_cert;
1583 smartlist_t *tokens = NULL;
1584 char digest[DIGEST_LEN];
1585 directory_token_t *tok;
1586 char fp_declared[DIGEST_LEN];
1587 char *eos;
1588 size_t len;
1589 int found;
1590 memarea_t *area = NULL;
1592 s = eat_whitespace(s);
1593 eos = strstr(s, "\ndir-key-certification");
1594 if (! eos) {
1595 log_warn(LD_DIR, "No signature found on key certificate");
1596 return NULL;
1598 eos = strstr(eos, "\n-----END SIGNATURE-----\n");
1599 if (! eos) {
1600 log_warn(LD_DIR, "No end-of-signature found on key certificate");
1601 return NULL;
1603 eos = strchr(eos+2, '\n');
1604 tor_assert(eos);
1605 ++eos;
1606 len = eos - s;
1608 tokens = smartlist_create();
1609 area = memarea_new();
1610 if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
1611 log_warn(LD_DIR, "Error tokenizing key certificate");
1612 goto err;
1614 if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
1615 "\ndir-key-certification", '\n') < 0)
1616 goto err;
1617 tok = smartlist_get(tokens, 0);
1618 if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
1619 log_warn(LD_DIR,
1620 "Key certificate does not begin with a recognized version (3).");
1621 goto err;
1624 cert = tor_malloc_zero(sizeof(authority_cert_t));
1625 memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
1627 tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
1628 tor_assert(tok->key);
1629 cert->signing_key = tok->key;
1630 tok->key = NULL;
1631 if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
1632 goto err;
1634 tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
1635 tor_assert(tok->key);
1636 cert->identity_key = tok->key;
1637 tok->key = NULL;
1639 tok = find_by_keyword(tokens, K_FINGERPRINT);
1640 tor_assert(tok->n_args);
1641 if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
1642 strlen(tok->args[0]))) {
1643 log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
1644 escaped(tok->args[0]));
1645 goto err;
1648 if (crypto_pk_get_digest(cert->identity_key,
1649 cert->cache_info.identity_digest))
1650 goto err;
1652 if (memcmp(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
1653 log_warn(LD_DIR, "Digest of certificate key didn't match declared "
1654 "fingerprint");
1655 goto err;
1658 tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
1659 if (tok) {
1660 struct in_addr in;
1661 char *address = NULL;
1662 tor_assert(tok->n_args);
1663 /* XXX021 use tor_addr_port_parse() below instead. -RD */
1664 if (parse_addr_port(LOG_WARN, tok->args[0], &address, NULL,
1665 &cert->dir_port)<0 ||
1666 tor_inet_aton(address, &in) == 0) {
1667 log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
1668 tor_free(address);
1669 goto err;
1671 cert->addr = ntohl(in.s_addr);
1672 tor_free(address);
1675 tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
1676 if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
1677 goto err;
1679 tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
1680 if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
1681 goto err;
1684 tok = smartlist_get(tokens, smartlist_len(tokens)-1);
1685 if (tok->tp != K_DIR_KEY_CERTIFICATION) {
1686 log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
1687 goto err;
1690 /* If we already have this cert, don't bother checking the signature. */
1691 old_cert = authority_cert_get_by_digests(
1692 cert->cache_info.identity_digest,
1693 cert->signing_key_digest);
1694 found = 0;
1695 if (old_cert) {
1696 /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
1697 * buy us much. */
1698 if (old_cert->cache_info.signed_descriptor_len == len &&
1699 old_cert->cache_info.signed_descriptor_body &&
1700 !memcmp(s, old_cert->cache_info.signed_descriptor_body, len)) {
1701 log_debug(LD_DIR, "We already checked the signature on this "
1702 "certificate; no need to do so again.");
1703 found = 1;
1704 cert->is_cross_certified = old_cert->is_cross_certified;
1707 if (!found) {
1708 if (check_signature_token(digest, tok, cert->identity_key, 0,
1709 "key certificate")) {
1710 goto err;
1713 if ((tok = find_opt_by_keyword(tokens, K_DIR_KEY_CROSSCERT))) {
1714 /* XXXX Once all authorities generate cross-certified certificates,
1715 * make this field mandatory. */
1716 if (check_signature_token(cert->cache_info.identity_digest,
1717 tok,
1718 cert->signing_key,
1719 CST_NO_CHECK_OBJTYPE,
1720 "key cross-certification")) {
1721 goto err;
1723 cert->is_cross_certified = 1;
1727 cert->cache_info.signed_descriptor_len = len;
1728 cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
1729 memcpy(cert->cache_info.signed_descriptor_body, s, len);
1730 cert->cache_info.signed_descriptor_body[len] = 0;
1731 cert->cache_info.saved_location = SAVED_NOWHERE;
1733 if (end_of_string) {
1734 *end_of_string = eat_whitespace(eos);
1736 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
1737 smartlist_free(tokens);
1738 if (area) {
1739 DUMP_AREA(area, "authority cert");
1740 memarea_drop_all(area);
1742 return cert;
1743 err:
1744 authority_cert_free(cert);
1745 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
1746 smartlist_free(tokens);
1747 if (area) {
1748 DUMP_AREA(area, "authority cert");
1749 memarea_drop_all(area);
1751 return NULL;
1754 /** Helper: given a string <b>s</b>, return the start of the next router-status
1755 * object (starting with "r " at the start of a line). If none is found,
1756 * return the start of the next directory signature. If none is found, return
1757 * the end of the string. */
1758 static INLINE const char *
1759 find_start_of_next_routerstatus(const char *s)
1761 const char *eos = strstr(s, "\nr ");
1762 if (eos) {
1763 const char *eos2 = tor_memstr(s, eos-s, "\ndirectory-signature");
1764 if (eos2 && eos2 < eos)
1765 return eos2;
1766 else
1767 return eos+1;
1768 } else {
1769 if ((eos = strstr(s, "\ndirectory-signature")))
1770 return eos+1;
1771 return s + strlen(s);
1775 /** Given a string at *<b>s</b>, containing a routerstatus object, and an
1776 * empty smartlist at <b>tokens</b>, parse and return the first router status
1777 * object in the string, and advance *<b>s</b> to just after the end of the
1778 * router status. Return NULL and advance *<b>s</b> on error.
1780 * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
1781 * routerstatus but use <b>vote_rs</b> instead.
1783 * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
1784 * consensus, and we should parse it according to the method used to
1785 * make that consensus.
1787 static routerstatus_t *
1788 routerstatus_parse_entry_from_string(memarea_t *area,
1789 const char **s, smartlist_t *tokens,
1790 networkstatus_t *vote,
1791 vote_routerstatus_t *vote_rs,
1792 int consensus_method)
1794 const char *eos;
1795 routerstatus_t *rs = NULL;
1796 directory_token_t *tok;
1797 char timebuf[ISO_TIME_LEN+1];
1798 struct in_addr in;
1799 tor_assert(tokens);
1800 tor_assert(bool_eq(vote, vote_rs));
1802 eos = find_start_of_next_routerstatus(*s);
1804 if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
1805 log_warn(LD_DIR, "Error tokenizing router status");
1806 goto err;
1808 if (smartlist_len(tokens) < 1) {
1809 log_warn(LD_DIR, "Impossibly short router status");
1810 goto err;
1812 tok = find_by_keyword(tokens, K_R);
1813 tor_assert(tok->n_args >= 8);
1814 if (vote_rs) {
1815 rs = &vote_rs->status;
1816 } else {
1817 rs = tor_malloc_zero(sizeof(routerstatus_t));
1820 if (!is_legal_nickname(tok->args[0])) {
1821 log_warn(LD_DIR,
1822 "Invalid nickname %s in router status; skipping.",
1823 escaped(tok->args[0]));
1824 goto err;
1826 strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
1828 if (digest_from_base64(rs->identity_digest, tok->args[1])) {
1829 log_warn(LD_DIR, "Error decoding identity digest %s",
1830 escaped(tok->args[1]));
1831 goto err;
1834 if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
1835 log_warn(LD_DIR, "Error decoding descriptor digest %s",
1836 escaped(tok->args[2]));
1837 goto err;
1840 if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
1841 tok->args[3], tok->args[4]) < 0 ||
1842 parse_iso_time(timebuf, &rs->published_on)<0) {
1843 log_warn(LD_DIR, "Error parsing time '%s %s'",
1844 tok->args[3], tok->args[4]);
1845 goto err;
1848 if (tor_inet_aton(tok->args[5], &in) == 0) {
1849 log_warn(LD_DIR, "Error parsing router address in network-status %s",
1850 escaped(tok->args[5]));
1851 goto err;
1853 rs->addr = ntohl(in.s_addr);
1855 rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
1856 rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
1858 tok = find_opt_by_keyword(tokens, K_S);
1859 if (tok && vote) {
1860 int i;
1861 vote_rs->flags = 0;
1862 for (i=0; i < tok->n_args; ++i) {
1863 int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
1864 if (p >= 0) {
1865 vote_rs->flags |= (1<<p);
1866 } else {
1867 log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
1868 escaped(tok->args[i]));
1869 goto err;
1872 } else if (tok) {
1873 int i;
1874 for (i=0; i < tok->n_args; ++i) {
1875 if (!strcmp(tok->args[i], "Exit"))
1876 rs->is_exit = 1;
1877 else if (!strcmp(tok->args[i], "Stable"))
1878 rs->is_stable = 1;
1879 else if (!strcmp(tok->args[i], "Fast"))
1880 rs->is_fast = 1;
1881 else if (!strcmp(tok->args[i], "Running"))
1882 rs->is_running = 1;
1883 else if (!strcmp(tok->args[i], "Named"))
1884 rs->is_named = 1;
1885 else if (!strcmp(tok->args[i], "Valid"))
1886 rs->is_valid = 1;
1887 else if (!strcmp(tok->args[i], "V2Dir"))
1888 rs->is_v2_dir = 1;
1889 else if (!strcmp(tok->args[i], "Guard"))
1890 rs->is_possible_guard = 1;
1891 else if (!strcmp(tok->args[i], "BadExit"))
1892 rs->is_bad_exit = 1;
1893 else if (!strcmp(tok->args[i], "BadDirectory"))
1894 rs->is_bad_directory = 1;
1895 else if (!strcmp(tok->args[i], "Authority"))
1896 rs->is_authority = 1;
1897 else if (!strcmp(tok->args[i], "Unnamed") &&
1898 consensus_method >= 2) {
1899 /* Unnamed is computed right by consensus method 2 and later. */
1900 rs->is_unnamed = 1;
1901 } else if (!strcmp(tok->args[i], "HSDir")) {
1902 rs->is_hs_dir = 1;
1906 if ((tok = find_opt_by_keyword(tokens, K_V))) {
1907 tor_assert(tok->n_args == 1);
1908 rs->version_known = 1;
1909 if (strcmpstart(tok->args[0], "Tor ")) {
1910 rs->version_supports_begindir = 1;
1911 rs->version_supports_extrainfo_upload = 1;
1912 rs->version_supports_conditional_consensus = 1;
1913 } else {
1914 rs->version_supports_begindir =
1915 tor_version_as_new_as(tok->args[0], "0.2.0.1-alpha");
1916 rs->version_supports_extrainfo_upload =
1917 tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
1918 rs->version_supports_v3_dir =
1919 tor_version_as_new_as(tok->args[0], "0.2.0.8-alpha");
1920 rs->version_supports_conditional_consensus =
1921 tor_version_as_new_as(tok->args[0], "0.2.1.1-alpha");
1923 if (vote_rs) {
1924 vote_rs->version = tor_strdup(tok->args[0]);
1928 /* handle weighting/bandwidth info */
1929 if ((tok = find_opt_by_keyword(tokens, K_W))) {
1930 int i;
1931 for (i=0; i < tok->n_args; ++i) {
1932 if (!strcmpstart(tok->args[i], "Bandwidth=")) {
1933 int ok;
1934 rs->bandwidth = (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
1935 10, 0, UINT32_MAX,
1936 &ok, NULL);
1937 if (!ok) {
1938 log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
1939 goto err;
1941 rs->has_bandwidth = 1;
1946 /* parse exit policy summaries */
1947 if ((tok = find_opt_by_keyword(tokens, K_P))) {
1948 tor_assert(tok->n_args == 1);
1949 if (strcmpstart(tok->args[0], "accept ") &&
1950 strcmpstart(tok->args[0], "reject ")) {
1951 log_warn(LD_DIR, "Unknown exit policy summary type %s.",
1952 escaped(tok->args[0]));
1953 goto err;
1955 /* XXX weasel: parse this into ports and represent them somehow smart,
1956 * maybe not here but somewhere on if we need it for the client.
1957 * we should still parse it here to check it's valid tho.
1959 rs->exitsummary = tor_strdup(tok->args[0]);
1960 rs->has_exitsummary = 1;
1963 if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
1964 rs->is_named = 0;
1966 goto done;
1967 err:
1968 if (rs && !vote_rs)
1969 routerstatus_free(rs);
1970 rs = NULL;
1971 done:
1972 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
1973 smartlist_clear(tokens);
1974 if (area) {
1975 DUMP_AREA(area, "routerstatus entry");
1976 memarea_clear(area);
1978 *s = eos;
1980 return rs;
1983 /** Helper to sort a smartlist of pointers to routerstatus_t */
1984 static int
1985 _compare_routerstatus_entries(const void **_a, const void **_b)
1987 const routerstatus_t *a = *_a, *b = *_b;
1988 return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
1991 /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
1992 static void
1993 _free_duplicate_routerstatus_entry(void *e)
1995 log_warn(LD_DIR,
1996 "Network-status has two entries for the same router. "
1997 "Dropping one.");
1998 routerstatus_free(e);
2001 /** Given a v2 network-status object in <b>s</b>, try to
2002 * parse it and return the result. Return NULL on failure. Check the
2003 * signature of the network status, but do not (yet) check the signing key for
2004 * authority.
2006 networkstatus_v2_t *
2007 networkstatus_v2_parse_from_string(const char *s)
2009 const char *eos;
2010 smartlist_t *tokens = smartlist_create();
2011 smartlist_t *footer_tokens = smartlist_create();
2012 networkstatus_v2_t *ns = NULL;
2013 char ns_digest[DIGEST_LEN];
2014 char tmp_digest[DIGEST_LEN];
2015 struct in_addr in;
2016 directory_token_t *tok;
2017 int i;
2018 memarea_t *area = NULL;
2020 if (router_get_networkstatus_v2_hash(s, ns_digest)) {
2021 log_warn(LD_DIR, "Unable to compute digest of network-status");
2022 goto err;
2025 area = memarea_new();
2026 eos = find_start_of_next_routerstatus(s);
2027 if (tokenize_string(area, s, eos, tokens, netstatus_token_table,0)) {
2028 log_warn(LD_DIR, "Error tokenizing network-status header.");
2029 goto err;
2031 ns = tor_malloc_zero(sizeof(networkstatus_v2_t));
2032 memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
2034 tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
2035 tor_assert(tok->n_args >= 1);
2036 if (strcmp(tok->args[0], "2")) {
2037 log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
2038 "%s", escaped(tok->args[0]));
2039 goto err;
2042 tok = find_by_keyword(tokens, K_DIR_SOURCE);
2043 tor_assert(tok->n_args >= 3);
2044 ns->source_address = tor_strdup(tok->args[0]);
2045 if (tor_inet_aton(tok->args[1], &in) == 0) {
2046 log_warn(LD_DIR, "Error parsing network-status source address %s",
2047 escaped(tok->args[1]));
2048 goto err;
2050 ns->source_addr = ntohl(in.s_addr);
2051 ns->source_dirport =
2052 (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
2053 if (ns->source_dirport == 0) {
2054 log_warn(LD_DIR, "Directory source without dirport; skipping.");
2055 goto err;
2058 tok = find_by_keyword(tokens, K_FINGERPRINT);
2059 tor_assert(tok->n_args);
2060 if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
2061 strlen(tok->args[0]))) {
2062 log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
2063 escaped(tok->args[0]));
2064 goto err;
2067 if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
2068 tor_assert(tok->n_args);
2069 ns->contact = tor_strdup(tok->args[0]);
2072 tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
2073 tor_assert(tok->key);
2074 ns->signing_key = tok->key;
2075 tok->key = NULL;
2077 if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
2078 log_warn(LD_DIR, "Couldn't compute signing key digest");
2079 goto err;
2081 if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
2082 log_warn(LD_DIR,
2083 "network-status fingerprint did not match dir-signing-key");
2084 goto err;
2087 if ((tok = find_opt_by_keyword(tokens, K_DIR_OPTIONS))) {
2088 for (i=0; i < tok->n_args; ++i) {
2089 if (!strcmp(tok->args[i], "Names"))
2090 ns->binds_names = 1;
2091 if (!strcmp(tok->args[i], "Versions"))
2092 ns->recommends_versions = 1;
2093 if (!strcmp(tok->args[i], "BadExits"))
2094 ns->lists_bad_exits = 1;
2095 if (!strcmp(tok->args[i], "BadDirectories"))
2096 ns->lists_bad_directories = 1;
2100 if (ns->recommends_versions) {
2101 if (!(tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
2102 log_warn(LD_DIR, "Missing client-versions on versioning directory");
2103 goto err;
2105 ns->client_versions = tor_strdup(tok->args[0]);
2107 if (!(tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS)) ||
2108 tok->n_args<1) {
2109 log_warn(LD_DIR, "Missing server-versions on versioning directory");
2110 goto err;
2112 ns->server_versions = tor_strdup(tok->args[0]);
2115 tok = find_by_keyword(tokens, K_PUBLISHED);
2116 tor_assert(tok->n_args == 1);
2117 if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
2118 goto err;
2121 ns->entries = smartlist_create();
2122 s = eos;
2123 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
2124 smartlist_clear(tokens);
2125 memarea_clear(area);
2126 while (!strcmpstart(s, "r ")) {
2127 routerstatus_t *rs;
2128 if ((rs = routerstatus_parse_entry_from_string(area, &s, tokens,
2129 NULL, NULL, 0)))
2130 smartlist_add(ns->entries, rs);
2132 smartlist_sort(ns->entries, _compare_routerstatus_entries);
2133 smartlist_uniq(ns->entries, _compare_routerstatus_entries,
2134 _free_duplicate_routerstatus_entry);
2136 if (tokenize_string(area,s, NULL, footer_tokens, dir_footer_token_table,0)) {
2137 log_warn(LD_DIR, "Error tokenizing network-status footer.");
2138 goto err;
2140 if (smartlist_len(footer_tokens) < 1) {
2141 log_warn(LD_DIR, "Too few items in network-status footer.");
2142 goto err;
2144 tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
2145 if (tok->tp != K_DIRECTORY_SIGNATURE) {
2146 log_warn(LD_DIR,
2147 "Expected network-status footer to end with a signature.");
2148 goto err;
2151 note_crypto_pk_op(VERIFY_DIR);
2152 if (check_signature_token(ns_digest, tok, ns->signing_key, 0,
2153 "network-status") < 0)
2154 goto err;
2156 goto done;
2157 err:
2158 if (ns)
2159 networkstatus_v2_free(ns);
2160 ns = NULL;
2161 done:
2162 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
2163 smartlist_free(tokens);
2164 SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
2165 smartlist_free(footer_tokens);
2166 if (area) {
2167 DUMP_AREA(area, "v2 networkstatus");
2168 memarea_drop_all(area);
2170 return ns;
2173 /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
2174 * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
2175 networkstatus_t *
2176 networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
2177 networkstatus_type_t ns_type)
2179 smartlist_t *tokens = smartlist_create();
2180 smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
2181 networkstatus_voter_info_t *voter = NULL;
2182 networkstatus_t *ns = NULL;
2183 char ns_digest[DIGEST_LEN];
2184 const char *cert, *end_of_header, *end_of_footer;
2185 directory_token_t *tok;
2186 int ok;
2187 struct in_addr in;
2188 int i, inorder, n_signatures = 0;
2189 memarea_t *area = NULL, *rs_area = NULL;
2190 tor_assert(s);
2192 if (eos_out)
2193 *eos_out = NULL;
2195 if (router_get_networkstatus_v3_hash(s, ns_digest)) {
2196 log_warn(LD_DIR, "Unable to compute digest of network-status");
2197 goto err;
2200 area = memarea_new();
2201 end_of_header = find_start_of_next_routerstatus(s);
2202 if (tokenize_string(area, s, end_of_header, tokens,
2203 (ns_type == NS_TYPE_CONSENSUS) ?
2204 networkstatus_consensus_token_table :
2205 networkstatus_token_table, 0)) {
2206 log_warn(LD_DIR, "Error tokenizing network-status vote header");
2207 goto err;
2210 ns = tor_malloc_zero(sizeof(networkstatus_t));
2211 memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
2213 if (ns_type != NS_TYPE_CONSENSUS) {
2214 const char *end_of_cert = NULL;
2215 if (!(cert = strstr(s, "\ndir-key-certificate-version")))
2216 goto err;
2217 ++cert;
2218 ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
2219 if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
2220 goto err;
2223 tok = find_by_keyword(tokens, K_VOTE_STATUS);
2224 tor_assert(tok->n_args);
2225 if (!strcmp(tok->args[0], "vote")) {
2226 ns->type = NS_TYPE_VOTE;
2227 } else if (!strcmp(tok->args[0], "consensus")) {
2228 ns->type = NS_TYPE_CONSENSUS;
2229 } else if (!strcmp(tok->args[0], "opinion")) {
2230 ns->type = NS_TYPE_OPINION;
2231 } else {
2232 log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
2233 escaped(tok->args[0]));
2234 goto err;
2236 if (ns_type != ns->type) {
2237 log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
2238 goto err;
2241 if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
2242 tok = find_by_keyword(tokens, K_PUBLISHED);
2243 if (parse_iso_time(tok->args[0], &ns->published))
2244 goto err;
2246 ns->supported_methods = smartlist_create();
2247 tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
2248 if (tok) {
2249 for (i=0; i < tok->n_args; ++i)
2250 smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
2251 } else {
2252 smartlist_add(ns->supported_methods, tor_strdup("1"));
2254 } else {
2255 tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
2256 if (tok) {
2257 ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
2258 &ok, NULL);
2259 if (!ok)
2260 goto err;
2261 } else {
2262 ns->consensus_method = 1;
2266 tok = find_by_keyword(tokens, K_VALID_AFTER);
2267 if (parse_iso_time(tok->args[0], &ns->valid_after))
2268 goto err;
2270 tok = find_by_keyword(tokens, K_FRESH_UNTIL);
2271 if (parse_iso_time(tok->args[0], &ns->fresh_until))
2272 goto err;
2274 tok = find_by_keyword(tokens, K_VALID_UNTIL);
2275 if (parse_iso_time(tok->args[0], &ns->valid_until))
2276 goto err;
2278 tok = find_by_keyword(tokens, K_VOTING_DELAY);
2279 tor_assert(tok->n_args >= 2);
2280 ns->vote_seconds =
2281 (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
2282 if (!ok)
2283 goto err;
2284 ns->dist_seconds =
2285 (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
2286 if (!ok)
2287 goto err;
2288 if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
2289 log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
2290 goto err;
2292 if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
2293 log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
2294 goto err;
2296 if (ns->vote_seconds < MIN_VOTE_SECONDS) {
2297 log_warn(LD_DIR, "Vote seconds is too short");
2298 goto err;
2300 if (ns->dist_seconds < MIN_DIST_SECONDS) {
2301 log_warn(LD_DIR, "Dist seconds is too short");
2302 goto err;
2305 if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
2306 ns->client_versions = tor_strdup(tok->args[0]);
2308 if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
2309 ns->server_versions = tor_strdup(tok->args[0]);
2312 tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
2313 ns->known_flags = smartlist_create();
2314 inorder = 1;
2315 for (i = 0; i < tok->n_args; ++i) {
2316 smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
2317 if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
2318 log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
2319 inorder = 0;
2322 if (!inorder) {
2323 log_warn(LD_DIR, "known-flags not in order");
2324 goto err;
2327 tok = find_opt_by_keyword(tokens, K_PARAMS);
2328 if (tok) {
2329 inorder = 1;
2330 ns->net_params = smartlist_create();
2331 for (i = 0; i < tok->n_args; ++i) {
2332 int ok=0;
2333 char *eq = strchr(tok->args[i], '=');
2334 if (!eq) {
2335 log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
2336 goto err;
2338 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
2339 if (!ok) {
2340 log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
2341 goto err;
2343 if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
2344 log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
2345 inorder = 0;
2347 smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
2349 if (!inorder) {
2350 log_warn(LD_DIR, "params not in order");
2351 goto err;
2355 ns->voters = smartlist_create();
2357 SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
2358 tok = _tok;
2359 if (tok->tp == K_DIR_SOURCE) {
2360 tor_assert(tok->n_args >= 6);
2362 if (voter)
2363 smartlist_add(ns->voters, voter);
2364 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2365 if (ns->type != NS_TYPE_CONSENSUS)
2366 memcpy(voter->vote_digest, ns_digest, DIGEST_LEN);
2368 voter->nickname = tor_strdup(tok->args[0]);
2369 if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
2370 base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
2371 tok->args[1], HEX_DIGEST_LEN) < 0) {
2372 log_warn(LD_DIR, "Error decoding identity digest %s in "
2373 "network-status vote.", escaped(tok->args[1]));
2374 goto err;
2376 if (ns->type != NS_TYPE_CONSENSUS &&
2377 memcmp(ns->cert->cache_info.identity_digest,
2378 voter->identity_digest, DIGEST_LEN)) {
2379 log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
2380 goto err;
2382 voter->address = tor_strdup(tok->args[2]);
2383 if (!tor_inet_aton(tok->args[3], &in)) {
2384 log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
2385 escaped(tok->args[3]));
2386 goto err;
2388 voter->addr = ntohl(in.s_addr);
2389 voter->dir_port = (uint16_t)
2390 tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
2391 if (!ok)
2392 goto err;
2393 voter->or_port = (uint16_t)
2394 tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
2395 if (!ok)
2396 goto err;
2397 } else if (tok->tp == K_CONTACT) {
2398 if (!voter || voter->contact) {
2399 log_warn(LD_DIR, "contact element is out of place.");
2400 goto err;
2402 voter->contact = tor_strdup(tok->args[0]);
2403 } else if (tok->tp == K_VOTE_DIGEST) {
2404 tor_assert(ns->type == NS_TYPE_CONSENSUS);
2405 tor_assert(tok->n_args >= 1);
2406 if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
2407 log_warn(LD_DIR, "vote-digest element is out of place.");
2408 goto err;
2410 if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
2411 base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
2412 tok->args[0], HEX_DIGEST_LEN) < 0) {
2413 log_warn(LD_DIR, "Error decoding vote digest %s in "
2414 "network-status consensus.", escaped(tok->args[0]));
2415 goto err;
2418 } SMARTLIST_FOREACH_END(_tok);
2419 if (voter) {
2420 smartlist_add(ns->voters, voter);
2421 voter = NULL;
2423 if (smartlist_len(ns->voters) == 0) {
2424 log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
2425 goto err;
2426 } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
2427 log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
2428 goto err;
2431 if (ns->type != NS_TYPE_CONSENSUS &&
2432 (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
2433 int bad = 1;
2434 if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
2435 networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
2436 if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
2437 tok->args[0], HEX_DIGEST_LEN)<0)
2438 bad = 1;
2439 else
2440 bad = 0;
2442 if (bad) {
2443 log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
2444 escaped(tok->args[0]));
2448 /* Parse routerstatus lines. */
2449 rs_tokens = smartlist_create();
2450 rs_area = memarea_new();
2451 s = end_of_header;
2452 ns->routerstatus_list = smartlist_create();
2454 while (!strcmpstart(s, "r ")) {
2455 if (ns->type != NS_TYPE_CONSENSUS) {
2456 vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2457 if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
2458 rs, 0))
2459 smartlist_add(ns->routerstatus_list, rs);
2460 else {
2461 tor_free(rs->version);
2462 tor_free(rs);
2464 } else {
2465 routerstatus_t *rs;
2466 if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
2467 NULL, NULL,
2468 ns->consensus_method)))
2469 smartlist_add(ns->routerstatus_list, rs);
2472 for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
2473 routerstatus_t *rs1, *rs2;
2474 if (ns->type != NS_TYPE_CONSENSUS) {
2475 vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
2476 vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
2477 rs1 = &a->status; rs2 = &b->status;
2478 } else {
2479 rs1 = smartlist_get(ns->routerstatus_list, i-1);
2480 rs2 = smartlist_get(ns->routerstatus_list, i);
2482 if (memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN) >= 0) {
2483 log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
2484 "digest");
2485 goto err;
2489 /* Parse footer; check signature. */
2490 footer_tokens = smartlist_create();
2491 if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
2492 ++end_of_footer;
2493 else
2494 end_of_footer = s + strlen(s);
2495 if (tokenize_string(area,s, end_of_footer, footer_tokens,
2496 networkstatus_vote_footer_token_table, 0)) {
2497 log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
2498 goto err;
2501 SMARTLIST_FOREACH(footer_tokens, directory_token_t *, _tok,
2503 char declared_identity[DIGEST_LEN];
2504 networkstatus_voter_info_t *v;
2505 tok = _tok;
2506 if (tok->tp != K_DIRECTORY_SIGNATURE)
2507 continue;
2508 tor_assert(tok->n_args >= 2);
2510 if (!tok->object_type ||
2511 strcmp(tok->object_type, "SIGNATURE") ||
2512 tok->object_size < 128 || tok->object_size > 512) {
2513 log_warn(LD_DIR, "Bad object type or length on directory-signature");
2514 goto err;
2517 if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
2518 base16_decode(declared_identity, sizeof(declared_identity),
2519 tok->args[0], HEX_DIGEST_LEN) < 0) {
2520 log_warn(LD_DIR, "Error decoding declared identity %s in "
2521 "network-status vote.", escaped(tok->args[0]));
2522 goto err;
2524 if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
2525 log_warn(LD_DIR, "ID on signature on network-status vote does not match "
2526 "any declared directory source.");
2527 goto err;
2529 if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
2530 base16_decode(v->signing_key_digest, sizeof(v->signing_key_digest),
2531 tok->args[1], HEX_DIGEST_LEN) < 0) {
2532 log_warn(LD_DIR, "Error decoding declared digest %s in "
2533 "network-status vote.", escaped(tok->args[1]));
2534 goto err;
2537 if (ns->type != NS_TYPE_CONSENSUS) {
2538 if (memcmp(declared_identity, ns->cert->cache_info.identity_digest,
2539 DIGEST_LEN)) {
2540 log_warn(LD_DIR, "Digest mismatch between declared and actual on "
2541 "network-status vote.");
2542 goto err;
2546 if (ns->type != NS_TYPE_CONSENSUS) {
2547 if (check_signature_token(ns_digest, tok, ns->cert->signing_key, 0,
2548 "network-status vote"))
2549 goto err;
2550 v->good_signature = 1;
2551 } else {
2552 if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING)
2553 goto err;
2554 /* We already parsed a vote from this voter. Use the first one. */
2555 if (v->signature) {
2556 log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
2557 "that contains two votes from the same voter. Ignoring "
2558 "the second vote.");
2559 continue;
2562 v->signature = tor_memdup(tok->object_body, tok->object_size);
2563 v->signature_len = (int) tok->object_size;
2565 ++n_signatures;
2568 if (! n_signatures) {
2569 log_warn(LD_DIR, "No signatures on networkstatus vote.");
2570 goto err;
2573 if (eos_out)
2574 *eos_out = end_of_footer;
2576 goto done;
2577 err:
2578 if (ns)
2579 networkstatus_vote_free(ns);
2580 ns = NULL;
2581 done:
2582 if (tokens) {
2583 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
2584 smartlist_free(tokens);
2586 if (voter) {
2587 tor_free(voter->nickname);
2588 tor_free(voter->address);
2589 tor_free(voter->contact);
2590 tor_free(voter->signature);
2591 tor_free(voter);
2593 if (rs_tokens) {
2594 SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_free(t));
2595 smartlist_free(rs_tokens);
2597 if (footer_tokens) {
2598 SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
2599 smartlist_free(footer_tokens);
2601 if (area) {
2602 DUMP_AREA(area, "v3 networkstatus");
2603 memarea_drop_all(area);
2605 if (rs_area)
2606 memarea_drop_all(rs_area);
2608 return ns;
2611 /** Parse a detached v3 networkstatus signature document between <b>s</b> and
2612 * <b>eos</b> and return the result. Return -1 on failure. */
2613 ns_detached_signatures_t *
2614 networkstatus_parse_detached_signatures(const char *s, const char *eos)
2616 /* XXXX there is too much duplicate shared between this function and
2617 * networkstatus_parse_vote_from_string(). */
2618 directory_token_t *tok;
2619 memarea_t *area = NULL;
2621 smartlist_t *tokens = smartlist_create();
2622 ns_detached_signatures_t *sigs =
2623 tor_malloc_zero(sizeof(ns_detached_signatures_t));
2625 if (!eos)
2626 eos = s + strlen(s);
2628 area = memarea_new();
2629 if (tokenize_string(area,s, eos, tokens,
2630 networkstatus_detached_signature_token_table, 0)) {
2631 log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
2632 goto err;
2635 tok = find_by_keyword(tokens, K_CONSENSUS_DIGEST);
2636 if (strlen(tok->args[0]) != HEX_DIGEST_LEN) {
2637 log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
2638 "networkstatus signatures");
2639 goto err;
2641 if (base16_decode(sigs->networkstatus_digest, DIGEST_LEN,
2642 tok->args[0], strlen(tok->args[0])) < 0) {
2643 log_warn(LD_DIR, "Bad encoding on on consensus-digest in detached "
2644 "networkstatus signatures");
2645 goto err;
2648 tok = find_by_keyword(tokens, K_VALID_AFTER);
2649 if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
2650 log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
2651 goto err;
2654 tok = find_by_keyword(tokens, K_FRESH_UNTIL);
2655 if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
2656 log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
2657 goto err;
2660 tok = find_by_keyword(tokens, K_VALID_UNTIL);
2661 if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
2662 log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
2663 goto err;
2666 sigs->signatures = smartlist_create();
2667 SMARTLIST_FOREACH(tokens, directory_token_t *, _tok,
2669 char id_digest[DIGEST_LEN];
2670 char sk_digest[DIGEST_LEN];
2671 networkstatus_voter_info_t *voter;
2673 tok = _tok;
2674 if (tok->tp != K_DIRECTORY_SIGNATURE)
2675 continue;
2676 tor_assert(tok->n_args >= 2);
2678 if (!tok->object_type ||
2679 strcmp(tok->object_type, "SIGNATURE") ||
2680 tok->object_size < 128 || tok->object_size > 512) {
2681 log_warn(LD_DIR, "Bad object type or length on directory-signature");
2682 goto err;
2685 if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
2686 base16_decode(id_digest, sizeof(id_digest),
2687 tok->args[0], HEX_DIGEST_LEN) < 0) {
2688 log_warn(LD_DIR, "Error decoding declared identity %s in "
2689 "network-status vote.", escaped(tok->args[0]));
2690 goto err;
2692 if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
2693 base16_decode(sk_digest, sizeof(sk_digest),
2694 tok->args[1], HEX_DIGEST_LEN) < 0) {
2695 log_warn(LD_DIR, "Error decoding declared digest %s in "
2696 "network-status vote.", escaped(tok->args[1]));
2697 goto err;
2700 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2701 memcpy(voter->identity_digest, id_digest, DIGEST_LEN);
2702 memcpy(voter->signing_key_digest, sk_digest, DIGEST_LEN);
2703 if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING)
2704 goto err;
2705 voter->signature = tor_memdup(tok->object_body, tok->object_size);
2706 voter->signature_len = (int) tok->object_size;
2708 smartlist_add(sigs->signatures, voter);
2711 goto done;
2712 err:
2713 ns_detached_signatures_free(sigs);
2714 sigs = NULL;
2715 done:
2716 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
2717 smartlist_free(tokens);
2718 if (area) {
2719 DUMP_AREA(area, "detached signatures");
2720 memarea_drop_all(area);
2722 return sigs;
2725 /** Parse the addr policy in the string <b>s</b> and return it. If
2726 * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
2727 * ADDR_POLICY_REJECT) for items that specify no action.
2729 addr_policy_t *
2730 router_parse_addr_policy_item_from_string(const char *s, int assume_action)
2732 directory_token_t *tok = NULL;
2733 const char *cp, *eos;
2734 /* Longest possible policy is "accept ffff:ffff:..255/ffff:...255:0-65535".
2735 * But note that there can be an arbitrary amount of space between the
2736 * accept and the address:mask/port element. */
2737 char line[TOR_ADDR_BUF_LEN*2 + 32];
2738 addr_policy_t *r;
2739 memarea_t *area = NULL;
2741 s = eat_whitespace(s);
2742 if ((*s == '*' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
2743 if (tor_snprintf(line, sizeof(line), "%s %s",
2744 assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
2745 log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
2746 return NULL;
2748 cp = line;
2749 tor_strlower(line);
2750 } else { /* assume an already well-formed address policy line */
2751 cp = s;
2754 eos = cp + strlen(cp);
2755 area = memarea_new();
2756 tok = get_next_token(area, &cp, eos, routerdesc_token_table);
2757 if (tok->tp == _ERR) {
2758 log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
2759 goto err;
2761 if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
2762 tok->tp != K_REJECT && tok->tp != K_REJECT6) {
2763 log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
2764 goto err;
2767 r = router_parse_addr_policy(tok);
2768 goto done;
2769 err:
2770 r = NULL;
2771 done:
2772 token_free(tok);
2773 if (area) {
2774 DUMP_AREA(area, "policy item");
2775 memarea_drop_all(area);
2777 return r;
2780 /** Add an exit policy stored in the token <b>tok</b> to the router info in
2781 * <b>router</b>. Return 0 on success, -1 on failure. */
2782 static int
2783 router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
2785 addr_policy_t *newe;
2786 newe = router_parse_addr_policy(tok);
2787 if (!newe)
2788 return -1;
2789 if (! router->exit_policy)
2790 router->exit_policy = smartlist_create();
2792 if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
2793 tor_addr_family(&newe->addr) == AF_INET)
2795 ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
2796 tor_addr_family(&newe->addr) == AF_INET6)) {
2797 log_warn(LD_DIR, "Mismatch between field type and address type in exit "
2798 "policy");
2799 addr_policy_free(newe);
2800 return -1;
2803 smartlist_add(router->exit_policy, newe);
2805 return 0;
2808 /** Given a K_ACCEPT or K_REJECT token and a router, create and return
2809 * a new exit_policy_t corresponding to the token. */
2810 static addr_policy_t *
2811 router_parse_addr_policy(directory_token_t *tok)
2813 addr_policy_t newe;
2814 char *arg;
2816 tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
2817 tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
2819 if (tok->n_args != 1)
2820 return NULL;
2821 arg = tok->args[0];
2823 if (!strcmpstart(arg,"private"))
2824 return router_parse_addr_policy_private(tok);
2826 memset(&newe, 0, sizeof(newe));
2828 if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
2829 newe.policy_type = ADDR_POLICY_REJECT;
2830 else
2831 newe.policy_type = ADDR_POLICY_ACCEPT;
2833 if (tor_addr_parse_mask_ports(arg, &newe.addr, &newe.maskbits,
2834 &newe.prt_min, &newe.prt_max) < 0) {
2835 log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
2836 return NULL;
2839 return addr_policy_get_canonical_entry(&newe);
2842 /** Parse an exit policy line of the format "accept/reject private:...".
2843 * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
2844 * router descriptors until earlier versions are obsolete.
2846 static addr_policy_t *
2847 router_parse_addr_policy_private(directory_token_t *tok)
2849 const char *arg;
2850 uint16_t port_min, port_max;
2851 addr_policy_t result;
2853 arg = tok->args[0];
2854 if (strcmpstart(arg, "private"))
2855 return NULL;
2857 arg += strlen("private");
2858 arg = (char*) eat_whitespace(arg);
2859 if (!arg || *arg != ':')
2860 return NULL;
2862 if (parse_port_range(arg+1, &port_min, &port_max)<0)
2863 return NULL;
2865 memset(&result, 0, sizeof(result));
2866 if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
2867 result.policy_type = ADDR_POLICY_REJECT;
2868 else
2869 result.policy_type = ADDR_POLICY_ACCEPT;
2870 result.is_private = 1;
2871 result.prt_min = port_min;
2872 result.prt_max = port_max;
2874 return addr_policy_get_canonical_entry(&result);
2877 /** Log and exit if <b>t</b> is malformed */
2878 void
2879 assert_addr_policy_ok(smartlist_t *lst)
2881 if (!lst) return;
2882 SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
2883 tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
2884 t->policy_type == ADDR_POLICY_ACCEPT);
2885 tor_assert(t->prt_min <= t->prt_max);
2890 * Low-level tokenizer for router descriptors and directories.
2893 /** Free all resources allocated for <b>tok</b> */
2894 static void
2895 token_free(directory_token_t *tok)
2897 tor_assert(tok);
2898 if (tok->key)
2899 crypto_free_pk_env(tok->key);
2902 #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
2903 #define ALLOC(sz) memarea_alloc(area,sz)
2904 #define STRDUP(str) memarea_strdup(area,str)
2905 #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
2907 #define RET_ERR(msg) \
2908 STMT_BEGIN \
2909 if (tok) token_free(tok); \
2910 tok = ALLOC_ZERO(sizeof(directory_token_t)); \
2911 tok->tp = _ERR; \
2912 tok->error = STRDUP(msg); \
2913 goto done_tokenizing; \
2914 STMT_END
2916 /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
2917 * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
2918 * Return <b>tok</b> on success, or a new _ERR token if the token didn't
2919 * conform to the syntax we wanted.
2921 static INLINE directory_token_t *
2922 token_check_object(memarea_t *area, const char *kwd,
2923 directory_token_t *tok, obj_syntax o_syn)
2925 char ebuf[128];
2926 switch (o_syn) {
2927 case NO_OBJ:
2928 /* No object is allowed for this token. */
2929 if (tok->object_body) {
2930 tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
2931 RET_ERR(ebuf);
2933 if (tok->key) {
2934 tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
2935 RET_ERR(ebuf);
2937 break;
2938 case NEED_OBJ:
2939 /* There must be a (non-key) object. */
2940 if (!tok->object_body) {
2941 tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
2942 RET_ERR(ebuf);
2944 break;
2945 case NEED_KEY_1024: /* There must be a 1024-bit public key. */
2946 case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
2947 if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) {
2948 tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
2949 kwd, (int)crypto_pk_keysize(tok->key));
2950 RET_ERR(ebuf);
2952 /* fall through */
2953 case NEED_KEY: /* There must be some kind of key. */
2954 if (!tok->key) {
2955 tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
2956 RET_ERR(ebuf);
2958 if (o_syn != NEED_SKEY_1024) {
2959 if (crypto_pk_key_is_private(tok->key)) {
2960 tor_snprintf(ebuf, sizeof(ebuf),
2961 "Private key given for %s, which wants a public key", kwd);
2962 RET_ERR(ebuf);
2964 } else { /* o_syn == NEED_SKEY_1024 */
2965 if (!crypto_pk_key_is_private(tok->key)) {
2966 tor_snprintf(ebuf, sizeof(ebuf),
2967 "Public key given for %s, which wants a private key", kwd);
2968 RET_ERR(ebuf);
2971 break;
2972 case OBJ_OK:
2973 /* Anything goes with this token. */
2974 break;
2977 done_tokenizing:
2978 return tok;
2981 /** Helper: parse space-separated arguments from the string <b>s</b> ending at
2982 * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
2983 * number of parsed elements into the n_args field of <b>tok</b>. Allocate
2984 * all storage in <b>area</b>. Return the number of arguments parsed, or
2985 * return -1 if there was an insanely high number of arguments. */
2986 static INLINE int
2987 get_token_arguments(memarea_t *area, directory_token_t *tok,
2988 const char *s, const char *eol)
2990 /** Largest number of arguments we'll accept to any token, ever. */
2991 #define MAX_ARGS 512
2992 char *mem = memarea_strndup(area, s, eol-s);
2993 char *cp = mem;
2994 int j = 0;
2995 char *args[MAX_ARGS];
2996 while (*cp) {
2997 if (j == MAX_ARGS)
2998 return -1;
2999 args[j++] = cp;
3000 cp = (char*)find_whitespace(cp);
3001 if (!cp || !*cp)
3002 break; /* End of the line. */
3003 *cp++ = '\0';
3004 cp = (char*)eat_whitespace(cp);
3006 tok->n_args = j;
3007 tok->args = memarea_memdup(area, args, j*sizeof(char*));
3008 return j;
3009 #undef MAX_ARGS
3012 /** Helper function: read the next token from *s, advance *s to the end of the
3013 * token, and return the parsed token. Parse *<b>s</b> according to the list
3014 * of tokens in <b>table</b>.
3016 static directory_token_t *
3017 get_next_token(memarea_t *area,
3018 const char **s, const char *eos, token_rule_t *table)
3020 /** Reject any object at least this big; it is probably an overflow, an
3021 * attack, a bug, or some other nonsense. */
3022 #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
3024 const char *next, *eol, *obstart;
3025 size_t obname_len;
3026 int i;
3027 directory_token_t *tok;
3028 obj_syntax o_syn = NO_OBJ;
3029 char ebuf[128];
3030 const char *kwd = "";
3032 tor_assert(area);
3033 tok = ALLOC_ZERO(sizeof(directory_token_t));
3034 tok->tp = _ERR;
3036 /* Set *s to first token, eol to end-of-line, next to after first token */
3037 *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
3038 tor_assert(eos >= *s);
3039 eol = memchr(*s, '\n', eos-*s);
3040 if (!eol)
3041 eol = eos;
3042 next = find_whitespace_eos(*s, eol);
3044 if (!strcmp_len(*s, "opt", next-*s)) {
3045 /* Skip past an "opt" at the start of the line. */
3046 *s = eat_whitespace_eos_no_nl(next, eol);
3047 next = find_whitespace_eos(*s, eol);
3048 } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
3049 RET_ERR("Unexpected EOF");
3052 /* Search the table for the appropriate entry. (I tried a binary search
3053 * instead, but it wasn't any faster.) */
3054 for (i = 0; table[i].t ; ++i) {
3055 if (!strcmp_len(*s, table[i].t, next-*s)) {
3056 /* We've found the keyword. */
3057 kwd = table[i].t;
3058 tok->tp = table[i].v;
3059 o_syn = table[i].os;
3060 *s = eat_whitespace_eos_no_nl(next, eol);
3061 /* We go ahead whether there are arguments or not, so that tok->args is
3062 * always set if we want arguments. */
3063 if (table[i].concat_args) {
3064 /* The keyword takes the line as a single argument */
3065 tok->args = ALLOC(sizeof(char*));
3066 tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
3067 tok->n_args = 1;
3068 } else {
3069 /* This keyword takes multiple arguments. */
3070 if (get_token_arguments(area, tok, *s, eol)<0) {
3071 tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
3072 RET_ERR(ebuf);
3074 *s = eol;
3076 if (tok->n_args < table[i].min_args) {
3077 tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
3078 RET_ERR(ebuf);
3079 } else if (tok->n_args > table[i].max_args) {
3080 tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
3081 RET_ERR(ebuf);
3083 break;
3087 if (tok->tp == _ERR) {
3088 /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
3089 if (**s == '@')
3090 tok->tp = _A_UNKNOWN;
3091 else
3092 tok->tp = K_OPT;
3093 tok->args = ALLOC(sizeof(char*));
3094 tok->args[0] = STRNDUP(*s, eol-*s);
3095 tok->n_args = 1;
3096 o_syn = OBJ_OK;
3099 /* Check whether there's an object present */
3100 *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
3101 tor_assert(eos >= *s);
3102 eol = memchr(*s, '\n', eos-*s);
3103 if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
3104 goto check_object;
3106 obstart = *s; /* Set obstart to start of object spec */
3107 if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
3108 strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
3109 (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
3110 RET_ERR("Malformed object: bad begin line");
3112 tok->object_type = STRNDUP(*s+11, eol-*s-16);
3113 obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
3114 *s = eol+1; /* Set *s to possible start of object data (could be eos) */
3116 /* Go to the end of the object */
3117 next = tor_memstr(*s, eos-*s, "-----END ");
3118 if (!next) {
3119 RET_ERR("Malformed object: missing object end line");
3121 tor_assert(eos >= next);
3122 eol = memchr(next, '\n', eos-next);
3123 if (!eol) /* end-of-line marker, or eos if there's no '\n' */
3124 eol = eos;
3125 /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
3126 if ((size_t)(eol-next) != 9+obname_len+5 ||
3127 strcmp_len(next+9, tok->object_type, obname_len) ||
3128 strcmp_len(eol-5, "-----", 5)) {
3129 snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
3130 tok->object_type);
3131 ebuf[sizeof(ebuf)-1] = '\0';
3132 RET_ERR(ebuf);
3134 if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
3135 RET_ERR("Couldn't parse object: missing footer or object much too big.");
3137 if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
3138 tok->key = crypto_new_pk_env();
3139 if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
3140 RET_ERR("Couldn't parse public key.");
3141 } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
3142 tok->key = crypto_new_pk_env();
3143 if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
3144 RET_ERR("Couldn't parse private key.");
3145 } else { /* If it's something else, try to base64-decode it */
3146 int r;
3147 tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
3148 r = base64_decode(tok->object_body, next-*s, *s, next-*s);
3149 if (r<0)
3150 RET_ERR("Malformed object: bad base64-encoded data");
3151 tok->object_size = r;
3153 *s = eol;
3155 check_object:
3156 tok = token_check_object(area, kwd, tok, o_syn);
3158 done_tokenizing:
3159 return tok;
3161 #undef RET_ERR
3162 #undef ALLOC
3163 #undef ALLOC_ZERO
3164 #undef STRDUP
3165 #undef STRNDUP
3168 /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
3169 * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
3170 * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
3171 * entire string.
3173 static int
3174 tokenize_string(memarea_t *area,
3175 const char *start, const char *end, smartlist_t *out,
3176 token_rule_t *table, int flags)
3178 const char **s;
3179 directory_token_t *tok = NULL;
3180 int counts[_NIL];
3181 int i;
3182 int first_nonannotation;
3183 int prev_len = smartlist_len(out);
3184 tor_assert(area);
3186 s = &start;
3187 if (!end)
3188 end = start+strlen(start);
3189 for (i = 0; i < _NIL; ++i)
3190 counts[i] = 0;
3192 SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]);
3194 while (*s < end && (!tok || tok->tp != _EOF)) {
3195 tok = get_next_token(area, s, end, table);
3196 if (tok->tp == _ERR) {
3197 log_warn(LD_DIR, "parse error: %s", tok->error);
3198 token_free(tok);
3199 return -1;
3201 ++counts[tok->tp];
3202 smartlist_add(out, tok);
3203 *s = eat_whitespace_eos(*s, end);
3206 if (flags & TS_NOCHECK)
3207 return 0;
3209 if ((flags & TS_ANNOTATIONS_OK)) {
3210 first_nonannotation = -1;
3211 for (i = 0; i < smartlist_len(out); ++i) {
3212 tok = smartlist_get(out, i);
3213 if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
3214 first_nonannotation = i;
3215 break;
3218 if (first_nonannotation < 0) {
3219 log_warn(LD_DIR, "parse error: item contains only annotations");
3220 return -1;
3222 for (i=first_nonannotation; i < smartlist_len(out); ++i) {
3223 tok = smartlist_get(out, i);
3224 if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
3225 log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
3226 return -1;
3229 if ((flags & TS_NO_NEW_ANNOTATIONS)) {
3230 if (first_nonannotation != prev_len) {
3231 log_warn(LD_DIR, "parse error: Unexpected annotations.");
3232 return -1;
3235 } else {
3236 for (i=0; i < smartlist_len(out); ++i) {
3237 tok = smartlist_get(out, i);
3238 if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
3239 log_warn(LD_DIR, "parse error: no annotations allowed.");
3240 return -1;
3243 first_nonannotation = 0;
3245 for (i = 0; table[i].t; ++i) {
3246 if (counts[table[i].v] < table[i].min_cnt) {
3247 log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
3248 return -1;
3250 if (counts[table[i].v] > table[i].max_cnt) {
3251 log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
3252 return -1;
3254 if (table[i].pos & AT_START) {
3255 if (smartlist_len(out) < 1 ||
3256 (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
3257 log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
3258 return -1;
3261 if (table[i].pos & AT_END) {
3262 if (smartlist_len(out) < 1 ||
3263 (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
3264 log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
3265 return -1;
3269 return 0;
3272 /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
3273 * NULL if no such keyword is found.
3275 static directory_token_t *
3276 find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
3278 SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
3279 return NULL;
3282 /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
3283 * with an assert if no such keyword is found.
3285 static directory_token_t *
3286 _find_by_keyword(smartlist_t *s, directory_keyword keyword,
3287 const char *keyword_as_string)
3289 directory_token_t *tok = find_opt_by_keyword(s, keyword);
3290 if (PREDICT_UNLIKELY(!tok)) {
3291 log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
3292 "been validated. Internal error.", keyword_as_string, (int)keyword);
3293 tor_assert(tok);
3295 return tok;
3298 /** Return a newly allocated smartlist of all accept or reject tokens in
3299 * <b>s</b>.
3301 static smartlist_t *
3302 find_all_exitpolicy(smartlist_t *s)
3304 smartlist_t *out = smartlist_create();
3305 SMARTLIST_FOREACH(s, directory_token_t *, t,
3306 if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
3307 t->tp == K_REJECT || t->tp == K_REJECT6)
3308 smartlist_add(out,t));
3309 return out;
3312 /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
3313 * occurrence of <b>start_str</b> through the first instance of c after the
3314 * first subsequent occurrence of <b>end_str</b>; store the 20-byte result in
3315 * <b>digest</b>; return 0 on success.
3317 * If no such substring exists, return -1.
3319 static int
3320 router_get_hash_impl(const char *s, size_t s_len, char *digest,
3321 const char *start_str,
3322 const char *end_str, char end_c)
3324 const char *start, *end;
3325 start = tor_memstr(s, s_len, start_str);
3326 if (!start) {
3327 log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
3328 return -1;
3330 if (start != s && *(start-1) != '\n') {
3331 log_warn(LD_DIR,
3332 "first occurrence of \"%s\" is not at the start of a line",
3333 start_str);
3334 return -1;
3336 end = tor_memstr(start+strlen(start_str),
3337 s_len - (start-s) - strlen(start_str), end_str);
3338 if (!end) {
3339 log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
3340 return -1;
3342 end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
3343 if (!end) {
3344 log_warn(LD_DIR,"couldn't find EOL");
3345 return -1;
3347 ++end;
3349 if (crypto_digest(digest, start, end-start)) {
3350 log_warn(LD_BUG,"couldn't compute digest");
3351 return -1;
3354 return 0;
3357 /** Parse the Tor version of the platform string <b>platform</b>,
3358 * and compare it to the version in <b>cutoff</b>. Return 1 if
3359 * the router is at least as new as the cutoff, else return 0.
3362 tor_version_as_new_as(const char *platform, const char *cutoff)
3364 tor_version_t cutoff_version, router_version;
3365 char *s, *s2, *start;
3366 char tmp[128];
3368 tor_assert(platform);
3370 if (tor_version_parse(cutoff, &cutoff_version)<0) {
3371 log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
3372 return 0;
3374 if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
3375 return 1;
3377 start = (char *)eat_whitespace(platform+3);
3378 if (!*start) return 0;
3379 s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
3380 s2 = (char*)eat_whitespace(s);
3381 if (!strcmpstart(s2, "(r"))
3382 s = (char*)find_whitespace(s2);
3384 if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
3385 return 0;
3386 strlcpy(tmp, start, s-start+1);
3388 if (tor_version_parse(tmp, &router_version)<0) {
3389 log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
3390 return 1; /* be safe and say yes */
3393 /* Here's why we don't need to do any special handling for svn revisions:
3394 * - If neither has an svn revision, we're fine.
3395 * - If the router doesn't have an svn revision, we can't assume that it
3396 * is "at least" any svn revision, so we need to return 0.
3397 * - If the target version doesn't have an svn revision, any svn revision
3398 * (or none at all) is good enough, so return 1.
3399 * - If both target and router have an svn revision, we compare them.
3402 return tor_version_compare(&router_version, &cutoff_version) >= 0;
3405 /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
3406 * Return 0 on success, -1 on failure. */
3408 tor_version_parse(const char *s, tor_version_t *out)
3410 char *eos=NULL;
3411 const char *cp=NULL;
3412 /* Format is:
3413 * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
3415 tor_assert(s);
3416 tor_assert(out);
3418 memset(out, 0, sizeof(tor_version_t));
3420 if (!strcasecmpstart(s, "Tor "))
3421 s += 4;
3423 /* Get major. */
3424 out->major = (int)strtol(s,&eos,10);
3425 if (!eos || eos==s || *eos != '.') return -1;
3426 cp = eos+1;
3428 /* Get minor */
3429 out->minor = (int) strtol(cp,&eos,10);
3430 if (!eos || eos==cp || *eos != '.') return -1;
3431 cp = eos+1;
3433 /* Get micro */
3434 out->micro = (int) strtol(cp,&eos,10);
3435 if (!eos || eos==cp) return -1;
3436 if (!*eos) {
3437 out->status = VER_RELEASE;
3438 out->patchlevel = 0;
3439 return 0;
3441 cp = eos;
3443 /* Get status */
3444 if (*cp == '.') {
3445 out->status = VER_RELEASE;
3446 ++cp;
3447 } else if (0==strncmp(cp, "pre", 3)) {
3448 out->status = VER_PRE;
3449 cp += 3;
3450 } else if (0==strncmp(cp, "rc", 2)) {
3451 out->status = VER_RC;
3452 cp += 2;
3453 } else {
3454 return -1;
3457 /* Get patchlevel */
3458 out->patchlevel = (int) strtol(cp,&eos,10);
3459 if (!eos || eos==cp) return -1;
3460 cp = eos;
3462 /* Get status tag. */
3463 if (*cp == '-' || *cp == '.')
3464 ++cp;
3465 eos = (char*) find_whitespace(cp);
3466 if (eos-cp >= (int)sizeof(out->status_tag))
3467 strlcpy(out->status_tag, cp, sizeof(out->status_tag));
3468 else {
3469 memcpy(out->status_tag, cp, eos-cp);
3470 out->status_tag[eos-cp] = 0;
3472 cp = eat_whitespace(eos);
3474 if (!strcmpstart(cp, "(r")) {
3475 cp += 2;
3476 out->svn_revision = (int) strtol(cp,&eos,10);
3479 return 0;
3482 /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
3483 * b. */
3485 tor_version_compare(tor_version_t *a, tor_version_t *b)
3487 int i;
3488 tor_assert(a);
3489 tor_assert(b);
3490 if ((i = a->major - b->major))
3491 return i;
3492 else if ((i = a->minor - b->minor))
3493 return i;
3494 else if ((i = a->micro - b->micro))
3495 return i;
3496 else if ((i = a->status - b->status))
3497 return i;
3498 else if ((i = a->patchlevel - b->patchlevel))
3499 return i;
3500 else if ((i = strcmp(a->status_tag, b->status_tag)))
3501 return i;
3502 else
3503 return a->svn_revision - b->svn_revision;
3506 /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
3508 static int
3509 tor_version_same_series(tor_version_t *a, tor_version_t *b)
3511 tor_assert(a);
3512 tor_assert(b);
3513 return ((a->major == b->major) &&
3514 (a->minor == b->minor) &&
3515 (a->micro == b->micro));
3518 /** Helper: Given pointers to two strings describing tor versions, return -1
3519 * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
3520 * Used to sort a list of versions. */
3521 static int
3522 _compare_tor_version_str_ptr(const void **_a, const void **_b)
3524 const char *a = *_a, *b = *_b;
3525 int ca, cb;
3526 tor_version_t va, vb;
3527 ca = tor_version_parse(a, &va);
3528 cb = tor_version_parse(b, &vb);
3529 /* If they both parse, compare them. */
3530 if (!ca && !cb)
3531 return tor_version_compare(&va,&vb);
3532 /* If one parses, it comes first. */
3533 if (!ca && cb)
3534 return -1;
3535 if (ca && !cb)
3536 return 1;
3537 /* If neither parses, compare strings. Also, the directory server admin
3538 ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
3539 return strcmp(a,b);
3542 /** Sort a list of string-representations of versions in ascending order. */
3543 void
3544 sort_version_list(smartlist_t *versions, int remove_duplicates)
3546 smartlist_sort(versions, _compare_tor_version_str_ptr);
3548 if (remove_duplicates)
3549 smartlist_uniq(versions, _compare_tor_version_str_ptr, _tor_free);
3552 /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
3553 * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
3554 * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
3555 * encrypted introduction points to the newly allocated
3556 * *<b>intro_points_encrypted_out</b>, their encrypted size to
3557 * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
3558 * to *<b>encoded_size_out</b>, and a pointer to the possibly next
3559 * descriptor to *<b>next_out</b>; return 0 for success (including validation)
3560 * and -1 for failure.
3563 rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
3564 char *desc_id_out,
3565 char **intro_points_encrypted_out,
3566 size_t *intro_points_encrypted_size_out,
3567 size_t *encoded_size_out,
3568 const char **next_out, const char *desc)
3570 rend_service_descriptor_t *result =
3571 tor_malloc_zero(sizeof(rend_service_descriptor_t));
3572 char desc_hash[DIGEST_LEN];
3573 const char *eos;
3574 smartlist_t *tokens = smartlist_create();
3575 directory_token_t *tok;
3576 char secret_id_part[DIGEST_LEN];
3577 int i, version, num_ok=1;
3578 smartlist_t *versions;
3579 char public_key_hash[DIGEST_LEN];
3580 char test_desc_id[DIGEST_LEN];
3581 memarea_t *area = NULL;
3582 tor_assert(desc);
3583 /* Check if desc starts correctly. */
3584 if (strncmp(desc, "rendezvous-service-descriptor ",
3585 strlen("rendezvous-service-descriptor "))) {
3586 log_info(LD_REND, "Descriptor does not start correctly.");
3587 goto err;
3589 /* Compute descriptor hash for later validation. */
3590 if (router_get_hash_impl(desc, strlen(desc), desc_hash,
3591 "rendezvous-service-descriptor ",
3592 "\nsignature", '\n') < 0) {
3593 log_warn(LD_REND, "Couldn't compute descriptor hash.");
3594 goto err;
3596 /* Determine end of string. */
3597 eos = strstr(desc, "\nrendezvous-service-descriptor ");
3598 if (!eos)
3599 eos = desc + strlen(desc);
3600 else
3601 eos = eos + 1;
3602 /* Check length. */
3603 if (strlen(desc) > REND_DESC_MAX_SIZE) {
3604 log_warn(LD_REND, "Descriptor length is %i which exceeds "
3605 "maximum rendezvous descriptor size of %i kilobytes.",
3606 (int)strlen(desc), REND_DESC_MAX_SIZE);
3607 goto err;
3609 /* Tokenize descriptor. */
3610 area = memarea_new();
3611 if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
3612 log_warn(LD_REND, "Error tokenizing descriptor.");
3613 goto err;
3615 /* Set next to next descriptor, if available. */
3616 *next_out = eos;
3617 /* Set length of encoded descriptor. */
3618 *encoded_size_out = eos - desc;
3619 /* Check min allowed length of token list. */
3620 if (smartlist_len(tokens) < 7) {
3621 log_warn(LD_REND, "Impossibly short descriptor.");
3622 goto err;
3624 /* Parse base32-encoded descriptor ID. */
3625 tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
3626 tor_assert(tok == smartlist_get(tokens, 0));
3627 tor_assert(tok->n_args == 1);
3628 if (strlen(tok->args[0]) != REND_DESC_ID_V2_LEN_BASE32 ||
3629 strspn(tok->args[0], BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
3630 log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
3631 goto err;
3633 if (base32_decode(desc_id_out, DIGEST_LEN,
3634 tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
3635 log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
3636 tok->args[0]);
3637 goto err;
3639 /* Parse descriptor version. */
3640 tok = find_by_keyword(tokens, R_VERSION);
3641 tor_assert(tok->n_args == 1);
3642 result->version =
3643 (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
3644 if (result->version != 2 || !num_ok) {
3645 /* If it's <2, it shouldn't be under this format. If the number
3646 * is greater than 2, we bumped it because we broke backward
3647 * compatibility. See how version numbers in our other formats
3648 * work. */
3649 log_warn(LD_REND, "Unrecognized descriptor version: %s",
3650 escaped(tok->args[0]));
3651 goto err;
3653 /* Parse public key. */
3654 tok = find_by_keyword(tokens, R_PERMANENT_KEY);
3655 result->pk = tok->key;
3656 tok->key = NULL; /* Prevent free */
3657 /* Parse secret ID part. */
3658 tok = find_by_keyword(tokens, R_SECRET_ID_PART);
3659 tor_assert(tok->n_args == 1);
3660 if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
3661 strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
3662 log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
3663 goto err;
3665 if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
3666 log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
3667 tok->args[0]);
3668 goto err;
3670 /* Parse publication time -- up-to-date check is done when storing the
3671 * descriptor. */
3672 tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
3673 tor_assert(tok->n_args == 1);
3674 if (parse_iso_time(tok->args[0], &result->timestamp) < 0) {
3675 log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
3676 goto err;
3678 /* Parse protocol versions. */
3679 tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
3680 tor_assert(tok->n_args == 1);
3681 versions = smartlist_create();
3682 smartlist_split_string(versions, tok->args[0], ",",
3683 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3684 for (i = 0; i < smartlist_len(versions); i++) {
3685 version = (int) tor_parse_long(smartlist_get(versions, i),
3686 10, 0, INT_MAX, &num_ok, NULL);
3687 if (!num_ok) /* It's a string; let's ignore it. */
3688 continue;
3689 result->protocols |= 1 << version;
3691 SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
3692 smartlist_free(versions);
3693 /* Parse encrypted introduction points. Don't verify. */
3694 tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
3695 if (tok) {
3696 if (strcmp(tok->object_type, "MESSAGE")) {
3697 log_warn(LD_DIR, "Bad object type: introduction points should be of "
3698 "type MESSAGE");
3699 goto err;
3701 *intro_points_encrypted_out = tor_memdup(tok->object_body,
3702 tok->object_size);
3703 *intro_points_encrypted_size_out = tok->object_size;
3704 } else {
3705 *intro_points_encrypted_out = NULL;
3706 *intro_points_encrypted_size_out = 0;
3708 /* Parse and verify signature. */
3709 tok = find_by_keyword(tokens, R_SIGNATURE);
3710 note_crypto_pk_op(VERIFY_RTR);
3711 if (check_signature_token(desc_hash, tok, result->pk, 0,
3712 "v2 rendezvous service descriptor") < 0)
3713 goto err;
3714 /* Verify that descriptor ID belongs to public key and secret ID part. */
3715 crypto_pk_get_digest(result->pk, public_key_hash);
3716 rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
3717 secret_id_part);
3718 if (memcmp(desc_id_out, test_desc_id, DIGEST_LEN)) {
3719 log_warn(LD_REND, "Parsed descriptor ID does not match "
3720 "computed descriptor ID.");
3721 goto err;
3723 goto done;
3724 err:
3725 if (result)
3726 rend_service_descriptor_free(result);
3727 result = NULL;
3728 done:
3729 if (tokens) {
3730 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
3731 smartlist_free(tokens);
3733 if (area)
3734 memarea_drop_all(area);
3735 *parsed_out = result;
3736 if (result)
3737 return 0;
3738 return -1;
3741 /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
3742 * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
3743 * write the result to a newly allocated string that is pointed to by
3744 * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
3745 * Return 0 if decryption was successful and -1 otherwise. */
3747 rend_decrypt_introduction_points(char **ipos_decrypted,
3748 size_t *ipos_decrypted_size,
3749 const char *descriptor_cookie,
3750 const char *ipos_encrypted,
3751 size_t ipos_encrypted_size)
3753 tor_assert(ipos_encrypted);
3754 tor_assert(descriptor_cookie);
3755 if (ipos_encrypted_size < 2) {
3756 log_warn(LD_REND, "Size of encrypted introduction points is too "
3757 "small.");
3758 return -1;
3760 if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
3761 char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
3762 session_key[CIPHER_KEY_LEN], *dec;
3763 int declen, client_blocks;
3764 size_t pos = 0, len, client_entries_len;
3765 crypto_digest_env_t *digest;
3766 crypto_cipher_env_t *cipher;
3767 client_blocks = (int) ipos_encrypted[1];
3768 client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
3769 REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
3770 if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
3771 log_warn(LD_REND, "Size of encrypted introduction points is too "
3772 "small.");
3773 return -1;
3775 memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
3776 digest = crypto_new_digest_env();
3777 crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
3778 crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
3779 crypto_digest_get_digest(digest, client_id,
3780 REND_BASIC_AUTH_CLIENT_ID_LEN);
3781 crypto_free_digest_env(digest);
3782 for (pos = 2; pos < 2 + client_entries_len;
3783 pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
3784 if (!memcmp(ipos_encrypted + pos, client_id,
3785 REND_BASIC_AUTH_CLIENT_ID_LEN)) {
3786 /* Attempt to decrypt introduction points. */
3787 cipher = crypto_create_init_cipher(descriptor_cookie, 0);
3788 if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
3789 + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
3790 CIPHER_KEY_LEN) < 0) {
3791 log_warn(LD_REND, "Could not decrypt session key for client.");
3792 crypto_free_cipher_env(cipher);
3793 return -1;
3795 crypto_free_cipher_env(cipher);
3796 cipher = crypto_create_init_cipher(session_key, 0);
3797 len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
3798 dec = tor_malloc(len);
3799 declen = crypto_cipher_decrypt_with_iv(cipher, dec, len,
3800 ipos_encrypted + 2 + client_entries_len,
3801 ipos_encrypted_size - 2 - client_entries_len);
3802 crypto_free_cipher_env(cipher);
3803 if (declen < 0) {
3804 log_warn(LD_REND, "Could not decrypt introduction point string.");
3805 tor_free(dec);
3806 return -1;
3808 if (memcmpstart(dec, declen, "introduction-point ")) {
3809 log_warn(LD_REND, "Decrypted introduction points don't "
3810 "look like we could parse them.");
3811 tor_free(dec);
3812 continue;
3814 *ipos_decrypted = dec;
3815 *ipos_decrypted_size = declen;
3816 return 0;
3819 log_warn(LD_REND, "Could not decrypt introduction points. Please "
3820 "check your authorization for this service!");
3821 return -1;
3822 } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
3823 crypto_cipher_env_t *cipher;
3824 char *dec;
3825 int declen;
3826 dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
3827 cipher = crypto_create_init_cipher(descriptor_cookie, 0);
3828 declen = crypto_cipher_decrypt_with_iv(cipher, dec,
3829 ipos_encrypted_size -
3830 CIPHER_IV_LEN - 1,
3831 ipos_encrypted + 1,
3832 ipos_encrypted_size - 1);
3833 crypto_free_cipher_env(cipher);
3834 if (declen < 0) {
3835 log_warn(LD_REND, "Decrypting introduction points failed!");
3836 tor_free(dec);
3837 return -1;
3839 *ipos_decrypted = dec;
3840 *ipos_decrypted_size = declen;
3841 return 0;
3842 } else {
3843 log_warn(LD_REND, "Unknown authorization type number: %d",
3844 ipos_encrypted[0]);
3845 return -1;
3849 /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
3850 * length <b>intro_points_encoded_size</b> and write the result to the
3851 * descriptor in <b>parsed</b>; return the number of successfully parsed
3852 * introduction points or -1 in case of a failure. */
3854 rend_parse_introduction_points(rend_service_descriptor_t *parsed,
3855 const char *intro_points_encoded,
3856 size_t intro_points_encoded_size)
3858 const char *current_ipo, *end_of_intro_points;
3859 smartlist_t *tokens;
3860 directory_token_t *tok;
3861 rend_intro_point_t *intro;
3862 extend_info_t *info;
3863 int result, num_ok=1;
3864 memarea_t *area = NULL;
3865 tor_assert(parsed);
3866 /** Function may only be invoked once. */
3867 tor_assert(!parsed->intro_nodes);
3868 tor_assert(intro_points_encoded);
3869 tor_assert(intro_points_encoded_size > 0);
3870 /* Consider one intro point after the other. */
3871 current_ipo = intro_points_encoded;
3872 end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
3873 tokens = smartlist_create();
3874 parsed->intro_nodes = smartlist_create();
3875 area = memarea_new();
3877 while (!memcmpstart(current_ipo, end_of_intro_points-current_ipo,
3878 "introduction-point ")) {
3879 /* Determine end of string. */
3880 const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
3881 "\nintroduction-point ");
3882 if (!eos)
3883 eos = end_of_intro_points;
3884 else
3885 eos = eos+1;
3886 tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
3887 /* Free tokens and clear token list. */
3888 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
3889 smartlist_clear(tokens);
3890 memarea_clear(area);
3891 /* Tokenize string. */
3892 if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
3893 log_warn(LD_REND, "Error tokenizing introduction point");
3894 goto err;
3896 /* Advance to next introduction point, if available. */
3897 current_ipo = eos;
3898 /* Check minimum allowed length of introduction point. */
3899 if (smartlist_len(tokens) < 5) {
3900 log_warn(LD_REND, "Impossibly short introduction point.");
3901 goto err;
3903 /* Allocate new intro point and extend info. */
3904 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
3905 info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
3906 /* Parse identifier. */
3907 tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
3908 if (base32_decode(info->identity_digest, DIGEST_LEN,
3909 tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
3910 log_warn(LD_REND, "Identity digest contains illegal characters: %s",
3911 tok->args[0]);
3912 rend_intro_point_free(intro);
3913 goto err;
3915 /* Write identifier to nickname. */
3916 info->nickname[0] = '$';
3917 base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
3918 info->identity_digest, DIGEST_LEN);
3919 /* Parse IP address. */
3920 tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
3921 if (tor_addr_from_str(&info->addr, tok->args[0])<0) {
3922 log_warn(LD_REND, "Could not parse introduction point address.");
3923 rend_intro_point_free(intro);
3924 goto err;
3926 if (tor_addr_family(&info->addr) != AF_INET) {
3927 log_warn(LD_REND, "Introduction point address was not ipv4.");
3928 rend_intro_point_free(intro);
3929 goto err;
3932 /* Parse onion port. */
3933 tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
3934 info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
3935 &num_ok,NULL);
3936 if (!info->port || !num_ok) {
3937 log_warn(LD_REND, "Introduction point onion port %s is invalid",
3938 escaped(tok->args[0]));
3939 rend_intro_point_free(intro);
3940 goto err;
3942 /* Parse onion key. */
3943 tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
3944 info->onion_key = tok->key;
3945 tok->key = NULL; /* Prevent free */
3946 /* Parse service key. */
3947 tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
3948 intro->intro_key = tok->key;
3949 tok->key = NULL; /* Prevent free */
3950 /* Add extend info to list of introduction points. */
3951 smartlist_add(parsed->intro_nodes, intro);
3953 result = smartlist_len(parsed->intro_nodes);
3954 goto done;
3956 err:
3957 result = -1;
3959 done:
3960 /* Free tokens and clear token list. */
3961 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
3962 smartlist_free(tokens);
3963 if (area)
3964 memarea_drop_all(area);
3966 return result;
3969 /** Parse the content of a client_key file in <b>ckstr</b> and add
3970 * rend_authorized_client_t's for each parsed client to
3971 * <b>parsed_clients</b>. Return the number of parsed clients as result
3972 * or -1 for failure. */
3974 rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
3976 int result = -1;
3977 smartlist_t *tokens;
3978 directory_token_t *tok;
3979 const char *current_entry = NULL;
3980 memarea_t *area = NULL;
3981 if (!ckstr || strlen(ckstr) == 0)
3982 return -1;
3983 tokens = smartlist_create();
3984 /* Begin parsing with first entry, skipping comments or whitespace at the
3985 * beginning. */
3986 area = memarea_new();
3987 current_entry = eat_whitespace(ckstr);
3988 while (!strcmpstart(current_entry, "client-name ")) {
3989 rend_authorized_client_t *parsed_entry;
3990 size_t len;
3991 char descriptor_cookie_base64[REND_DESC_COOKIE_LEN_BASE64+2+1];
3992 char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
3993 /* Determine end of string. */
3994 const char *eos = strstr(current_entry, "\nclient-name ");
3995 if (!eos)
3996 eos = current_entry + strlen(current_entry);
3997 else
3998 eos = eos + 1;
3999 /* Free tokens and clear token list. */
4000 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
4001 smartlist_clear(tokens);
4002 memarea_clear(area);
4003 /* Tokenize string. */
4004 if (tokenize_string(area, current_entry, eos, tokens,
4005 client_keys_token_table, 0)) {
4006 log_warn(LD_REND, "Error tokenizing client keys file.");
4007 goto err;
4009 /* Advance to next entry, if available. */
4010 current_entry = eos;
4011 /* Check minimum allowed length of token list. */
4012 if (smartlist_len(tokens) < 2) {
4013 log_warn(LD_REND, "Impossibly short client key entry.");
4014 goto err;
4016 /* Parse client name. */
4017 tok = find_by_keyword(tokens, C_CLIENT_NAME);
4018 tor_assert(tok == smartlist_get(tokens, 0));
4019 tor_assert(tok->n_args == 1);
4021 len = strlen(tok->args[0]);
4022 if (len < 1 || len > 19 ||
4023 strspn(tok->args[0], REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
4024 log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
4025 "between 1 and 19, and valid characters are "
4026 "[A-Za-z0-9+-_].)", tok->args[0]);
4027 goto err;
4029 /* Check if client name is duplicate. */
4030 if (strmap_get(parsed_clients, tok->args[0])) {
4031 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
4032 "duplicate client name: '%s'. Ignoring.", tok->args[0]);
4033 goto err;
4035 parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
4036 parsed_entry->client_name = tor_strdup(tok->args[0]);
4037 strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
4038 /* Parse client key. */
4039 tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
4040 if (tok) {
4041 parsed_entry->client_key = tok->key;
4042 tok->key = NULL; /* Prevent free */
4045 /* Parse descriptor cookie. */
4046 tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
4047 tor_assert(tok->n_args == 1);
4048 if (strlen(tok->args[0]) != REND_DESC_COOKIE_LEN_BASE64 + 2) {
4049 log_warn(LD_REND, "Descriptor cookie has illegal length: %s",
4050 escaped(tok->args[0]));
4051 goto err;
4053 /* The size of descriptor_cookie_tmp needs to be REND_DESC_COOKIE_LEN+2,
4054 * because a base64 encoding of length 24 does not fit into 16 bytes in all
4055 * cases. */
4056 if ((base64_decode(descriptor_cookie_tmp, REND_DESC_COOKIE_LEN+2,
4057 tok->args[0], REND_DESC_COOKIE_LEN_BASE64+2+1)
4058 != REND_DESC_COOKIE_LEN)) {
4059 log_warn(LD_REND, "Descriptor cookie contains illegal characters: "
4060 "%s", descriptor_cookie_base64);
4061 goto err;
4063 memcpy(parsed_entry->descriptor_cookie, descriptor_cookie_tmp,
4064 REND_DESC_COOKIE_LEN);
4066 result = strmap_size(parsed_clients);
4067 goto done;
4068 err:
4069 result = -1;
4070 done:
4071 /* Free tokens and clear token list. */
4072 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
4073 smartlist_free(tokens);
4074 if (area)
4075 memarea_drop_all(area);
4076 return result;