correct a point about logging
[tor.git] / src / or / routerparse.c
blob2bf072b3cf6f9e94ff03d4e18ac638d9670239f5
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-2012, 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 "config.h"
14 #include "circuitbuild.h"
15 #include "dirserv.h"
16 #include "dirvote.h"
17 #include "policies.h"
18 #include "rendcommon.h"
19 #include "router.h"
20 #include "routerlist.h"
21 #include "memarea.h"
22 #include "microdesc.h"
23 #include "networkstatus.h"
24 #include "rephist.h"
25 #include "routerparse.h"
26 #undef log
27 #include <math.h>
29 /****************************************************************************/
31 /** Enumeration of possible token types. The ones starting with K_ correspond
32 * to directory 'keywords'. _ERR is an error in the tokenizing process, _EOF
33 * is an end-of-file marker, and _NIL is used to encode not-a-token.
35 typedef enum {
36 K_ACCEPT = 0,
37 K_ACCEPT6,
38 K_DIRECTORY_SIGNATURE,
39 K_RECOMMENDED_SOFTWARE,
40 K_REJECT,
41 K_REJECT6,
42 K_ROUTER,
43 K_SIGNED_DIRECTORY,
44 K_SIGNING_KEY,
45 K_ONION_KEY,
46 K_ROUTER_SIGNATURE,
47 K_PUBLISHED,
48 K_RUNNING_ROUTERS,
49 K_ROUTER_STATUS,
50 K_PLATFORM,
51 K_OPT,
52 K_BANDWIDTH,
53 K_CONTACT,
54 K_NETWORK_STATUS,
55 K_UPTIME,
56 K_DIR_SIGNING_KEY,
57 K_FAMILY,
58 K_FINGERPRINT,
59 K_HIBERNATING,
60 K_READ_HISTORY,
61 K_WRITE_HISTORY,
62 K_NETWORK_STATUS_VERSION,
63 K_DIR_SOURCE,
64 K_DIR_OPTIONS,
65 K_CLIENT_VERSIONS,
66 K_SERVER_VERSIONS,
67 K_OR_ADDRESS,
68 K_P,
69 K_R,
70 K_S,
71 K_V,
72 K_W,
73 K_M,
74 K_EXTRA_INFO,
75 K_EXTRA_INFO_DIGEST,
76 K_CACHES_EXTRA_INFO,
77 K_HIDDEN_SERVICE_DIR,
78 K_ALLOW_SINGLE_HOP_EXITS,
80 K_DIRREQ_END,
81 K_DIRREQ_V2_IPS,
82 K_DIRREQ_V3_IPS,
83 K_DIRREQ_V2_REQS,
84 K_DIRREQ_V3_REQS,
85 K_DIRREQ_V2_SHARE,
86 K_DIRREQ_V3_SHARE,
87 K_DIRREQ_V2_RESP,
88 K_DIRREQ_V3_RESP,
89 K_DIRREQ_V2_DIR,
90 K_DIRREQ_V3_DIR,
91 K_DIRREQ_V2_TUN,
92 K_DIRREQ_V3_TUN,
93 K_ENTRY_END,
94 K_ENTRY_IPS,
95 K_CELL_END,
96 K_CELL_PROCESSED,
97 K_CELL_QUEUED,
98 K_CELL_TIME,
99 K_CELL_CIRCS,
100 K_EXIT_END,
101 K_EXIT_WRITTEN,
102 K_EXIT_READ,
103 K_EXIT_OPENED,
105 K_DIR_KEY_CERTIFICATE_VERSION,
106 K_DIR_IDENTITY_KEY,
107 K_DIR_KEY_PUBLISHED,
108 K_DIR_KEY_EXPIRES,
109 K_DIR_KEY_CERTIFICATION,
110 K_DIR_KEY_CROSSCERT,
111 K_DIR_ADDRESS,
113 K_VOTE_STATUS,
114 K_VALID_AFTER,
115 K_FRESH_UNTIL,
116 K_VALID_UNTIL,
117 K_VOTING_DELAY,
119 K_KNOWN_FLAGS,
120 K_PARAMS,
121 K_BW_WEIGHTS,
122 K_VOTE_DIGEST,
123 K_CONSENSUS_DIGEST,
124 K_ADDITIONAL_DIGEST,
125 K_ADDITIONAL_SIGNATURE,
126 K_CONSENSUS_METHODS,
127 K_CONSENSUS_METHOD,
128 K_LEGACY_DIR_KEY,
129 K_DIRECTORY_FOOTER,
131 A_PURPOSE,
132 A_LAST_LISTED,
133 _A_UNKNOWN,
135 R_RENDEZVOUS_SERVICE_DESCRIPTOR,
136 R_VERSION,
137 R_PERMANENT_KEY,
138 R_SECRET_ID_PART,
139 R_PUBLICATION_TIME,
140 R_PROTOCOL_VERSIONS,
141 R_INTRODUCTION_POINTS,
142 R_SIGNATURE,
144 R_IPO_IDENTIFIER,
145 R_IPO_IP_ADDRESS,
146 R_IPO_ONION_PORT,
147 R_IPO_ONION_KEY,
148 R_IPO_SERVICE_KEY,
150 C_CLIENT_NAME,
151 C_DESCRIPTOR_COOKIE,
152 C_CLIENT_KEY,
154 _ERR,
155 _EOF,
156 _NIL
157 } directory_keyword;
159 #define MIN_ANNOTATION A_PURPOSE
160 #define MAX_ANNOTATION _A_UNKNOWN
162 /** Structure to hold a single directory token.
164 * We parse a directory by breaking it into "tokens", each consisting
165 * of a keyword, a line full of arguments, and a binary object. The
166 * arguments and object are both optional, depending on the keyword
167 * type.
169 * This structure is only allocated in memareas; do not allocate it on
170 * the heap, or token_clear() won't work.
172 typedef struct directory_token_t {
173 directory_keyword tp; /**< Type of the token. */
174 int n_args:30; /**< Number of elements in args */
175 char **args; /**< Array of arguments from keyword line. */
177 char *object_type; /**< -----BEGIN [object_type]-----*/
178 size_t object_size; /**< Bytes in object_body */
179 char *object_body; /**< Contents of object, base64-decoded. */
181 crypto_pk_t *key; /**< For public keys only. Heap-allocated. */
183 char *error; /**< For _ERR tokens only. */
184 } directory_token_t;
186 /* ********************************************************************** */
188 /** We use a table of rules to decide how to parse each token type. */
190 /** Rules for whether the keyword needs an object. */
191 typedef enum {
192 NO_OBJ, /**< No object, ever. */
193 NEED_OBJ, /**< Object is required. */
194 NEED_SKEY_1024,/**< Object is required, and must be a 1024 bit private key */
195 NEED_KEY_1024, /**< Object is required, and must be a 1024 bit public key */
196 NEED_KEY, /**< Object is required, and must be a public key. */
197 OBJ_OK, /**< Object is optional. */
198 } obj_syntax;
200 #define AT_START 1
201 #define AT_END 2
203 /** Determines the parsing rules for a single token type. */
204 typedef struct token_rule_t {
205 /** The string value of the keyword identifying the type of item. */
206 const char *t;
207 /** The corresponding directory_keyword enum. */
208 directory_keyword v;
209 /** Minimum number of arguments for this item */
210 int min_args;
211 /** Maximum number of arguments for this item */
212 int max_args;
213 /** If true, we concatenate all arguments for this item into a single
214 * string. */
215 int concat_args;
216 /** Requirements on object syntax for this item. */
217 obj_syntax os;
218 /** Lowest number of times this item may appear in a document. */
219 int min_cnt;
220 /** Highest number of times this item may appear in a document. */
221 int max_cnt;
222 /** One or more of AT_START/AT_END to limit where the item may appear in a
223 * document. */
224 int pos;
225 /** True iff this token is an annotation. */
226 int is_annotation;
227 } token_rule_t;
230 * Helper macros to define token tables. 's' is a string, 't' is a
231 * directory_keyword, 'a' is a trio of argument multiplicities, and 'o' is an
232 * object syntax.
236 /** Appears to indicate the end of a table. */
237 #define END_OF_TABLE { NULL, _NIL, 0,0,0, NO_OBJ, 0, INT_MAX, 0, 0 }
238 /** An item with no restrictions: used for obsolete document types */
239 #define T(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0, 0 }
240 /** An item with no restrictions on multiplicity or location. */
241 #define T0N(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0, 0 }
242 /** An item that must appear exactly once */
243 #define T1(s,t,a,o) { s, t, a, o, 1, 1, 0, 0 }
244 /** An item that must appear exactly once, at the start of the document */
245 #define T1_START(s,t,a,o) { s, t, a, o, 1, 1, AT_START, 0 }
246 /** An item that must appear exactly once, at the end of the document */
247 #define T1_END(s,t,a,o) { s, t, a, o, 1, 1, AT_END, 0 }
248 /** An item that must appear one or more times */
249 #define T1N(s,t,a,o) { s, t, a, o, 1, INT_MAX, 0, 0 }
250 /** An item that must appear no more than once */
251 #define T01(s,t,a,o) { s, t, a, o, 0, 1, 0, 0 }
252 /** An annotation that must appear no more than once */
253 #define A01(s,t,a,o) { s, t, a, o, 0, 1, 0, 1 }
255 /* Argument multiplicity: any number of arguments. */
256 #define ARGS 0,INT_MAX,0
257 /* Argument multiplicity: no arguments. */
258 #define NO_ARGS 0,0,0
259 /* Argument multiplicity: concatenate all arguments. */
260 #define CONCAT_ARGS 1,1,1
261 /* Argument multiplicity: at least <b>n</b> arguments. */
262 #define GE(n) n,INT_MAX,0
263 /* Argument multiplicity: exactly <b>n</b> arguments. */
264 #define EQ(n) n,n,0
266 /** List of tokens recognized in router descriptors */
267 static token_rule_t routerdesc_token_table[] = {
268 T0N("reject", K_REJECT, ARGS, NO_OBJ ),
269 T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
270 T0N("reject6", K_REJECT6, ARGS, NO_OBJ ),
271 T0N("accept6", K_ACCEPT6, ARGS, NO_OBJ ),
272 T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
273 T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
274 T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
275 T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
276 T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
277 T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
278 T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
279 T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
280 T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
281 T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
282 T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
283 T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
284 T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
285 T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
286 T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
288 T01("family", K_FAMILY, ARGS, NO_OBJ ),
289 T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
290 T0N("or-address", K_OR_ADDRESS, GE(1), NO_OBJ ),
292 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
293 T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
294 A01("@purpose", A_PURPOSE, GE(1), NO_OBJ ),
296 END_OF_TABLE
299 /** List of tokens recognized in extra-info documents. */
300 static token_rule_t extrainfo_token_table[] = {
301 T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
302 T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
303 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
304 T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
305 T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
306 T01("dirreq-stats-end", K_DIRREQ_END, ARGS, NO_OBJ ),
307 T01("dirreq-v2-ips", K_DIRREQ_V2_IPS, ARGS, NO_OBJ ),
308 T01("dirreq-v3-ips", K_DIRREQ_V3_IPS, ARGS, NO_OBJ ),
309 T01("dirreq-v2-reqs", K_DIRREQ_V2_REQS, ARGS, NO_OBJ ),
310 T01("dirreq-v3-reqs", K_DIRREQ_V3_REQS, ARGS, NO_OBJ ),
311 T01("dirreq-v2-share", K_DIRREQ_V2_SHARE, ARGS, NO_OBJ ),
312 T01("dirreq-v3-share", K_DIRREQ_V3_SHARE, ARGS, NO_OBJ ),
313 T01("dirreq-v2-resp", K_DIRREQ_V2_RESP, ARGS, NO_OBJ ),
314 T01("dirreq-v3-resp", K_DIRREQ_V3_RESP, ARGS, NO_OBJ ),
315 T01("dirreq-v2-direct-dl", K_DIRREQ_V2_DIR, ARGS, NO_OBJ ),
316 T01("dirreq-v3-direct-dl", K_DIRREQ_V3_DIR, ARGS, NO_OBJ ),
317 T01("dirreq-v2-tunneled-dl", K_DIRREQ_V2_TUN, ARGS, NO_OBJ ),
318 T01("dirreq-v3-tunneled-dl", K_DIRREQ_V3_TUN, ARGS, NO_OBJ ),
319 T01("entry-stats-end", K_ENTRY_END, ARGS, NO_OBJ ),
320 T01("entry-ips", K_ENTRY_IPS, ARGS, NO_OBJ ),
321 T01("cell-stats-end", K_CELL_END, ARGS, NO_OBJ ),
322 T01("cell-processed-cells", K_CELL_PROCESSED, ARGS, NO_OBJ ),
323 T01("cell-queued-cells", K_CELL_QUEUED, ARGS, NO_OBJ ),
324 T01("cell-time-in-queue", K_CELL_TIME, ARGS, NO_OBJ ),
325 T01("cell-circuits-per-decile", K_CELL_CIRCS, ARGS, NO_OBJ ),
326 T01("exit-stats-end", K_EXIT_END, ARGS, NO_OBJ ),
327 T01("exit-kibibytes-written", K_EXIT_WRITTEN, ARGS, NO_OBJ ),
328 T01("exit-kibibytes-read", K_EXIT_READ, ARGS, NO_OBJ ),
329 T01("exit-streams-opened", K_EXIT_OPENED, ARGS, NO_OBJ ),
331 T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
333 END_OF_TABLE
336 /** List of tokens recognized in the body part of v2 and v3 networkstatus
337 * documents. */
338 static token_rule_t rtrstatus_token_table[] = {
339 T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
340 T1( "r", K_R, GE(7), NO_OBJ ),
341 T1( "s", K_S, ARGS, NO_OBJ ),
342 T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
343 T01("w", K_W, ARGS, NO_OBJ ),
344 T0N("m", K_M, CONCAT_ARGS, NO_OBJ ),
345 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
346 END_OF_TABLE
349 /** List of tokens recognized in the header part of v2 networkstatus documents.
351 static token_rule_t netstatus_token_table[] = {
352 T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
353 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
354 T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
355 T1( "dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
356 T1( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
357 T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
358 GE(1), NO_OBJ ),
359 T1( "dir-source", K_DIR_SOURCE, GE(3), NO_OBJ ),
360 T01("dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ ),
361 T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
362 T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
364 END_OF_TABLE
367 /** List of tokens recognized in the footer of v1/v2 directory/networkstatus
368 * footers. */
369 static token_rule_t dir_footer_token_table[] = {
370 T1("directory-signature", K_DIRECTORY_SIGNATURE, EQ(1), NEED_OBJ ),
371 END_OF_TABLE
374 /** List of tokens recognized in v1 directory headers/footers. */
375 static token_rule_t dir_token_table[] = {
376 /* don't enforce counts; this is obsolete. */
377 T( "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ ),
378 T( "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ ),
379 T( "recommended-software",K_RECOMMENDED_SOFTWARE,CONCAT_ARGS, NO_OBJ ),
380 T( "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ ),
382 T( "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ ),
383 T( "router-status", K_ROUTER_STATUS, ARGS, NO_OBJ ),
384 T( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
385 T( "opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
386 T( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
387 T( "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK ),
388 T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
390 END_OF_TABLE
393 /** List of tokens common to V3 authority certificates and V3 consensuses. */
394 #define CERTIFICATE_MEMBERS \
395 T1("dir-key-certificate-version", K_DIR_KEY_CERTIFICATE_VERSION, \
396 GE(1), NO_OBJ ), \
397 T1("dir-identity-key", K_DIR_IDENTITY_KEY, NO_ARGS, NEED_KEY ),\
398 T1("dir-key-published",K_DIR_KEY_PUBLISHED, CONCAT_ARGS, NO_OBJ), \
399 T1("dir-key-expires", K_DIR_KEY_EXPIRES, CONCAT_ARGS, NO_OBJ), \
400 T1("dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY ),\
401 T01("dir-key-crosscert", K_DIR_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),\
402 T1("dir-key-certification", K_DIR_KEY_CERTIFICATION, \
403 NO_ARGS, NEED_OBJ), \
404 T01("dir-address", K_DIR_ADDRESS, GE(1), NO_OBJ),
406 /** List of tokens recognized in V3 authority certificates. */
407 static token_rule_t dir_key_certificate_table[] = {
408 CERTIFICATE_MEMBERS
409 T1("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
410 END_OF_TABLE
413 /** List of tokens recognized in rendezvous service descriptors */
414 static token_rule_t desc_token_table[] = {
415 T1_START("rendezvous-service-descriptor", R_RENDEZVOUS_SERVICE_DESCRIPTOR,
416 EQ(1), NO_OBJ),
417 T1("version", R_VERSION, EQ(1), NO_OBJ),
418 T1("permanent-key", R_PERMANENT_KEY, NO_ARGS, NEED_KEY_1024),
419 T1("secret-id-part", R_SECRET_ID_PART, EQ(1), NO_OBJ),
420 T1("publication-time", R_PUBLICATION_TIME, CONCAT_ARGS, NO_OBJ),
421 T1("protocol-versions", R_PROTOCOL_VERSIONS, EQ(1), NO_OBJ),
422 T01("introduction-points", R_INTRODUCTION_POINTS, NO_ARGS, NEED_OBJ),
423 T1_END("signature", R_SIGNATURE, NO_ARGS, NEED_OBJ),
424 END_OF_TABLE
427 /** List of tokens recognized in the (encrypted) list of introduction points of
428 * rendezvous service descriptors */
429 static token_rule_t ipo_token_table[] = {
430 T1_START("introduction-point", R_IPO_IDENTIFIER, EQ(1), NO_OBJ),
431 T1("ip-address", R_IPO_IP_ADDRESS, EQ(1), NO_OBJ),
432 T1("onion-port", R_IPO_ONION_PORT, EQ(1), NO_OBJ),
433 T1("onion-key", R_IPO_ONION_KEY, NO_ARGS, NEED_KEY_1024),
434 T1("service-key", R_IPO_SERVICE_KEY, NO_ARGS, NEED_KEY_1024),
435 END_OF_TABLE
438 /** List of tokens recognized in the (possibly encrypted) list of introduction
439 * points of rendezvous service descriptors */
440 static token_rule_t client_keys_token_table[] = {
441 T1_START("client-name", C_CLIENT_NAME, CONCAT_ARGS, NO_OBJ),
442 T1("descriptor-cookie", C_DESCRIPTOR_COOKIE, EQ(1), NO_OBJ),
443 T01("client-key", C_CLIENT_KEY, NO_ARGS, NEED_SKEY_1024),
444 END_OF_TABLE
447 /** List of tokens recognized in V3 networkstatus votes. */
448 static token_rule_t networkstatus_token_table[] = {
449 T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
450 GE(1), NO_OBJ ),
451 T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
452 T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
453 T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
454 T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
455 T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
456 T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
457 T1("known-flags", K_KNOWN_FLAGS, ARGS, NO_OBJ ),
458 T01("params", K_PARAMS, ARGS, NO_OBJ ),
459 T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
461 CERTIFICATE_MEMBERS
463 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
464 T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
465 T1( "dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
466 T01("legacy-dir-key", K_LEGACY_DIR_KEY, GE(1), NO_OBJ ),
467 T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
468 T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
469 T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
470 T1( "consensus-methods", K_CONSENSUS_METHODS, GE(1), NO_OBJ ),
472 END_OF_TABLE
475 /** List of tokens recognized in V3 networkstatus consensuses. */
476 static token_rule_t networkstatus_consensus_token_table[] = {
477 T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
478 GE(1), NO_OBJ ),
479 T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
480 T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
481 T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
482 T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
483 T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
485 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
487 T1N("dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
488 T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
489 T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
491 T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
493 T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
494 T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
495 T01("consensus-method", K_CONSENSUS_METHOD, EQ(1), NO_OBJ),
496 T01("params", K_PARAMS, ARGS, NO_OBJ ),
498 END_OF_TABLE
501 /** List of tokens recognized in the footer of v1/v2 directory/networkstatus
502 * footers. */
503 static token_rule_t networkstatus_vote_footer_token_table[] = {
504 T01("directory-footer", K_DIRECTORY_FOOTER, NO_ARGS, NO_OBJ ),
505 T01("bandwidth-weights", K_BW_WEIGHTS, ARGS, NO_OBJ ),
506 T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
507 END_OF_TABLE
510 /** List of tokens recognized in detached networkstatus signature documents. */
511 static token_rule_t networkstatus_detached_signature_token_table[] = {
512 T1_START("consensus-digest", K_CONSENSUS_DIGEST, GE(1), NO_OBJ ),
513 T("additional-digest", K_ADDITIONAL_DIGEST,GE(3), NO_OBJ ),
514 T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
515 T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
516 T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
517 T("additional-signature", K_ADDITIONAL_SIGNATURE, GE(4), NEED_OBJ ),
518 T1N("directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
519 END_OF_TABLE
522 /** List of tokens recognized in microdescriptors */
523 static token_rule_t microdesc_token_table[] = {
524 T1_START("onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024),
525 T01("family", K_FAMILY, ARGS, NO_OBJ ),
526 T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
527 A01("@last-listed", A_LAST_LISTED, CONCAT_ARGS, NO_OBJ ),
528 END_OF_TABLE
531 #undef T
533 /* static function prototypes */
534 static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
535 static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
536 static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
538 static int router_get_hash_impl(const char *s, size_t s_len, char *digest,
539 const char *start_str, const char *end_str,
540 char end_char,
541 digest_algorithm_t alg);
542 static int router_get_hashes_impl(const char *s, size_t s_len,
543 digests_t *digests,
544 const char *start_str, const char *end_str,
545 char end_char);
546 static void token_clear(directory_token_t *tok);
547 static smartlist_t *find_all_by_keyword(smartlist_t *s, directory_keyword k);
548 static smartlist_t *find_all_exitpolicy(smartlist_t *s);
549 static directory_token_t *_find_by_keyword(smartlist_t *s,
550 directory_keyword keyword,
551 const char *keyword_str);
552 #define find_by_keyword(s, keyword) _find_by_keyword((s), (keyword), #keyword)
553 static directory_token_t *find_opt_by_keyword(smartlist_t *s,
554 directory_keyword keyword);
556 #define TS_ANNOTATIONS_OK 1
557 #define TS_NOCHECK 2
558 #define TS_NO_NEW_ANNOTATIONS 4
559 static int tokenize_string(memarea_t *area,
560 const char *start, const char *end,
561 smartlist_t *out,
562 token_rule_t *table,
563 int flags);
564 static directory_token_t *get_next_token(memarea_t *area,
565 const char **s,
566 const char *eos,
567 token_rule_t *table);
568 #define CST_CHECK_AUTHORITY (1<<0)
569 #define CST_NO_CHECK_OBJTYPE (1<<1)
570 static int check_signature_token(const char *digest,
571 ssize_t digest_len,
572 directory_token_t *tok,
573 crypto_pk_t *pkey,
574 int flags,
575 const char *doctype);
576 static crypto_pk_t *find_dir_signing_key(const char *str, const char *eos);
578 #undef DEBUG_AREA_ALLOC
580 #ifdef DEBUG_AREA_ALLOC
581 #define DUMP_AREA(a,name) STMT_BEGIN \
582 size_t alloc=0, used=0; \
583 memarea_get_stats((a),&alloc,&used); \
584 log_debug(LD_MM, "Area for %s has %lu allocated; using %lu.", \
585 name, (unsigned long)alloc, (unsigned long)used); \
586 STMT_END
587 #else
588 #define DUMP_AREA(a,name) STMT_NIL
589 #endif
591 /** Last time we dumped a descriptor to disk. */
592 static time_t last_desc_dumped = 0;
594 /** For debugging purposes, dump unparseable descriptor *<b>desc</b> of
595 * type *<b>type</b> to file $DATADIR/unparseable-desc. Do not write more
596 * than one descriptor to disk per minute. If there is already such a
597 * file in the data directory, overwrite it. */
598 static void
599 dump_desc(const char *desc, const char *type)
601 time_t now = time(NULL);
602 tor_assert(desc);
603 tor_assert(type);
604 if (!last_desc_dumped || last_desc_dumped + 60 < now) {
605 char *debugfile = get_datadir_fname("unparseable-desc");
606 size_t filelen = 50 + strlen(type) + strlen(desc);
607 char *content = tor_malloc_zero(filelen);
608 tor_snprintf(content, filelen, "Unable to parse descriptor of type "
609 "%s:\n%s", type, desc);
610 write_str_to_file(debugfile, content, 0);
611 log_info(LD_DIR, "Unable to parse descriptor of type %s. See file "
612 "unparseable-desc in data directory for details.", type);
613 tor_free(content);
614 tor_free(debugfile);
615 last_desc_dumped = now;
619 /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
620 * <b>s</b>. Return 0 on success, -1 on failure.
623 router_get_dir_hash(const char *s, char *digest)
625 return router_get_hash_impl(s, strlen(s), digest,
626 "signed-directory","\ndirectory-signature",'\n',
627 DIGEST_SHA1);
630 /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
631 * <b>s</b>. Return 0 on success, -1 on failure.
634 router_get_router_hash(const char *s, size_t s_len, char *digest)
636 return router_get_hash_impl(s, s_len, digest,
637 "router ","\nrouter-signature", '\n',
638 DIGEST_SHA1);
641 /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
642 * string in <b>s</b>. Return 0 on success, -1 on failure.
645 router_get_runningrouters_hash(const char *s, char *digest)
647 return router_get_hash_impl(s, strlen(s), digest,
648 "network-status","\ndirectory-signature", '\n',
649 DIGEST_SHA1);
652 /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
653 * string in <b>s</b>. Return 0 on success, -1 on failure. */
655 router_get_networkstatus_v2_hash(const char *s, char *digest)
657 return router_get_hash_impl(s, strlen(s), digest,
658 "network-status-version","\ndirectory-signature",
659 '\n',
660 DIGEST_SHA1);
663 /** Set <b>digests</b> to all the digests of the consensus document in
664 * <b>s</b> */
666 router_get_networkstatus_v3_hashes(const char *s, digests_t *digests)
668 return router_get_hashes_impl(s,strlen(s),digests,
669 "network-status-version",
670 "\ndirectory-signature",
671 ' ');
674 /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
675 * string in <b>s</b>. Return 0 on success, -1 on failure. */
677 router_get_networkstatus_v3_hash(const char *s, char *digest,
678 digest_algorithm_t alg)
680 return router_get_hash_impl(s, strlen(s), digest,
681 "network-status-version",
682 "\ndirectory-signature",
683 ' ', alg);
686 /** Set <b>digest</b> to the SHA-1 digest of the hash of the <b>s_len</b>-byte
687 * extrainfo string at <b>s</b>. Return 0 on success, -1 on failure. */
689 router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
691 return router_get_hash_impl(s, s_len, digest, "extra-info",
692 "\nrouter-signature",'\n', DIGEST_SHA1);
695 /** Helper: used to generate signatures for routers, directories and
696 * network-status objects. Given a digest in <b>digest</b> and a secret
697 * <b>private_key</b>, generate an PKCS1-padded signature, BASE64-encode it,
698 * surround it with -----BEGIN/END----- pairs, and write it to the
699 * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
700 * failure.
703 router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
704 size_t digest_len, crypto_pk_t *private_key)
706 char *signature;
707 size_t i, keysize;
708 int siglen;
710 keysize = crypto_pk_keysize(private_key);
711 signature = tor_malloc(keysize);
712 siglen = crypto_pk_private_sign(private_key, signature, keysize,
713 digest, digest_len);
714 if (siglen < 0) {
715 log_warn(LD_BUG,"Couldn't sign digest.");
716 goto err;
718 if (strlcat(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
719 goto truncated;
721 i = strlen(buf);
722 if (base64_encode(buf+i, buf_len-i, signature, siglen) < 0) {
723 log_warn(LD_BUG,"couldn't base64-encode signature");
724 goto err;
727 if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
728 goto truncated;
730 tor_free(signature);
731 return 0;
733 truncated:
734 log_warn(LD_BUG,"tried to exceed string length.");
735 err:
736 tor_free(signature);
737 return -1;
740 /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
741 * <b>versionlist</b>. Else, return VS_EMPTY if versionlist has no
742 * entries. Else, return VS_OLD if every member of
743 * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
744 * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
745 * the same series (major.minor.micro) as <b>myversion</b>, but no such member
746 * is newer than <b>myversion.</b>. Else, return VS_NEW if every member of
747 * <b>versionlist</b> is older than <b>myversion</b>. Else, return
748 * VS_UNRECOMMENDED.
750 * (versionlist is a comma-separated list of version strings,
751 * optionally prefixed with "Tor". Versions that can't be parsed are
752 * ignored.)
754 version_status_t
755 tor_version_is_obsolete(const char *myversion, const char *versionlist)
757 tor_version_t mine, other;
758 int found_newer = 0, found_older = 0, found_newer_in_series = 0,
759 found_any_in_series = 0, r, same;
760 version_status_t ret = VS_UNRECOMMENDED;
761 smartlist_t *version_sl;
763 log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
764 myversion, versionlist);
766 if (tor_version_parse(myversion, &mine)) {
767 log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
768 tor_assert(0);
770 version_sl = smartlist_new();
771 smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
773 if (!strlen(versionlist)) { /* no authorities cared or agreed */
774 ret = VS_EMPTY;
775 goto done;
778 SMARTLIST_FOREACH_BEGIN(version_sl, const char *, cp) {
779 if (!strcmpstart(cp, "Tor "))
780 cp += 4;
782 if (tor_version_parse(cp, &other)) {
783 /* Couldn't parse other; it can't be a match. */
784 } else {
785 same = tor_version_same_series(&mine, &other);
786 if (same)
787 found_any_in_series = 1;
788 r = tor_version_compare(&mine, &other);
789 if (r==0) {
790 ret = VS_RECOMMENDED;
791 goto done;
792 } else if (r<0) {
793 found_newer = 1;
794 if (same)
795 found_newer_in_series = 1;
796 } else if (r>0) {
797 found_older = 1;
800 } SMARTLIST_FOREACH_END(cp);
802 /* We didn't find the listed version. Is it new or old? */
803 if (found_any_in_series && !found_newer_in_series && found_newer) {
804 ret = VS_NEW_IN_SERIES;
805 } else if (found_newer && !found_older) {
806 ret = VS_OLD;
807 } else if (found_older && !found_newer) {
808 ret = VS_NEW;
809 } else {
810 ret = VS_UNRECOMMENDED;
813 done:
814 SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
815 smartlist_free(version_sl);
816 return ret;
819 /** Read a signed directory from <b>str</b>. If it's well-formed, return 0.
820 * Otherwise, return -1. If we're a directory cache, cache it.
823 router_parse_directory(const char *str)
825 directory_token_t *tok;
826 char digest[DIGEST_LEN];
827 time_t published_on;
828 int r;
829 const char *end, *cp, *str_dup = str;
830 smartlist_t *tokens = NULL;
831 crypto_pk_t *declared_key = NULL;
832 memarea_t *area = memarea_new();
834 /* XXXX This could be simplified a lot, but it will all go away
835 * once pre-0.1.1.8 is obsolete, and for now it's better not to
836 * touch it. */
838 if (router_get_dir_hash(str, digest)) {
839 log_warn(LD_DIR, "Unable to compute digest of directory");
840 goto err;
842 log_debug(LD_DIR,"Received directory hashes to %s",hex_str(digest,4));
844 /* Check signature first, before we try to tokenize. */
845 cp = str;
846 while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
847 cp = end;
848 if (cp == str || !cp) {
849 log_warn(LD_DIR, "No signature found on directory."); goto err;
851 ++cp;
852 tokens = smartlist_new();
853 if (tokenize_string(area,cp,strchr(cp,'\0'),tokens,dir_token_table,0)) {
854 log_warn(LD_DIR, "Error tokenizing directory signature"); goto err;
856 if (smartlist_len(tokens) != 1) {
857 log_warn(LD_DIR, "Unexpected number of tokens in signature"); goto err;
859 tok=smartlist_get(tokens,0);
860 if (tok->tp != K_DIRECTORY_SIGNATURE) {
861 log_warn(LD_DIR,"Expected a single directory signature"); goto err;
863 declared_key = find_dir_signing_key(str, str+strlen(str));
864 note_crypto_pk_op(VERIFY_DIR);
865 if (check_signature_token(digest, DIGEST_LEN, tok, declared_key,
866 CST_CHECK_AUTHORITY, "directory")<0)
867 goto err;
869 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
870 smartlist_clear(tokens);
871 memarea_clear(area);
873 /* Now try to parse the first part of the directory. */
874 if ((end = strstr(str,"\nrouter "))) {
875 ++end;
876 } else if ((end = strstr(str, "\ndirectory-signature"))) {
877 ++end;
878 } else {
879 end = str + strlen(str);
882 if (tokenize_string(area,str,end,tokens,dir_token_table,0)) {
883 log_warn(LD_DIR, "Error tokenizing directory"); goto err;
886 tok = find_by_keyword(tokens, K_PUBLISHED);
887 tor_assert(tok->n_args == 1);
889 if (parse_iso_time(tok->args[0], &published_on) < 0) {
890 goto err;
893 /* Now that we know the signature is okay, and we have a
894 * publication time, cache the directory. */
895 if (directory_caches_v1_dir_info(get_options()) &&
896 !authdir_mode_v1(get_options()))
897 dirserv_set_cached_directory(str, published_on, 0);
899 r = 0;
900 goto done;
901 err:
902 dump_desc(str_dup, "v1 directory");
903 r = -1;
904 done:
905 if (declared_key) crypto_pk_free(declared_key);
906 if (tokens) {
907 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
908 smartlist_free(tokens);
910 if (area) {
911 DUMP_AREA(area, "v1 directory");
912 memarea_drop_all(area);
914 return r;
917 /** Read a signed router status statement from <b>str</b>. If it's
918 * well-formed, return 0. Otherwise, return -1. If we're a directory cache,
919 * cache it.*/
921 router_parse_runningrouters(const char *str)
923 char digest[DIGEST_LEN];
924 directory_token_t *tok;
925 time_t published_on;
926 int r = -1;
927 crypto_pk_t *declared_key = NULL;
928 smartlist_t *tokens = NULL;
929 const char *eos = str + strlen(str), *str_dup = str;
930 memarea_t *area = NULL;
932 if (router_get_runningrouters_hash(str, digest)) {
933 log_warn(LD_DIR, "Unable to compute digest of running-routers");
934 goto err;
936 area = memarea_new();
937 tokens = smartlist_new();
938 if (tokenize_string(area,str,eos,tokens,dir_token_table,0)) {
939 log_warn(LD_DIR, "Error tokenizing running-routers"); goto err;
941 tok = smartlist_get(tokens,0);
942 if (tok->tp != K_NETWORK_STATUS) {
943 log_warn(LD_DIR, "Network-status starts with wrong token");
944 goto err;
947 tok = find_by_keyword(tokens, K_PUBLISHED);
948 tor_assert(tok->n_args == 1);
949 if (parse_iso_time(tok->args[0], &published_on) < 0) {
950 goto err;
952 if (!(tok = find_opt_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
953 log_warn(LD_DIR, "Missing signature on running-routers");
954 goto err;
956 declared_key = find_dir_signing_key(str, eos);
957 note_crypto_pk_op(VERIFY_DIR);
958 if (check_signature_token(digest, DIGEST_LEN, tok, declared_key,
959 CST_CHECK_AUTHORITY, "running-routers")
960 < 0)
961 goto err;
963 /* Now that we know the signature is okay, and we have a
964 * publication time, cache the list. */
965 if (get_options()->DirPort_set && !authdir_mode_v1(get_options()))
966 dirserv_set_cached_directory(str, published_on, 1);
968 r = 0;
969 err:
970 dump_desc(str_dup, "v1 running-routers");
971 if (declared_key) crypto_pk_free(declared_key);
972 if (tokens) {
973 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
974 smartlist_free(tokens);
976 if (area) {
977 DUMP_AREA(area, "v1 running-routers");
978 memarea_drop_all(area);
980 return r;
983 /** Given a directory or running-routers string in <b>str</b>, try to
984 * find the its dir-signing-key token (if any). If this token is
985 * present, extract and return the key. Return NULL on failure. */
986 static crypto_pk_t *
987 find_dir_signing_key(const char *str, const char *eos)
989 const char *cp;
990 directory_token_t *tok;
991 crypto_pk_t *key = NULL;
992 memarea_t *area = NULL;
993 tor_assert(str);
994 tor_assert(eos);
996 /* Is there a dir-signing-key in the directory? */
997 cp = tor_memstr(str, eos-str, "\nopt dir-signing-key");
998 if (!cp)
999 cp = tor_memstr(str, eos-str, "\ndir-signing-key");
1000 if (!cp)
1001 return NULL;
1002 ++cp; /* Now cp points to the start of the token. */
1004 area = memarea_new();
1005 tok = get_next_token(area, &cp, eos, dir_token_table);
1006 if (!tok) {
1007 log_warn(LD_DIR, "Unparseable dir-signing-key token");
1008 goto done;
1010 if (tok->tp != K_DIR_SIGNING_KEY) {
1011 log_warn(LD_DIR, "Dir-signing-key token did not parse as expected");
1012 goto done;
1015 if (tok->key) {
1016 key = tok->key;
1017 tok->key = NULL; /* steal reference. */
1018 } else {
1019 log_warn(LD_DIR, "Dir-signing-key token contained no key");
1022 done:
1023 if (tok) token_clear(tok);
1024 if (area) {
1025 DUMP_AREA(area, "dir-signing-key token");
1026 memarea_drop_all(area);
1028 return key;
1031 /** Return true iff <b>key</b> is allowed to sign directories.
1033 static int
1034 dir_signing_key_is_trusted(crypto_pk_t *key)
1036 char digest[DIGEST_LEN];
1037 if (!key) return 0;
1038 if (crypto_pk_get_digest(key, digest) < 0) {
1039 log_warn(LD_DIR, "Error computing dir-signing-key digest");
1040 return 0;
1042 if (!router_digest_is_trusted_dir(digest)) {
1043 log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
1044 return 0;
1046 return 1;
1049 /** Check whether the object body of the token in <b>tok</b> has a good
1050 * signature for <b>digest</b> using key <b>pkey</b>. If
1051 * <b>CST_CHECK_AUTHORITY</b> is set, make sure that <b>pkey</b> is the key of
1052 * a directory authority. If <b>CST_NO_CHECK_OBJTYPE</b> is set, do not check
1053 * the object type of the signature object. Use <b>doctype</b> as the type of
1054 * the document when generating log messages. Return 0 on success, negative
1055 * on failure.
1057 static int
1058 check_signature_token(const char *digest,
1059 ssize_t digest_len,
1060 directory_token_t *tok,
1061 crypto_pk_t *pkey,
1062 int flags,
1063 const char *doctype)
1065 char *signed_digest;
1066 size_t keysize;
1067 const int check_authority = (flags & CST_CHECK_AUTHORITY);
1068 const int check_objtype = ! (flags & CST_NO_CHECK_OBJTYPE);
1070 tor_assert(pkey);
1071 tor_assert(tok);
1072 tor_assert(digest);
1073 tor_assert(doctype);
1075 if (check_authority && !dir_signing_key_is_trusted(pkey)) {
1076 log_warn(LD_DIR, "Key on %s did not come from an authority; rejecting",
1077 doctype);
1078 return -1;
1081 if (check_objtype) {
1082 if (strcmp(tok->object_type, "SIGNATURE")) {
1083 log_warn(LD_DIR, "Bad object type on %s signature", doctype);
1084 return -1;
1088 keysize = crypto_pk_keysize(pkey);
1089 signed_digest = tor_malloc(keysize);
1090 if (crypto_pk_public_checksig(pkey, signed_digest, keysize,
1091 tok->object_body, tok->object_size)
1092 < digest_len) {
1093 log_warn(LD_DIR, "Error reading %s: invalid signature.", doctype);
1094 tor_free(signed_digest);
1095 return -1;
1097 // log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
1098 // hex_str(signed_digest,4));
1099 if (tor_memneq(digest, signed_digest, digest_len)) {
1100 log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
1101 tor_free(signed_digest);
1102 return -1;
1104 tor_free(signed_digest);
1105 return 0;
1108 /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
1109 * or to the first of the annotations proceeding the next router or
1110 * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
1111 * we found an extrainfo, or false if found a router. Do not scan beyond
1112 * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
1113 static int
1114 find_start_of_next_router_or_extrainfo(const char **s_ptr,
1115 const char *eos,
1116 int *is_extrainfo_out)
1118 const char *annotations = NULL;
1119 const char *s = *s_ptr;
1121 s = eat_whitespace_eos(s, eos);
1123 while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
1124 /* We're at the start of a line. */
1125 tor_assert(*s != '\n');
1127 if (*s == '@' && !annotations) {
1128 annotations = s;
1129 } else if (*s == 'r' && !strcmpstart(s, "router ")) {
1130 *s_ptr = annotations ? annotations : s;
1131 *is_extrainfo_out = 0;
1132 return 0;
1133 } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
1134 *s_ptr = annotations ? annotations : s;
1135 *is_extrainfo_out = 1;
1136 return 0;
1139 if (!(s = memchr(s+1, '\n', eos-(s+1))))
1140 break;
1141 s = eat_whitespace_eos(s, eos);
1143 return -1;
1146 /** Given a string *<b>s</b> containing a concatenated sequence of router
1147 * descriptors (or extra-info documents if <b>is_extrainfo</b> is set), parses
1148 * them and stores the result in <b>dest</b>. All routers are marked running
1149 * and valid. Advances *s to a point immediately following the last router
1150 * entry. Ignore any trailing router entries that are not complete.
1152 * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
1153 * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
1154 * isn't SAVED_NOWHERE, remember the offset of each descriptor.
1156 * Returns 0 on success and -1 on failure.
1159 router_parse_list_from_string(const char **s, const char *eos,
1160 smartlist_t *dest,
1161 saved_location_t saved_location,
1162 int want_extrainfo,
1163 int allow_annotations,
1164 const char *prepend_annotations)
1166 routerinfo_t *router;
1167 extrainfo_t *extrainfo;
1168 signed_descriptor_t *signed_desc;
1169 void *elt;
1170 const char *end, *start;
1171 int have_extrainfo;
1173 tor_assert(s);
1174 tor_assert(*s);
1175 tor_assert(dest);
1177 start = *s;
1178 if (!eos)
1179 eos = *s + strlen(*s);
1181 tor_assert(eos >= *s);
1183 while (1) {
1184 if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
1185 break;
1187 end = tor_memstr(*s, eos-*s, "\nrouter-signature");
1188 if (end)
1189 end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
1190 if (end)
1191 end += strlen("\n-----END SIGNATURE-----\n");
1193 if (!end)
1194 break;
1196 elt = NULL;
1198 if (have_extrainfo && want_extrainfo) {
1199 routerlist_t *rl = router_get_routerlist();
1200 extrainfo = extrainfo_parse_entry_from_string(*s, end,
1201 saved_location != SAVED_IN_CACHE,
1202 rl->identity_map);
1203 if (extrainfo) {
1204 signed_desc = &extrainfo->cache_info;
1205 elt = extrainfo;
1207 } else if (!have_extrainfo && !want_extrainfo) {
1208 router = router_parse_entry_from_string(*s, end,
1209 saved_location != SAVED_IN_CACHE,
1210 allow_annotations,
1211 prepend_annotations);
1212 if (router) {
1213 log_debug(LD_DIR, "Read router '%s', purpose '%s'",
1214 router_describe(router),
1215 router_purpose_to_string(router->purpose));
1216 signed_desc = &router->cache_info;
1217 elt = router;
1220 if (!elt) {
1221 *s = end;
1222 continue;
1224 if (saved_location != SAVED_NOWHERE) {
1225 signed_desc->saved_location = saved_location;
1226 signed_desc->saved_offset = *s - start;
1228 *s = end;
1229 smartlist_add(dest, elt);
1232 return 0;
1235 /* For debugging: define to count every descriptor digest we've seen so we
1236 * know if we need to try harder to avoid duplicate verifies. */
1237 #undef COUNT_DISTINCT_DIGESTS
1239 #ifdef COUNT_DISTINCT_DIGESTS
1240 static digestmap_t *verified_digests = NULL;
1241 #endif
1243 /** Log the total count of the number of distinct router digests we've ever
1244 * verified. When compared to the number of times we've verified routerdesc
1245 * signatures <i>in toto</i>, this will tell us if we're doing too much
1246 * multiple-verification. */
1247 void
1248 dump_distinct_digest_count(int severity)
1250 #ifdef COUNT_DISTINCT_DIGESTS
1251 if (!verified_digests)
1252 verified_digests = digestmap_new();
1253 log(severity, LD_GENERAL, "%d *distinct* router digests verified",
1254 digestmap_size(verified_digests));
1255 #else
1256 (void)severity; /* suppress "unused parameter" warning */
1257 #endif
1260 /** Helper function: reads a single router entry from *<b>s</b> ...
1261 * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
1262 * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
1263 * s through end into the signed_descriptor_body of the resulting
1264 * routerinfo_t.
1266 * If <b>end</b> is NULL, <b>s</b> must be properly NUL-terminated.
1268 * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
1269 * before the router; if it's false, reject the router if it's annotated. If
1270 * <b>prepend_annotations</b> is set, it should contain some annotations:
1271 * append them to the front of the router before parsing it, and keep them
1272 * around when caching the router.
1274 * Only one of allow_annotations and prepend_annotations may be set.
1276 routerinfo_t *
1277 router_parse_entry_from_string(const char *s, const char *end,
1278 int cache_copy, int allow_annotations,
1279 const char *prepend_annotations)
1281 routerinfo_t *router = NULL;
1282 char digest[128];
1283 smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
1284 directory_token_t *tok;
1285 struct in_addr in;
1286 const char *start_of_annotations, *cp, *s_dup = s;
1287 size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
1288 int ok = 1;
1289 memarea_t *area = NULL;
1291 tor_assert(!allow_annotations || !prepend_annotations);
1293 if (!end) {
1294 end = s + strlen(s);
1297 /* point 'end' to a point immediately after the final newline. */
1298 while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
1299 --end;
1301 area = memarea_new();
1302 tokens = smartlist_new();
1303 if (prepend_annotations) {
1304 if (tokenize_string(area,prepend_annotations,NULL,tokens,
1305 routerdesc_token_table,TS_NOCHECK)) {
1306 log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
1307 goto err;
1311 start_of_annotations = s;
1312 cp = tor_memstr(s, end-s, "\nrouter ");
1313 if (!cp) {
1314 if (end-s < 7 || strcmpstart(s, "router ")) {
1315 log_warn(LD_DIR, "No router keyword found.");
1316 goto err;
1318 } else {
1319 s = cp+1;
1322 if (start_of_annotations != s) { /* We have annotations */
1323 if (allow_annotations) {
1324 if (tokenize_string(area,start_of_annotations,s,tokens,
1325 routerdesc_token_table,TS_NOCHECK)) {
1326 log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
1327 goto err;
1329 } else {
1330 log_warn(LD_DIR, "Found unexpected annotations on router descriptor not "
1331 "loaded from disk. Dropping it.");
1332 goto err;
1336 if (router_get_router_hash(s, end - s, digest) < 0) {
1337 log_warn(LD_DIR, "Couldn't compute router hash.");
1338 goto err;
1341 int flags = 0;
1342 if (allow_annotations)
1343 flags |= TS_ANNOTATIONS_OK;
1344 if (prepend_annotations)
1345 flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
1347 if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
1348 log_warn(LD_DIR, "Error tokenizing router descriptor.");
1349 goto err;
1353 if (smartlist_len(tokens) < 2) {
1354 log_warn(LD_DIR, "Impossibly short router descriptor.");
1355 goto err;
1358 tok = find_by_keyword(tokens, K_ROUTER);
1359 tor_assert(tok->n_args >= 5);
1361 router = tor_malloc_zero(sizeof(routerinfo_t));
1362 router->cache_info.routerlist_index = -1;
1363 router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
1364 router->cache_info.signed_descriptor_len = end-s;
1365 if (cache_copy) {
1366 size_t len = router->cache_info.signed_descriptor_len +
1367 router->cache_info.annotations_len;
1368 char *cp =
1369 router->cache_info.signed_descriptor_body = tor_malloc(len+1);
1370 if (prepend_annotations) {
1371 memcpy(cp, prepend_annotations, prepend_len);
1372 cp += prepend_len;
1374 /* This assertion will always succeed.
1375 * len == signed_desc_len + annotations_len
1376 * == end-s + s-start_of_annotations + prepend_len
1377 * == end-start_of_annotations + prepend_len
1378 * We already wrote prepend_len bytes into the buffer; now we're
1379 * writing end-start_of_annotations -NM. */
1380 tor_assert(cp+(end-start_of_annotations) ==
1381 router->cache_info.signed_descriptor_body+len);
1382 memcpy(cp, start_of_annotations, end-start_of_annotations);
1383 router->cache_info.signed_descriptor_body[len] = '\0';
1384 tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
1386 memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
1388 router->nickname = tor_strdup(tok->args[0]);
1389 if (!is_legal_nickname(router->nickname)) {
1390 log_warn(LD_DIR,"Router nickname is invalid");
1391 goto err;
1393 router->address = tor_strdup(tok->args[1]);
1394 if (!tor_inet_aton(router->address, &in)) {
1395 log_warn(LD_DIR,"Router address is not an IP address.");
1396 goto err;
1398 router->addr = ntohl(in.s_addr);
1400 router->or_port =
1401 (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
1402 if (!ok) {
1403 log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
1404 goto err;
1406 router->dir_port =
1407 (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
1408 if (!ok) {
1409 log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
1410 goto err;
1413 tok = find_by_keyword(tokens, K_BANDWIDTH);
1414 tor_assert(tok->n_args >= 3);
1415 router->bandwidthrate = (int)
1416 tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
1418 if (!ok) {
1419 log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
1420 escaped(tok->args[0]));
1421 goto err;
1423 router->bandwidthburst =
1424 (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
1425 if (!ok) {
1426 log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
1427 goto err;
1429 router->bandwidthcapacity = (int)
1430 tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
1431 if (!ok) {
1432 log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
1433 goto err;
1436 if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
1437 tor_assert(tok->n_args);
1438 router->purpose = router_purpose_from_string(tok->args[0]);
1439 } else {
1440 router->purpose = ROUTER_PURPOSE_GENERAL;
1442 router->cache_info.send_unencrypted =
1443 (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
1445 if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
1446 tor_assert(tok->n_args >= 1);
1447 router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
1448 if (!ok) {
1449 log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
1450 goto err;
1454 if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
1455 tor_assert(tok->n_args >= 1);
1456 router->is_hibernating
1457 = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
1460 tok = find_by_keyword(tokens, K_PUBLISHED);
1461 tor_assert(tok->n_args == 1);
1462 if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
1463 goto err;
1465 tok = find_by_keyword(tokens, K_ONION_KEY);
1466 if (!crypto_pk_public_exponent_ok(tok->key)) {
1467 log_warn(LD_DIR,
1468 "Relay's onion key had invalid exponent.");
1469 goto err;
1471 router->onion_pkey = tok->key;
1472 tok->key = NULL; /* Prevent free */
1474 tok = find_by_keyword(tokens, K_SIGNING_KEY);
1475 router->identity_pkey = tok->key;
1476 tok->key = NULL; /* Prevent free */
1477 if (crypto_pk_get_digest(router->identity_pkey,
1478 router->cache_info.identity_digest)) {
1479 log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
1482 if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
1483 /* If there's a fingerprint line, it must match the identity digest. */
1484 char d[DIGEST_LEN];
1485 tor_assert(tok->n_args == 1);
1486 tor_strstrip(tok->args[0], " ");
1487 if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
1488 log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
1489 escaped(tok->args[0]));
1490 goto err;
1492 if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
1493 log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
1494 tok->args[0]);
1495 goto err;
1499 if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
1500 router->platform = tor_strdup(tok->args[0]);
1503 if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
1504 router->contact_info = tor_strdup(tok->args[0]);
1507 if (find_opt_by_keyword(tokens, K_REJECT6) ||
1508 find_opt_by_keyword(tokens, K_ACCEPT6)) {
1509 log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
1510 "older Tors.");
1511 goto err;
1514 smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
1515 if (or_addresses) {
1516 SMARTLIST_FOREACH_BEGIN(or_addresses, directory_token_t *, t) {
1517 tor_addr_t a;
1518 maskbits_t bits;
1519 uint16_t port_min, port_max;
1520 /* XXXX Prop186 the full spec allows much more than this. */
1521 if (tor_addr_parse_mask_ports(t->args[0], &a, &bits, &port_min,
1522 &port_max) == AF_INET6 &&
1523 bits == 128 &&
1524 port_min == port_max) {
1525 /* Okay, this is one we can understand. */
1526 tor_addr_copy(&router->ipv6_addr, &a);
1527 router->ipv6_orport = port_min;
1528 break;
1530 } SMARTLIST_FOREACH_END(t);
1531 smartlist_free(or_addresses);
1534 exit_policy_tokens = find_all_exitpolicy(tokens);
1535 if (!smartlist_len(exit_policy_tokens)) {
1536 log_warn(LD_DIR, "No exit policy tokens in descriptor.");
1537 goto err;
1539 SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
1540 if (router_add_exit_policy(router,t)<0) {
1541 log_warn(LD_DIR,"Error in exit policy");
1542 goto err;
1544 policy_expand_private(&router->exit_policy);
1545 if (policy_is_reject_star(router->exit_policy))
1546 router->policy_is_reject_star = 1;
1548 if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
1549 int i;
1550 router->declared_family = smartlist_new();
1551 for (i=0;i<tok->n_args;++i) {
1552 if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
1553 log_warn(LD_DIR, "Illegal nickname %s in family line",
1554 escaped(tok->args[i]));
1555 goto err;
1557 smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
1561 if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
1562 router->caches_extra_info = 1;
1564 if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
1565 router->allow_single_hop_exits = 1;
1567 if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
1568 tor_assert(tok->n_args >= 1);
1569 if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
1570 base16_decode(router->cache_info.extra_info_digest,
1571 DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
1572 } else {
1573 log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
1577 if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
1578 router->wants_to_be_hs_dir = 1;
1581 tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
1582 note_crypto_pk_op(VERIFY_RTR);
1583 #ifdef COUNT_DISTINCT_DIGESTS
1584 if (!verified_digests)
1585 verified_digests = digestmap_new();
1586 digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
1587 #endif
1588 if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
1589 "router descriptor") < 0)
1590 goto err;
1592 if (!router->or_port) {
1593 log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
1594 goto err;
1597 if (!router->platform) {
1598 router->platform = tor_strdup("<unknown>");
1601 goto done;
1603 err:
1604 dump_desc(s_dup, "router descriptor");
1605 routerinfo_free(router);
1606 router = NULL;
1607 done:
1608 if (tokens) {
1609 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
1610 smartlist_free(tokens);
1612 smartlist_free(exit_policy_tokens);
1613 if (area) {
1614 DUMP_AREA(area, "routerinfo");
1615 memarea_drop_all(area);
1617 return router;
1620 /** Parse a single extrainfo entry from the string <b>s</b>, ending at
1621 * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
1622 * <b>cache_copy</b> is true, make a copy of the extra-info document in the
1623 * cache_info fields of the result. If <b>routermap</b> is provided, use it
1624 * as a map from router identity to routerinfo_t when looking up signing keys.
1626 extrainfo_t *
1627 extrainfo_parse_entry_from_string(const char *s, const char *end,
1628 int cache_copy, struct digest_ri_map_t *routermap)
1630 extrainfo_t *extrainfo = NULL;
1631 char digest[128];
1632 smartlist_t *tokens = NULL;
1633 directory_token_t *tok;
1634 crypto_pk_t *key = NULL;
1635 routerinfo_t *router = NULL;
1636 memarea_t *area = NULL;
1637 const char *s_dup = s;
1639 if (!end) {
1640 end = s + strlen(s);
1643 /* point 'end' to a point immediately after the final newline. */
1644 while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
1645 --end;
1647 if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
1648 log_warn(LD_DIR, "Couldn't compute router hash.");
1649 goto err;
1651 tokens = smartlist_new();
1652 area = memarea_new();
1653 if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
1654 log_warn(LD_DIR, "Error tokenizing extra-info document.");
1655 goto err;
1658 if (smartlist_len(tokens) < 2) {
1659 log_warn(LD_DIR, "Impossibly short extra-info document.");
1660 goto err;
1663 tok = smartlist_get(tokens,0);
1664 if (tok->tp != K_EXTRA_INFO) {
1665 log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
1666 goto err;
1669 extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
1670 extrainfo->cache_info.is_extrainfo = 1;
1671 if (cache_copy)
1672 extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
1673 extrainfo->cache_info.signed_descriptor_len = end-s;
1674 memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
1676 tor_assert(tok->n_args >= 2);
1677 if (!is_legal_nickname(tok->args[0])) {
1678 log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
1679 goto err;
1681 strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
1682 if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
1683 base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
1684 tok->args[1], HEX_DIGEST_LEN)) {
1685 log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
1686 escaped(tok->args[1]));
1687 goto err;
1690 tok = find_by_keyword(tokens, K_PUBLISHED);
1691 if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
1692 log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
1693 escaped(tok->args[0]));
1694 goto err;
1697 if (routermap &&
1698 (router = digestmap_get((digestmap_t*)routermap,
1699 extrainfo->cache_info.identity_digest))) {
1700 key = router->identity_pkey;
1703 tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
1704 if (strcmp(tok->object_type, "SIGNATURE") ||
1705 tok->object_size < 128 || tok->object_size > 512) {
1706 log_warn(LD_DIR, "Bad object type or length on extra-info signature");
1707 goto err;
1710 if (key) {
1711 note_crypto_pk_op(VERIFY_RTR);
1712 if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
1713 "extra-info") < 0)
1714 goto err;
1716 if (router)
1717 extrainfo->cache_info.send_unencrypted =
1718 router->cache_info.send_unencrypted;
1719 } else {
1720 extrainfo->pending_sig = tor_memdup(tok->object_body,
1721 tok->object_size);
1722 extrainfo->pending_sig_len = tok->object_size;
1725 goto done;
1726 err:
1727 dump_desc(s_dup, "extra-info descriptor");
1728 extrainfo_free(extrainfo);
1729 extrainfo = NULL;
1730 done:
1731 if (tokens) {
1732 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
1733 smartlist_free(tokens);
1735 if (area) {
1736 DUMP_AREA(area, "extrainfo");
1737 memarea_drop_all(area);
1739 return extrainfo;
1742 /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
1743 * the first character after the certificate. */
1744 authority_cert_t *
1745 authority_cert_parse_from_string(const char *s, const char **end_of_string)
1747 /** Reject any certificate at least this big; it is probably an overflow, an
1748 * attack, a bug, or some other nonsense. */
1749 #define MAX_CERT_SIZE (128*1024)
1751 authority_cert_t *cert = NULL, *old_cert;
1752 smartlist_t *tokens = NULL;
1753 char digest[DIGEST_LEN];
1754 directory_token_t *tok;
1755 char fp_declared[DIGEST_LEN];
1756 char *eos;
1757 size_t len;
1758 int found;
1759 memarea_t *area = NULL;
1760 const char *s_dup = s;
1762 s = eat_whitespace(s);
1763 eos = strstr(s, "\ndir-key-certification");
1764 if (! eos) {
1765 log_warn(LD_DIR, "No signature found on key certificate");
1766 return NULL;
1768 eos = strstr(eos, "\n-----END SIGNATURE-----\n");
1769 if (! eos) {
1770 log_warn(LD_DIR, "No end-of-signature found on key certificate");
1771 return NULL;
1773 eos = strchr(eos+2, '\n');
1774 tor_assert(eos);
1775 ++eos;
1776 len = eos - s;
1778 if (len > MAX_CERT_SIZE) {
1779 log_warn(LD_DIR, "Certificate is far too big (at %lu bytes long); "
1780 "rejecting", (unsigned long)len);
1781 return NULL;
1784 tokens = smartlist_new();
1785 area = memarea_new();
1786 if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
1787 log_warn(LD_DIR, "Error tokenizing key certificate");
1788 goto err;
1790 if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
1791 "\ndir-key-certification", '\n', DIGEST_SHA1) < 0)
1792 goto err;
1793 tok = smartlist_get(tokens, 0);
1794 if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
1795 log_warn(LD_DIR,
1796 "Key certificate does not begin with a recognized version (3).");
1797 goto err;
1800 cert = tor_malloc_zero(sizeof(authority_cert_t));
1801 memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
1803 tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
1804 tor_assert(tok->key);
1805 cert->signing_key = tok->key;
1806 tok->key = NULL;
1807 if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
1808 goto err;
1810 tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
1811 tor_assert(tok->key);
1812 cert->identity_key = tok->key;
1813 tok->key = NULL;
1815 tok = find_by_keyword(tokens, K_FINGERPRINT);
1816 tor_assert(tok->n_args);
1817 if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
1818 strlen(tok->args[0]))) {
1819 log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
1820 escaped(tok->args[0]));
1821 goto err;
1824 if (crypto_pk_get_digest(cert->identity_key,
1825 cert->cache_info.identity_digest))
1826 goto err;
1828 if (tor_memneq(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
1829 log_warn(LD_DIR, "Digest of certificate key didn't match declared "
1830 "fingerprint");
1831 goto err;
1834 tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
1835 if (tok) {
1836 struct in_addr in;
1837 char *address = NULL;
1838 tor_assert(tok->n_args);
1839 /* XXX024 use some tor_addr parse function below instead. -RD */
1840 if (tor_addr_port_split(LOG_WARN, tok->args[0], &address,
1841 &cert->dir_port) < 0 ||
1842 tor_inet_aton(address, &in) == 0) {
1843 log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
1844 tor_free(address);
1845 goto err;
1847 cert->addr = ntohl(in.s_addr);
1848 tor_free(address);
1851 tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
1852 if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
1853 goto err;
1855 tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
1856 if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
1857 goto err;
1860 tok = smartlist_get(tokens, smartlist_len(tokens)-1);
1861 if (tok->tp != K_DIR_KEY_CERTIFICATION) {
1862 log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
1863 goto err;
1866 /* If we already have this cert, don't bother checking the signature. */
1867 old_cert = authority_cert_get_by_digests(
1868 cert->cache_info.identity_digest,
1869 cert->signing_key_digest);
1870 found = 0;
1871 if (old_cert) {
1872 /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
1873 * buy us much. */
1874 if (old_cert->cache_info.signed_descriptor_len == len &&
1875 old_cert->cache_info.signed_descriptor_body &&
1876 tor_memeq(s, old_cert->cache_info.signed_descriptor_body, len)) {
1877 log_debug(LD_DIR, "We already checked the signature on this "
1878 "certificate; no need to do so again.");
1879 found = 1;
1880 cert->is_cross_certified = old_cert->is_cross_certified;
1883 if (!found) {
1884 if (check_signature_token(digest, DIGEST_LEN, tok, cert->identity_key, 0,
1885 "key certificate")) {
1886 goto err;
1889 if ((tok = find_opt_by_keyword(tokens, K_DIR_KEY_CROSSCERT))) {
1890 /* XXXX Once all authorities generate cross-certified certificates,
1891 * make this field mandatory. */
1892 if (check_signature_token(cert->cache_info.identity_digest,
1893 DIGEST_LEN,
1894 tok,
1895 cert->signing_key,
1896 CST_NO_CHECK_OBJTYPE,
1897 "key cross-certification")) {
1898 goto err;
1900 cert->is_cross_certified = 1;
1904 cert->cache_info.signed_descriptor_len = len;
1905 cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
1906 memcpy(cert->cache_info.signed_descriptor_body, s, len);
1907 cert->cache_info.signed_descriptor_body[len] = 0;
1908 cert->cache_info.saved_location = SAVED_NOWHERE;
1910 if (end_of_string) {
1911 *end_of_string = eat_whitespace(eos);
1913 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
1914 smartlist_free(tokens);
1915 if (area) {
1916 DUMP_AREA(area, "authority cert");
1917 memarea_drop_all(area);
1919 return cert;
1920 err:
1921 dump_desc(s_dup, "authority cert");
1922 authority_cert_free(cert);
1923 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
1924 smartlist_free(tokens);
1925 if (area) {
1926 DUMP_AREA(area, "authority cert");
1927 memarea_drop_all(area);
1929 return NULL;
1932 /** Helper: given a string <b>s</b>, return the start of the next router-status
1933 * object (starting with "r " at the start of a line). If none is found,
1934 * return the start of the directory footer, or the next directory signature.
1935 * If none is found, return the end of the string. */
1936 static INLINE const char *
1937 find_start_of_next_routerstatus(const char *s)
1939 const char *eos, *footer, *sig;
1940 if ((eos = strstr(s, "\nr ")))
1941 ++eos;
1942 else
1943 eos = s + strlen(s);
1945 footer = tor_memstr(s, eos-s, "\ndirectory-footer");
1946 sig = tor_memstr(s, eos-s, "\ndirectory-signature");
1948 if (footer && sig)
1949 return MIN(footer, sig) + 1;
1950 else if (footer)
1951 return footer+1;
1952 else if (sig)
1953 return sig+1;
1954 else
1955 return eos;
1958 /** Given a string at *<b>s</b>, containing a routerstatus object, and an
1959 * empty smartlist at <b>tokens</b>, parse and return the first router status
1960 * object in the string, and advance *<b>s</b> to just after the end of the
1961 * router status. Return NULL and advance *<b>s</b> on error.
1963 * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
1964 * routerstatus but use <b>vote_rs</b> instead.
1966 * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
1967 * consensus, and we should parse it according to the method used to
1968 * make that consensus.
1970 * Parse according to the syntax used by the consensus flavor <b>flav</b>.
1972 static routerstatus_t *
1973 routerstatus_parse_entry_from_string(memarea_t *area,
1974 const char **s, smartlist_t *tokens,
1975 networkstatus_t *vote,
1976 vote_routerstatus_t *vote_rs,
1977 int consensus_method,
1978 consensus_flavor_t flav)
1980 const char *eos, *s_dup = *s;
1981 routerstatus_t *rs = NULL;
1982 directory_token_t *tok;
1983 char timebuf[ISO_TIME_LEN+1];
1984 struct in_addr in;
1985 int offset = 0;
1986 tor_assert(tokens);
1987 tor_assert(bool_eq(vote, vote_rs));
1989 if (!consensus_method)
1990 flav = FLAV_NS;
1991 tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
1993 eos = find_start_of_next_routerstatus(*s);
1995 if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
1996 log_warn(LD_DIR, "Error tokenizing router status");
1997 goto err;
1999 if (smartlist_len(tokens) < 1) {
2000 log_warn(LD_DIR, "Impossibly short router status");
2001 goto err;
2003 tok = find_by_keyword(tokens, K_R);
2004 tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
2005 if (flav == FLAV_NS) {
2006 if (tok->n_args < 8) {
2007 log_warn(LD_DIR, "Too few arguments to r");
2008 goto err;
2010 } else if (flav == FLAV_MICRODESC) {
2011 offset = -1; /* There is no identity digest */
2014 if (vote_rs) {
2015 rs = &vote_rs->status;
2016 } else {
2017 rs = tor_malloc_zero(sizeof(routerstatus_t));
2020 if (!is_legal_nickname(tok->args[0])) {
2021 log_warn(LD_DIR,
2022 "Invalid nickname %s in router status; skipping.",
2023 escaped(tok->args[0]));
2024 goto err;
2026 strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
2028 if (digest_from_base64(rs->identity_digest, tok->args[1])) {
2029 log_warn(LD_DIR, "Error decoding identity digest %s",
2030 escaped(tok->args[1]));
2031 goto err;
2034 if (flav == FLAV_NS) {
2035 if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
2036 log_warn(LD_DIR, "Error decoding descriptor digest %s",
2037 escaped(tok->args[2]));
2038 goto err;
2042 if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
2043 tok->args[3+offset], tok->args[4+offset]) < 0 ||
2044 parse_iso_time(timebuf, &rs->published_on)<0) {
2045 log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
2046 tok->args[3+offset], tok->args[4+offset],
2047 offset, (int)flav);
2048 goto err;
2051 if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
2052 log_warn(LD_DIR, "Error parsing router address in network-status %s",
2053 escaped(tok->args[5+offset]));
2054 goto err;
2056 rs->addr = ntohl(in.s_addr);
2058 rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
2059 10,0,65535,NULL,NULL);
2060 rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
2061 10,0,65535,NULL,NULL);
2063 tok = find_opt_by_keyword(tokens, K_S);
2064 if (tok && vote) {
2065 int i;
2066 vote_rs->flags = 0;
2067 for (i=0; i < tok->n_args; ++i) {
2068 int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
2069 if (p >= 0) {
2070 vote_rs->flags |= (1<<p);
2071 } else {
2072 log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
2073 escaped(tok->args[i]));
2074 goto err;
2077 } else if (tok) {
2078 int i;
2079 for (i=0; i < tok->n_args; ++i) {
2080 if (!strcmp(tok->args[i], "Exit"))
2081 rs->is_exit = 1;
2082 else if (!strcmp(tok->args[i], "Stable"))
2083 rs->is_stable = 1;
2084 else if (!strcmp(tok->args[i], "Fast"))
2085 rs->is_fast = 1;
2086 else if (!strcmp(tok->args[i], "Running"))
2087 rs->is_flagged_running = 1;
2088 else if (!strcmp(tok->args[i], "Named"))
2089 rs->is_named = 1;
2090 else if (!strcmp(tok->args[i], "Valid"))
2091 rs->is_valid = 1;
2092 else if (!strcmp(tok->args[i], "V2Dir"))
2093 rs->is_v2_dir = 1;
2094 else if (!strcmp(tok->args[i], "Guard"))
2095 rs->is_possible_guard = 1;
2096 else if (!strcmp(tok->args[i], "BadExit"))
2097 rs->is_bad_exit = 1;
2098 else if (!strcmp(tok->args[i], "BadDirectory"))
2099 rs->is_bad_directory = 1;
2100 else if (!strcmp(tok->args[i], "Authority"))
2101 rs->is_authority = 1;
2102 else if (!strcmp(tok->args[i], "Unnamed") &&
2103 consensus_method >= 2) {
2104 /* Unnamed is computed right by consensus method 2 and later. */
2105 rs->is_unnamed = 1;
2106 } else if (!strcmp(tok->args[i], "HSDir")) {
2107 rs->is_hs_dir = 1;
2111 if ((tok = find_opt_by_keyword(tokens, K_V))) {
2112 tor_assert(tok->n_args == 1);
2113 rs->version_known = 1;
2114 if (strcmpstart(tok->args[0], "Tor ")) {
2115 rs->version_supports_begindir = 1;
2116 rs->version_supports_extrainfo_upload = 1;
2117 rs->version_supports_conditional_consensus = 1;
2118 rs->version_supports_microdesc_cache = 1;
2119 rs->version_supports_optimistic_data = 1;
2120 } else {
2121 rs->version_supports_begindir =
2122 tor_version_as_new_as(tok->args[0], "0.2.0.1-alpha");
2123 rs->version_supports_extrainfo_upload =
2124 tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
2125 rs->version_supports_v3_dir =
2126 tor_version_as_new_as(tok->args[0], "0.2.0.8-alpha");
2127 rs->version_supports_conditional_consensus =
2128 tor_version_as_new_as(tok->args[0], "0.2.1.1-alpha");
2129 rs->version_supports_microdesc_cache =
2130 tor_version_supports_microdescriptors(tok->args[0]);
2131 rs->version_supports_optimistic_data =
2132 tor_version_as_new_as(tok->args[0], "0.2.3.1-alpha");
2134 if (vote_rs) {
2135 vote_rs->version = tor_strdup(tok->args[0]);
2139 /* handle weighting/bandwidth info */
2140 if ((tok = find_opt_by_keyword(tokens, K_W))) {
2141 int i;
2142 for (i=0; i < tok->n_args; ++i) {
2143 if (!strcmpstart(tok->args[i], "Bandwidth=")) {
2144 int ok;
2145 rs->bandwidth = (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
2146 10, 0, UINT32_MAX,
2147 &ok, NULL);
2148 if (!ok) {
2149 log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
2150 goto err;
2152 rs->has_bandwidth = 1;
2153 } else if (!strcmpstart(tok->args[i], "Measured=")) {
2154 int ok;
2155 rs->measured_bw =
2156 (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
2157 10, 0, UINT32_MAX, &ok, NULL);
2158 if (!ok) {
2159 log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
2160 escaped(tok->args[i]));
2161 goto err;
2163 rs->has_measured_bw = 1;
2168 /* parse exit policy summaries */
2169 if ((tok = find_opt_by_keyword(tokens, K_P))) {
2170 tor_assert(tok->n_args == 1);
2171 if (strcmpstart(tok->args[0], "accept ") &&
2172 strcmpstart(tok->args[0], "reject ")) {
2173 log_warn(LD_DIR, "Unknown exit policy summary type %s.",
2174 escaped(tok->args[0]));
2175 goto err;
2177 /* XXX weasel: parse this into ports and represent them somehow smart,
2178 * maybe not here but somewhere on if we need it for the client.
2179 * we should still parse it here to check it's valid tho.
2181 rs->exitsummary = tor_strdup(tok->args[0]);
2182 rs->has_exitsummary = 1;
2185 if (vote_rs) {
2186 SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
2187 if (t->tp == K_M && t->n_args) {
2188 vote_microdesc_hash_t *line =
2189 tor_malloc(sizeof(vote_microdesc_hash_t));
2190 line->next = vote_rs->microdesc;
2191 line->microdesc_hash_line = tor_strdup(t->args[0]);
2192 vote_rs->microdesc = line;
2194 } SMARTLIST_FOREACH_END(t);
2195 } else if (flav == FLAV_MICRODESC) {
2196 tok = find_opt_by_keyword(tokens, K_M);
2197 if (tok) {
2198 tor_assert(tok->n_args);
2199 if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
2200 log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
2201 escaped(tok->args[0]));
2202 goto err;
2204 } else {
2205 log_info(LD_BUG, "Found an entry in networkstatus with no "
2206 "microdescriptor digest. (Router %s=%s at %s:%d.)",
2207 rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
2208 fmt_addr32(rs->addr), rs->or_port);
2212 if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
2213 rs->is_named = 0;
2215 goto done;
2216 err:
2217 dump_desc(s_dup, "routerstatus entry");
2218 if (rs && !vote_rs)
2219 routerstatus_free(rs);
2220 rs = NULL;
2221 done:
2222 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2223 smartlist_clear(tokens);
2224 if (area) {
2225 DUMP_AREA(area, "routerstatus entry");
2226 memarea_clear(area);
2228 *s = eos;
2230 return rs;
2233 /** Helper to sort a smartlist of pointers to routerstatus_t */
2235 compare_routerstatus_entries(const void **_a, const void **_b)
2237 const routerstatus_t *a = *_a, *b = *_b;
2238 return fast_memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
2241 /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
2242 static void
2243 _free_duplicate_routerstatus_entry(void *e)
2245 log_warn(LD_DIR,
2246 "Network-status has two entries for the same router. "
2247 "Dropping one.");
2248 routerstatus_free(e);
2251 /** Given a v2 network-status object in <b>s</b>, try to
2252 * parse it and return the result. Return NULL on failure. Check the
2253 * signature of the network status, but do not (yet) check the signing key for
2254 * authority.
2256 networkstatus_v2_t *
2257 networkstatus_v2_parse_from_string(const char *s)
2259 const char *eos, *s_dup = s;
2260 smartlist_t *tokens = smartlist_new();
2261 smartlist_t *footer_tokens = smartlist_new();
2262 networkstatus_v2_t *ns = NULL;
2263 char ns_digest[DIGEST_LEN];
2264 char tmp_digest[DIGEST_LEN];
2265 struct in_addr in;
2266 directory_token_t *tok;
2267 int i;
2268 memarea_t *area = NULL;
2270 if (router_get_networkstatus_v2_hash(s, ns_digest)) {
2271 log_warn(LD_DIR, "Unable to compute digest of network-status");
2272 goto err;
2275 area = memarea_new();
2276 eos = find_start_of_next_routerstatus(s);
2277 if (tokenize_string(area, s, eos, tokens, netstatus_token_table,0)) {
2278 log_warn(LD_DIR, "Error tokenizing network-status header.");
2279 goto err;
2281 ns = tor_malloc_zero(sizeof(networkstatus_v2_t));
2282 memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
2284 tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
2285 tor_assert(tok->n_args >= 1);
2286 if (strcmp(tok->args[0], "2")) {
2287 log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
2288 "%s", escaped(tok->args[0]));
2289 goto err;
2292 tok = find_by_keyword(tokens, K_DIR_SOURCE);
2293 tor_assert(tok->n_args >= 3);
2294 ns->source_address = tor_strdup(tok->args[0]);
2295 if (tor_inet_aton(tok->args[1], &in) == 0) {
2296 log_warn(LD_DIR, "Error parsing network-status source address %s",
2297 escaped(tok->args[1]));
2298 goto err;
2300 ns->source_addr = ntohl(in.s_addr);
2301 ns->source_dirport =
2302 (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
2303 if (ns->source_dirport == 0) {
2304 log_warn(LD_DIR, "Directory source without dirport; skipping.");
2305 goto err;
2308 tok = find_by_keyword(tokens, K_FINGERPRINT);
2309 tor_assert(tok->n_args);
2310 if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
2311 strlen(tok->args[0]))) {
2312 log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
2313 escaped(tok->args[0]));
2314 goto err;
2317 if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
2318 tor_assert(tok->n_args);
2319 ns->contact = tor_strdup(tok->args[0]);
2322 tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
2323 tor_assert(tok->key);
2324 ns->signing_key = tok->key;
2325 tok->key = NULL;
2327 if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
2328 log_warn(LD_DIR, "Couldn't compute signing key digest");
2329 goto err;
2331 if (tor_memneq(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
2332 log_warn(LD_DIR,
2333 "network-status fingerprint did not match dir-signing-key");
2334 goto err;
2337 if ((tok = find_opt_by_keyword(tokens, K_DIR_OPTIONS))) {
2338 for (i=0; i < tok->n_args; ++i) {
2339 if (!strcmp(tok->args[i], "Names"))
2340 ns->binds_names = 1;
2341 if (!strcmp(tok->args[i], "Versions"))
2342 ns->recommends_versions = 1;
2343 if (!strcmp(tok->args[i], "BadExits"))
2344 ns->lists_bad_exits = 1;
2345 if (!strcmp(tok->args[i], "BadDirectories"))
2346 ns->lists_bad_directories = 1;
2350 if (ns->recommends_versions) {
2351 if (!(tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
2352 log_warn(LD_DIR, "Missing client-versions on versioning directory");
2353 goto err;
2355 ns->client_versions = tor_strdup(tok->args[0]);
2357 if (!(tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS)) ||
2358 tok->n_args<1) {
2359 log_warn(LD_DIR, "Missing server-versions on versioning directory");
2360 goto err;
2362 ns->server_versions = tor_strdup(tok->args[0]);
2365 tok = find_by_keyword(tokens, K_PUBLISHED);
2366 tor_assert(tok->n_args == 1);
2367 if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
2368 goto err;
2371 ns->entries = smartlist_new();
2372 s = eos;
2373 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2374 smartlist_clear(tokens);
2375 memarea_clear(area);
2376 while (!strcmpstart(s, "r ")) {
2377 routerstatus_t *rs;
2378 if ((rs = routerstatus_parse_entry_from_string(area, &s, tokens,
2379 NULL, NULL, 0, 0)))
2380 smartlist_add(ns->entries, rs);
2382 smartlist_sort(ns->entries, compare_routerstatus_entries);
2383 smartlist_uniq(ns->entries, compare_routerstatus_entries,
2384 _free_duplicate_routerstatus_entry);
2386 if (tokenize_string(area,s, NULL, footer_tokens, dir_footer_token_table,0)) {
2387 log_warn(LD_DIR, "Error tokenizing network-status footer.");
2388 goto err;
2390 if (smartlist_len(footer_tokens) < 1) {
2391 log_warn(LD_DIR, "Too few items in network-status footer.");
2392 goto err;
2394 tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
2395 if (tok->tp != K_DIRECTORY_SIGNATURE) {
2396 log_warn(LD_DIR,
2397 "Expected network-status footer to end with a signature.");
2398 goto err;
2401 note_crypto_pk_op(VERIFY_DIR);
2402 if (check_signature_token(ns_digest, DIGEST_LEN, tok, ns->signing_key, 0,
2403 "network-status") < 0)
2404 goto err;
2406 goto done;
2407 err:
2408 dump_desc(s_dup, "v2 networkstatus");
2409 networkstatus_v2_free(ns);
2410 ns = NULL;
2411 done:
2412 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2413 smartlist_free(tokens);
2414 SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
2415 smartlist_free(footer_tokens);
2416 if (area) {
2417 DUMP_AREA(area, "v2 networkstatus");
2418 memarea_drop_all(area);
2420 return ns;
2423 /** Verify the bandwidth weights of a network status document */
2425 networkstatus_verify_bw_weights(networkstatus_t *ns)
2427 int64_t weight_scale;
2428 int64_t G=0, M=0, E=0, D=0, T=0;
2429 double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
2430 double Gtotal=0, Mtotal=0, Etotal=0;
2431 const char *casename = NULL;
2432 int valid = 1;
2434 weight_scale = circuit_build_times_get_bw_scale(ns);
2435 Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
2436 Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
2437 Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
2438 Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
2439 Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
2440 Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
2441 Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
2442 Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
2443 Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
2444 Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
2445 Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
2447 if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
2448 || Wem<0 || Wee<0 || Wed<0) {
2449 log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
2450 return 0;
2453 // First, sanity check basic summing properties that hold for all cases
2454 // We use > 1 as the check for these because they are computed as integers.
2455 // Sometimes there are rounding errors.
2456 if (fabs(Wmm - weight_scale) > 1) {
2457 log_warn(LD_BUG, "Wmm=%f != "I64_FORMAT,
2458 Wmm, I64_PRINTF_ARG(weight_scale));
2459 valid = 0;
2462 if (fabs(Wem - Wee) > 1) {
2463 log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
2464 valid = 0;
2467 if (fabs(Wgm - Wgg) > 1) {
2468 log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
2469 valid = 0;
2472 if (fabs(Weg - Wed) > 1) {
2473 log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
2474 valid = 0;
2477 if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
2478 log_warn(LD_BUG, "Wgg=%f != "I64_FORMAT" - Wmg=%f", Wgg,
2479 I64_PRINTF_ARG(weight_scale), Wmg);
2480 valid = 0;
2483 if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
2484 log_warn(LD_BUG, "Wee=%f != "I64_FORMAT" - Wme=%f", Wee,
2485 I64_PRINTF_ARG(weight_scale), Wme);
2486 valid = 0;
2489 if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
2490 log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != "I64_FORMAT,
2491 Wgd, Wmd, Wed, I64_PRINTF_ARG(weight_scale));
2492 valid = 0;
2495 Wgg /= weight_scale;
2496 Wgm /= weight_scale;
2497 Wgd /= weight_scale;
2499 Wmg /= weight_scale;
2500 Wmm /= weight_scale;
2501 Wme /= weight_scale;
2502 Wmd /= weight_scale;
2504 Weg /= weight_scale;
2505 Wem /= weight_scale;
2506 Wee /= weight_scale;
2507 Wed /= weight_scale;
2509 // Then, gather G, M, E, D, T to determine case
2510 SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
2511 if (rs->has_bandwidth) {
2512 T += rs->bandwidth;
2513 if (rs->is_exit && rs->is_possible_guard) {
2514 D += rs->bandwidth;
2515 Gtotal += Wgd*rs->bandwidth;
2516 Mtotal += Wmd*rs->bandwidth;
2517 Etotal += Wed*rs->bandwidth;
2518 } else if (rs->is_exit) {
2519 E += rs->bandwidth;
2520 Mtotal += Wme*rs->bandwidth;
2521 Etotal += Wee*rs->bandwidth;
2522 } else if (rs->is_possible_guard) {
2523 G += rs->bandwidth;
2524 Gtotal += Wgg*rs->bandwidth;
2525 Mtotal += Wmg*rs->bandwidth;
2526 } else {
2527 M += rs->bandwidth;
2528 Mtotal += Wmm*rs->bandwidth;
2530 } else {
2531 log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
2532 routerstatus_describe(rs));
2534 } SMARTLIST_FOREACH_END(rs);
2536 // Finally, check equality conditions depending upon case 1, 2 or 3
2537 // Full equality cases: 1, 3b
2538 // Partial equality cases: 2b (E=G), 3a (M=E)
2539 // Fully unknown: 2a
2540 if (3*E >= T && 3*G >= T) {
2541 // Case 1: Neither are scarce
2542 casename = "Case 1";
2543 if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
2544 log_warn(LD_DIR,
2545 "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
2546 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2547 " T="I64_FORMAT". "
2548 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2549 casename, Etotal, Mtotal,
2550 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2551 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2552 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2553 valid = 0;
2555 if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
2556 log_warn(LD_DIR,
2557 "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
2558 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2559 " T="I64_FORMAT". "
2560 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2561 casename, Etotal, Gtotal,
2562 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2563 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2564 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2565 valid = 0;
2567 if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
2568 log_warn(LD_DIR,
2569 "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
2570 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2571 " T="I64_FORMAT". "
2572 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2573 casename, Mtotal, Gtotal,
2574 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2575 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2576 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2577 valid = 0;
2579 } else if (3*E < T && 3*G < T) {
2580 int64_t R = MIN(E, G);
2581 int64_t S = MAX(E, G);
2583 * Case 2: Both Guards and Exits are scarce
2584 * Balance D between E and G, depending upon
2585 * D capacity and scarcity. Devote no extra
2586 * bandwidth to middle nodes.
2588 if (R+D < S) { // Subcase a
2589 double Rtotal, Stotal;
2590 if (E < G) {
2591 Rtotal = Etotal;
2592 Stotal = Gtotal;
2593 } else {
2594 Rtotal = Gtotal;
2595 Stotal = Etotal;
2597 casename = "Case 2a";
2598 // Rtotal < Stotal
2599 if (Rtotal > Stotal) {
2600 log_warn(LD_DIR,
2601 "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
2602 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2603 " T="I64_FORMAT". "
2604 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2605 casename, Rtotal, Stotal,
2606 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2607 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2608 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2609 valid = 0;
2611 // Rtotal < T/3
2612 if (3*Rtotal > T) {
2613 log_warn(LD_DIR,
2614 "Bw Weight Failure for %s: 3*Rtotal %f > T "
2615 I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
2616 " D="I64_FORMAT" T="I64_FORMAT". "
2617 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2618 casename, Rtotal*3, I64_PRINTF_ARG(T),
2619 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2620 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2621 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2622 valid = 0;
2624 // Stotal < T/3
2625 if (3*Stotal > T) {
2626 log_warn(LD_DIR,
2627 "Bw Weight Failure for %s: 3*Stotal %f > T "
2628 I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
2629 " D="I64_FORMAT" T="I64_FORMAT". "
2630 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2631 casename, Stotal*3, I64_PRINTF_ARG(T),
2632 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2633 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2634 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2635 valid = 0;
2637 // Mtotal > T/3
2638 if (3*Mtotal < T) {
2639 log_warn(LD_DIR,
2640 "Bw Weight Failure for %s: 3*Mtotal %f < T "
2641 I64_FORMAT". "
2642 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2643 " T="I64_FORMAT". "
2644 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2645 casename, Mtotal*3, I64_PRINTF_ARG(T),
2646 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2647 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2648 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2649 valid = 0;
2651 } else { // Subcase b: R+D > S
2652 casename = "Case 2b";
2654 /* Check the rare-M redirect case. */
2655 if (D != 0 && 3*M < T) {
2656 casename = "Case 2b (balanced)";
2657 if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
2658 log_warn(LD_DIR,
2659 "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
2660 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2661 " T="I64_FORMAT". "
2662 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2663 casename, Etotal, Mtotal,
2664 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2665 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2666 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2667 valid = 0;
2669 if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
2670 log_warn(LD_DIR,
2671 "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
2672 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2673 " T="I64_FORMAT". "
2674 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2675 casename, Etotal, Gtotal,
2676 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2677 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2678 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2679 valid = 0;
2681 if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
2682 log_warn(LD_DIR,
2683 "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
2684 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2685 " T="I64_FORMAT". "
2686 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2687 casename, Mtotal, Gtotal,
2688 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2689 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2690 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2691 valid = 0;
2693 } else {
2694 if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
2695 log_warn(LD_DIR,
2696 "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
2697 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2698 " T="I64_FORMAT". "
2699 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2700 casename, Etotal, Gtotal,
2701 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2702 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2703 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2704 valid = 0;
2708 } else { // if (E < T/3 || G < T/3) {
2709 int64_t S = MIN(E, G);
2710 int64_t NS = MAX(E, G);
2711 if (3*(S+D) < T) { // Subcase a:
2712 double Stotal;
2713 double NStotal;
2714 if (G < E) {
2715 casename = "Case 3a (G scarce)";
2716 Stotal = Gtotal;
2717 NStotal = Etotal;
2718 } else { // if (G >= E) {
2719 casename = "Case 3a (E scarce)";
2720 NStotal = Gtotal;
2721 Stotal = Etotal;
2723 // Stotal < T/3
2724 if (3*Stotal > T) {
2725 log_warn(LD_DIR,
2726 "Bw Weight Failure for %s: 3*Stotal %f > T "
2727 I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
2728 " D="I64_FORMAT" T="I64_FORMAT". "
2729 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2730 casename, Stotal*3, I64_PRINTF_ARG(T),
2731 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2732 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2733 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2734 valid = 0;
2736 if (NS >= M) {
2737 if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
2738 log_warn(LD_DIR,
2739 "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
2740 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2741 " T="I64_FORMAT". "
2742 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2743 casename, NStotal, Mtotal,
2744 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2745 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2746 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2747 valid = 0;
2749 } else {
2750 // if NS < M, NStotal > T/3 because only one of G or E is scarce
2751 if (3*NStotal < T) {
2752 log_warn(LD_DIR,
2753 "Bw Weight Failure for %s: 3*NStotal %f < T "
2754 I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT
2755 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT". "
2756 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2757 casename, NStotal*3, I64_PRINTF_ARG(T),
2758 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2759 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2760 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2761 valid = 0;
2764 } else { // Subcase b: S+D >= T/3
2765 casename = "Case 3b";
2766 if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
2767 log_warn(LD_DIR,
2768 "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
2769 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2770 " T="I64_FORMAT". "
2771 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2772 casename, Etotal, Mtotal,
2773 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2774 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2775 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2776 valid = 0;
2778 if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
2779 log_warn(LD_DIR,
2780 "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
2781 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2782 " T="I64_FORMAT". "
2783 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2784 casename, Etotal, Gtotal,
2785 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2786 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2787 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2788 valid = 0;
2790 if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
2791 log_warn(LD_DIR,
2792 "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
2793 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2794 " T="I64_FORMAT". "
2795 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2796 casename, Mtotal, Gtotal,
2797 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2798 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2799 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2800 valid = 0;
2805 if (valid)
2806 log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
2807 casename);
2809 return valid;
2812 /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
2813 * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
2814 networkstatus_t *
2815 networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
2816 networkstatus_type_t ns_type)
2818 smartlist_t *tokens = smartlist_new();
2819 smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
2820 networkstatus_voter_info_t *voter = NULL;
2821 networkstatus_t *ns = NULL;
2822 digests_t ns_digests;
2823 const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
2824 directory_token_t *tok;
2825 int ok;
2826 struct in_addr in;
2827 int i, inorder, n_signatures = 0;
2828 memarea_t *area = NULL, *rs_area = NULL;
2829 consensus_flavor_t flav = FLAV_NS;
2830 char *last_kwd=NULL;
2832 tor_assert(s);
2834 if (eos_out)
2835 *eos_out = NULL;
2837 if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
2838 log_warn(LD_DIR, "Unable to compute digest of network-status");
2839 goto err;
2842 area = memarea_new();
2843 end_of_header = find_start_of_next_routerstatus(s);
2844 if (tokenize_string(area, s, end_of_header, tokens,
2845 (ns_type == NS_TYPE_CONSENSUS) ?
2846 networkstatus_consensus_token_table :
2847 networkstatus_token_table, 0)) {
2848 log_warn(LD_DIR, "Error tokenizing network-status vote header");
2849 goto err;
2852 ns = tor_malloc_zero(sizeof(networkstatus_t));
2853 memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
2855 tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
2856 tor_assert(tok);
2857 if (tok->n_args > 1) {
2858 int flavor = networkstatus_parse_flavor_name(tok->args[1]);
2859 if (flavor < 0) {
2860 log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
2861 escaped(tok->args[1]));
2862 goto err;
2864 ns->flavor = flav = flavor;
2866 if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
2867 log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
2868 goto err;
2871 if (ns_type != NS_TYPE_CONSENSUS) {
2872 const char *end_of_cert = NULL;
2873 if (!(cert = strstr(s, "\ndir-key-certificate-version")))
2874 goto err;
2875 ++cert;
2876 ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
2877 if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
2878 goto err;
2881 tok = find_by_keyword(tokens, K_VOTE_STATUS);
2882 tor_assert(tok->n_args);
2883 if (!strcmp(tok->args[0], "vote")) {
2884 ns->type = NS_TYPE_VOTE;
2885 } else if (!strcmp(tok->args[0], "consensus")) {
2886 ns->type = NS_TYPE_CONSENSUS;
2887 } else if (!strcmp(tok->args[0], "opinion")) {
2888 ns->type = NS_TYPE_OPINION;
2889 } else {
2890 log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
2891 escaped(tok->args[0]));
2892 goto err;
2894 if (ns_type != ns->type) {
2895 log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
2896 goto err;
2899 if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
2900 tok = find_by_keyword(tokens, K_PUBLISHED);
2901 if (parse_iso_time(tok->args[0], &ns->published))
2902 goto err;
2904 ns->supported_methods = smartlist_new();
2905 tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
2906 if (tok) {
2907 for (i=0; i < tok->n_args; ++i)
2908 smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
2909 } else {
2910 smartlist_add(ns->supported_methods, tor_strdup("1"));
2912 } else {
2913 tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
2914 if (tok) {
2915 ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
2916 &ok, NULL);
2917 if (!ok)
2918 goto err;
2919 } else {
2920 ns->consensus_method = 1;
2924 tok = find_by_keyword(tokens, K_VALID_AFTER);
2925 if (parse_iso_time(tok->args[0], &ns->valid_after))
2926 goto err;
2928 tok = find_by_keyword(tokens, K_FRESH_UNTIL);
2929 if (parse_iso_time(tok->args[0], &ns->fresh_until))
2930 goto err;
2932 tok = find_by_keyword(tokens, K_VALID_UNTIL);
2933 if (parse_iso_time(tok->args[0], &ns->valid_until))
2934 goto err;
2936 tok = find_by_keyword(tokens, K_VOTING_DELAY);
2937 tor_assert(tok->n_args >= 2);
2938 ns->vote_seconds =
2939 (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
2940 if (!ok)
2941 goto err;
2942 ns->dist_seconds =
2943 (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
2944 if (!ok)
2945 goto err;
2946 if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
2947 log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
2948 goto err;
2950 if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
2951 log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
2952 goto err;
2954 if (ns->vote_seconds < MIN_VOTE_SECONDS) {
2955 log_warn(LD_DIR, "Vote seconds is too short");
2956 goto err;
2958 if (ns->dist_seconds < MIN_DIST_SECONDS) {
2959 log_warn(LD_DIR, "Dist seconds is too short");
2960 goto err;
2963 if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
2964 ns->client_versions = tor_strdup(tok->args[0]);
2966 if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
2967 ns->server_versions = tor_strdup(tok->args[0]);
2970 tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
2971 ns->known_flags = smartlist_new();
2972 inorder = 1;
2973 for (i = 0; i < tok->n_args; ++i) {
2974 smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
2975 if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
2976 log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
2977 inorder = 0;
2980 if (!inorder) {
2981 log_warn(LD_DIR, "known-flags not in order");
2982 goto err;
2985 tok = find_opt_by_keyword(tokens, K_PARAMS);
2986 if (tok) {
2987 int any_dups = 0;
2988 inorder = 1;
2989 ns->net_params = smartlist_new();
2990 for (i = 0; i < tok->n_args; ++i) {
2991 int ok=0;
2992 char *eq = strchr(tok->args[i], '=');
2993 size_t eq_pos;
2994 if (!eq) {
2995 log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
2996 goto err;
2998 eq_pos = eq-tok->args[i];
2999 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
3000 if (!ok) {
3001 log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
3002 goto err;
3004 if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
3005 log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
3006 inorder = 0;
3008 if (last_kwd && eq_pos == strlen(last_kwd) &&
3009 fast_memeq(last_kwd, tok->args[i], eq_pos)) {
3010 log_warn(LD_DIR, "Duplicate value for %s parameter",
3011 escaped(tok->args[i]));
3012 any_dups = 1;
3014 tor_free(last_kwd);
3015 last_kwd = tor_strndup(tok->args[i], eq_pos);
3016 smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
3018 if (!inorder) {
3019 log_warn(LD_DIR, "params not in order");
3020 goto err;
3022 if (any_dups) {
3023 log_warn(LD_DIR, "Duplicate in parameters");
3024 goto err;
3028 ns->voters = smartlist_new();
3030 SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
3031 tok = _tok;
3032 if (tok->tp == K_DIR_SOURCE) {
3033 tor_assert(tok->n_args >= 6);
3035 if (voter)
3036 smartlist_add(ns->voters, voter);
3037 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
3038 voter->sigs = smartlist_new();
3039 if (ns->type != NS_TYPE_CONSENSUS)
3040 memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
3042 voter->nickname = tor_strdup(tok->args[0]);
3043 if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
3044 base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
3045 tok->args[1], HEX_DIGEST_LEN) < 0) {
3046 log_warn(LD_DIR, "Error decoding identity digest %s in "
3047 "network-status vote.", escaped(tok->args[1]));
3048 goto err;
3050 if (ns->type != NS_TYPE_CONSENSUS &&
3051 tor_memneq(ns->cert->cache_info.identity_digest,
3052 voter->identity_digest, DIGEST_LEN)) {
3053 log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
3054 goto err;
3056 voter->address = tor_strdup(tok->args[2]);
3057 if (!tor_inet_aton(tok->args[3], &in)) {
3058 log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
3059 escaped(tok->args[3]));
3060 goto err;
3062 voter->addr = ntohl(in.s_addr);
3063 voter->dir_port = (uint16_t)
3064 tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
3065 if (!ok)
3066 goto err;
3067 voter->or_port = (uint16_t)
3068 tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
3069 if (!ok)
3070 goto err;
3071 } else if (tok->tp == K_CONTACT) {
3072 if (!voter || voter->contact) {
3073 log_warn(LD_DIR, "contact element is out of place.");
3074 goto err;
3076 voter->contact = tor_strdup(tok->args[0]);
3077 } else if (tok->tp == K_VOTE_DIGEST) {
3078 tor_assert(ns->type == NS_TYPE_CONSENSUS);
3079 tor_assert(tok->n_args >= 1);
3080 if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
3081 log_warn(LD_DIR, "vote-digest element is out of place.");
3082 goto err;
3084 if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
3085 base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
3086 tok->args[0], HEX_DIGEST_LEN) < 0) {
3087 log_warn(LD_DIR, "Error decoding vote digest %s in "
3088 "network-status consensus.", escaped(tok->args[0]));
3089 goto err;
3092 } SMARTLIST_FOREACH_END(_tok);
3093 if (voter) {
3094 smartlist_add(ns->voters, voter);
3095 voter = NULL;
3097 if (smartlist_len(ns->voters) == 0) {
3098 log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
3099 goto err;
3100 } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
3101 log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
3102 goto err;
3105 if (ns->type != NS_TYPE_CONSENSUS &&
3106 (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
3107 int bad = 1;
3108 if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
3109 networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
3110 if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
3111 tok->args[0], HEX_DIGEST_LEN)<0)
3112 bad = 1;
3113 else
3114 bad = 0;
3116 if (bad) {
3117 log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
3118 escaped(tok->args[0]));
3122 /* Parse routerstatus lines. */
3123 rs_tokens = smartlist_new();
3124 rs_area = memarea_new();
3125 s = end_of_header;
3126 ns->routerstatus_list = smartlist_new();
3128 while (!strcmpstart(s, "r ")) {
3129 if (ns->type != NS_TYPE_CONSENSUS) {
3130 vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3131 if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
3132 rs, 0, 0))
3133 smartlist_add(ns->routerstatus_list, rs);
3134 else {
3135 tor_free(rs->version);
3136 tor_free(rs);
3138 } else {
3139 routerstatus_t *rs;
3140 if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
3141 NULL, NULL,
3142 ns->consensus_method,
3143 flav)))
3144 smartlist_add(ns->routerstatus_list, rs);
3147 for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
3148 routerstatus_t *rs1, *rs2;
3149 if (ns->type != NS_TYPE_CONSENSUS) {
3150 vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
3151 vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
3152 rs1 = &a->status; rs2 = &b->status;
3153 } else {
3154 rs1 = smartlist_get(ns->routerstatus_list, i-1);
3155 rs2 = smartlist_get(ns->routerstatus_list, i);
3157 if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
3158 >= 0) {
3159 log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
3160 "digest");
3161 goto err;
3165 /* Parse footer; check signature. */
3166 footer_tokens = smartlist_new();
3167 if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
3168 ++end_of_footer;
3169 else
3170 end_of_footer = s + strlen(s);
3171 if (tokenize_string(area,s, end_of_footer, footer_tokens,
3172 networkstatus_vote_footer_token_table, 0)) {
3173 log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
3174 goto err;
3178 int found_sig = 0;
3179 SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
3180 tok = _tok;
3181 if (tok->tp == K_DIRECTORY_SIGNATURE)
3182 found_sig = 1;
3183 else if (found_sig) {
3184 log_warn(LD_DIR, "Extraneous token after first directory-signature");
3185 goto err;
3187 } SMARTLIST_FOREACH_END(_tok);
3190 if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
3191 if (tok != smartlist_get(footer_tokens, 0)) {
3192 log_warn(LD_DIR, "Misplaced directory-footer token");
3193 goto err;
3197 tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
3198 if (tok) {
3199 ns->weight_params = smartlist_new();
3200 for (i = 0; i < tok->n_args; ++i) {
3201 int ok=0;
3202 char *eq = strchr(tok->args[i], '=');
3203 if (!eq) {
3204 log_warn(LD_DIR, "Bad element '%s' in weight params",
3205 escaped(tok->args[i]));
3206 goto err;
3208 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
3209 if (!ok) {
3210 log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
3211 goto err;
3213 smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));
3217 SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
3218 char declared_identity[DIGEST_LEN];
3219 networkstatus_voter_info_t *v;
3220 document_signature_t *sig;
3221 const char *id_hexdigest = NULL;
3222 const char *sk_hexdigest = NULL;
3223 digest_algorithm_t alg = DIGEST_SHA1;
3224 tok = _tok;
3225 if (tok->tp != K_DIRECTORY_SIGNATURE)
3226 continue;
3227 tor_assert(tok->n_args >= 2);
3228 if (tok->n_args == 2) {
3229 id_hexdigest = tok->args[0];
3230 sk_hexdigest = tok->args[1];
3231 } else {
3232 const char *algname = tok->args[0];
3233 int a;
3234 id_hexdigest = tok->args[1];
3235 sk_hexdigest = tok->args[2];
3236 a = crypto_digest_algorithm_parse_name(algname);
3237 if (a<0) {
3238 log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
3239 escaped(algname));
3240 continue;
3242 alg = a;
3245 if (!tok->object_type ||
3246 strcmp(tok->object_type, "SIGNATURE") ||
3247 tok->object_size < 128 || tok->object_size > 512) {
3248 log_warn(LD_DIR, "Bad object type or length on directory-signature");
3249 goto err;
3252 if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
3253 base16_decode(declared_identity, sizeof(declared_identity),
3254 id_hexdigest, HEX_DIGEST_LEN) < 0) {
3255 log_warn(LD_DIR, "Error decoding declared identity %s in "
3256 "network-status vote.", escaped(id_hexdigest));
3257 goto err;
3259 if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
3260 log_warn(LD_DIR, "ID on signature on network-status vote does not match "
3261 "any declared directory source.");
3262 goto err;
3264 sig = tor_malloc_zero(sizeof(document_signature_t));
3265 memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
3266 sig->alg = alg;
3267 if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
3268 base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
3269 sk_hexdigest, HEX_DIGEST_LEN) < 0) {
3270 log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
3271 "network-status vote.", escaped(sk_hexdigest));
3272 tor_free(sig);
3273 goto err;
3276 if (ns->type != NS_TYPE_CONSENSUS) {
3277 if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
3278 DIGEST_LEN)) {
3279 log_warn(LD_DIR, "Digest mismatch between declared and actual on "
3280 "network-status vote.");
3281 tor_free(sig);
3282 goto err;
3286 if (voter_get_sig_by_algorithm(v, sig->alg)) {
3287 /* We already parsed a vote with this algorithm from this voter. Use the
3288 first one. */
3289 log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
3290 "that contains two votes from the same voter with the same "
3291 "algorithm. Ignoring the second vote.");
3292 tor_free(sig);
3293 continue;
3296 if (ns->type != NS_TYPE_CONSENSUS) {
3297 if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
3298 tok, ns->cert->signing_key, 0,
3299 "network-status vote")) {
3300 tor_free(sig);
3301 goto err;
3303 sig->good_signature = 1;
3304 } else {
3305 if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
3306 tor_free(sig);
3307 goto err;
3309 sig->signature = tor_memdup(tok->object_body, tok->object_size);
3310 sig->signature_len = (int) tok->object_size;
3312 smartlist_add(v->sigs, sig);
3314 ++n_signatures;
3315 } SMARTLIST_FOREACH_END(_tok);
3317 if (! n_signatures) {
3318 log_warn(LD_DIR, "No signatures on networkstatus vote.");
3319 goto err;
3320 } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
3321 log_warn(LD_DIR, "Received more than one signature on a "
3322 "network-status vote.");
3323 goto err;
3326 if (eos_out)
3327 *eos_out = end_of_footer;
3329 goto done;
3330 err:
3331 dump_desc(s_dup, "v3 networkstatus");
3332 networkstatus_vote_free(ns);
3333 ns = NULL;
3334 done:
3335 if (tokens) {
3336 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
3337 smartlist_free(tokens);
3339 if (voter) {
3340 if (voter->sigs) {
3341 SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
3342 document_signature_free(sig));
3343 smartlist_free(voter->sigs);
3345 tor_free(voter->nickname);
3346 tor_free(voter->address);
3347 tor_free(voter->contact);
3348 tor_free(voter);
3350 if (rs_tokens) {
3351 SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
3352 smartlist_free(rs_tokens);
3354 if (footer_tokens) {
3355 SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
3356 smartlist_free(footer_tokens);
3358 if (area) {
3359 DUMP_AREA(area, "v3 networkstatus");
3360 memarea_drop_all(area);
3362 if (rs_area)
3363 memarea_drop_all(rs_area);
3364 tor_free(last_kwd);
3366 return ns;
3369 /** Return the digests_t that holds the digests of the
3370 * <b>flavor_name</b>-flavored networkstatus according to the detached
3371 * signatures document <b>sigs</b>, allocating a new digests_t as neeeded. */
3372 static digests_t *
3373 detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
3375 digests_t *d = strmap_get(sigs->digests, flavor_name);
3376 if (!d) {
3377 d = tor_malloc_zero(sizeof(digests_t));
3378 strmap_set(sigs->digests, flavor_name, d);
3380 return d;
3383 /** Return the list of signatures of the <b>flavor_name</b>-flavored
3384 * networkstatus according to the detached signatures document <b>sigs</b>,
3385 * allocating a new digests_t as neeeded. */
3386 static smartlist_t *
3387 detached_get_signatures(ns_detached_signatures_t *sigs,
3388 const char *flavor_name)
3390 smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
3391 if (!sl) {
3392 sl = smartlist_new();
3393 strmap_set(sigs->signatures, flavor_name, sl);
3395 return sl;
3398 /** Parse a detached v3 networkstatus signature document between <b>s</b> and
3399 * <b>eos</b> and return the result. Return -1 on failure. */
3400 ns_detached_signatures_t *
3401 networkstatus_parse_detached_signatures(const char *s, const char *eos)
3403 /* XXXX there is too much duplicate shared between this function and
3404 * networkstatus_parse_vote_from_string(). */
3405 directory_token_t *tok;
3406 memarea_t *area = NULL;
3407 digests_t *digests;
3409 smartlist_t *tokens = smartlist_new();
3410 ns_detached_signatures_t *sigs =
3411 tor_malloc_zero(sizeof(ns_detached_signatures_t));
3412 sigs->digests = strmap_new();
3413 sigs->signatures = strmap_new();
3415 if (!eos)
3416 eos = s + strlen(s);
3418 area = memarea_new();
3419 if (tokenize_string(area,s, eos, tokens,
3420 networkstatus_detached_signature_token_table, 0)) {
3421 log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
3422 goto err;
3425 /* Grab all the digest-like tokens. */
3426 SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
3427 const char *algname;
3428 digest_algorithm_t alg;
3429 const char *flavor;
3430 const char *hexdigest;
3431 size_t expected_length;
3433 tok = _tok;
3435 if (tok->tp == K_CONSENSUS_DIGEST) {
3436 algname = "sha1";
3437 alg = DIGEST_SHA1;
3438 flavor = "ns";
3439 hexdigest = tok->args[0];
3440 } else if (tok->tp == K_ADDITIONAL_DIGEST) {
3441 int a = crypto_digest_algorithm_parse_name(tok->args[1]);
3442 if (a<0) {
3443 log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
3444 continue;
3446 alg = (digest_algorithm_t) a;
3447 flavor = tok->args[0];
3448 algname = tok->args[1];
3449 hexdigest = tok->args[2];
3450 } else {
3451 continue;
3454 expected_length =
3455 (alg == DIGEST_SHA1) ? HEX_DIGEST_LEN : HEX_DIGEST256_LEN;
3457 if (strlen(hexdigest) != expected_length) {
3458 log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
3459 "networkstatus signatures");
3460 goto err;
3462 digests = detached_get_digests(sigs, flavor);
3463 tor_assert(digests);
3464 if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
3465 log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
3466 "signatures document", flavor, algname);
3467 continue;
3469 if (base16_decode(digests->d[alg], DIGEST256_LEN,
3470 hexdigest, strlen(hexdigest)) < 0) {
3471 log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
3472 "networkstatus signatures");
3473 goto err;
3475 } SMARTLIST_FOREACH_END(_tok);
3477 tok = find_by_keyword(tokens, K_VALID_AFTER);
3478 if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
3479 log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
3480 goto err;
3483 tok = find_by_keyword(tokens, K_FRESH_UNTIL);
3484 if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
3485 log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
3486 goto err;
3489 tok = find_by_keyword(tokens, K_VALID_UNTIL);
3490 if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
3491 log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
3492 goto err;
3495 SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
3496 const char *id_hexdigest;
3497 const char *sk_hexdigest;
3498 const char *algname;
3499 const char *flavor;
3500 digest_algorithm_t alg;
3502 char id_digest[DIGEST_LEN];
3503 char sk_digest[DIGEST_LEN];
3504 smartlist_t *siglist;
3505 document_signature_t *sig;
3506 int is_duplicate;
3508 tok = _tok;
3509 if (tok->tp == K_DIRECTORY_SIGNATURE) {
3510 tor_assert(tok->n_args >= 2);
3511 flavor = "ns";
3512 algname = "sha1";
3513 id_hexdigest = tok->args[0];
3514 sk_hexdigest = tok->args[1];
3515 } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
3516 tor_assert(tok->n_args >= 4);
3517 flavor = tok->args[0];
3518 algname = tok->args[1];
3519 id_hexdigest = tok->args[2];
3520 sk_hexdigest = tok->args[3];
3521 } else {
3522 continue;
3526 int a = crypto_digest_algorithm_parse_name(algname);
3527 if (a<0) {
3528 log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
3529 continue;
3531 alg = (digest_algorithm_t) a;
3534 if (!tok->object_type ||
3535 strcmp(tok->object_type, "SIGNATURE") ||
3536 tok->object_size < 128 || tok->object_size > 512) {
3537 log_warn(LD_DIR, "Bad object type or length on directory-signature");
3538 goto err;
3541 if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
3542 base16_decode(id_digest, sizeof(id_digest),
3543 id_hexdigest, HEX_DIGEST_LEN) < 0) {
3544 log_warn(LD_DIR, "Error decoding declared identity %s in "
3545 "network-status vote.", escaped(id_hexdigest));
3546 goto err;
3548 if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
3549 base16_decode(sk_digest, sizeof(sk_digest),
3550 sk_hexdigest, HEX_DIGEST_LEN) < 0) {
3551 log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
3552 "network-status vote.", escaped(sk_hexdigest));
3553 goto err;
3556 siglist = detached_get_signatures(sigs, flavor);
3557 is_duplicate = 0;
3558 SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
3559 if (dsig->alg == alg &&
3560 tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
3561 tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
3562 is_duplicate = 1;
3565 if (is_duplicate) {
3566 log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
3567 "found.");
3568 continue;
3571 sig = tor_malloc_zero(sizeof(document_signature_t));
3572 sig->alg = alg;
3573 memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
3574 memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
3575 if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
3576 tor_free(sig);
3577 goto err;
3579 sig->signature = tor_memdup(tok->object_body, tok->object_size);
3580 sig->signature_len = (int) tok->object_size;
3582 smartlist_add(siglist, sig);
3583 } SMARTLIST_FOREACH_END(_tok);
3585 goto done;
3586 err:
3587 ns_detached_signatures_free(sigs);
3588 sigs = NULL;
3589 done:
3590 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
3591 smartlist_free(tokens);
3592 if (area) {
3593 DUMP_AREA(area, "detached signatures");
3594 memarea_drop_all(area);
3596 return sigs;
3599 /** Parse the addr policy in the string <b>s</b> and return it. If
3600 * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
3601 * ADDR_POLICY_REJECT) for items that specify no action.
3603 addr_policy_t *
3604 router_parse_addr_policy_item_from_string(const char *s, int assume_action)
3606 directory_token_t *tok = NULL;
3607 const char *cp, *eos;
3608 /* Longest possible policy is "accept ffff:ffff:..255/ffff:...255:0-65535".
3609 * But note that there can be an arbitrary amount of space between the
3610 * accept and the address:mask/port element. */
3611 char line[TOR_ADDR_BUF_LEN*2 + 32];
3612 addr_policy_t *r;
3613 memarea_t *area = NULL;
3615 s = eat_whitespace(s);
3616 if ((*s == '*' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
3617 if (tor_snprintf(line, sizeof(line), "%s %s",
3618 assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
3619 log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
3620 return NULL;
3622 cp = line;
3623 tor_strlower(line);
3624 } else { /* assume an already well-formed address policy line */
3625 cp = s;
3628 eos = cp + strlen(cp);
3629 area = memarea_new();
3630 tok = get_next_token(area, &cp, eos, routerdesc_token_table);
3631 if (tok->tp == _ERR) {
3632 log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
3633 goto err;
3635 if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
3636 tok->tp != K_REJECT && tok->tp != K_REJECT6) {
3637 log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
3638 goto err;
3641 r = router_parse_addr_policy(tok);
3642 goto done;
3643 err:
3644 r = NULL;
3645 done:
3646 token_clear(tok);
3647 if (area) {
3648 DUMP_AREA(area, "policy item");
3649 memarea_drop_all(area);
3651 return r;
3654 /** Add an exit policy stored in the token <b>tok</b> to the router info in
3655 * <b>router</b>. Return 0 on success, -1 on failure. */
3656 static int
3657 router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
3659 addr_policy_t *newe;
3660 newe = router_parse_addr_policy(tok);
3661 if (!newe)
3662 return -1;
3663 if (! router->exit_policy)
3664 router->exit_policy = smartlist_new();
3666 if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
3667 tor_addr_family(&newe->addr) == AF_INET)
3669 ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
3670 tor_addr_family(&newe->addr) == AF_INET6)) {
3671 log_warn(LD_DIR, "Mismatch between field type and address type in exit "
3672 "policy");
3673 addr_policy_free(newe);
3674 return -1;
3677 smartlist_add(router->exit_policy, newe);
3679 return 0;
3682 /** Given a K_ACCEPT or K_REJECT token and a router, create and return
3683 * a new exit_policy_t corresponding to the token. */
3684 static addr_policy_t *
3685 router_parse_addr_policy(directory_token_t *tok)
3687 addr_policy_t newe;
3688 char *arg;
3690 tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
3691 tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
3693 if (tok->n_args != 1)
3694 return NULL;
3695 arg = tok->args[0];
3697 if (!strcmpstart(arg,"private"))
3698 return router_parse_addr_policy_private(tok);
3700 memset(&newe, 0, sizeof(newe));
3702 if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
3703 newe.policy_type = ADDR_POLICY_REJECT;
3704 else
3705 newe.policy_type = ADDR_POLICY_ACCEPT;
3707 if (tor_addr_parse_mask_ports(arg, &newe.addr, &newe.maskbits,
3708 &newe.prt_min, &newe.prt_max) < 0) {
3709 log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
3710 return NULL;
3713 return addr_policy_get_canonical_entry(&newe);
3716 /** Parse an exit policy line of the format "accept/reject private:...".
3717 * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
3718 * router descriptors until earlier versions are obsolete.
3720 static addr_policy_t *
3721 router_parse_addr_policy_private(directory_token_t *tok)
3723 const char *arg;
3724 uint16_t port_min, port_max;
3725 addr_policy_t result;
3727 arg = tok->args[0];
3728 if (strcmpstart(arg, "private"))
3729 return NULL;
3731 arg += strlen("private");
3732 arg = (char*) eat_whitespace(arg);
3733 if (!arg || *arg != ':')
3734 return NULL;
3736 if (parse_port_range(arg+1, &port_min, &port_max)<0)
3737 return NULL;
3739 memset(&result, 0, sizeof(result));
3740 if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
3741 result.policy_type = ADDR_POLICY_REJECT;
3742 else
3743 result.policy_type = ADDR_POLICY_ACCEPT;
3744 result.is_private = 1;
3745 result.prt_min = port_min;
3746 result.prt_max = port_max;
3748 return addr_policy_get_canonical_entry(&result);
3751 /** Log and exit if <b>t</b> is malformed */
3752 void
3753 assert_addr_policy_ok(smartlist_t *lst)
3755 if (!lst) return;
3756 SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
3757 tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
3758 t->policy_type == ADDR_POLICY_ACCEPT);
3759 tor_assert(t->prt_min <= t->prt_max);
3764 * Low-level tokenizer for router descriptors and directories.
3767 /** Free all resources allocated for <b>tok</b> */
3768 static void
3769 token_clear(directory_token_t *tok)
3771 if (tok->key)
3772 crypto_pk_free(tok->key);
3775 #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
3776 #define ALLOC(sz) memarea_alloc(area,sz)
3777 #define STRDUP(str) memarea_strdup(area,str)
3778 #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
3780 #define RET_ERR(msg) \
3781 STMT_BEGIN \
3782 if (tok) token_clear(tok); \
3783 tok = ALLOC_ZERO(sizeof(directory_token_t)); \
3784 tok->tp = _ERR; \
3785 tok->error = STRDUP(msg); \
3786 goto done_tokenizing; \
3787 STMT_END
3789 /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
3790 * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
3791 * Return <b>tok</b> on success, or a new _ERR token if the token didn't
3792 * conform to the syntax we wanted.
3794 static INLINE directory_token_t *
3795 token_check_object(memarea_t *area, const char *kwd,
3796 directory_token_t *tok, obj_syntax o_syn)
3798 char ebuf[128];
3799 switch (o_syn) {
3800 case NO_OBJ:
3801 /* No object is allowed for this token. */
3802 if (tok->object_body) {
3803 tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
3804 RET_ERR(ebuf);
3806 if (tok->key) {
3807 tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
3808 RET_ERR(ebuf);
3810 break;
3811 case NEED_OBJ:
3812 /* There must be a (non-key) object. */
3813 if (!tok->object_body) {
3814 tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
3815 RET_ERR(ebuf);
3817 break;
3818 case NEED_KEY_1024: /* There must be a 1024-bit public key. */
3819 case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
3820 if (tok->key && crypto_pk_num_bits(tok->key) != PK_BYTES*8) {
3821 tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
3822 kwd, crypto_pk_num_bits(tok->key));
3823 RET_ERR(ebuf);
3825 /* fall through */
3826 case NEED_KEY: /* There must be some kind of key. */
3827 if (!tok->key) {
3828 tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
3829 RET_ERR(ebuf);
3831 if (o_syn != NEED_SKEY_1024) {
3832 if (crypto_pk_key_is_private(tok->key)) {
3833 tor_snprintf(ebuf, sizeof(ebuf),
3834 "Private key given for %s, which wants a public key", kwd);
3835 RET_ERR(ebuf);
3837 } else { /* o_syn == NEED_SKEY_1024 */
3838 if (!crypto_pk_key_is_private(tok->key)) {
3839 tor_snprintf(ebuf, sizeof(ebuf),
3840 "Public key given for %s, which wants a private key", kwd);
3841 RET_ERR(ebuf);
3844 break;
3845 case OBJ_OK:
3846 /* Anything goes with this token. */
3847 break;
3850 done_tokenizing:
3851 return tok;
3854 /** Helper: parse space-separated arguments from the string <b>s</b> ending at
3855 * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
3856 * number of parsed elements into the n_args field of <b>tok</b>. Allocate
3857 * all storage in <b>area</b>. Return the number of arguments parsed, or
3858 * return -1 if there was an insanely high number of arguments. */
3859 static INLINE int
3860 get_token_arguments(memarea_t *area, directory_token_t *tok,
3861 const char *s, const char *eol)
3863 /** Largest number of arguments we'll accept to any token, ever. */
3864 #define MAX_ARGS 512
3865 char *mem = memarea_strndup(area, s, eol-s);
3866 char *cp = mem;
3867 int j = 0;
3868 char *args[MAX_ARGS];
3869 while (*cp) {
3870 if (j == MAX_ARGS)
3871 return -1;
3872 args[j++] = cp;
3873 cp = (char*)find_whitespace(cp);
3874 if (!cp || !*cp)
3875 break; /* End of the line. */
3876 *cp++ = '\0';
3877 cp = (char*)eat_whitespace(cp);
3879 tok->n_args = j;
3880 tok->args = memarea_memdup(area, args, j*sizeof(char*));
3881 return j;
3882 #undef MAX_ARGS
3885 /** Helper function: read the next token from *s, advance *s to the end of the
3886 * token, and return the parsed token. Parse *<b>s</b> according to the list
3887 * of tokens in <b>table</b>.
3889 static directory_token_t *
3890 get_next_token(memarea_t *area,
3891 const char **s, const char *eos, token_rule_t *table)
3893 /** Reject any object at least this big; it is probably an overflow, an
3894 * attack, a bug, or some other nonsense. */
3895 #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
3896 /** Reject any line at least this big; it is probably an overflow, an
3897 * attack, a bug, or some other nonsense. */
3898 #define MAX_LINE_LENGTH (128*1024)
3900 const char *next, *eol, *obstart;
3901 size_t obname_len;
3902 int i;
3903 directory_token_t *tok;
3904 obj_syntax o_syn = NO_OBJ;
3905 char ebuf[128];
3906 const char *kwd = "";
3908 tor_assert(area);
3909 tok = ALLOC_ZERO(sizeof(directory_token_t));
3910 tok->tp = _ERR;
3912 /* Set *s to first token, eol to end-of-line, next to after first token */
3913 *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
3914 tor_assert(eos >= *s);
3915 eol = memchr(*s, '\n', eos-*s);
3916 if (!eol)
3917 eol = eos;
3918 if (eol - *s > MAX_LINE_LENGTH) {
3919 RET_ERR("Line far too long");
3922 next = find_whitespace_eos(*s, eol);
3924 if (!strcmp_len(*s, "opt", next-*s)) {
3925 /* Skip past an "opt" at the start of the line. */
3926 *s = eat_whitespace_eos_no_nl(next, eol);
3927 next = find_whitespace_eos(*s, eol);
3928 } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
3929 RET_ERR("Unexpected EOF");
3932 /* Search the table for the appropriate entry. (I tried a binary search
3933 * instead, but it wasn't any faster.) */
3934 for (i = 0; table[i].t ; ++i) {
3935 if (!strcmp_len(*s, table[i].t, next-*s)) {
3936 /* We've found the keyword. */
3937 kwd = table[i].t;
3938 tok->tp = table[i].v;
3939 o_syn = table[i].os;
3940 *s = eat_whitespace_eos_no_nl(next, eol);
3941 /* We go ahead whether there are arguments or not, so that tok->args is
3942 * always set if we want arguments. */
3943 if (table[i].concat_args) {
3944 /* The keyword takes the line as a single argument */
3945 tok->args = ALLOC(sizeof(char*));
3946 tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
3947 tok->n_args = 1;
3948 } else {
3949 /* This keyword takes multiple arguments. */
3950 if (get_token_arguments(area, tok, *s, eol)<0) {
3951 tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
3952 RET_ERR(ebuf);
3954 *s = eol;
3956 if (tok->n_args < table[i].min_args) {
3957 tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
3958 RET_ERR(ebuf);
3959 } else if (tok->n_args > table[i].max_args) {
3960 tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
3961 RET_ERR(ebuf);
3963 break;
3967 if (tok->tp == _ERR) {
3968 /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
3969 if (**s == '@')
3970 tok->tp = _A_UNKNOWN;
3971 else
3972 tok->tp = K_OPT;
3973 tok->args = ALLOC(sizeof(char*));
3974 tok->args[0] = STRNDUP(*s, eol-*s);
3975 tok->n_args = 1;
3976 o_syn = OBJ_OK;
3979 /* Check whether there's an object present */
3980 *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
3981 tor_assert(eos >= *s);
3982 eol = memchr(*s, '\n', eos-*s);
3983 if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
3984 goto check_object;
3986 obstart = *s; /* Set obstart to start of object spec */
3987 if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
3988 strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
3989 (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
3990 RET_ERR("Malformed object: bad begin line");
3992 tok->object_type = STRNDUP(*s+11, eol-*s-16);
3993 obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
3994 *s = eol+1; /* Set *s to possible start of object data (could be eos) */
3996 /* Go to the end of the object */
3997 next = tor_memstr(*s, eos-*s, "-----END ");
3998 if (!next) {
3999 RET_ERR("Malformed object: missing object end line");
4001 tor_assert(eos >= next);
4002 eol = memchr(next, '\n', eos-next);
4003 if (!eol) /* end-of-line marker, or eos if there's no '\n' */
4004 eol = eos;
4005 /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
4006 if ((size_t)(eol-next) != 9+obname_len+5 ||
4007 strcmp_len(next+9, tok->object_type, obname_len) ||
4008 strcmp_len(eol-5, "-----", 5)) {
4009 snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
4010 tok->object_type);
4011 ebuf[sizeof(ebuf)-1] = '\0';
4012 RET_ERR(ebuf);
4014 if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
4015 RET_ERR("Couldn't parse object: missing footer or object much too big.");
4017 if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
4018 tok->key = crypto_pk_new();
4019 if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
4020 RET_ERR("Couldn't parse public key.");
4021 } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
4022 tok->key = crypto_pk_new();
4023 if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
4024 RET_ERR("Couldn't parse private key.");
4025 } else { /* If it's something else, try to base64-decode it */
4026 int r;
4027 tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
4028 r = base64_decode(tok->object_body, next-*s, *s, next-*s);
4029 if (r<0)
4030 RET_ERR("Malformed object: bad base64-encoded data");
4031 tok->object_size = r;
4033 *s = eol;
4035 check_object:
4036 tok = token_check_object(area, kwd, tok, o_syn);
4038 done_tokenizing:
4039 return tok;
4041 #undef RET_ERR
4042 #undef ALLOC
4043 #undef ALLOC_ZERO
4044 #undef STRDUP
4045 #undef STRNDUP
4048 /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
4049 * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
4050 * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
4051 * entire string.
4053 static int
4054 tokenize_string(memarea_t *area,
4055 const char *start, const char *end, smartlist_t *out,
4056 token_rule_t *table, int flags)
4058 const char **s;
4059 directory_token_t *tok = NULL;
4060 int counts[_NIL];
4061 int i;
4062 int first_nonannotation;
4063 int prev_len = smartlist_len(out);
4064 tor_assert(area);
4066 s = &start;
4067 if (!end)
4068 end = start+strlen(start);
4069 for (i = 0; i < _NIL; ++i)
4070 counts[i] = 0;
4072 SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]);
4074 while (*s < end && (!tok || tok->tp != _EOF)) {
4075 tok = get_next_token(area, s, end, table);
4076 if (tok->tp == _ERR) {
4077 log_warn(LD_DIR, "parse error: %s", tok->error);
4078 token_clear(tok);
4079 return -1;
4081 ++counts[tok->tp];
4082 smartlist_add(out, tok);
4083 *s = eat_whitespace_eos(*s, end);
4086 if (flags & TS_NOCHECK)
4087 return 0;
4089 if ((flags & TS_ANNOTATIONS_OK)) {
4090 first_nonannotation = -1;
4091 for (i = 0; i < smartlist_len(out); ++i) {
4092 tok = smartlist_get(out, i);
4093 if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
4094 first_nonannotation = i;
4095 break;
4098 if (first_nonannotation < 0) {
4099 log_warn(LD_DIR, "parse error: item contains only annotations");
4100 return -1;
4102 for (i=first_nonannotation; i < smartlist_len(out); ++i) {
4103 tok = smartlist_get(out, i);
4104 if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
4105 log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
4106 return -1;
4109 if ((flags & TS_NO_NEW_ANNOTATIONS)) {
4110 if (first_nonannotation != prev_len) {
4111 log_warn(LD_DIR, "parse error: Unexpected annotations.");
4112 return -1;
4115 } else {
4116 for (i=0; i < smartlist_len(out); ++i) {
4117 tok = smartlist_get(out, i);
4118 if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
4119 log_warn(LD_DIR, "parse error: no annotations allowed.");
4120 return -1;
4123 first_nonannotation = 0;
4125 for (i = 0; table[i].t; ++i) {
4126 if (counts[table[i].v] < table[i].min_cnt) {
4127 log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
4128 return -1;
4130 if (counts[table[i].v] > table[i].max_cnt) {
4131 log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
4132 return -1;
4134 if (table[i].pos & AT_START) {
4135 if (smartlist_len(out) < 1 ||
4136 (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
4137 log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
4138 return -1;
4141 if (table[i].pos & AT_END) {
4142 if (smartlist_len(out) < 1 ||
4143 (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
4144 log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
4145 return -1;
4149 return 0;
4152 /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
4153 * NULL if no such keyword is found.
4155 static directory_token_t *
4156 find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
4158 SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
4159 return NULL;
4162 /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
4163 * with an assert if no such keyword is found.
4165 static directory_token_t *
4166 _find_by_keyword(smartlist_t *s, directory_keyword keyword,
4167 const char *keyword_as_string)
4169 directory_token_t *tok = find_opt_by_keyword(s, keyword);
4170 if (PREDICT_UNLIKELY(!tok)) {
4171 log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
4172 "been validated. Internal error.", keyword_as_string, (int)keyword);
4173 tor_assert(tok);
4175 return tok;
4178 /** If there are any directory_token_t entries in <b>s</b> whose keyword is
4179 * <b>k</b>, return a newly allocated smartlist_t containing all such entries,
4180 * in the same order in which they occur in <b>s</b>. Otherwise return
4181 * NULL. */
4182 static smartlist_t *
4183 find_all_by_keyword(smartlist_t *s, directory_keyword k)
4185 smartlist_t *out = NULL;
4186 SMARTLIST_FOREACH(s, directory_token_t *, t,
4187 if (t->tp == k) {
4188 if (!out)
4189 out = smartlist_new();
4190 smartlist_add(out, t);
4192 return out;
4195 /** Return a newly allocated smartlist of all accept or reject tokens in
4196 * <b>s</b>.
4198 static smartlist_t *
4199 find_all_exitpolicy(smartlist_t *s)
4201 smartlist_t *out = smartlist_new();
4202 SMARTLIST_FOREACH(s, directory_token_t *, t,
4203 if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
4204 t->tp == K_REJECT || t->tp == K_REJECT6)
4205 smartlist_add(out,t));
4206 return out;
4209 /** Helper function for <b>router_get_hash_impl</b>: given <b>s</b>,
4210 * <b>s_len</b>, <b>start_str</b>, <b>end_str</b>, and <b>end_c</b> with the
4211 * same semantics as in that function, set *<b>start_out</b> (inclusive) and
4212 * *<b>end_out</b> (exclusive) to the boundaries of the string to be hashed.
4214 * Return 0 on success and -1 on failure.
4216 static int
4217 router_get_hash_impl_helper(const char *s, size_t s_len,
4218 const char *start_str,
4219 const char *end_str, char end_c,
4220 const char **start_out, const char **end_out)
4222 const char *start, *end;
4223 start = tor_memstr(s, s_len, start_str);
4224 if (!start) {
4225 log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
4226 return -1;
4228 if (start != s && *(start-1) != '\n') {
4229 log_warn(LD_DIR,
4230 "first occurrence of \"%s\" is not at the start of a line",
4231 start_str);
4232 return -1;
4234 end = tor_memstr(start+strlen(start_str),
4235 s_len - (start-s) - strlen(start_str), end_str);
4236 if (!end) {
4237 log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
4238 return -1;
4240 end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
4241 if (!end) {
4242 log_warn(LD_DIR,"couldn't find EOL");
4243 return -1;
4245 ++end;
4247 *start_out = start;
4248 *end_out = end;
4249 return 0;
4252 /** Compute the digest of the substring of <b>s</b> taken from the first
4253 * occurrence of <b>start_str</b> through the first instance of c after the
4254 * first subsequent occurrence of <b>end_str</b>; store the 20-byte result in
4255 * <b>digest</b>; return 0 on success.
4257 * If no such substring exists, return -1.
4259 static int
4260 router_get_hash_impl(const char *s, size_t s_len, char *digest,
4261 const char *start_str,
4262 const char *end_str, char end_c,
4263 digest_algorithm_t alg)
4265 const char *start=NULL, *end=NULL;
4266 if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
4267 &start,&end)<0)
4268 return -1;
4270 if (alg == DIGEST_SHA1) {
4271 if (crypto_digest(digest, start, end-start)) {
4272 log_warn(LD_BUG,"couldn't compute digest");
4273 return -1;
4275 } else {
4276 if (crypto_digest256(digest, start, end-start, alg)) {
4277 log_warn(LD_BUG,"couldn't compute digest");
4278 return -1;
4282 return 0;
4285 /** As router_get_hash_impl, but compute all hashes. */
4286 static int
4287 router_get_hashes_impl(const char *s, size_t s_len, digests_t *digests,
4288 const char *start_str,
4289 const char *end_str, char end_c)
4291 const char *start=NULL, *end=NULL;
4292 if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
4293 &start,&end)<0)
4294 return -1;
4296 if (crypto_digest_all(digests, start, end-start)) {
4297 log_warn(LD_BUG,"couldn't compute digests");
4298 return -1;
4301 return 0;
4304 /** Assuming that s starts with a microdesc, return the start of the
4305 * *NEXT* one. Return NULL on "not found." */
4306 static const char *
4307 find_start_of_next_microdesc(const char *s, const char *eos)
4309 int started_with_annotations;
4310 s = eat_whitespace_eos(s, eos);
4311 if (!s)
4312 return NULL;
4314 #define CHECK_LENGTH() STMT_BEGIN \
4315 if (s+32 > eos) \
4316 return NULL; \
4317 STMT_END
4319 #define NEXT_LINE() STMT_BEGIN \
4320 s = memchr(s, '\n', eos-s); \
4321 if (!s || s+1 >= eos) \
4322 return NULL; \
4323 s++; \
4324 STMT_END
4326 CHECK_LENGTH();
4328 started_with_annotations = (*s == '@');
4330 if (started_with_annotations) {
4331 /* Start by advancing to the first non-annotation line. */
4332 while (*s == '@')
4333 NEXT_LINE();
4335 CHECK_LENGTH();
4337 /* Now we should be pointed at an onion-key line. If we are, then skip
4338 * it. */
4339 if (!strcmpstart(s, "onion-key"))
4340 NEXT_LINE();
4342 /* Okay, now we're pointed at the first line of the microdescriptor which is
4343 not an annotation or onion-key. The next line that _is_ an annotation or
4344 onion-key is the start of the next microdescriptor. */
4345 while (s+32 < eos) {
4346 if (*s == '@' || !strcmpstart(s, "onion-key"))
4347 return s;
4348 NEXT_LINE();
4350 return NULL;
4352 #undef CHECK_LENGTH
4353 #undef NEXT_LINE
4356 /** Parse as many microdescriptors as are found from the string starting at
4357 * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
4358 * annotations we recognize and ignore ones we don't. If <b>copy_body</b> is
4359 * true, then strdup the bodies of the microdescriptors. Return all newly
4360 * parsed microdescriptors in a newly allocated smartlist_t. */
4361 smartlist_t *
4362 microdescs_parse_from_string(const char *s, const char *eos,
4363 int allow_annotations, int copy_body)
4365 smartlist_t *tokens;
4366 smartlist_t *result;
4367 microdesc_t *md = NULL;
4368 memarea_t *area;
4369 const char *start = s;
4370 const char *start_of_next_microdesc;
4371 int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
4373 directory_token_t *tok;
4375 if (!eos)
4376 eos = s + strlen(s);
4378 s = eat_whitespace_eos(s, eos);
4379 area = memarea_new();
4380 result = smartlist_new();
4381 tokens = smartlist_new();
4383 while (s < eos) {
4384 start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
4385 if (!start_of_next_microdesc)
4386 start_of_next_microdesc = eos;
4388 if (tokenize_string(area, s, start_of_next_microdesc, tokens,
4389 microdesc_token_table, flags)) {
4390 log_warn(LD_DIR, "Unparseable microdescriptor");
4391 goto next;
4394 md = tor_malloc_zero(sizeof(microdesc_t));
4396 const char *cp = tor_memstr(s, start_of_next_microdesc-s,
4397 "onion-key");
4398 tor_assert(cp);
4400 md->bodylen = start_of_next_microdesc - cp;
4401 if (copy_body)
4402 md->body = tor_strndup(cp, md->bodylen);
4403 else
4404 md->body = (char*)cp;
4405 md->off = cp - start;
4408 if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
4409 if (parse_iso_time(tok->args[0], &md->last_listed)) {
4410 log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
4411 goto next;
4415 tok = find_by_keyword(tokens, K_ONION_KEY);
4416 if (!crypto_pk_public_exponent_ok(tok->key)) {
4417 log_warn(LD_DIR,
4418 "Relay's onion key had invalid exponent.");
4419 goto next;
4421 md->onion_pkey = tok->key;
4422 tok->key = NULL;
4424 if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
4425 int i;
4426 md->family = smartlist_new();
4427 for (i=0;i<tok->n_args;++i) {
4428 if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
4429 log_warn(LD_DIR, "Illegal nickname %s in family line",
4430 escaped(tok->args[i]));
4431 goto next;
4433 smartlist_add(md->family, tor_strdup(tok->args[i]));
4437 if ((tok = find_opt_by_keyword(tokens, K_P))) {
4438 md->exit_policy = parse_short_policy(tok->args[0]);
4441 crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
4443 smartlist_add(result, md);
4445 md = NULL;
4446 next:
4447 microdesc_free(md);
4448 md = NULL;
4450 memarea_clear(area);
4451 smartlist_clear(tokens);
4452 s = start_of_next_microdesc;
4455 memarea_drop_all(area);
4456 smartlist_free(tokens);
4458 return result;
4461 /** Return true iff this Tor version can answer directory questions
4462 * about microdescriptors. */
4464 tor_version_supports_microdescriptors(const char *platform)
4466 return tor_version_as_new_as(platform, "0.2.3.1-alpha");
4469 /** Parse the Tor version of the platform string <b>platform</b>,
4470 * and compare it to the version in <b>cutoff</b>. Return 1 if
4471 * the router is at least as new as the cutoff, else return 0.
4474 tor_version_as_new_as(const char *platform, const char *cutoff)
4476 tor_version_t cutoff_version, router_version;
4477 char *s, *s2, *start;
4478 char tmp[128];
4480 tor_assert(platform);
4482 if (tor_version_parse(cutoff, &cutoff_version)<0) {
4483 log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
4484 return 0;
4486 if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
4487 return 1;
4489 start = (char *)eat_whitespace(platform+3);
4490 if (!*start) return 0;
4491 s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
4492 s2 = (char*)eat_whitespace(s);
4493 if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
4494 s = (char*)find_whitespace(s2);
4496 if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
4497 return 0;
4498 strlcpy(tmp, start, s-start+1);
4500 if (tor_version_parse(tmp, &router_version)<0) {
4501 log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
4502 return 1; /* be safe and say yes */
4505 /* Here's why we don't need to do any special handling for svn revisions:
4506 * - If neither has an svn revision, we're fine.
4507 * - If the router doesn't have an svn revision, we can't assume that it
4508 * is "at least" any svn revision, so we need to return 0.
4509 * - If the target version doesn't have an svn revision, any svn revision
4510 * (or none at all) is good enough, so return 1.
4511 * - If both target and router have an svn revision, we compare them.
4514 return tor_version_compare(&router_version, &cutoff_version) >= 0;
4517 /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
4518 * Return 0 on success, -1 on failure. */
4520 tor_version_parse(const char *s, tor_version_t *out)
4522 char *eos=NULL;
4523 const char *cp=NULL;
4524 /* Format is:
4525 * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
4527 tor_assert(s);
4528 tor_assert(out);
4530 memset(out, 0, sizeof(tor_version_t));
4532 if (!strcasecmpstart(s, "Tor "))
4533 s += 4;
4535 /* Get major. */
4536 out->major = (int)strtol(s,&eos,10);
4537 if (!eos || eos==s || *eos != '.') return -1;
4538 cp = eos+1;
4540 /* Get minor */
4541 out->minor = (int) strtol(cp,&eos,10);
4542 if (!eos || eos==cp || *eos != '.') return -1;
4543 cp = eos+1;
4545 /* Get micro */
4546 out->micro = (int) strtol(cp,&eos,10);
4547 if (!eos || eos==cp) return -1;
4548 if (!*eos) {
4549 out->status = VER_RELEASE;
4550 out->patchlevel = 0;
4551 return 0;
4553 cp = eos;
4555 /* Get status */
4556 if (*cp == '.') {
4557 out->status = VER_RELEASE;
4558 ++cp;
4559 } else if (0==strncmp(cp, "pre", 3)) {
4560 out->status = VER_PRE;
4561 cp += 3;
4562 } else if (0==strncmp(cp, "rc", 2)) {
4563 out->status = VER_RC;
4564 cp += 2;
4565 } else {
4566 return -1;
4569 /* Get patchlevel */
4570 out->patchlevel = (int) strtol(cp,&eos,10);
4571 if (!eos || eos==cp) return -1;
4572 cp = eos;
4574 /* Get status tag. */
4575 if (*cp == '-' || *cp == '.')
4576 ++cp;
4577 eos = (char*) find_whitespace(cp);
4578 if (eos-cp >= (int)sizeof(out->status_tag))
4579 strlcpy(out->status_tag, cp, sizeof(out->status_tag));
4580 else {
4581 memcpy(out->status_tag, cp, eos-cp);
4582 out->status_tag[eos-cp] = 0;
4584 cp = eat_whitespace(eos);
4586 if (!strcmpstart(cp, "(r")) {
4587 cp += 2;
4588 out->svn_revision = (int) strtol(cp,&eos,10);
4589 } else if (!strcmpstart(cp, "(git-")) {
4590 char *close_paren = strchr(cp, ')');
4591 int hexlen;
4592 char digest[DIGEST_LEN];
4593 if (! close_paren)
4594 return -1;
4595 cp += 5;
4596 if (close_paren-cp > HEX_DIGEST_LEN)
4597 return -1;
4598 hexlen = (int)(close_paren-cp);
4599 memset(digest, 0, sizeof(digest));
4600 if ( hexlen == 0 || (hexlen % 2) == 1)
4601 return -1;
4602 if (base16_decode(digest, hexlen/2, cp, hexlen))
4603 return -1;
4604 memcpy(out->git_tag, digest, hexlen/2);
4605 out->git_tag_len = hexlen/2;
4608 return 0;
4611 /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
4612 * b. */
4614 tor_version_compare(tor_version_t *a, tor_version_t *b)
4616 int i;
4617 tor_assert(a);
4618 tor_assert(b);
4619 if ((i = a->major - b->major))
4620 return i;
4621 else if ((i = a->minor - b->minor))
4622 return i;
4623 else if ((i = a->micro - b->micro))
4624 return i;
4625 else if ((i = a->status - b->status))
4626 return i;
4627 else if ((i = a->patchlevel - b->patchlevel))
4628 return i;
4629 else if ((i = strcmp(a->status_tag, b->status_tag)))
4630 return i;
4631 else if ((i = a->svn_revision - b->svn_revision))
4632 return i;
4633 else if ((i = a->git_tag_len - b->git_tag_len))
4634 return i;
4635 else if (a->git_tag_len)
4636 return fast_memcmp(a->git_tag, b->git_tag, a->git_tag_len);
4637 else
4638 return 0;
4641 /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
4644 tor_version_same_series(tor_version_t *a, tor_version_t *b)
4646 tor_assert(a);
4647 tor_assert(b);
4648 return ((a->major == b->major) &&
4649 (a->minor == b->minor) &&
4650 (a->micro == b->micro));
4653 /** Helper: Given pointers to two strings describing tor versions, return -1
4654 * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
4655 * Used to sort a list of versions. */
4656 static int
4657 _compare_tor_version_str_ptr(const void **_a, const void **_b)
4659 const char *a = *_a, *b = *_b;
4660 int ca, cb;
4661 tor_version_t va, vb;
4662 ca = tor_version_parse(a, &va);
4663 cb = tor_version_parse(b, &vb);
4664 /* If they both parse, compare them. */
4665 if (!ca && !cb)
4666 return tor_version_compare(&va,&vb);
4667 /* If one parses, it comes first. */
4668 if (!ca && cb)
4669 return -1;
4670 if (ca && !cb)
4671 return 1;
4672 /* If neither parses, compare strings. Also, the directory server admin
4673 ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
4674 return strcmp(a,b);
4677 /** Sort a list of string-representations of versions in ascending order. */
4678 void
4679 sort_version_list(smartlist_t *versions, int remove_duplicates)
4681 smartlist_sort(versions, _compare_tor_version_str_ptr);
4683 if (remove_duplicates)
4684 smartlist_uniq(versions, _compare_tor_version_str_ptr, _tor_free);
4687 /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
4688 * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
4689 * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
4690 * encrypted introduction points to the newly allocated
4691 * *<b>intro_points_encrypted_out</b>, their encrypted size to
4692 * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
4693 * to *<b>encoded_size_out</b>, and a pointer to the possibly next
4694 * descriptor to *<b>next_out</b>; return 0 for success (including validation)
4695 * and -1 for failure.
4698 rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
4699 char *desc_id_out,
4700 char **intro_points_encrypted_out,
4701 size_t *intro_points_encrypted_size_out,
4702 size_t *encoded_size_out,
4703 const char **next_out, const char *desc)
4705 rend_service_descriptor_t *result =
4706 tor_malloc_zero(sizeof(rend_service_descriptor_t));
4707 char desc_hash[DIGEST_LEN];
4708 const char *eos;
4709 smartlist_t *tokens = smartlist_new();
4710 directory_token_t *tok;
4711 char secret_id_part[DIGEST_LEN];
4712 int i, version, num_ok=1;
4713 smartlist_t *versions;
4714 char public_key_hash[DIGEST_LEN];
4715 char test_desc_id[DIGEST_LEN];
4716 memarea_t *area = NULL;
4717 tor_assert(desc);
4718 /* Check if desc starts correctly. */
4719 if (strncmp(desc, "rendezvous-service-descriptor ",
4720 strlen("rendezvous-service-descriptor "))) {
4721 log_info(LD_REND, "Descriptor does not start correctly.");
4722 goto err;
4724 /* Compute descriptor hash for later validation. */
4725 if (router_get_hash_impl(desc, strlen(desc), desc_hash,
4726 "rendezvous-service-descriptor ",
4727 "\nsignature", '\n', DIGEST_SHA1) < 0) {
4728 log_warn(LD_REND, "Couldn't compute descriptor hash.");
4729 goto err;
4731 /* Determine end of string. */
4732 eos = strstr(desc, "\nrendezvous-service-descriptor ");
4733 if (!eos)
4734 eos = desc + strlen(desc);
4735 else
4736 eos = eos + 1;
4737 /* Check length. */
4738 if (eos-desc > REND_DESC_MAX_SIZE) {
4739 /* XXX023 If we are parsing this descriptor as a server, this
4740 * should be a protocol warning. */
4741 log_warn(LD_REND, "Descriptor length is %d which exceeds "
4742 "maximum rendezvous descriptor size of %d bytes.",
4743 (int)(eos-desc), REND_DESC_MAX_SIZE);
4744 goto err;
4746 /* Tokenize descriptor. */
4747 area = memarea_new();
4748 if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
4749 log_warn(LD_REND, "Error tokenizing descriptor.");
4750 goto err;
4752 /* Set next to next descriptor, if available. */
4753 *next_out = eos;
4754 /* Set length of encoded descriptor. */
4755 *encoded_size_out = eos - desc;
4756 /* Check min allowed length of token list. */
4757 if (smartlist_len(tokens) < 7) {
4758 log_warn(LD_REND, "Impossibly short descriptor.");
4759 goto err;
4761 /* Parse base32-encoded descriptor ID. */
4762 tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
4763 tor_assert(tok == smartlist_get(tokens, 0));
4764 tor_assert(tok->n_args == 1);
4765 if (strlen(tok->args[0]) != REND_DESC_ID_V2_LEN_BASE32 ||
4766 strspn(tok->args[0], BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
4767 log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
4768 goto err;
4770 if (base32_decode(desc_id_out, DIGEST_LEN,
4771 tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
4772 log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
4773 tok->args[0]);
4774 goto err;
4776 /* Parse descriptor version. */
4777 tok = find_by_keyword(tokens, R_VERSION);
4778 tor_assert(tok->n_args == 1);
4779 result->version =
4780 (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
4781 if (result->version != 2 || !num_ok) {
4782 /* If it's <2, it shouldn't be under this format. If the number
4783 * is greater than 2, we bumped it because we broke backward
4784 * compatibility. See how version numbers in our other formats
4785 * work. */
4786 log_warn(LD_REND, "Unrecognized descriptor version: %s",
4787 escaped(tok->args[0]));
4788 goto err;
4790 /* Parse public key. */
4791 tok = find_by_keyword(tokens, R_PERMANENT_KEY);
4792 result->pk = tok->key;
4793 tok->key = NULL; /* Prevent free */
4794 /* Parse secret ID part. */
4795 tok = find_by_keyword(tokens, R_SECRET_ID_PART);
4796 tor_assert(tok->n_args == 1);
4797 if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
4798 strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
4799 log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
4800 goto err;
4802 if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
4803 log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
4804 tok->args[0]);
4805 goto err;
4807 /* Parse publication time -- up-to-date check is done when storing the
4808 * descriptor. */
4809 tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
4810 tor_assert(tok->n_args == 1);
4811 if (parse_iso_time(tok->args[0], &result->timestamp) < 0) {
4812 log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
4813 goto err;
4815 /* Parse protocol versions. */
4816 tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
4817 tor_assert(tok->n_args == 1);
4818 versions = smartlist_new();
4819 smartlist_split_string(versions, tok->args[0], ",",
4820 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4821 for (i = 0; i < smartlist_len(versions); i++) {
4822 version = (int) tor_parse_long(smartlist_get(versions, i),
4823 10, 0, INT_MAX, &num_ok, NULL);
4824 if (!num_ok) /* It's a string; let's ignore it. */
4825 continue;
4826 if (version >= REND_PROTOCOL_VERSION_BITMASK_WIDTH)
4827 /* Avoid undefined left-shift behaviour. */
4828 continue;
4829 result->protocols |= 1 << version;
4831 SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
4832 smartlist_free(versions);
4833 /* Parse encrypted introduction points. Don't verify. */
4834 tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
4835 if (tok) {
4836 if (strcmp(tok->object_type, "MESSAGE")) {
4837 log_warn(LD_DIR, "Bad object type: introduction points should be of "
4838 "type MESSAGE");
4839 goto err;
4841 *intro_points_encrypted_out = tor_memdup(tok->object_body,
4842 tok->object_size);
4843 *intro_points_encrypted_size_out = tok->object_size;
4844 } else {
4845 *intro_points_encrypted_out = NULL;
4846 *intro_points_encrypted_size_out = 0;
4848 /* Parse and verify signature. */
4849 tok = find_by_keyword(tokens, R_SIGNATURE);
4850 note_crypto_pk_op(VERIFY_RTR);
4851 if (check_signature_token(desc_hash, DIGEST_LEN, tok, result->pk, 0,
4852 "v2 rendezvous service descriptor") < 0)
4853 goto err;
4854 /* Verify that descriptor ID belongs to public key and secret ID part. */
4855 crypto_pk_get_digest(result->pk, public_key_hash);
4856 rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
4857 secret_id_part);
4858 if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
4859 log_warn(LD_REND, "Parsed descriptor ID does not match "
4860 "computed descriptor ID.");
4861 goto err;
4863 goto done;
4864 err:
4865 rend_service_descriptor_free(result);
4866 result = NULL;
4867 done:
4868 if (tokens) {
4869 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
4870 smartlist_free(tokens);
4872 if (area)
4873 memarea_drop_all(area);
4874 *parsed_out = result;
4875 if (result)
4876 return 0;
4877 return -1;
4880 /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
4881 * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
4882 * write the result to a newly allocated string that is pointed to by
4883 * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
4884 * Return 0 if decryption was successful and -1 otherwise. */
4886 rend_decrypt_introduction_points(char **ipos_decrypted,
4887 size_t *ipos_decrypted_size,
4888 const char *descriptor_cookie,
4889 const char *ipos_encrypted,
4890 size_t ipos_encrypted_size)
4892 tor_assert(ipos_encrypted);
4893 tor_assert(descriptor_cookie);
4894 if (ipos_encrypted_size < 2) {
4895 log_warn(LD_REND, "Size of encrypted introduction points is too "
4896 "small.");
4897 return -1;
4899 if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
4900 char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
4901 session_key[CIPHER_KEY_LEN], *dec;
4902 int declen, client_blocks;
4903 size_t pos = 0, len, client_entries_len;
4904 crypto_digest_t *digest;
4905 crypto_cipher_t *cipher;
4906 client_blocks = (int) ipos_encrypted[1];
4907 client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
4908 REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
4909 if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
4910 log_warn(LD_REND, "Size of encrypted introduction points is too "
4911 "small.");
4912 return -1;
4914 memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
4915 digest = crypto_digest_new();
4916 crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
4917 crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
4918 crypto_digest_get_digest(digest, client_id,
4919 REND_BASIC_AUTH_CLIENT_ID_LEN);
4920 crypto_digest_free(digest);
4921 for (pos = 2; pos < 2 + client_entries_len;
4922 pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
4923 if (tor_memeq(ipos_encrypted + pos, client_id,
4924 REND_BASIC_AUTH_CLIENT_ID_LEN)) {
4925 /* Attempt to decrypt introduction points. */
4926 cipher = crypto_cipher_new(descriptor_cookie);
4927 if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
4928 + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
4929 CIPHER_KEY_LEN) < 0) {
4930 log_warn(LD_REND, "Could not decrypt session key for client.");
4931 crypto_cipher_free(cipher);
4932 return -1;
4934 crypto_cipher_free(cipher);
4936 len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
4937 dec = tor_malloc(len);
4938 declen = crypto_cipher_decrypt_with_iv(session_key, dec, len,
4939 ipos_encrypted + 2 + client_entries_len,
4940 ipos_encrypted_size - 2 - client_entries_len);
4942 if (declen < 0) {
4943 log_warn(LD_REND, "Could not decrypt introduction point string.");
4944 tor_free(dec);
4945 return -1;
4947 if (fast_memcmpstart(dec, declen, "introduction-point ")) {
4948 log_warn(LD_REND, "Decrypted introduction points don't "
4949 "look like we could parse them.");
4950 tor_free(dec);
4951 continue;
4953 *ipos_decrypted = dec;
4954 *ipos_decrypted_size = declen;
4955 return 0;
4958 log_warn(LD_REND, "Could not decrypt introduction points. Please "
4959 "check your authorization for this service!");
4960 return -1;
4961 } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
4962 char *dec;
4963 int declen;
4964 if (ipos_encrypted_size < CIPHER_IV_LEN + 2) {
4965 log_warn(LD_REND, "Size of encrypted introduction points is too "
4966 "small.");
4967 return -1;
4969 dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
4971 declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec,
4972 ipos_encrypted_size -
4973 CIPHER_IV_LEN - 1,
4974 ipos_encrypted + 1,
4975 ipos_encrypted_size - 1);
4977 if (declen < 0) {
4978 log_warn(LD_REND, "Decrypting introduction points failed!");
4979 tor_free(dec);
4980 return -1;
4982 *ipos_decrypted = dec;
4983 *ipos_decrypted_size = declen;
4984 return 0;
4985 } else {
4986 log_warn(LD_REND, "Unknown authorization type number: %d",
4987 ipos_encrypted[0]);
4988 return -1;
4992 /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
4993 * length <b>intro_points_encoded_size</b> and write the result to the
4994 * descriptor in <b>parsed</b>; return the number of successfully parsed
4995 * introduction points or -1 in case of a failure. */
4997 rend_parse_introduction_points(rend_service_descriptor_t *parsed,
4998 const char *intro_points_encoded,
4999 size_t intro_points_encoded_size)
5001 const char *current_ipo, *end_of_intro_points;
5002 smartlist_t *tokens;
5003 directory_token_t *tok;
5004 rend_intro_point_t *intro;
5005 extend_info_t *info;
5006 int result, num_ok=1;
5007 memarea_t *area = NULL;
5008 tor_assert(parsed);
5009 /** Function may only be invoked once. */
5010 tor_assert(!parsed->intro_nodes);
5011 tor_assert(intro_points_encoded);
5012 tor_assert(intro_points_encoded_size > 0);
5013 /* Consider one intro point after the other. */
5014 current_ipo = intro_points_encoded;
5015 end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
5016 tokens = smartlist_new();
5017 parsed->intro_nodes = smartlist_new();
5018 area = memarea_new();
5020 while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
5021 "introduction-point ")) {
5022 /* Determine end of string. */
5023 const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
5024 "\nintroduction-point ");
5025 if (!eos)
5026 eos = end_of_intro_points;
5027 else
5028 eos = eos+1;
5029 tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
5030 /* Free tokens and clear token list. */
5031 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
5032 smartlist_clear(tokens);
5033 memarea_clear(area);
5034 /* Tokenize string. */
5035 if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
5036 log_warn(LD_REND, "Error tokenizing introduction point");
5037 goto err;
5039 /* Advance to next introduction point, if available. */
5040 current_ipo = eos;
5041 /* Check minimum allowed length of introduction point. */
5042 if (smartlist_len(tokens) < 5) {
5043 log_warn(LD_REND, "Impossibly short introduction point.");
5044 goto err;
5046 /* Allocate new intro point and extend info. */
5047 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
5048 info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
5049 /* Parse identifier. */
5050 tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
5051 if (base32_decode(info->identity_digest, DIGEST_LEN,
5052 tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
5053 log_warn(LD_REND, "Identity digest contains illegal characters: %s",
5054 tok->args[0]);
5055 rend_intro_point_free(intro);
5056 goto err;
5058 /* Write identifier to nickname. */
5059 info->nickname[0] = '$';
5060 base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
5061 info->identity_digest, DIGEST_LEN);
5062 /* Parse IP address. */
5063 tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
5064 if (tor_addr_parse(&info->addr, tok->args[0])<0) {
5065 log_warn(LD_REND, "Could not parse introduction point address.");
5066 rend_intro_point_free(intro);
5067 goto err;
5069 if (tor_addr_family(&info->addr) != AF_INET) {
5070 log_warn(LD_REND, "Introduction point address was not ipv4.");
5071 rend_intro_point_free(intro);
5072 goto err;
5075 /* Parse onion port. */
5076 tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
5077 info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
5078 &num_ok,NULL);
5079 if (!info->port || !num_ok) {
5080 log_warn(LD_REND, "Introduction point onion port %s is invalid",
5081 escaped(tok->args[0]));
5082 rend_intro_point_free(intro);
5083 goto err;
5085 /* Parse onion key. */
5086 tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
5087 if (!crypto_pk_public_exponent_ok(tok->key)) {
5088 log_warn(LD_REND,
5089 "Introduction point's onion key had invalid exponent.");
5090 rend_intro_point_free(intro);
5091 goto err;
5093 info->onion_key = tok->key;
5094 tok->key = NULL; /* Prevent free */
5095 /* Parse service key. */
5096 tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
5097 if (!crypto_pk_public_exponent_ok(tok->key)) {
5098 log_warn(LD_REND,
5099 "Introduction point key had invalid exponent.");
5100 rend_intro_point_free(intro);
5101 goto err;
5103 intro->intro_key = tok->key;
5104 tok->key = NULL; /* Prevent free */
5105 /* Add extend info to list of introduction points. */
5106 smartlist_add(parsed->intro_nodes, intro);
5108 result = smartlist_len(parsed->intro_nodes);
5109 goto done;
5111 err:
5112 result = -1;
5114 done:
5115 /* Free tokens and clear token list. */
5116 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
5117 smartlist_free(tokens);
5118 if (area)
5119 memarea_drop_all(area);
5121 return result;
5124 /** Parse the content of a client_key file in <b>ckstr</b> and add
5125 * rend_authorized_client_t's for each parsed client to
5126 * <b>parsed_clients</b>. Return the number of parsed clients as result
5127 * or -1 for failure. */
5129 rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
5131 int result = -1;
5132 smartlist_t *tokens;
5133 directory_token_t *tok;
5134 const char *current_entry = NULL;
5135 memarea_t *area = NULL;
5136 if (!ckstr || strlen(ckstr) == 0)
5137 return -1;
5138 tokens = smartlist_new();
5139 /* Begin parsing with first entry, skipping comments or whitespace at the
5140 * beginning. */
5141 area = memarea_new();
5142 current_entry = eat_whitespace(ckstr);
5143 while (!strcmpstart(current_entry, "client-name ")) {
5144 rend_authorized_client_t *parsed_entry;
5145 size_t len;
5146 char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
5147 /* Determine end of string. */
5148 const char *eos = strstr(current_entry, "\nclient-name ");
5149 if (!eos)
5150 eos = current_entry + strlen(current_entry);
5151 else
5152 eos = eos + 1;
5153 /* Free tokens and clear token list. */
5154 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
5155 smartlist_clear(tokens);
5156 memarea_clear(area);
5157 /* Tokenize string. */
5158 if (tokenize_string(area, current_entry, eos, tokens,
5159 client_keys_token_table, 0)) {
5160 log_warn(LD_REND, "Error tokenizing client keys file.");
5161 goto err;
5163 /* Advance to next entry, if available. */
5164 current_entry = eos;
5165 /* Check minimum allowed length of token list. */
5166 if (smartlist_len(tokens) < 2) {
5167 log_warn(LD_REND, "Impossibly short client key entry.");
5168 goto err;
5170 /* Parse client name. */
5171 tok = find_by_keyword(tokens, C_CLIENT_NAME);
5172 tor_assert(tok == smartlist_get(tokens, 0));
5173 tor_assert(tok->n_args == 1);
5175 len = strlen(tok->args[0]);
5176 if (len < 1 || len > 19 ||
5177 strspn(tok->args[0], REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
5178 log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
5179 "between 1 and 19, and valid characters are "
5180 "[A-Za-z0-9+-_].)", tok->args[0]);
5181 goto err;
5183 /* Check if client name is duplicate. */
5184 if (strmap_get(parsed_clients, tok->args[0])) {
5185 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
5186 "duplicate client name: '%s'. Ignoring.", tok->args[0]);
5187 goto err;
5189 parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
5190 parsed_entry->client_name = tor_strdup(tok->args[0]);
5191 strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
5192 /* Parse client key. */
5193 tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
5194 if (tok) {
5195 parsed_entry->client_key = tok->key;
5196 tok->key = NULL; /* Prevent free */
5199 /* Parse descriptor cookie. */
5200 tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
5201 tor_assert(tok->n_args == 1);
5202 if (strlen(tok->args[0]) != REND_DESC_COOKIE_LEN_BASE64 + 2) {
5203 log_warn(LD_REND, "Descriptor cookie has illegal length: %s",
5204 escaped(tok->args[0]));
5205 goto err;
5207 /* The size of descriptor_cookie_tmp needs to be REND_DESC_COOKIE_LEN+2,
5208 * because a base64 encoding of length 24 does not fit into 16 bytes in all
5209 * cases. */
5210 if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
5211 tok->args[0], strlen(tok->args[0]))
5212 != REND_DESC_COOKIE_LEN) {
5213 log_warn(LD_REND, "Descriptor cookie contains illegal characters: "
5214 "%s", escaped(tok->args[0]));
5215 goto err;
5217 memcpy(parsed_entry->descriptor_cookie, descriptor_cookie_tmp,
5218 REND_DESC_COOKIE_LEN);
5220 result = strmap_size(parsed_clients);
5221 goto done;
5222 err:
5223 result = -1;
5224 done:
5225 /* Free tokens and clear token list. */
5226 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
5227 smartlist_free(tokens);
5228 if (area)
5229 memarea_drop_all(area);
5230 return result;