Look at the correct protocol for supports_v3_rendezvous_point
[tor/appveyor.git] / src / or / routerparse.c
blob3eda024f0fc9411bf9f30e8b04835e70d1cf2c32
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-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file routerparse.c
9 * \brief Code to parse and validate router descriptors, consenus directories,
10 * and similar objects.
12 * The objects parsed by this module use a common text-based metaformat,
13 * documented in dir-spec.txt in torspec.git. This module is itself divided
14 * into two major kinds of function: code to handle the metaformat, and code
15 * to convert from particular instances of the metaformat into the
16 * objects that Tor uses.
18 * The generic parsing code works by calling a table-based tokenizer on the
19 * input string. Each token corresponds to a single line with a token, plus
20 * optional arguments on that line, plus an optional base-64 encoded object
21 * after that line. Each token has a definition in a table of token_rule_t
22 * entries that describes how many arguments it can take, whether it takes an
23 * object, how many times it may appear, whether it must appear first, and so
24 * on.
26 * The tokenizer function tokenize_string() converts its string input into a
27 * smartlist full of instances of directory_token_t, according to a provided
28 * table of token_rule_t.
30 * The generic parts of this module additionally include functions for
31 * finding the start and end of signed information inside a signed object, and
32 * computing the digest that will be signed.
34 * There are also functions for saving objects to disk that have caused
35 * parsing to fail.
37 * The specific parts of this module describe conversions between
38 * particular lists of directory_token_t and particular objects. The
39 * kinds of objects that can be parsed here are:
40 * <ul>
41 * <li>router descriptors (managed from routerlist.c)
42 * <li>extra-info documents (managed from routerlist.c)
43 * <li>microdescriptors (managed from microdesc.c)
44 * <li>vote and consensus networkstatus documents, and the routerstatus_t
45 * objects that they comprise (managed from networkstatus.c)
46 * <li>detached-signature objects used by authorities for gathering
47 * signatures on the networkstatus consensus (managed from dirvote.c)
48 * <li>authority key certificates (managed from routerlist.c)
49 * <li>hidden service descriptors (managed from rendcommon.c and rendcache.c)
50 * </ul>
52 * For no terribly good reason, the functions to <i>generate</i> signatures on
53 * the above directory objects are also in this module.
54 **/
56 #define ROUTERPARSE_PRIVATE
58 #include "or.h"
59 #include "config.h"
60 #include "circuitstats.h"
61 #include "dirserv.h"
62 #include "dirvote.h"
63 #include "parsecommon.h"
64 #include "policies.h"
65 #include "protover.h"
66 #include "rendcommon.h"
67 #include "router.h"
68 #include "routerlist.h"
69 #include "memarea.h"
70 #include "microdesc.h"
71 #include "networkstatus.h"
72 #include "rephist.h"
73 #include "routerkeys.h"
74 #include "routerparse.h"
75 #include "entrynodes.h"
76 #include "torcert.h"
77 #include "sandbox.h"
78 #include "shared_random.h"
80 #undef log
81 #include <math.h>
83 /****************************************************************************/
85 /** List of tokens recognized in router descriptors */
86 static token_rule_t routerdesc_token_table[] = {
87 T0N("reject", K_REJECT, ARGS, NO_OBJ ),
88 T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
89 T0N("reject6", K_REJECT6, ARGS, NO_OBJ ),
90 T0N("accept6", K_ACCEPT6, ARGS, NO_OBJ ),
91 T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
92 T01("ipv6-policy", K_IPV6_POLICY, CONCAT_ARGS, NO_OBJ),
93 T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
94 T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
95 T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
96 T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
97 T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
98 T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
99 T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
100 T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
101 T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
102 T01("proto", K_PROTO, CONCAT_ARGS, NO_OBJ ),
103 T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
104 T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
105 T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
106 T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
107 T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
108 T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
109 T01("master-key-ed25519", K_MASTER_KEY_ED25519, GE(1), NO_OBJ ),
110 T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
111 T01("onion-key-crosscert", K_ONION_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),
112 T01("ntor-onion-key-crosscert", K_NTOR_ONION_KEY_CROSSCERT,
113 EQ(1), NEED_OBJ ),
115 T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
117 T01("family", K_FAMILY, ARGS, NO_OBJ ),
118 T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
119 T0N("or-address", K_OR_ADDRESS, GE(1), NO_OBJ ),
121 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
122 T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
123 A01("@purpose", A_PURPOSE, GE(1), NO_OBJ ),
124 T01("tunnelled-dir-server",K_DIR_TUNNELLED, NO_ARGS, NO_OBJ ),
126 END_OF_TABLE
129 /** List of tokens recognized in extra-info documents. */
130 static token_rule_t extrainfo_token_table[] = {
131 T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
132 T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
133 T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
134 T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
135 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
136 T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
137 T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
138 T01("dirreq-stats-end", K_DIRREQ_END, ARGS, NO_OBJ ),
139 T01("dirreq-v2-ips", K_DIRREQ_V2_IPS, ARGS, NO_OBJ ),
140 T01("dirreq-v3-ips", K_DIRREQ_V3_IPS, ARGS, NO_OBJ ),
141 T01("dirreq-v2-reqs", K_DIRREQ_V2_REQS, ARGS, NO_OBJ ),
142 T01("dirreq-v3-reqs", K_DIRREQ_V3_REQS, ARGS, NO_OBJ ),
143 T01("dirreq-v2-share", K_DIRREQ_V2_SHARE, ARGS, NO_OBJ ),
144 T01("dirreq-v3-share", K_DIRREQ_V3_SHARE, ARGS, NO_OBJ ),
145 T01("dirreq-v2-resp", K_DIRREQ_V2_RESP, ARGS, NO_OBJ ),
146 T01("dirreq-v3-resp", K_DIRREQ_V3_RESP, ARGS, NO_OBJ ),
147 T01("dirreq-v2-direct-dl", K_DIRREQ_V2_DIR, ARGS, NO_OBJ ),
148 T01("dirreq-v3-direct-dl", K_DIRREQ_V3_DIR, ARGS, NO_OBJ ),
149 T01("dirreq-v2-tunneled-dl", K_DIRREQ_V2_TUN, ARGS, NO_OBJ ),
150 T01("dirreq-v3-tunneled-dl", K_DIRREQ_V3_TUN, ARGS, NO_OBJ ),
151 T01("entry-stats-end", K_ENTRY_END, ARGS, NO_OBJ ),
152 T01("entry-ips", K_ENTRY_IPS, ARGS, NO_OBJ ),
153 T01("cell-stats-end", K_CELL_END, ARGS, NO_OBJ ),
154 T01("cell-processed-cells", K_CELL_PROCESSED, ARGS, NO_OBJ ),
155 T01("cell-queued-cells", K_CELL_QUEUED, ARGS, NO_OBJ ),
156 T01("cell-time-in-queue", K_CELL_TIME, ARGS, NO_OBJ ),
157 T01("cell-circuits-per-decile", K_CELL_CIRCS, ARGS, NO_OBJ ),
158 T01("exit-stats-end", K_EXIT_END, ARGS, NO_OBJ ),
159 T01("exit-kibibytes-written", K_EXIT_WRITTEN, ARGS, NO_OBJ ),
160 T01("exit-kibibytes-read", K_EXIT_READ, ARGS, NO_OBJ ),
161 T01("exit-streams-opened", K_EXIT_OPENED, ARGS, NO_OBJ ),
163 T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
165 END_OF_TABLE
168 /** List of tokens recognized in the body part of v3 networkstatus
169 * documents. */
170 static token_rule_t rtrstatus_token_table[] = {
171 T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
172 T1( "r", K_R, GE(7), NO_OBJ ),
173 T0N("a", K_A, GE(1), NO_OBJ ),
174 T1( "s", K_S, ARGS, NO_OBJ ),
175 T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
176 T01("w", K_W, ARGS, NO_OBJ ),
177 T0N("m", K_M, CONCAT_ARGS, NO_OBJ ),
178 T0N("id", K_ID, GE(2), NO_OBJ ),
179 T01("pr", K_PROTO, CONCAT_ARGS, NO_OBJ ),
180 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
181 END_OF_TABLE
184 /** List of tokens common to V3 authority certificates and V3 consensuses. */
185 #define CERTIFICATE_MEMBERS \
186 T1("dir-key-certificate-version", K_DIR_KEY_CERTIFICATE_VERSION, \
187 GE(1), NO_OBJ ), \
188 T1("dir-identity-key", K_DIR_IDENTITY_KEY, NO_ARGS, NEED_KEY ),\
189 T1("dir-key-published",K_DIR_KEY_PUBLISHED, CONCAT_ARGS, NO_OBJ), \
190 T1("dir-key-expires", K_DIR_KEY_EXPIRES, CONCAT_ARGS, NO_OBJ), \
191 T1("dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY ),\
192 T1("dir-key-crosscert", K_DIR_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),\
193 T1("dir-key-certification", K_DIR_KEY_CERTIFICATION, \
194 NO_ARGS, NEED_OBJ), \
195 T01("dir-address", K_DIR_ADDRESS, GE(1), NO_OBJ),
197 /** List of tokens recognized in V3 authority certificates. */
198 static token_rule_t dir_key_certificate_table[] = {
199 CERTIFICATE_MEMBERS
200 T1("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
201 END_OF_TABLE
204 /** List of tokens recognized in rendezvous service descriptors */
205 static token_rule_t desc_token_table[] = {
206 T1_START("rendezvous-service-descriptor", R_RENDEZVOUS_SERVICE_DESCRIPTOR,
207 EQ(1), NO_OBJ),
208 T1("version", R_VERSION, EQ(1), NO_OBJ),
209 T1("permanent-key", R_PERMANENT_KEY, NO_ARGS, NEED_KEY_1024),
210 T1("secret-id-part", R_SECRET_ID_PART, EQ(1), NO_OBJ),
211 T1("publication-time", R_PUBLICATION_TIME, CONCAT_ARGS, NO_OBJ),
212 T1("protocol-versions", R_PROTOCOL_VERSIONS, EQ(1), NO_OBJ),
213 T01("introduction-points", R_INTRODUCTION_POINTS, NO_ARGS, NEED_OBJ),
214 T1_END("signature", R_SIGNATURE, NO_ARGS, NEED_OBJ),
215 END_OF_TABLE
218 /** List of tokens recognized in the (encrypted) list of introduction points of
219 * rendezvous service descriptors */
220 static token_rule_t ipo_token_table[] = {
221 T1_START("introduction-point", R_IPO_IDENTIFIER, EQ(1), NO_OBJ),
222 T1("ip-address", R_IPO_IP_ADDRESS, EQ(1), NO_OBJ),
223 T1("onion-port", R_IPO_ONION_PORT, EQ(1), NO_OBJ),
224 T1("onion-key", R_IPO_ONION_KEY, NO_ARGS, NEED_KEY_1024),
225 T1("service-key", R_IPO_SERVICE_KEY, NO_ARGS, NEED_KEY_1024),
226 END_OF_TABLE
229 /** List of tokens recognized in the (possibly encrypted) list of introduction
230 * points of rendezvous service descriptors */
231 static token_rule_t client_keys_token_table[] = {
232 T1_START("client-name", C_CLIENT_NAME, CONCAT_ARGS, NO_OBJ),
233 T1("descriptor-cookie", C_DESCRIPTOR_COOKIE, EQ(1), NO_OBJ),
234 T01("client-key", C_CLIENT_KEY, NO_ARGS, NEED_SKEY_1024),
235 END_OF_TABLE
238 /** List of tokens recognized in V3 networkstatus votes. */
239 static token_rule_t networkstatus_token_table[] = {
240 T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
241 GE(1), NO_OBJ ),
242 T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
243 T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
244 T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
245 T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
246 T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
247 T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
248 T1("known-flags", K_KNOWN_FLAGS, ARGS, NO_OBJ ),
249 T01("params", K_PARAMS, ARGS, NO_OBJ ),
250 T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
251 T01("signing-ed25519", K_SIGNING_CERT_ED, NO_ARGS , NEED_OBJ ),
252 T01("shared-rand-participate",K_SR_FLAG, NO_ARGS, NO_OBJ ),
253 T0N("shared-rand-commit", K_COMMIT, GE(3), NO_OBJ ),
254 T01("shared-rand-previous-value", K_PREVIOUS_SRV,EQ(2), NO_OBJ ),
255 T01("shared-rand-current-value", K_CURRENT_SRV, EQ(2), NO_OBJ ),
256 T0N("package", K_PACKAGE, CONCAT_ARGS, NO_OBJ ),
257 T01("recommended-client-protocols", K_RECOMMENDED_CLIENT_PROTOCOLS,
258 CONCAT_ARGS, NO_OBJ ),
259 T01("recommended-relay-protocols", K_RECOMMENDED_RELAY_PROTOCOLS,
260 CONCAT_ARGS, NO_OBJ ),
261 T01("required-client-protocols", K_REQUIRED_CLIENT_PROTOCOLS,
262 CONCAT_ARGS, NO_OBJ ),
263 T01("required-relay-protocols", K_REQUIRED_RELAY_PROTOCOLS,
264 CONCAT_ARGS, NO_OBJ ),
266 CERTIFICATE_MEMBERS
268 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
269 T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
270 T1( "dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
271 T01("legacy-dir-key", K_LEGACY_DIR_KEY, GE(1), NO_OBJ ),
272 T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
273 T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
274 T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
275 T1( "consensus-methods", K_CONSENSUS_METHODS, GE(1), NO_OBJ ),
277 END_OF_TABLE
280 /** List of tokens recognized in V3 networkstatus consensuses. */
281 static token_rule_t networkstatus_consensus_token_table[] = {
282 T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
283 GE(1), NO_OBJ ),
284 T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
285 T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
286 T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
287 T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
288 T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
290 T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
292 T1N("dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
293 T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
294 T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
296 T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
298 T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
299 T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
300 T01("consensus-method", K_CONSENSUS_METHOD, EQ(1), NO_OBJ),
301 T01("params", K_PARAMS, ARGS, NO_OBJ ),
303 T01("shared-rand-previous-value", K_PREVIOUS_SRV, EQ(2), NO_OBJ ),
304 T01("shared-rand-current-value", K_CURRENT_SRV, EQ(2), NO_OBJ ),
306 T01("recommended-client-protocols", K_RECOMMENDED_CLIENT_PROTOCOLS,
307 CONCAT_ARGS, NO_OBJ ),
308 T01("recommended-relay-protocols", K_RECOMMENDED_RELAY_PROTOCOLS,
309 CONCAT_ARGS, NO_OBJ ),
310 T01("required-client-protocols", K_REQUIRED_CLIENT_PROTOCOLS,
311 CONCAT_ARGS, NO_OBJ ),
312 T01("required-relay-protocols", K_REQUIRED_RELAY_PROTOCOLS,
313 CONCAT_ARGS, NO_OBJ ),
315 END_OF_TABLE
318 /** List of tokens recognized in the footer of v1 directory footers. */
319 static token_rule_t networkstatus_vote_footer_token_table[] = {
320 T01("directory-footer", K_DIRECTORY_FOOTER, NO_ARGS, NO_OBJ ),
321 T01("bandwidth-weights", K_BW_WEIGHTS, ARGS, NO_OBJ ),
322 T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
323 END_OF_TABLE
326 /** List of tokens recognized in detached networkstatus signature documents. */
327 static token_rule_t networkstatus_detached_signature_token_table[] = {
328 T1_START("consensus-digest", K_CONSENSUS_DIGEST, GE(1), NO_OBJ ),
329 T("additional-digest", K_ADDITIONAL_DIGEST,GE(3), NO_OBJ ),
330 T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
331 T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
332 T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
333 T("additional-signature", K_ADDITIONAL_SIGNATURE, GE(4), NEED_OBJ ),
334 T1N("directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
335 END_OF_TABLE
338 /** List of tokens recognized in microdescriptors */
339 static token_rule_t microdesc_token_table[] = {
340 T1_START("onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024),
341 T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
342 T0N("id", K_ID, GE(2), NO_OBJ ),
343 T0N("a", K_A, GE(1), NO_OBJ ),
344 T01("family", K_FAMILY, ARGS, NO_OBJ ),
345 T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
346 T01("p6", K_P6, CONCAT_ARGS, NO_OBJ ),
347 A01("@last-listed", A_LAST_LISTED, CONCAT_ARGS, NO_OBJ ),
348 END_OF_TABLE
351 #undef T
353 /* static function prototypes */
354 static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
355 static addr_policy_t *router_parse_addr_policy(directory_token_t *tok,
356 unsigned fmt_flags);
357 static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
359 static int router_get_hash_impl_helper(const char *s, size_t s_len,
360 const char *start_str,
361 const char *end_str, char end_c,
362 int log_severity,
363 const char **start_out, const char **end_out);
364 static int router_get_hash_impl(const char *s, size_t s_len, char *digest,
365 const char *start_str, const char *end_str,
366 char end_char,
367 digest_algorithm_t alg);
368 static int router_get_hashes_impl(const char *s, size_t s_len,
369 common_digests_t *digests,
370 const char *start_str, const char *end_str,
371 char end_char);
372 static smartlist_t *find_all_exitpolicy(smartlist_t *s);
374 #define CST_NO_CHECK_OBJTYPE (1<<0)
375 static int check_signature_token(const char *digest,
376 ssize_t digest_len,
377 directory_token_t *tok,
378 crypto_pk_t *pkey,
379 int flags,
380 const char *doctype);
382 #undef DEBUG_AREA_ALLOC
384 #ifdef DEBUG_AREA_ALLOC
385 #define DUMP_AREA(a,name) STMT_BEGIN \
386 size_t alloc=0, used=0; \
387 memarea_get_stats((a),&alloc,&used); \
388 log_debug(LD_MM, "Area for %s has %lu allocated; using %lu.", \
389 name, (unsigned long)alloc, (unsigned long)used); \
390 STMT_END
391 #else /* !(defined(DEBUG_AREA_ALLOC)) */
392 #define DUMP_AREA(a,name) STMT_NIL
393 #endif /* defined(DEBUG_AREA_ALLOC) */
395 /* Dump mechanism for unparseable descriptors */
397 /** List of dumped descriptors for FIFO cleanup purposes */
398 STATIC smartlist_t *descs_dumped = NULL;
399 /** Total size of dumped descriptors for FIFO cleanup */
400 STATIC uint64_t len_descs_dumped = 0;
401 /** Directory to stash dumps in */
402 static int have_dump_desc_dir = 0;
403 static int problem_with_dump_desc_dir = 0;
405 #define DESC_DUMP_DATADIR_SUBDIR "unparseable-descs"
406 #define DESC_DUMP_BASE_FILENAME "unparseable-desc"
408 /** Find the dump directory and check if we'll be able to create it */
409 static void
410 dump_desc_init(void)
412 char *dump_desc_dir;
414 dump_desc_dir = get_datadir_fname(DESC_DUMP_DATADIR_SUBDIR);
417 * We just check for it, don't create it at this point; we'll
418 * create it when we need it if it isn't already there.
420 if (check_private_dir(dump_desc_dir, CPD_CHECK, get_options()->User) < 0) {
421 /* Error, log and flag it as having a problem */
422 log_notice(LD_DIR,
423 "Doesn't look like we'll be able to create descriptor dump "
424 "directory %s; dumps will be disabled.",
425 dump_desc_dir);
426 problem_with_dump_desc_dir = 1;
427 tor_free(dump_desc_dir);
428 return;
431 /* Check if it exists */
432 switch (file_status(dump_desc_dir)) {
433 case FN_DIR:
434 /* We already have a directory */
435 have_dump_desc_dir = 1;
436 break;
437 case FN_NOENT:
438 /* Nothing, we'll need to create it later */
439 have_dump_desc_dir = 0;
440 break;
441 case FN_ERROR:
442 /* Log and flag having a problem */
443 log_notice(LD_DIR,
444 "Couldn't check whether descriptor dump directory %s already"
445 " exists: %s",
446 dump_desc_dir, strerror(errno));
447 problem_with_dump_desc_dir = 1;
448 break;
449 case FN_FILE:
450 case FN_EMPTY:
451 default:
452 /* Something else was here! */
453 log_notice(LD_DIR,
454 "Descriptor dump directory %s already exists and isn't a "
455 "directory",
456 dump_desc_dir);
457 problem_with_dump_desc_dir = 1;
460 if (have_dump_desc_dir && !problem_with_dump_desc_dir) {
461 dump_desc_populate_fifo_from_directory(dump_desc_dir);
464 tor_free(dump_desc_dir);
467 /** Create the dump directory if needed and possible */
468 static void
469 dump_desc_create_dir(void)
471 char *dump_desc_dir;
473 /* If the problem flag is set, skip it */
474 if (problem_with_dump_desc_dir) return;
476 /* Do we need it? */
477 if (!have_dump_desc_dir) {
478 dump_desc_dir = get_datadir_fname(DESC_DUMP_DATADIR_SUBDIR);
480 if (check_private_dir(dump_desc_dir, CPD_CREATE,
481 get_options()->User) < 0) {
482 log_notice(LD_DIR,
483 "Failed to create descriptor dump directory %s",
484 dump_desc_dir);
485 problem_with_dump_desc_dir = 1;
488 /* Okay, we created it */
489 have_dump_desc_dir = 1;
491 tor_free(dump_desc_dir);
495 /** Dump desc FIFO/cleanup; take ownership of the given filename, add it to
496 * the FIFO, and clean up the oldest entries to the extent they exceed the
497 * configured cap. If any old entries with a matching hash existed, they
498 * just got overwritten right before this was called and we should adjust
499 * the total size counter without deleting them.
501 static void
502 dump_desc_fifo_add_and_clean(char *filename, const uint8_t *digest_sha256,
503 size_t len)
505 dumped_desc_t *ent = NULL, *tmp;
506 uint64_t max_len;
508 tor_assert(filename != NULL);
509 tor_assert(digest_sha256 != NULL);
511 if (descs_dumped == NULL) {
512 /* We better have no length, then */
513 tor_assert(len_descs_dumped == 0);
514 /* Make a smartlist */
515 descs_dumped = smartlist_new();
518 /* Make a new entry to put this one in */
519 ent = tor_malloc_zero(sizeof(*ent));
520 ent->filename = filename;
521 ent->len = len;
522 ent->when = time(NULL);
523 memcpy(ent->digest_sha256, digest_sha256, DIGEST256_LEN);
525 /* Do we need to do some cleanup? */
526 max_len = get_options()->MaxUnparseableDescSizeToLog;
527 /* Iterate over the list until we've freed enough space */
528 while (len > max_len - len_descs_dumped &&
529 smartlist_len(descs_dumped) > 0) {
530 /* Get the oldest thing on the list */
531 tmp = (dumped_desc_t *)(smartlist_get(descs_dumped, 0));
534 * Check if it matches the filename we just added, so we don't delete
535 * something we just emitted if we get repeated identical descriptors.
537 if (strcmp(tmp->filename, filename) != 0) {
538 /* Delete it and adjust the length counter */
539 tor_unlink(tmp->filename);
540 tor_assert(len_descs_dumped >= tmp->len);
541 len_descs_dumped -= tmp->len;
542 log_info(LD_DIR,
543 "Deleting old unparseable descriptor dump %s due to "
544 "space limits",
545 tmp->filename);
546 } else {
548 * Don't delete, but do adjust the counter since we will bump it
549 * later
551 tor_assert(len_descs_dumped >= tmp->len);
552 len_descs_dumped -= tmp->len;
553 log_info(LD_DIR,
554 "Replacing old descriptor dump %s with new identical one",
555 tmp->filename);
558 /* Free it and remove it from the list */
559 smartlist_del_keeporder(descs_dumped, 0);
560 tor_free(tmp->filename);
561 tor_free(tmp);
564 /* Append our entry to the end of the list and bump the counter */
565 smartlist_add(descs_dumped, ent);
566 len_descs_dumped += len;
569 /** Check if we already have a descriptor for this hash and move it to the
570 * head of the queue if so. Return 1 if one existed and 0 otherwise.
572 static int
573 dump_desc_fifo_bump_hash(const uint8_t *digest_sha256)
575 dumped_desc_t *match = NULL;
577 tor_assert(digest_sha256);
579 if (descs_dumped) {
580 /* Find a match if one exists */
581 SMARTLIST_FOREACH_BEGIN(descs_dumped, dumped_desc_t *, ent) {
582 if (ent &&
583 tor_memeq(ent->digest_sha256, digest_sha256, DIGEST256_LEN)) {
585 * Save a pointer to the match and remove it from its current
586 * position.
588 match = ent;
589 SMARTLIST_DEL_CURRENT_KEEPORDER(descs_dumped, ent);
590 break;
592 } SMARTLIST_FOREACH_END(ent);
594 if (match) {
595 /* Update the timestamp */
596 match->when = time(NULL);
597 /* Add it back at the end of the list */
598 smartlist_add(descs_dumped, match);
600 /* Indicate we found one */
601 return 1;
605 return 0;
608 /** Clean up on exit; just memory, leave the dumps behind
610 STATIC void
611 dump_desc_fifo_cleanup(void)
613 if (descs_dumped) {
614 /* Free each descriptor */
615 SMARTLIST_FOREACH_BEGIN(descs_dumped, dumped_desc_t *, ent) {
616 tor_assert(ent);
617 tor_free(ent->filename);
618 tor_free(ent);
619 } SMARTLIST_FOREACH_END(ent);
620 /* Free the list */
621 smartlist_free(descs_dumped);
622 descs_dumped = NULL;
623 len_descs_dumped = 0;
627 /** Handle one file for dump_desc_populate_fifo_from_directory(); make sure
628 * the filename is sensibly formed and matches the file content, and either
629 * return a dumped_desc_t for it or remove the file and return NULL.
631 MOCK_IMPL(STATIC dumped_desc_t *,
632 dump_desc_populate_one_file, (const char *dirname, const char *f))
634 dumped_desc_t *ent = NULL;
635 char *path = NULL, *desc = NULL;
636 const char *digest_str;
637 char digest[DIGEST256_LEN], content_digest[DIGEST256_LEN];
638 /* Expected prefix before digest in filenames */
639 const char *f_pfx = DESC_DUMP_BASE_FILENAME ".";
641 * Stat while reading; this is important in case the file
642 * contains a NUL character.
644 struct stat st;
646 /* Sanity-check args */
647 tor_assert(dirname != NULL);
648 tor_assert(f != NULL);
650 /* Form the full path */
651 tor_asprintf(&path, "%s" PATH_SEPARATOR "%s", dirname, f);
653 /* Check that f has the form DESC_DUMP_BASE_FILENAME.<digest256> */
655 if (!strcmpstart(f, f_pfx)) {
656 /* It matches the form, but is the digest parseable as such? */
657 digest_str = f + strlen(f_pfx);
658 if (base16_decode(digest, DIGEST256_LEN,
659 digest_str, strlen(digest_str)) != DIGEST256_LEN) {
660 /* We failed to decode it */
661 digest_str = NULL;
663 } else {
664 /* No match */
665 digest_str = NULL;
668 if (!digest_str) {
669 /* We couldn't get a sensible digest */
670 log_notice(LD_DIR,
671 "Removing unrecognized filename %s from unparseable "
672 "descriptors directory", f);
673 tor_unlink(path);
674 /* We're done */
675 goto done;
679 * The filename has the form DESC_DUMP_BASE_FILENAME "." <digest256> and
680 * we've decoded the digest. Next, check that we can read it and the
681 * content matches this digest. We are relying on the fact that if the
682 * file contains a '\0', read_file_to_str() will allocate space for and
683 * read the entire file and return the correct size in st.
685 desc = read_file_to_str(path, RFTS_IGNORE_MISSING|RFTS_BIN, &st);
686 if (!desc) {
687 /* We couldn't read it */
688 log_notice(LD_DIR,
689 "Failed to read %s from unparseable descriptors directory; "
690 "attempting to remove it.", f);
691 tor_unlink(path);
692 /* We're done */
693 goto done;
696 #if SIZE_MAX > UINT64_MAX
697 if (BUG((uint64_t)st.st_size > (uint64_t)SIZE_MAX)) {
698 /* LCOV_EXCL_START
699 * Should be impossible since RFTS above should have failed to read the
700 * huge file into RAM. */
701 goto done;
702 /* LCOV_EXCL_STOP */
704 #endif /* SIZE_MAX > UINT64_MAX */
705 if (BUG(st.st_size < 0)) {
706 /* LCOV_EXCL_START
707 * Should be impossible, since the OS isn't supposed to be b0rken. */
708 goto done;
709 /* LCOV_EXCL_STOP */
711 /* (Now we can be sure that st.st_size is safe to cast to a size_t.) */
714 * We got one; now compute its digest and check that it matches the
715 * filename.
717 if (crypto_digest256((char *)content_digest, desc, (size_t) st.st_size,
718 DIGEST_SHA256) < 0) {
719 /* Weird, but okay */
720 log_info(LD_DIR,
721 "Unable to hash content of %s from unparseable descriptors "
722 "directory", f);
723 tor_unlink(path);
724 /* We're done */
725 goto done;
728 /* Compare the digests */
729 if (tor_memneq(digest, content_digest, DIGEST256_LEN)) {
730 /* No match */
731 log_info(LD_DIR,
732 "Hash of %s from unparseable descriptors directory didn't "
733 "match its filename; removing it", f);
734 tor_unlink(path);
735 /* We're done */
736 goto done;
739 /* Okay, it's a match, we should prepare ent */
740 ent = tor_malloc_zero(sizeof(dumped_desc_t));
741 ent->filename = path;
742 memcpy(ent->digest_sha256, digest, DIGEST256_LEN);
743 ent->len = (size_t) st.st_size;
744 ent->when = st.st_mtime;
745 /* Null out path so we don't free it out from under ent */
746 path = NULL;
748 done:
749 /* Free allocations if we had them */
750 tor_free(desc);
751 tor_free(path);
753 return ent;
756 /** Sort helper for dump_desc_populate_fifo_from_directory(); compares
757 * the when field of dumped_desc_ts in a smartlist to put the FIFO in
758 * the correct order after reconstructing it from the directory.
760 static int
761 dump_desc_compare_fifo_entries(const void **a_v, const void **b_v)
763 const dumped_desc_t **a = (const dumped_desc_t **)a_v;
764 const dumped_desc_t **b = (const dumped_desc_t **)b_v;
766 if ((a != NULL) && (*a != NULL)) {
767 if ((b != NULL) && (*b != NULL)) {
768 /* We have sensible dumped_desc_ts to compare */
769 if ((*a)->when < (*b)->when) {
770 return -1;
771 } else if ((*a)->when == (*b)->when) {
772 return 0;
773 } else {
774 return 1;
776 } else {
778 * We shouldn't see this, but what the hell, NULLs precede everythin
779 * else
781 return 1;
783 } else {
784 return -1;
788 /** Scan the contents of the directory, and update FIFO/counters; this will
789 * consistency-check descriptor dump filenames against hashes of descriptor
790 * dump file content, and remove any inconsistent/unreadable dumps, and then
791 * reconstruct the dump FIFO as closely as possible for the last time the
792 * tor process shut down. If a previous dump was repeated more than once and
793 * moved ahead in the FIFO, the mtime will not have been updated and the
794 * reconstructed order will be wrong, but will always be a permutation of
795 * the original.
797 STATIC void
798 dump_desc_populate_fifo_from_directory(const char *dirname)
800 smartlist_t *files = NULL;
801 dumped_desc_t *ent = NULL;
803 tor_assert(dirname != NULL);
805 /* Get a list of files */
806 files = tor_listdir(dirname);
807 if (!files) {
808 log_notice(LD_DIR,
809 "Unable to get contents of unparseable descriptor dump "
810 "directory %s",
811 dirname);
812 return;
816 * Iterate through the list and decide which files should go in the
817 * FIFO and which should be purged.
820 SMARTLIST_FOREACH_BEGIN(files, char *, f) {
821 /* Try to get a FIFO entry */
822 ent = dump_desc_populate_one_file(dirname, f);
823 if (ent) {
825 * We got one; add it to the FIFO. No need for duplicate checking
826 * here since we just verified the name and digest match.
829 /* Make sure we have a list to add it to */
830 if (!descs_dumped) {
831 descs_dumped = smartlist_new();
832 len_descs_dumped = 0;
835 /* Add it and adjust the counter */
836 smartlist_add(descs_dumped, ent);
837 len_descs_dumped += ent->len;
840 * If we didn't, we will have unlinked the file if necessary and
841 * possible, and emitted a log message about it, so just go on to
842 * the next.
844 } SMARTLIST_FOREACH_END(f);
846 /* Did we get anything? */
847 if (descs_dumped != NULL) {
848 /* Sort the FIFO in order of increasing timestamp */
849 smartlist_sort(descs_dumped, dump_desc_compare_fifo_entries);
851 /* Log some stats */
852 log_info(LD_DIR,
853 "Reloaded unparseable descriptor dump FIFO with %d dump(s) "
854 "totaling " U64_FORMAT " bytes",
855 smartlist_len(descs_dumped), U64_PRINTF_ARG(len_descs_dumped));
858 /* Free the original list */
859 SMARTLIST_FOREACH(files, char *, f, tor_free(f));
860 smartlist_free(files);
863 /** For debugging purposes, dump unparseable descriptor *<b>desc</b> of
864 * type *<b>type</b> to file $DATADIR/unparseable-desc. Do not write more
865 * than one descriptor to disk per minute. If there is already such a
866 * file in the data directory, overwrite it. */
867 MOCK_IMPL(STATIC void,
868 dump_desc,(const char *desc, const char *type))
870 tor_assert(desc);
871 tor_assert(type);
872 size_t len;
873 /* The SHA256 of the string */
874 uint8_t digest_sha256[DIGEST256_LEN];
875 char digest_sha256_hex[HEX_DIGEST256_LEN+1];
876 /* Filename to log it to */
877 char *debugfile, *debugfile_base;
879 /* Get the hash for logging purposes anyway */
880 len = strlen(desc);
881 if (crypto_digest256((char *)digest_sha256, desc, len,
882 DIGEST_SHA256) < 0) {
883 log_info(LD_DIR,
884 "Unable to parse descriptor of type %s, and unable to even hash"
885 " it!", type);
886 goto err;
889 base16_encode(digest_sha256_hex, sizeof(digest_sha256_hex),
890 (const char *)digest_sha256, sizeof(digest_sha256));
893 * We mention type and hash in the main log; don't clutter up the files
894 * with anything but the exact dump.
896 tor_asprintf(&debugfile_base,
897 DESC_DUMP_BASE_FILENAME ".%s", digest_sha256_hex);
898 debugfile = get_datadir_fname2(DESC_DUMP_DATADIR_SUBDIR, debugfile_base);
901 * Check if the sandbox is active or will become active; see comment
902 * below at the log message for why.
904 if (!(sandbox_is_active() || get_options()->Sandbox)) {
905 if (len <= get_options()->MaxUnparseableDescSizeToLog) {
906 if (!dump_desc_fifo_bump_hash(digest_sha256)) {
907 /* Create the directory if needed */
908 dump_desc_create_dir();
909 /* Make sure we've got it */
910 if (have_dump_desc_dir && !problem_with_dump_desc_dir) {
911 /* Write it, and tell the main log about it */
912 write_str_to_file(debugfile, desc, 1);
913 log_info(LD_DIR,
914 "Unable to parse descriptor of type %s with hash %s and "
915 "length %lu. See file %s in data directory for details.",
916 type, digest_sha256_hex, (unsigned long)len,
917 debugfile_base);
918 dump_desc_fifo_add_and_clean(debugfile, digest_sha256, len);
919 /* Since we handed ownership over, don't free debugfile later */
920 debugfile = NULL;
921 } else {
922 /* Problem with the subdirectory */
923 log_info(LD_DIR,
924 "Unable to parse descriptor of type %s with hash %s and "
925 "length %lu. Descriptor not dumped because we had a "
926 "problem creating the " DESC_DUMP_DATADIR_SUBDIR
927 " subdirectory",
928 type, digest_sha256_hex, (unsigned long)len);
929 /* We do have to free debugfile in this case */
931 } else {
932 /* We already had one with this hash dumped */
933 log_info(LD_DIR,
934 "Unable to parse descriptor of type %s with hash %s and "
935 "length %lu. Descriptor not dumped because one with that "
936 "hash has already been dumped.",
937 type, digest_sha256_hex, (unsigned long)len);
938 /* We do have to free debugfile in this case */
940 } else {
941 /* Just log that it happened without dumping */
942 log_info(LD_DIR,
943 "Unable to parse descriptor of type %s with hash %s and "
944 "length %lu. Descriptor not dumped because it exceeds maximum"
945 " log size all by itself.",
946 type, digest_sha256_hex, (unsigned long)len);
947 /* We do have to free debugfile in this case */
949 } else {
951 * Not logging because the sandbox is active and seccomp2 apparently
952 * doesn't have a sensible way to allow filenames according to a pattern
953 * match. (If we ever figure out how to say "allow writes to /regex/",
954 * remove this checK).
956 log_info(LD_DIR,
957 "Unable to parse descriptor of type %s with hash %s and "
958 "length %lu. Descriptor not dumped because the sandbox is "
959 "configured",
960 type, digest_sha256_hex, (unsigned long)len);
963 tor_free(debugfile_base);
964 tor_free(debugfile);
966 err:
967 return;
970 /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
971 * <b>s</b>. Return 0 on success, -1 on failure.
974 router_get_dir_hash(const char *s, char *digest)
976 return router_get_hash_impl(s, strlen(s), digest,
977 "signed-directory","\ndirectory-signature",'\n',
978 DIGEST_SHA1);
981 /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
982 * <b>s</b>. Return 0 on success, -1 on failure.
985 router_get_router_hash(const char *s, size_t s_len, char *digest)
987 return router_get_hash_impl(s, s_len, digest,
988 "router ","\nrouter-signature", '\n',
989 DIGEST_SHA1);
992 /** Try to find the start and end of the signed portion of a networkstatus
993 * document in <b>s</b>. On success, set <b>start_out</b> to the first
994 * character of the document, and <b>end_out</b> to a position one after the
995 * final character of the signed document, and return 0. On failure, return
996 * -1. */
998 router_get_networkstatus_v3_signed_boundaries(const char *s,
999 const char **start_out,
1000 const char **end_out)
1002 return router_get_hash_impl_helper(s, strlen(s),
1003 "network-status-version",
1004 "\ndirectory-signature",
1005 ' ', LOG_INFO,
1006 start_out, end_out);
1009 /** Set <b>digest_out</b> to the SHA3-256 digest of the signed portion of the
1010 * networkstatus vote in <b>s</b> -- or of the entirety of <b>s</b> if no
1011 * signed portion can be identified. Return 0 on success, -1 on failure. */
1013 router_get_networkstatus_v3_sha3_as_signed(uint8_t *digest_out,
1014 const char *s)
1016 const char *start, *end;
1017 if (router_get_networkstatus_v3_signed_boundaries(s, &start, &end) < 0) {
1018 start = s;
1019 end = s + strlen(s);
1021 tor_assert(start);
1022 tor_assert(end);
1023 return crypto_digest256((char*)digest_out, start, end-start,
1024 DIGEST_SHA3_256);
1027 /** Set <b>digests</b> to all the digests of the consensus document in
1028 * <b>s</b> */
1030 router_get_networkstatus_v3_hashes(const char *s, common_digests_t *digests)
1032 return router_get_hashes_impl(s,strlen(s),digests,
1033 "network-status-version",
1034 "\ndirectory-signature",
1035 ' ');
1038 /** Set <b>digest</b> to the SHA-1 digest of the hash of the <b>s_len</b>-byte
1039 * extrainfo string at <b>s</b>. Return 0 on success, -1 on failure. */
1041 router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
1043 return router_get_hash_impl(s, s_len, digest, "extra-info",
1044 "\nrouter-signature",'\n', DIGEST_SHA1);
1047 /** Helper: used to generate signatures for routers, directories and
1048 * network-status objects. Given a <b>digest_len</b>-byte digest in
1049 * <b>digest</b> and a secret <b>private_key</b>, generate an PKCS1-padded
1050 * signature, BASE64-encode it, surround it with -----BEGIN/END----- pairs,
1051 * and return the new signature on success or NULL on failure.
1053 char *
1054 router_get_dirobj_signature(const char *digest,
1055 size_t digest_len,
1056 const crypto_pk_t *private_key)
1058 char *signature;
1059 size_t i, keysize;
1060 int siglen;
1061 char *buf = NULL;
1062 size_t buf_len;
1063 /* overestimate of BEGIN/END lines total len. */
1064 #define BEGIN_END_OVERHEAD_LEN 64
1066 keysize = crypto_pk_keysize(private_key);
1067 signature = tor_malloc(keysize);
1068 siglen = crypto_pk_private_sign(private_key, signature, keysize,
1069 digest, digest_len);
1070 if (siglen < 0) {
1071 log_warn(LD_BUG,"Couldn't sign digest.");
1072 goto err;
1075 /* The *2 here is a ridiculous overestimate of base-64 overhead. */
1076 buf_len = (siglen * 2) + BEGIN_END_OVERHEAD_LEN;
1077 buf = tor_malloc(buf_len);
1079 if (strlcpy(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
1080 goto truncated;
1082 i = strlen(buf);
1083 if (base64_encode(buf+i, buf_len-i, signature, siglen,
1084 BASE64_ENCODE_MULTILINE) < 0) {
1085 log_warn(LD_BUG,"couldn't base64-encode signature");
1086 goto err;
1089 if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
1090 goto truncated;
1092 tor_free(signature);
1093 return buf;
1095 truncated:
1096 log_warn(LD_BUG,"tried to exceed string length.");
1097 err:
1098 tor_free(signature);
1099 tor_free(buf);
1100 return NULL;
1103 /** Helper: used to generate signatures for routers, directories and
1104 * network-status objects. Given a digest in <b>digest</b> and a secret
1105 * <b>private_key</b>, generate a PKCS1-padded signature, BASE64-encode it,
1106 * surround it with -----BEGIN/END----- pairs, and write it to the
1107 * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
1108 * failure.
1111 router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
1112 size_t digest_len, crypto_pk_t *private_key)
1114 size_t sig_len, s_len;
1115 char *sig = router_get_dirobj_signature(digest, digest_len, private_key);
1116 if (!sig) {
1117 log_warn(LD_BUG, "No signature generated");
1118 return -1;
1120 sig_len = strlen(sig);
1121 s_len = strlen(buf);
1122 if (sig_len + s_len + 1 > buf_len) {
1123 log_warn(LD_BUG, "Not enough room for signature");
1124 tor_free(sig);
1125 return -1;
1127 memcpy(buf+s_len, sig, sig_len+1);
1128 tor_free(sig);
1129 return 0;
1132 /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
1133 * <b>versionlist</b>. Else, return VS_EMPTY if versionlist has no
1134 * entries. Else, return VS_OLD if every member of
1135 * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
1136 * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
1137 * the same series (major.minor.micro) as <b>myversion</b>, but no such member
1138 * is newer than <b>myversion.</b>. Else, return VS_NEW if every member of
1139 * <b>versionlist</b> is older than <b>myversion</b>. Else, return
1140 * VS_UNRECOMMENDED.
1142 * (versionlist is a comma-separated list of version strings,
1143 * optionally prefixed with "Tor". Versions that can't be parsed are
1144 * ignored.)
1146 version_status_t
1147 tor_version_is_obsolete(const char *myversion, const char *versionlist)
1149 tor_version_t mine, other;
1150 int found_newer = 0, found_older = 0, found_newer_in_series = 0,
1151 found_any_in_series = 0, r, same;
1152 version_status_t ret = VS_UNRECOMMENDED;
1153 smartlist_t *version_sl;
1155 log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
1156 myversion, versionlist);
1158 if (tor_version_parse(myversion, &mine)) {
1159 log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
1160 tor_assert(0);
1162 version_sl = smartlist_new();
1163 smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
1165 if (!strlen(versionlist)) { /* no authorities cared or agreed */
1166 ret = VS_EMPTY;
1167 goto done;
1170 SMARTLIST_FOREACH_BEGIN(version_sl, const char *, cp) {
1171 if (!strcmpstart(cp, "Tor "))
1172 cp += 4;
1174 if (tor_version_parse(cp, &other)) {
1175 /* Couldn't parse other; it can't be a match. */
1176 } else {
1177 same = tor_version_same_series(&mine, &other);
1178 if (same)
1179 found_any_in_series = 1;
1180 r = tor_version_compare(&mine, &other);
1181 if (r==0) {
1182 ret = VS_RECOMMENDED;
1183 goto done;
1184 } else if (r<0) {
1185 found_newer = 1;
1186 if (same)
1187 found_newer_in_series = 1;
1188 } else if (r>0) {
1189 found_older = 1;
1192 } SMARTLIST_FOREACH_END(cp);
1194 /* We didn't find the listed version. Is it new or old? */
1195 if (found_any_in_series && !found_newer_in_series && found_newer) {
1196 ret = VS_NEW_IN_SERIES;
1197 } else if (found_newer && !found_older) {
1198 ret = VS_OLD;
1199 } else if (found_older && !found_newer) {
1200 ret = VS_NEW;
1201 } else {
1202 ret = VS_UNRECOMMENDED;
1205 done:
1206 SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
1207 smartlist_free(version_sl);
1208 return ret;
1211 MOCK_IMPL(STATIC int,
1212 signed_digest_equals, (const uint8_t *d1, const uint8_t *d2, size_t len))
1214 return tor_memeq(d1, d2, len);
1217 /** Check whether the object body of the token in <b>tok</b> has a good
1218 * signature for <b>digest</b> using key <b>pkey</b>.
1219 * If <b>CST_NO_CHECK_OBJTYPE</b> is set, do not check
1220 * the object type of the signature object. Use <b>doctype</b> as the type of
1221 * the document when generating log messages. Return 0 on success, negative
1222 * on failure.
1224 static int
1225 check_signature_token(const char *digest,
1226 ssize_t digest_len,
1227 directory_token_t *tok,
1228 crypto_pk_t *pkey,
1229 int flags,
1230 const char *doctype)
1232 char *signed_digest;
1233 size_t keysize;
1234 const int check_objtype = ! (flags & CST_NO_CHECK_OBJTYPE);
1236 tor_assert(pkey);
1237 tor_assert(tok);
1238 tor_assert(digest);
1239 tor_assert(doctype);
1241 if (check_objtype) {
1242 if (strcmp(tok->object_type, "SIGNATURE")) {
1243 log_warn(LD_DIR, "Bad object type on %s signature", doctype);
1244 return -1;
1248 keysize = crypto_pk_keysize(pkey);
1249 signed_digest = tor_malloc(keysize);
1250 if (crypto_pk_public_checksig(pkey, signed_digest, keysize,
1251 tok->object_body, tok->object_size)
1252 < digest_len) {
1253 log_warn(LD_DIR, "Error reading %s: invalid signature.", doctype);
1254 tor_free(signed_digest);
1255 return -1;
1257 // log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
1258 // hex_str(signed_digest,4));
1259 if (! signed_digest_equals((const uint8_t *)digest,
1260 (const uint8_t *)signed_digest, digest_len)) {
1261 log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
1262 tor_free(signed_digest);
1263 return -1;
1265 tor_free(signed_digest);
1266 return 0;
1269 /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
1270 * or to the first of the annotations proceeding the next router or
1271 * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
1272 * we found an extrainfo, or false if found a router. Do not scan beyond
1273 * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
1274 static int
1275 find_start_of_next_router_or_extrainfo(const char **s_ptr,
1276 const char *eos,
1277 int *is_extrainfo_out)
1279 const char *annotations = NULL;
1280 const char *s = *s_ptr;
1282 s = eat_whitespace_eos(s, eos);
1284 while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
1285 /* We're at the start of a line. */
1286 tor_assert(*s != '\n');
1288 if (*s == '@' && !annotations) {
1289 annotations = s;
1290 } else if (*s == 'r' && !strcmpstart(s, "router ")) {
1291 *s_ptr = annotations ? annotations : s;
1292 *is_extrainfo_out = 0;
1293 return 0;
1294 } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
1295 *s_ptr = annotations ? annotations : s;
1296 *is_extrainfo_out = 1;
1297 return 0;
1300 if (!(s = memchr(s+1, '\n', eos-(s+1))))
1301 break;
1302 s = eat_whitespace_eos(s, eos);
1304 return -1;
1307 /** Given a string *<b>s</b> containing a concatenated sequence of router
1308 * descriptors (or extra-info documents if <b>is_extrainfo</b> is set), parses
1309 * them and stores the result in <b>dest</b>. All routers are marked running
1310 * and valid. Advances *s to a point immediately following the last router
1311 * entry. Ignore any trailing router entries that are not complete.
1313 * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
1314 * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
1315 * isn't SAVED_NOWHERE, remember the offset of each descriptor.
1317 * Returns 0 on success and -1 on failure. Adds a digest to
1318 * <b>invalid_digests_out</b> for every entry that was unparseable or
1319 * invalid. (This may cause duplicate entries.)
1322 router_parse_list_from_string(const char **s, const char *eos,
1323 smartlist_t *dest,
1324 saved_location_t saved_location,
1325 int want_extrainfo,
1326 int allow_annotations,
1327 const char *prepend_annotations,
1328 smartlist_t *invalid_digests_out)
1330 routerinfo_t *router;
1331 extrainfo_t *extrainfo;
1332 signed_descriptor_t *signed_desc = NULL;
1333 void *elt;
1334 const char *end, *start;
1335 int have_extrainfo;
1337 tor_assert(s);
1338 tor_assert(*s);
1339 tor_assert(dest);
1341 start = *s;
1342 if (!eos)
1343 eos = *s + strlen(*s);
1345 tor_assert(eos >= *s);
1347 while (1) {
1348 char raw_digest[DIGEST_LEN];
1349 int have_raw_digest = 0;
1350 int dl_again = 0;
1351 if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
1352 break;
1354 end = tor_memstr(*s, eos-*s, "\nrouter-signature");
1355 if (end)
1356 end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
1357 if (end)
1358 end += strlen("\n-----END SIGNATURE-----\n");
1360 if (!end)
1361 break;
1363 elt = NULL;
1365 if (have_extrainfo && want_extrainfo) {
1366 routerlist_t *rl = router_get_routerlist();
1367 have_raw_digest = router_get_extrainfo_hash(*s, end-*s, raw_digest) == 0;
1368 extrainfo = extrainfo_parse_entry_from_string(*s, end,
1369 saved_location != SAVED_IN_CACHE,
1370 rl->identity_map, &dl_again);
1371 if (extrainfo) {
1372 signed_desc = &extrainfo->cache_info;
1373 elt = extrainfo;
1375 } else if (!have_extrainfo && !want_extrainfo) {
1376 have_raw_digest = router_get_router_hash(*s, end-*s, raw_digest) == 0;
1377 router = router_parse_entry_from_string(*s, end,
1378 saved_location != SAVED_IN_CACHE,
1379 allow_annotations,
1380 prepend_annotations, &dl_again);
1381 if (router) {
1382 log_debug(LD_DIR, "Read router '%s', purpose '%s'",
1383 router_describe(router),
1384 router_purpose_to_string(router->purpose));
1385 signed_desc = &router->cache_info;
1386 elt = router;
1389 if (! elt && ! dl_again && have_raw_digest && invalid_digests_out) {
1390 smartlist_add(invalid_digests_out, tor_memdup(raw_digest, DIGEST_LEN));
1392 if (!elt) {
1393 *s = end;
1394 continue;
1396 if (saved_location != SAVED_NOWHERE) {
1397 tor_assert(signed_desc);
1398 signed_desc->saved_location = saved_location;
1399 signed_desc->saved_offset = *s - start;
1401 *s = end;
1402 smartlist_add(dest, elt);
1405 return 0;
1408 /* For debugging: define to count every descriptor digest we've seen so we
1409 * know if we need to try harder to avoid duplicate verifies. */
1410 #undef COUNT_DISTINCT_DIGESTS
1412 #ifdef COUNT_DISTINCT_DIGESTS
1413 static digestmap_t *verified_digests = NULL;
1414 #endif
1416 /** Log the total count of the number of distinct router digests we've ever
1417 * verified. When compared to the number of times we've verified routerdesc
1418 * signatures <i>in toto</i>, this will tell us if we're doing too much
1419 * multiple-verification. */
1420 void
1421 dump_distinct_digest_count(int severity)
1423 #ifdef COUNT_DISTINCT_DIGESTS
1424 if (!verified_digests)
1425 verified_digests = digestmap_new();
1426 tor_log(severity, LD_GENERAL, "%d *distinct* router digests verified",
1427 digestmap_size(verified_digests));
1428 #else /* !(defined(COUNT_DISTINCT_DIGESTS)) */
1429 (void)severity; /* suppress "unused parameter" warning */
1430 #endif /* defined(COUNT_DISTINCT_DIGESTS) */
1433 /** Try to find an IPv6 OR port in <b>list</b> of directory_token_t's
1434 * with at least one argument (use GE(1) in setup). If found, store
1435 * address and port number to <b>addr_out</b> and
1436 * <b>port_out</b>. Return number of OR ports found. */
1437 static int
1438 find_single_ipv6_orport(const smartlist_t *list,
1439 tor_addr_t *addr_out,
1440 uint16_t *port_out)
1442 int ret = 0;
1443 tor_assert(list != NULL);
1444 tor_assert(addr_out != NULL);
1445 tor_assert(port_out != NULL);
1447 SMARTLIST_FOREACH_BEGIN(list, directory_token_t *, t) {
1448 tor_addr_t a;
1449 maskbits_t bits;
1450 uint16_t port_min, port_max;
1451 tor_assert(t->n_args >= 1);
1452 /* XXXX Prop186 the full spec allows much more than this. */
1453 if (tor_addr_parse_mask_ports(t->args[0], 0,
1454 &a, &bits, &port_min,
1455 &port_max) == AF_INET6 &&
1456 bits == 128 &&
1457 port_min == port_max) {
1458 /* Okay, this is one we can understand. Use it and ignore
1459 any potential more addresses in list. */
1460 tor_addr_copy(addr_out, &a);
1461 *port_out = port_min;
1462 ret = 1;
1463 break;
1465 } SMARTLIST_FOREACH_END(t);
1467 return ret;
1470 /** Helper function: reads a single router entry from *<b>s</b> ...
1471 * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
1472 * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
1473 * s through end into the signed_descriptor_body of the resulting
1474 * routerinfo_t.
1476 * If <b>end</b> is NULL, <b>s</b> must be properly NUL-terminated.
1478 * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
1479 * before the router; if it's false, reject the router if it's annotated. If
1480 * <b>prepend_annotations</b> is set, it should contain some annotations:
1481 * append them to the front of the router before parsing it, and keep them
1482 * around when caching the router.
1484 * Only one of allow_annotations and prepend_annotations may be set.
1486 * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
1487 * if it's okay to try to download a descriptor with this same digest again,
1488 * and 0 if it isn't. (It might not be okay to download it again if part of
1489 * the part covered by the digest is invalid.)
1491 routerinfo_t *
1492 router_parse_entry_from_string(const char *s, const char *end,
1493 int cache_copy, int allow_annotations,
1494 const char *prepend_annotations,
1495 int *can_dl_again_out)
1497 routerinfo_t *router = NULL;
1498 char digest[128];
1499 smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
1500 directory_token_t *tok;
1501 struct in_addr in;
1502 const char *start_of_annotations, *cp, *s_dup = s;
1503 size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
1504 int ok = 1;
1505 memarea_t *area = NULL;
1506 tor_cert_t *ntor_cc_cert = NULL;
1507 /* Do not set this to '1' until we have parsed everything that we intend to
1508 * parse that's covered by the hash. */
1509 int can_dl_again = 0;
1511 tor_assert(!allow_annotations || !prepend_annotations);
1513 if (!end) {
1514 end = s + strlen(s);
1517 /* point 'end' to a point immediately after the final newline. */
1518 while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
1519 --end;
1521 area = memarea_new();
1522 tokens = smartlist_new();
1523 if (prepend_annotations) {
1524 if (tokenize_string(area,prepend_annotations,NULL,tokens,
1525 routerdesc_token_table,TS_NOCHECK)) {
1526 log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
1527 goto err;
1531 start_of_annotations = s;
1532 cp = tor_memstr(s, end-s, "\nrouter ");
1533 if (!cp) {
1534 if (end-s < 7 || strcmpstart(s, "router ")) {
1535 log_warn(LD_DIR, "No router keyword found.");
1536 goto err;
1538 } else {
1539 s = cp+1;
1542 if (start_of_annotations != s) { /* We have annotations */
1543 if (allow_annotations) {
1544 if (tokenize_string(area,start_of_annotations,s,tokens,
1545 routerdesc_token_table,TS_NOCHECK)) {
1546 log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
1547 goto err;
1549 } else {
1550 log_warn(LD_DIR, "Found unexpected annotations on router descriptor not "
1551 "loaded from disk. Dropping it.");
1552 goto err;
1556 if (router_get_router_hash(s, end - s, digest) < 0) {
1557 log_warn(LD_DIR, "Couldn't compute router hash.");
1558 goto err;
1561 int flags = 0;
1562 if (allow_annotations)
1563 flags |= TS_ANNOTATIONS_OK;
1564 if (prepend_annotations)
1565 flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
1567 if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
1568 log_warn(LD_DIR, "Error tokenizing router descriptor.");
1569 goto err;
1573 if (smartlist_len(tokens) < 2) {
1574 log_warn(LD_DIR, "Impossibly short router descriptor.");
1575 goto err;
1578 tok = find_by_keyword(tokens, K_ROUTER);
1579 const int router_token_pos = smartlist_pos(tokens, tok);
1580 tor_assert(tok->n_args >= 5);
1582 router = tor_malloc_zero(sizeof(routerinfo_t));
1583 router->cert_expiration_time = TIME_MAX;
1584 router->cache_info.routerlist_index = -1;
1585 router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
1586 router->cache_info.signed_descriptor_len = end-s;
1587 if (cache_copy) {
1588 size_t len = router->cache_info.signed_descriptor_len +
1589 router->cache_info.annotations_len;
1590 char *signed_body =
1591 router->cache_info.signed_descriptor_body = tor_malloc(len+1);
1592 if (prepend_annotations) {
1593 memcpy(signed_body, prepend_annotations, prepend_len);
1594 signed_body += prepend_len;
1596 /* This assertion will always succeed.
1597 * len == signed_desc_len + annotations_len
1598 * == end-s + s-start_of_annotations + prepend_len
1599 * == end-start_of_annotations + prepend_len
1600 * We already wrote prepend_len bytes into the buffer; now we're
1601 * writing end-start_of_annotations -NM. */
1602 tor_assert(signed_body+(end-start_of_annotations) ==
1603 router->cache_info.signed_descriptor_body+len);
1604 memcpy(signed_body, start_of_annotations, end-start_of_annotations);
1605 router->cache_info.signed_descriptor_body[len] = '\0';
1606 tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
1608 memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
1610 router->nickname = tor_strdup(tok->args[0]);
1611 if (!is_legal_nickname(router->nickname)) {
1612 log_warn(LD_DIR,"Router nickname is invalid");
1613 goto err;
1615 if (!tor_inet_aton(tok->args[1], &in)) {
1616 log_warn(LD_DIR,"Router address is not an IP address.");
1617 goto err;
1619 router->addr = ntohl(in.s_addr);
1621 router->or_port =
1622 (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
1623 if (!ok) {
1624 log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
1625 goto err;
1627 router->dir_port =
1628 (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
1629 if (!ok) {
1630 log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
1631 goto err;
1634 tok = find_by_keyword(tokens, K_BANDWIDTH);
1635 tor_assert(tok->n_args >= 3);
1636 router->bandwidthrate = (int)
1637 tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
1639 if (!ok) {
1640 log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
1641 escaped(tok->args[0]));
1642 goto err;
1644 router->bandwidthburst =
1645 (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
1646 if (!ok) {
1647 log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
1648 goto err;
1650 router->bandwidthcapacity = (int)
1651 tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
1652 if (!ok) {
1653 log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
1654 goto err;
1657 if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
1658 tor_assert(tok->n_args);
1659 router->purpose = router_purpose_from_string(tok->args[0]);
1660 } else {
1661 router->purpose = ROUTER_PURPOSE_GENERAL;
1663 router->cache_info.send_unencrypted =
1664 (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
1666 if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
1667 tor_assert(tok->n_args >= 1);
1668 router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
1669 if (!ok) {
1670 log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
1671 goto err;
1675 if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
1676 tor_assert(tok->n_args >= 1);
1677 router->is_hibernating
1678 = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
1681 tok = find_by_keyword(tokens, K_PUBLISHED);
1682 tor_assert(tok->n_args == 1);
1683 if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
1684 goto err;
1686 tok = find_by_keyword(tokens, K_ONION_KEY);
1687 if (!crypto_pk_public_exponent_ok(tok->key)) {
1688 log_warn(LD_DIR,
1689 "Relay's onion key had invalid exponent.");
1690 goto err;
1692 router->onion_pkey = tok->key;
1693 tok->key = NULL; /* Prevent free */
1695 if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
1696 curve25519_public_key_t k;
1697 tor_assert(tok->n_args >= 1);
1698 if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
1699 log_warn(LD_DIR, "Bogus ntor-onion-key in routerinfo");
1700 goto err;
1702 router->onion_curve25519_pkey =
1703 tor_memdup(&k, sizeof(curve25519_public_key_t));
1706 tok = find_by_keyword(tokens, K_SIGNING_KEY);
1707 router->identity_pkey = tok->key;
1708 tok->key = NULL; /* Prevent free */
1709 if (crypto_pk_get_digest(router->identity_pkey,
1710 router->cache_info.identity_digest)) {
1711 log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
1715 directory_token_t *ed_sig_tok, *ed_cert_tok, *cc_tap_tok, *cc_ntor_tok,
1716 *master_key_tok;
1717 ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
1718 ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
1719 master_key_tok = find_opt_by_keyword(tokens, K_MASTER_KEY_ED25519);
1720 cc_tap_tok = find_opt_by_keyword(tokens, K_ONION_KEY_CROSSCERT);
1721 cc_ntor_tok = find_opt_by_keyword(tokens, K_NTOR_ONION_KEY_CROSSCERT);
1722 int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok +
1723 !!cc_tap_tok + !!cc_ntor_tok;
1724 if ((n_ed_toks != 0 && n_ed_toks != 4) ||
1725 (n_ed_toks == 4 && !router->onion_curve25519_pkey)) {
1726 log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
1727 "cross-certification support");
1728 goto err;
1730 if (master_key_tok && !ed_sig_tok) {
1731 log_warn(LD_DIR, "Router descriptor has ed25519 master key but no "
1732 "certificate");
1733 goto err;
1735 if (ed_sig_tok) {
1736 tor_assert(ed_cert_tok && cc_tap_tok && cc_ntor_tok);
1737 const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
1738 if (ed_cert_token_pos == -1 || router_token_pos == -1 ||
1739 (ed_cert_token_pos != router_token_pos + 1 &&
1740 ed_cert_token_pos != router_token_pos - 1)) {
1741 log_warn(LD_DIR, "Ed25519 certificate in wrong position");
1742 goto err;
1744 if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
1745 log_warn(LD_DIR, "Ed25519 signature in wrong position");
1746 goto err;
1748 if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
1749 log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
1750 goto err;
1752 if (strcmp(cc_ntor_tok->object_type, "ED25519 CERT")) {
1753 log_warn(LD_DIR, "Wrong object type on ntor-onion-key-crosscert "
1754 "in decriptor");
1755 goto err;
1757 if (strcmp(cc_tap_tok->object_type, "CROSSCERT")) {
1758 log_warn(LD_DIR, "Wrong object type on onion-key-crosscert "
1759 "in decriptor");
1760 goto err;
1762 if (strcmp(cc_ntor_tok->args[0], "0") &&
1763 strcmp(cc_ntor_tok->args[0], "1")) {
1764 log_warn(LD_DIR, "Bad sign bit on ntor-onion-key-crosscert");
1765 goto err;
1767 int ntor_cc_sign_bit = !strcmp(cc_ntor_tok->args[0], "1");
1769 uint8_t d256[DIGEST256_LEN];
1770 const char *signed_start, *signed_end;
1771 tor_cert_t *cert = tor_cert_parse(
1772 (const uint8_t*)ed_cert_tok->object_body,
1773 ed_cert_tok->object_size);
1774 if (! cert) {
1775 log_warn(LD_DIR, "Couldn't parse ed25519 cert");
1776 goto err;
1778 /* makes sure it gets freed. */
1779 router->cache_info.signing_key_cert = cert;
1781 if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
1782 ! cert->signing_key_included) {
1783 log_warn(LD_DIR, "Invalid form for ed25519 cert");
1784 goto err;
1787 if (master_key_tok) {
1788 /* This token is optional, but if it's present, it must match
1789 * the signature in the signing cert, or supplant it. */
1790 tor_assert(master_key_tok->n_args >= 1);
1791 ed25519_public_key_t pkey;
1792 if (ed25519_public_from_base64(&pkey, master_key_tok->args[0])<0) {
1793 log_warn(LD_DIR, "Can't parse ed25519 master key");
1794 goto err;
1797 if (fast_memneq(&cert->signing_key.pubkey,
1798 pkey.pubkey, ED25519_PUBKEY_LEN)) {
1799 log_warn(LD_DIR, "Ed25519 master key does not match "
1800 "key in certificate");
1801 goto err;
1804 ntor_cc_cert = tor_cert_parse((const uint8_t*)cc_ntor_tok->object_body,
1805 cc_ntor_tok->object_size);
1806 if (!ntor_cc_cert) {
1807 log_warn(LD_DIR, "Couldn't parse ntor-onion-key-crosscert cert");
1808 goto err;
1810 if (ntor_cc_cert->cert_type != CERT_TYPE_ONION_ID ||
1811 ! ed25519_pubkey_eq(&ntor_cc_cert->signed_key, &cert->signing_key)) {
1812 log_warn(LD_DIR, "Invalid contents for ntor-onion-key-crosscert cert");
1813 goto err;
1816 ed25519_public_key_t ntor_cc_pk;
1817 if (ed25519_public_key_from_curve25519_public_key(&ntor_cc_pk,
1818 router->onion_curve25519_pkey,
1819 ntor_cc_sign_bit)<0) {
1820 log_warn(LD_DIR, "Error converting onion key to ed25519");
1821 goto err;
1824 if (router_get_hash_impl_helper(s, end-s, "router ",
1825 "\nrouter-sig-ed25519",
1826 ' ', LOG_WARN,
1827 &signed_start, &signed_end) < 0) {
1828 log_warn(LD_DIR, "Can't find ed25519-signed portion of descriptor");
1829 goto err;
1831 crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
1832 crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
1833 strlen(ED_DESC_SIGNATURE_PREFIX));
1834 crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
1835 crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
1836 crypto_digest_free(d);
1838 ed25519_checkable_t check[3];
1839 int check_ok[3];
1840 time_t expires = TIME_MAX;
1841 if (tor_cert_get_checkable_sig(&check[0], cert, NULL, &expires) < 0) {
1842 log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
1843 goto err;
1845 if (tor_cert_get_checkable_sig(&check[1],
1846 ntor_cc_cert, &ntor_cc_pk, &expires) < 0) {
1847 log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
1848 goto err;
1851 if (ed25519_signature_from_base64(&check[2].signature,
1852 ed_sig_tok->args[0])<0) {
1853 log_warn(LD_DIR, "Couldn't decode ed25519 signature");
1854 goto err;
1856 check[2].pubkey = &cert->signed_key;
1857 check[2].msg = d256;
1858 check[2].len = DIGEST256_LEN;
1860 if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
1861 log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
1862 goto err;
1865 if (check_tap_onion_key_crosscert(
1866 (const uint8_t*)cc_tap_tok->object_body,
1867 (int)cc_tap_tok->object_size,
1868 router->onion_pkey,
1869 &cert->signing_key,
1870 (const uint8_t*)router->cache_info.identity_digest)<0) {
1871 log_warn(LD_DIR, "Incorrect TAP cross-verification");
1872 goto err;
1875 /* We check this before adding it to the routerlist. */
1876 router->cert_expiration_time = expires;
1880 if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
1881 /* If there's a fingerprint line, it must match the identity digest. */
1882 char d[DIGEST_LEN];
1883 tor_assert(tok->n_args == 1);
1884 tor_strstrip(tok->args[0], " ");
1885 if (base16_decode(d, DIGEST_LEN,
1886 tok->args[0], strlen(tok->args[0])) != DIGEST_LEN) {
1887 log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
1888 escaped(tok->args[0]));
1889 goto err;
1891 if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
1892 log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
1893 tok->args[0]);
1894 goto err;
1898 if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
1899 router->platform = tor_strdup(tok->args[0]);
1902 if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
1903 router->protocol_list = tor_strdup(tok->args[0]);
1906 if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
1907 router->contact_info = tor_strdup(tok->args[0]);
1910 if (find_opt_by_keyword(tokens, K_REJECT6) ||
1911 find_opt_by_keyword(tokens, K_ACCEPT6)) {
1912 log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
1913 "older Tors.");
1914 goto err;
1917 smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
1918 if (or_addresses) {
1919 find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
1920 &router->ipv6_orport);
1921 smartlist_free(or_addresses);
1924 exit_policy_tokens = find_all_exitpolicy(tokens);
1925 if (!smartlist_len(exit_policy_tokens)) {
1926 log_warn(LD_DIR, "No exit policy tokens in descriptor.");
1927 goto err;
1929 SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
1930 if (router_add_exit_policy(router,t)<0) {
1931 log_warn(LD_DIR,"Error in exit policy");
1932 goto err;
1934 policy_expand_private(&router->exit_policy);
1936 if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
1937 router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
1938 if (! router->ipv6_exit_policy) {
1939 log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
1940 goto err;
1944 if (policy_is_reject_star(router->exit_policy, AF_INET, 1) &&
1945 (!router->ipv6_exit_policy ||
1946 short_policy_is_reject_star(router->ipv6_exit_policy)))
1947 router->policy_is_reject_star = 1;
1949 if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
1950 int i;
1951 router->declared_family = smartlist_new();
1952 for (i=0;i<tok->n_args;++i) {
1953 if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
1954 log_warn(LD_DIR, "Illegal nickname %s in family line",
1955 escaped(tok->args[i]));
1956 goto err;
1958 smartlist_add_strdup(router->declared_family, tok->args[i]);
1962 if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
1963 router->caches_extra_info = 1;
1965 if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
1966 router->allow_single_hop_exits = 1;
1968 if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
1969 tor_assert(tok->n_args >= 1);
1970 if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
1971 if (base16_decode(router->cache_info.extra_info_digest, DIGEST_LEN,
1972 tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN) {
1973 log_warn(LD_DIR,"Invalid extra info digest");
1975 } else {
1976 log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
1979 if (tok->n_args >= 2) {
1980 if (digest256_from_base64(router->cache_info.extra_info_digest256,
1981 tok->args[1]) < 0) {
1982 log_warn(LD_DIR, "Invalid extra info digest256 %s",
1983 escaped(tok->args[1]));
1988 if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
1989 router->wants_to_be_hs_dir = 1;
1992 /* This router accepts tunnelled directory requests via begindir if it has
1993 * an open dirport or it included "tunnelled-dir-server". */
1994 if (find_opt_by_keyword(tokens, K_DIR_TUNNELLED) || router->dir_port > 0) {
1995 router->supports_tunnelled_dir_requests = 1;
1998 tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
1999 #ifdef COUNT_DISTINCT_DIGESTS
2000 if (!verified_digests)
2001 verified_digests = digestmap_new();
2002 digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
2003 #endif
2005 if (!router->or_port) {
2006 log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
2007 goto err;
2010 /* We've checked everything that's covered by the hash. */
2011 can_dl_again = 1;
2012 if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
2013 "router descriptor") < 0)
2014 goto err;
2016 if (!router->platform) {
2017 router->platform = tor_strdup("<unknown>");
2019 goto done;
2021 err:
2022 dump_desc(s_dup, "router descriptor");
2023 routerinfo_free(router);
2024 router = NULL;
2025 done:
2026 tor_cert_free(ntor_cc_cert);
2027 if (tokens) {
2028 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2029 smartlist_free(tokens);
2031 smartlist_free(exit_policy_tokens);
2032 if (area) {
2033 DUMP_AREA(area, "routerinfo");
2034 memarea_drop_all(area);
2036 if (can_dl_again_out)
2037 *can_dl_again_out = can_dl_again;
2038 return router;
2041 /** Parse a single extrainfo entry from the string <b>s</b>, ending at
2042 * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
2043 * <b>cache_copy</b> is true, make a copy of the extra-info document in the
2044 * cache_info fields of the result. If <b>routermap</b> is provided, use it
2045 * as a map from router identity to routerinfo_t when looking up signing keys.
2047 * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
2048 * if it's okay to try to download an extrainfo with this same digest again,
2049 * and 0 if it isn't. (It might not be okay to download it again if part of
2050 * the part covered by the digest is invalid.)
2052 extrainfo_t *
2053 extrainfo_parse_entry_from_string(const char *s, const char *end,
2054 int cache_copy, struct digest_ri_map_t *routermap,
2055 int *can_dl_again_out)
2057 extrainfo_t *extrainfo = NULL;
2058 char digest[128];
2059 smartlist_t *tokens = NULL;
2060 directory_token_t *tok;
2061 crypto_pk_t *key = NULL;
2062 routerinfo_t *router = NULL;
2063 memarea_t *area = NULL;
2064 const char *s_dup = s;
2065 /* Do not set this to '1' until we have parsed everything that we intend to
2066 * parse that's covered by the hash. */
2067 int can_dl_again = 0;
2069 if (BUG(s == NULL))
2070 return NULL;
2072 if (!end) {
2073 end = s + strlen(s);
2076 /* point 'end' to a point immediately after the final newline. */
2077 while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
2078 --end;
2080 if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
2081 log_warn(LD_DIR, "Couldn't compute router hash.");
2082 goto err;
2084 tokens = smartlist_new();
2085 area = memarea_new();
2086 if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
2087 log_warn(LD_DIR, "Error tokenizing extra-info document.");
2088 goto err;
2091 if (smartlist_len(tokens) < 2) {
2092 log_warn(LD_DIR, "Impossibly short extra-info document.");
2093 goto err;
2096 /* XXXX Accept this in position 1 too, and ed identity in position 0. */
2097 tok = smartlist_get(tokens,0);
2098 if (tok->tp != K_EXTRA_INFO) {
2099 log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
2100 goto err;
2103 extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
2104 extrainfo->cache_info.is_extrainfo = 1;
2105 if (cache_copy)
2106 extrainfo->cache_info.signed_descriptor_body = tor_memdup_nulterm(s,end-s);
2107 extrainfo->cache_info.signed_descriptor_len = end-s;
2108 memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
2109 crypto_digest256((char*)extrainfo->digest256, s, end-s, DIGEST_SHA256);
2111 tor_assert(tok->n_args >= 2);
2112 if (!is_legal_nickname(tok->args[0])) {
2113 log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
2114 goto err;
2116 strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
2117 if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
2118 base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
2119 tok->args[1], HEX_DIGEST_LEN) != DIGEST_LEN) {
2120 log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
2121 escaped(tok->args[1]));
2122 goto err;
2125 tok = find_by_keyword(tokens, K_PUBLISHED);
2126 if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
2127 log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
2128 escaped(tok->args[0]));
2129 goto err;
2133 directory_token_t *ed_sig_tok, *ed_cert_tok;
2134 ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
2135 ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
2136 int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok;
2137 if (n_ed_toks != 0 && n_ed_toks != 2) {
2138 log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
2139 "cross-certification support");
2140 goto err;
2142 if (ed_sig_tok) {
2143 tor_assert(ed_cert_tok);
2144 const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
2145 if (ed_cert_token_pos != 1) {
2146 /* Accept this in position 0 XXXX */
2147 log_warn(LD_DIR, "Ed25519 certificate in wrong position");
2148 goto err;
2150 if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
2151 log_warn(LD_DIR, "Ed25519 signature in wrong position");
2152 goto err;
2154 if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
2155 log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
2156 goto err;
2159 uint8_t d256[DIGEST256_LEN];
2160 const char *signed_start, *signed_end;
2161 tor_cert_t *cert = tor_cert_parse(
2162 (const uint8_t*)ed_cert_tok->object_body,
2163 ed_cert_tok->object_size);
2164 if (! cert) {
2165 log_warn(LD_DIR, "Couldn't parse ed25519 cert");
2166 goto err;
2168 /* makes sure it gets freed. */
2169 extrainfo->cache_info.signing_key_cert = cert;
2171 if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
2172 ! cert->signing_key_included) {
2173 log_warn(LD_DIR, "Invalid form for ed25519 cert");
2174 goto err;
2177 if (router_get_hash_impl_helper(s, end-s, "extra-info ",
2178 "\nrouter-sig-ed25519",
2179 ' ', LOG_WARN,
2180 &signed_start, &signed_end) < 0) {
2181 log_warn(LD_DIR, "Can't find ed25519-signed portion of extrainfo");
2182 goto err;
2184 crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
2185 crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
2186 strlen(ED_DESC_SIGNATURE_PREFIX));
2187 crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
2188 crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
2189 crypto_digest_free(d);
2191 ed25519_checkable_t check[2];
2192 int check_ok[2];
2193 if (tor_cert_get_checkable_sig(&check[0], cert, NULL, NULL) < 0) {
2194 log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
2195 goto err;
2198 if (ed25519_signature_from_base64(&check[1].signature,
2199 ed_sig_tok->args[0])<0) {
2200 log_warn(LD_DIR, "Couldn't decode ed25519 signature");
2201 goto err;
2203 check[1].pubkey = &cert->signed_key;
2204 check[1].msg = d256;
2205 check[1].len = DIGEST256_LEN;
2207 if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
2208 log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
2209 goto err;
2211 /* We don't check the certificate expiration time: checking that it
2212 * matches the cert in the router descriptor is adequate. */
2216 /* We've checked everything that's covered by the hash. */
2217 can_dl_again = 1;
2219 if (routermap &&
2220 (router = digestmap_get((digestmap_t*)routermap,
2221 extrainfo->cache_info.identity_digest))) {
2222 key = router->identity_pkey;
2225 tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
2226 if (strcmp(tok->object_type, "SIGNATURE") ||
2227 tok->object_size < 128 || tok->object_size > 512) {
2228 log_warn(LD_DIR, "Bad object type or length on extra-info signature");
2229 goto err;
2232 if (key) {
2233 if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
2234 "extra-info") < 0)
2235 goto err;
2237 if (router)
2238 extrainfo->cache_info.send_unencrypted =
2239 router->cache_info.send_unencrypted;
2240 } else {
2241 extrainfo->pending_sig = tor_memdup(tok->object_body,
2242 tok->object_size);
2243 extrainfo->pending_sig_len = tok->object_size;
2246 goto done;
2247 err:
2248 dump_desc(s_dup, "extra-info descriptor");
2249 extrainfo_free(extrainfo);
2250 extrainfo = NULL;
2251 done:
2252 if (tokens) {
2253 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2254 smartlist_free(tokens);
2256 if (area) {
2257 DUMP_AREA(area, "extrainfo");
2258 memarea_drop_all(area);
2260 if (can_dl_again_out)
2261 *can_dl_again_out = can_dl_again;
2262 return extrainfo;
2265 /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
2266 * the first character after the certificate. */
2267 authority_cert_t *
2268 authority_cert_parse_from_string(const char *s, const char **end_of_string)
2270 /** Reject any certificate at least this big; it is probably an overflow, an
2271 * attack, a bug, or some other nonsense. */
2272 #define MAX_CERT_SIZE (128*1024)
2274 authority_cert_t *cert = NULL, *old_cert;
2275 smartlist_t *tokens = NULL;
2276 char digest[DIGEST_LEN];
2277 directory_token_t *tok;
2278 char fp_declared[DIGEST_LEN];
2279 char *eos;
2280 size_t len;
2281 int found;
2282 memarea_t *area = NULL;
2283 const char *s_dup = s;
2285 s = eat_whitespace(s);
2286 eos = strstr(s, "\ndir-key-certification");
2287 if (! eos) {
2288 log_warn(LD_DIR, "No signature found on key certificate");
2289 return NULL;
2291 eos = strstr(eos, "\n-----END SIGNATURE-----\n");
2292 if (! eos) {
2293 log_warn(LD_DIR, "No end-of-signature found on key certificate");
2294 return NULL;
2296 eos = strchr(eos+2, '\n');
2297 tor_assert(eos);
2298 ++eos;
2299 len = eos - s;
2301 if (len > MAX_CERT_SIZE) {
2302 log_warn(LD_DIR, "Certificate is far too big (at %lu bytes long); "
2303 "rejecting", (unsigned long)len);
2304 return NULL;
2307 tokens = smartlist_new();
2308 area = memarea_new();
2309 if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
2310 log_warn(LD_DIR, "Error tokenizing key certificate");
2311 goto err;
2313 if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
2314 "\ndir-key-certification", '\n', DIGEST_SHA1) < 0)
2315 goto err;
2316 tok = smartlist_get(tokens, 0);
2317 if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
2318 log_warn(LD_DIR,
2319 "Key certificate does not begin with a recognized version (3).");
2320 goto err;
2323 cert = tor_malloc_zero(sizeof(authority_cert_t));
2324 memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
2326 tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
2327 tor_assert(tok->key);
2328 cert->signing_key = tok->key;
2329 tok->key = NULL;
2330 if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
2331 goto err;
2333 tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
2334 tor_assert(tok->key);
2335 cert->identity_key = tok->key;
2336 tok->key = NULL;
2338 tok = find_by_keyword(tokens, K_FINGERPRINT);
2339 tor_assert(tok->n_args);
2340 if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
2341 strlen(tok->args[0])) != DIGEST_LEN) {
2342 log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
2343 escaped(tok->args[0]));
2344 goto err;
2347 if (crypto_pk_get_digest(cert->identity_key,
2348 cert->cache_info.identity_digest))
2349 goto err;
2351 if (tor_memneq(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
2352 log_warn(LD_DIR, "Digest of certificate key didn't match declared "
2353 "fingerprint");
2354 goto err;
2357 tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
2358 if (tok) {
2359 struct in_addr in;
2360 char *address = NULL;
2361 tor_assert(tok->n_args);
2362 /* XXX++ use some tor_addr parse function below instead. -RD */
2363 if (tor_addr_port_split(LOG_WARN, tok->args[0], &address,
2364 &cert->dir_port) < 0 ||
2365 tor_inet_aton(address, &in) == 0) {
2366 log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
2367 tor_free(address);
2368 goto err;
2370 cert->addr = ntohl(in.s_addr);
2371 tor_free(address);
2374 tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
2375 if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
2376 goto err;
2378 tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
2379 if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
2380 goto err;
2383 tok = smartlist_get(tokens, smartlist_len(tokens)-1);
2384 if (tok->tp != K_DIR_KEY_CERTIFICATION) {
2385 log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
2386 goto err;
2389 /* If we already have this cert, don't bother checking the signature. */
2390 old_cert = authority_cert_get_by_digests(
2391 cert->cache_info.identity_digest,
2392 cert->signing_key_digest);
2393 found = 0;
2394 if (old_cert) {
2395 /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
2396 * buy us much. */
2397 if (old_cert->cache_info.signed_descriptor_len == len &&
2398 old_cert->cache_info.signed_descriptor_body &&
2399 tor_memeq(s, old_cert->cache_info.signed_descriptor_body, len)) {
2400 log_debug(LD_DIR, "We already checked the signature on this "
2401 "certificate; no need to do so again.");
2402 found = 1;
2405 if (!found) {
2406 if (check_signature_token(digest, DIGEST_LEN, tok, cert->identity_key, 0,
2407 "key certificate")) {
2408 goto err;
2411 tok = find_by_keyword(tokens, K_DIR_KEY_CROSSCERT);
2412 if (check_signature_token(cert->cache_info.identity_digest,
2413 DIGEST_LEN,
2414 tok,
2415 cert->signing_key,
2416 CST_NO_CHECK_OBJTYPE,
2417 "key cross-certification")) {
2418 goto err;
2422 cert->cache_info.signed_descriptor_len = len;
2423 cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
2424 memcpy(cert->cache_info.signed_descriptor_body, s, len);
2425 cert->cache_info.signed_descriptor_body[len] = 0;
2426 cert->cache_info.saved_location = SAVED_NOWHERE;
2428 if (end_of_string) {
2429 *end_of_string = eat_whitespace(eos);
2431 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2432 smartlist_free(tokens);
2433 if (area) {
2434 DUMP_AREA(area, "authority cert");
2435 memarea_drop_all(area);
2437 return cert;
2438 err:
2439 dump_desc(s_dup, "authority cert");
2440 authority_cert_free(cert);
2441 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2442 smartlist_free(tokens);
2443 if (area) {
2444 DUMP_AREA(area, "authority cert");
2445 memarea_drop_all(area);
2447 return NULL;
2450 /** Helper: given a string <b>s</b>, return the start of the next router-status
2451 * object (starting with "r " at the start of a line). If none is found,
2452 * return the start of the directory footer, or the next directory signature.
2453 * If none is found, return the end of the string. */
2454 static inline const char *
2455 find_start_of_next_routerstatus(const char *s)
2457 const char *eos, *footer, *sig;
2458 if ((eos = strstr(s, "\nr ")))
2459 ++eos;
2460 else
2461 eos = s + strlen(s);
2463 footer = tor_memstr(s, eos-s, "\ndirectory-footer");
2464 sig = tor_memstr(s, eos-s, "\ndirectory-signature");
2466 if (footer && sig)
2467 return MIN(footer, sig) + 1;
2468 else if (footer)
2469 return footer+1;
2470 else if (sig)
2471 return sig+1;
2472 else
2473 return eos;
2476 /** Parse the GuardFraction string from a consensus or vote.
2478 * If <b>vote</b> or <b>vote_rs</b> are set the document getting
2479 * parsed is a vote routerstatus. Otherwise it's a consensus. This is
2480 * the same semantic as in routerstatus_parse_entry_from_string(). */
2481 STATIC int
2482 routerstatus_parse_guardfraction(const char *guardfraction_str,
2483 networkstatus_t *vote,
2484 vote_routerstatus_t *vote_rs,
2485 routerstatus_t *rs)
2487 int ok;
2488 const char *end_of_header = NULL;
2489 int is_consensus = !vote_rs;
2490 uint32_t guardfraction;
2492 tor_assert(bool_eq(vote, vote_rs));
2494 /* If this info comes from a consensus, but we should't apply
2495 guardfraction, just exit. */
2496 if (is_consensus && !should_apply_guardfraction(NULL)) {
2497 return 0;
2500 end_of_header = strchr(guardfraction_str, '=');
2501 if (!end_of_header) {
2502 return -1;
2505 guardfraction = (uint32_t)tor_parse_ulong(end_of_header+1,
2506 10, 0, 100, &ok, NULL);
2507 if (!ok) {
2508 log_warn(LD_DIR, "Invalid GuardFraction %s", escaped(guardfraction_str));
2509 return -1;
2512 log_debug(LD_GENERAL, "[*] Parsed %s guardfraction '%s' for '%s'.",
2513 is_consensus ? "consensus" : "vote",
2514 guardfraction_str, rs->nickname);
2516 if (!is_consensus) { /* We are parsing a vote */
2517 vote_rs->status.guardfraction_percentage = guardfraction;
2518 vote_rs->status.has_guardfraction = 1;
2519 } else {
2520 /* We are parsing a consensus. Only apply guardfraction to guards. */
2521 if (rs->is_possible_guard) {
2522 rs->guardfraction_percentage = guardfraction;
2523 rs->has_guardfraction = 1;
2524 } else {
2525 log_warn(LD_BUG, "Got GuardFraction for non-guard %s. "
2526 "This is not supposed to happen. Not applying. ", rs->nickname);
2530 return 0;
2533 /** Given a string at *<b>s</b>, containing a routerstatus object, and an
2534 * empty smartlist at <b>tokens</b>, parse and return the first router status
2535 * object in the string, and advance *<b>s</b> to just after the end of the
2536 * router status. Return NULL and advance *<b>s</b> on error.
2538 * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
2539 * routerstatus but use <b>vote_rs</b> instead.
2541 * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
2542 * consensus, and we should parse it according to the method used to
2543 * make that consensus.
2545 * Parse according to the syntax used by the consensus flavor <b>flav</b>.
2547 STATIC routerstatus_t *
2548 routerstatus_parse_entry_from_string(memarea_t *area,
2549 const char **s, smartlist_t *tokens,
2550 networkstatus_t *vote,
2551 vote_routerstatus_t *vote_rs,
2552 int consensus_method,
2553 consensus_flavor_t flav)
2555 const char *eos, *s_dup = *s;
2556 routerstatus_t *rs = NULL;
2557 directory_token_t *tok;
2558 char timebuf[ISO_TIME_LEN+1];
2559 struct in_addr in;
2560 int offset = 0;
2561 tor_assert(tokens);
2562 tor_assert(bool_eq(vote, vote_rs));
2564 if (!consensus_method)
2565 flav = FLAV_NS;
2566 tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
2568 eos = find_start_of_next_routerstatus(*s);
2570 if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
2571 log_warn(LD_DIR, "Error tokenizing router status");
2572 goto err;
2574 if (smartlist_len(tokens) < 1) {
2575 log_warn(LD_DIR, "Impossibly short router status");
2576 goto err;
2578 tok = find_by_keyword(tokens, K_R);
2579 tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
2580 if (flav == FLAV_NS) {
2581 if (tok->n_args < 8) {
2582 log_warn(LD_DIR, "Too few arguments to r");
2583 goto err;
2585 } else if (flav == FLAV_MICRODESC) {
2586 offset = -1; /* There is no descriptor digest in an md consensus r line */
2589 if (vote_rs) {
2590 rs = &vote_rs->status;
2591 } else {
2592 rs = tor_malloc_zero(sizeof(routerstatus_t));
2595 if (!is_legal_nickname(tok->args[0])) {
2596 log_warn(LD_DIR,
2597 "Invalid nickname %s in router status; skipping.",
2598 escaped(tok->args[0]));
2599 goto err;
2601 strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
2603 if (digest_from_base64(rs->identity_digest, tok->args[1])) {
2604 log_warn(LD_DIR, "Error decoding identity digest %s",
2605 escaped(tok->args[1]));
2606 goto err;
2609 if (flav == FLAV_NS) {
2610 if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
2611 log_warn(LD_DIR, "Error decoding descriptor digest %s",
2612 escaped(tok->args[2]));
2613 goto err;
2617 if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
2618 tok->args[3+offset], tok->args[4+offset]) < 0 ||
2619 parse_iso_time(timebuf, &rs->published_on)<0) {
2620 log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
2621 tok->args[3+offset], tok->args[4+offset],
2622 offset, (int)flav);
2623 goto err;
2626 if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
2627 log_warn(LD_DIR, "Error parsing router address in network-status %s",
2628 escaped(tok->args[5+offset]));
2629 goto err;
2631 rs->addr = ntohl(in.s_addr);
2633 rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
2634 10,0,65535,NULL,NULL);
2635 rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
2636 10,0,65535,NULL,NULL);
2639 smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
2640 if (a_lines) {
2641 find_single_ipv6_orport(a_lines, &rs->ipv6_addr, &rs->ipv6_orport);
2642 smartlist_free(a_lines);
2646 tok = find_opt_by_keyword(tokens, K_S);
2647 if (tok && vote) {
2648 int i;
2649 vote_rs->flags = 0;
2650 for (i=0; i < tok->n_args; ++i) {
2651 int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
2652 if (p >= 0) {
2653 vote_rs->flags |= (U64_LITERAL(1)<<p);
2654 } else {
2655 log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
2656 escaped(tok->args[i]));
2657 goto err;
2660 } else if (tok) {
2661 /* This is a consensus, not a vote. */
2662 int i;
2663 for (i=0; i < tok->n_args; ++i) {
2664 if (!strcmp(tok->args[i], "Exit"))
2665 rs->is_exit = 1;
2666 else if (!strcmp(tok->args[i], "Stable"))
2667 rs->is_stable = 1;
2668 else if (!strcmp(tok->args[i], "Fast"))
2669 rs->is_fast = 1;
2670 else if (!strcmp(tok->args[i], "Running"))
2671 rs->is_flagged_running = 1;
2672 else if (!strcmp(tok->args[i], "Named"))
2673 rs->is_named = 1;
2674 else if (!strcmp(tok->args[i], "Valid"))
2675 rs->is_valid = 1;
2676 else if (!strcmp(tok->args[i], "Guard"))
2677 rs->is_possible_guard = 1;
2678 else if (!strcmp(tok->args[i], "BadExit"))
2679 rs->is_bad_exit = 1;
2680 else if (!strcmp(tok->args[i], "Authority"))
2681 rs->is_authority = 1;
2682 else if (!strcmp(tok->args[i], "Unnamed") &&
2683 consensus_method >= 2) {
2684 /* Unnamed is computed right by consensus method 2 and later. */
2685 rs->is_unnamed = 1;
2686 } else if (!strcmp(tok->args[i], "HSDir")) {
2687 rs->is_hs_dir = 1;
2688 } else if (!strcmp(tok->args[i], "V2Dir")) {
2689 rs->is_v2_dir = 1;
2692 /* These are implied true by having been included in a consensus made
2693 * with a given method */
2694 rs->is_flagged_running = 1; /* Starting with consensus method 4. */
2695 if (consensus_method >= MIN_METHOD_FOR_EXCLUDING_INVALID_NODES)
2696 rs->is_valid = 1;
2698 int found_protocol_list = 0;
2699 if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
2700 found_protocol_list = 1;
2701 rs->protocols_known = 1;
2702 rs->supports_extend2_cells =
2703 protocol_list_supports_protocol(tok->args[0], PRT_RELAY, 2);
2704 rs->supports_ed25519_link_handshake =
2705 protocol_list_supports_protocol(tok->args[0], PRT_LINKAUTH, 3);
2706 rs->supports_ed25519_hs_intro =
2707 protocol_list_supports_protocol(tok->args[0], PRT_HSINTRO, 4);
2708 rs->supports_v3_hsdir =
2709 protocol_list_supports_protocol(tok->args[0], PRT_HSDIR,
2710 PROTOVER_HSDIR_V3);
2711 rs->supports_v3_rendezvous_point =
2712 protocol_list_supports_protocol(tok->args[0], PRT_HSREND,
2713 PROTOVER_HS_RENDEZVOUS_POINT_V3);
2715 if ((tok = find_opt_by_keyword(tokens, K_V))) {
2716 tor_assert(tok->n_args == 1);
2717 if (!strcmpstart(tok->args[0], "Tor ") && !found_protocol_list) {
2718 /* We only do version checks like this in the case where
2719 * the version is a "Tor" version, and where there is no
2720 * list of protocol versions that we should be looking at instead. */
2721 rs->supports_extend2_cells =
2722 tor_version_as_new_as(tok->args[0], "0.2.4.8-alpha");
2723 rs->protocols_known = 1;
2725 if (!strcmpstart(tok->args[0], "Tor ") && found_protocol_list) {
2726 /* Bug #22447 forces us to filter on this version. */
2727 if (!tor_version_as_new_as(tok->args[0], "0.3.0.8")) {
2728 rs->supports_v3_hsdir = 0;
2731 if (vote_rs) {
2732 vote_rs->version = tor_strdup(tok->args[0]);
2736 /* handle weighting/bandwidth info */
2737 if ((tok = find_opt_by_keyword(tokens, K_W))) {
2738 int i;
2739 for (i=0; i < tok->n_args; ++i) {
2740 if (!strcmpstart(tok->args[i], "Bandwidth=")) {
2741 int ok;
2742 rs->bandwidth_kb =
2743 (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
2744 10, 0, UINT32_MAX,
2745 &ok, NULL);
2746 if (!ok) {
2747 log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
2748 goto err;
2750 rs->has_bandwidth = 1;
2751 } else if (!strcmpstart(tok->args[i], "Measured=") && vote_rs) {
2752 int ok;
2753 vote_rs->measured_bw_kb =
2754 (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
2755 10, 0, UINT32_MAX, &ok, NULL);
2756 if (!ok) {
2757 log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
2758 escaped(tok->args[i]));
2759 goto err;
2761 vote_rs->has_measured_bw = 1;
2762 vote->has_measured_bws = 1;
2763 } else if (!strcmpstart(tok->args[i], "Unmeasured=1")) {
2764 rs->bw_is_unmeasured = 1;
2765 } else if (!strcmpstart(tok->args[i], "GuardFraction=")) {
2766 if (routerstatus_parse_guardfraction(tok->args[i],
2767 vote, vote_rs, rs) < 0) {
2768 goto err;
2774 /* parse exit policy summaries */
2775 if ((tok = find_opt_by_keyword(tokens, K_P))) {
2776 tor_assert(tok->n_args == 1);
2777 if (strcmpstart(tok->args[0], "accept ") &&
2778 strcmpstart(tok->args[0], "reject ")) {
2779 log_warn(LD_DIR, "Unknown exit policy summary type %s.",
2780 escaped(tok->args[0]));
2781 goto err;
2783 /* XXX weasel: parse this into ports and represent them somehow smart,
2784 * maybe not here but somewhere on if we need it for the client.
2785 * we should still parse it here to check it's valid tho.
2787 rs->exitsummary = tor_strdup(tok->args[0]);
2788 rs->has_exitsummary = 1;
2791 if (vote_rs) {
2792 SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
2793 if (t->tp == K_M && t->n_args) {
2794 vote_microdesc_hash_t *line =
2795 tor_malloc(sizeof(vote_microdesc_hash_t));
2796 line->next = vote_rs->microdesc;
2797 line->microdesc_hash_line = tor_strdup(t->args[0]);
2798 vote_rs->microdesc = line;
2800 if (t->tp == K_ID) {
2801 tor_assert(t->n_args >= 2);
2802 if (!strcmp(t->args[0], "ed25519")) {
2803 vote_rs->has_ed25519_listing = 1;
2804 if (strcmp(t->args[1], "none") &&
2805 digest256_from_base64((char*)vote_rs->ed25519_id,
2806 t->args[1])<0) {
2807 log_warn(LD_DIR, "Bogus ed25519 key in networkstatus vote");
2808 goto err;
2812 if (t->tp == K_PROTO) {
2813 tor_assert(t->n_args == 1);
2814 vote_rs->protocols = tor_strdup(t->args[0]);
2816 } SMARTLIST_FOREACH_END(t);
2817 } else if (flav == FLAV_MICRODESC) {
2818 tok = find_opt_by_keyword(tokens, K_M);
2819 if (tok) {
2820 tor_assert(tok->n_args);
2821 if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
2822 log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
2823 escaped(tok->args[0]));
2824 goto err;
2826 } else {
2827 log_info(LD_BUG, "Found an entry in networkstatus with no "
2828 "microdescriptor digest. (Router %s ($%s) at %s:%d.)",
2829 rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
2830 fmt_addr32(rs->addr), rs->or_port);
2834 if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
2835 rs->is_named = 0;
2837 goto done;
2838 err:
2839 dump_desc(s_dup, "routerstatus entry");
2840 if (rs && !vote_rs)
2841 routerstatus_free(rs);
2842 rs = NULL;
2843 done:
2844 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
2845 smartlist_clear(tokens);
2846 if (area) {
2847 DUMP_AREA(area, "routerstatus entry");
2848 memarea_clear(area);
2850 *s = eos;
2852 return rs;
2856 compare_vote_routerstatus_entries(const void **_a, const void **_b)
2858 const vote_routerstatus_t *a = *_a, *b = *_b;
2859 return fast_memcmp(a->status.identity_digest, b->status.identity_digest,
2860 DIGEST_LEN);
2863 /** Verify the bandwidth weights of a network status document */
2865 networkstatus_verify_bw_weights(networkstatus_t *ns, int consensus_method)
2867 int64_t G=0, M=0, E=0, D=0, T=0;
2868 double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
2869 double Gtotal=0, Mtotal=0, Etotal=0;
2870 const char *casename = NULL;
2871 int valid = 1;
2872 (void) consensus_method;
2874 const int64_t weight_scale = networkstatus_get_weight_scale_param(ns);
2875 tor_assert(weight_scale >= 1);
2876 Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
2877 Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
2878 Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
2879 Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
2880 Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
2881 Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
2882 Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
2883 Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
2884 Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
2885 Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
2886 Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
2888 if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
2889 || Wem<0 || Wee<0 || Wed<0) {
2890 log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
2891 return 0;
2894 // First, sanity check basic summing properties that hold for all cases
2895 // We use > 1 as the check for these because they are computed as integers.
2896 // Sometimes there are rounding errors.
2897 if (fabs(Wmm - weight_scale) > 1) {
2898 log_warn(LD_BUG, "Wmm=%f != "I64_FORMAT,
2899 Wmm, I64_PRINTF_ARG(weight_scale));
2900 valid = 0;
2903 if (fabs(Wem - Wee) > 1) {
2904 log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
2905 valid = 0;
2908 if (fabs(Wgm - Wgg) > 1) {
2909 log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
2910 valid = 0;
2913 if (fabs(Weg - Wed) > 1) {
2914 log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
2915 valid = 0;
2918 if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
2919 log_warn(LD_BUG, "Wgg=%f != "I64_FORMAT" - Wmg=%f", Wgg,
2920 I64_PRINTF_ARG(weight_scale), Wmg);
2921 valid = 0;
2924 if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
2925 log_warn(LD_BUG, "Wee=%f != "I64_FORMAT" - Wme=%f", Wee,
2926 I64_PRINTF_ARG(weight_scale), Wme);
2927 valid = 0;
2930 if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
2931 log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != "I64_FORMAT,
2932 Wgd, Wmd, Wed, I64_PRINTF_ARG(weight_scale));
2933 valid = 0;
2936 Wgg /= weight_scale;
2937 Wgm /= weight_scale; (void) Wgm; // unused from here on.
2938 Wgd /= weight_scale;
2940 Wmg /= weight_scale;
2941 Wmm /= weight_scale;
2942 Wme /= weight_scale;
2943 Wmd /= weight_scale;
2945 Weg /= weight_scale; (void) Weg; // unused from here on.
2946 Wem /= weight_scale; (void) Wem; // unused from here on.
2947 Wee /= weight_scale;
2948 Wed /= weight_scale;
2950 // Then, gather G, M, E, D, T to determine case
2951 SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
2952 int is_exit = 0;
2953 /* Bug #2203: Don't count bad exits as exits for balancing */
2954 is_exit = rs->is_exit && !rs->is_bad_exit;
2955 if (rs->has_bandwidth) {
2956 T += rs->bandwidth_kb;
2957 if (is_exit && rs->is_possible_guard) {
2958 D += rs->bandwidth_kb;
2959 Gtotal += Wgd*rs->bandwidth_kb;
2960 Mtotal += Wmd*rs->bandwidth_kb;
2961 Etotal += Wed*rs->bandwidth_kb;
2962 } else if (is_exit) {
2963 E += rs->bandwidth_kb;
2964 Mtotal += Wme*rs->bandwidth_kb;
2965 Etotal += Wee*rs->bandwidth_kb;
2966 } else if (rs->is_possible_guard) {
2967 G += rs->bandwidth_kb;
2968 Gtotal += Wgg*rs->bandwidth_kb;
2969 Mtotal += Wmg*rs->bandwidth_kb;
2970 } else {
2971 M += rs->bandwidth_kb;
2972 Mtotal += Wmm*rs->bandwidth_kb;
2974 } else {
2975 log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
2976 routerstatus_describe(rs));
2978 } SMARTLIST_FOREACH_END(rs);
2980 // Finally, check equality conditions depending upon case 1, 2 or 3
2981 // Full equality cases: 1, 3b
2982 // Partial equality cases: 2b (E=G), 3a (M=E)
2983 // Fully unknown: 2a
2984 if (3*E >= T && 3*G >= T) {
2985 // Case 1: Neither are scarce
2986 casename = "Case 1";
2987 if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
2988 log_warn(LD_DIR,
2989 "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
2990 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
2991 " T="I64_FORMAT". "
2992 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
2993 casename, Etotal, Mtotal,
2994 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
2995 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
2996 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
2997 valid = 0;
2999 if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
3000 log_warn(LD_DIR,
3001 "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
3002 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3003 " T="I64_FORMAT". "
3004 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3005 casename, Etotal, Gtotal,
3006 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3007 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3008 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3009 valid = 0;
3011 if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
3012 log_warn(LD_DIR,
3013 "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
3014 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3015 " T="I64_FORMAT". "
3016 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3017 casename, Mtotal, Gtotal,
3018 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3019 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3020 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3021 valid = 0;
3023 } else if (3*E < T && 3*G < T) {
3024 int64_t R = MIN(E, G);
3025 int64_t S = MAX(E, G);
3027 * Case 2: Both Guards and Exits are scarce
3028 * Balance D between E and G, depending upon
3029 * D capacity and scarcity. Devote no extra
3030 * bandwidth to middle nodes.
3032 if (R+D < S) { // Subcase a
3033 double Rtotal, Stotal;
3034 if (E < G) {
3035 Rtotal = Etotal;
3036 Stotal = Gtotal;
3037 } else {
3038 Rtotal = Gtotal;
3039 Stotal = Etotal;
3041 casename = "Case 2a";
3042 // Rtotal < Stotal
3043 if (Rtotal > Stotal) {
3044 log_warn(LD_DIR,
3045 "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
3046 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3047 " T="I64_FORMAT". "
3048 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3049 casename, Rtotal, Stotal,
3050 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3051 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3052 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3053 valid = 0;
3055 // Rtotal < T/3
3056 if (3*Rtotal > T) {
3057 log_warn(LD_DIR,
3058 "Bw Weight Failure for %s: 3*Rtotal %f > T "
3059 I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
3060 " D="I64_FORMAT" T="I64_FORMAT". "
3061 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3062 casename, Rtotal*3, I64_PRINTF_ARG(T),
3063 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3064 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3065 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3066 valid = 0;
3068 // Stotal < T/3
3069 if (3*Stotal > T) {
3070 log_warn(LD_DIR,
3071 "Bw Weight Failure for %s: 3*Stotal %f > T "
3072 I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
3073 " D="I64_FORMAT" T="I64_FORMAT". "
3074 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3075 casename, Stotal*3, I64_PRINTF_ARG(T),
3076 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3077 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3078 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3079 valid = 0;
3081 // Mtotal > T/3
3082 if (3*Mtotal < T) {
3083 log_warn(LD_DIR,
3084 "Bw Weight Failure for %s: 3*Mtotal %f < T "
3085 I64_FORMAT". "
3086 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3087 " T="I64_FORMAT". "
3088 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3089 casename, Mtotal*3, I64_PRINTF_ARG(T),
3090 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3091 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3092 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3093 valid = 0;
3095 } else { // Subcase b: R+D > S
3096 casename = "Case 2b";
3098 /* Check the rare-M redirect case. */
3099 if (D != 0 && 3*M < T) {
3100 casename = "Case 2b (balanced)";
3101 if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
3102 log_warn(LD_DIR,
3103 "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
3104 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3105 " T="I64_FORMAT". "
3106 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3107 casename, Etotal, Mtotal,
3108 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3109 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3110 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3111 valid = 0;
3113 if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
3114 log_warn(LD_DIR,
3115 "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
3116 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3117 " T="I64_FORMAT". "
3118 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3119 casename, Etotal, Gtotal,
3120 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3121 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3122 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3123 valid = 0;
3125 if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
3126 log_warn(LD_DIR,
3127 "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
3128 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3129 " T="I64_FORMAT". "
3130 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3131 casename, Mtotal, Gtotal,
3132 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3133 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3134 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3135 valid = 0;
3137 } else {
3138 if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
3139 log_warn(LD_DIR,
3140 "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
3141 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3142 " T="I64_FORMAT". "
3143 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3144 casename, Etotal, Gtotal,
3145 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3146 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3147 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3148 valid = 0;
3152 } else { // if (E < T/3 || G < T/3) {
3153 int64_t S = MIN(E, G);
3154 int64_t NS = MAX(E, G);
3155 if (3*(S+D) < T) { // Subcase a:
3156 double Stotal;
3157 double NStotal;
3158 if (G < E) {
3159 casename = "Case 3a (G scarce)";
3160 Stotal = Gtotal;
3161 NStotal = Etotal;
3162 } else { // if (G >= E) {
3163 casename = "Case 3a (E scarce)";
3164 NStotal = Gtotal;
3165 Stotal = Etotal;
3167 // Stotal < T/3
3168 if (3*Stotal > T) {
3169 log_warn(LD_DIR,
3170 "Bw Weight Failure for %s: 3*Stotal %f > T "
3171 I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
3172 " D="I64_FORMAT" T="I64_FORMAT". "
3173 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3174 casename, Stotal*3, I64_PRINTF_ARG(T),
3175 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3176 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3177 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3178 valid = 0;
3180 if (NS >= M) {
3181 if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
3182 log_warn(LD_DIR,
3183 "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
3184 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3185 " T="I64_FORMAT". "
3186 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3187 casename, NStotal, Mtotal,
3188 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3189 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3190 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3191 valid = 0;
3193 } else {
3194 // if NS < M, NStotal > T/3 because only one of G or E is scarce
3195 if (3*NStotal < T) {
3196 log_warn(LD_DIR,
3197 "Bw Weight Failure for %s: 3*NStotal %f < T "
3198 I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT
3199 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT". "
3200 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3201 casename, NStotal*3, I64_PRINTF_ARG(T),
3202 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3203 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3204 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3205 valid = 0;
3208 } else { // Subcase b: S+D >= T/3
3209 casename = "Case 3b";
3210 if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
3211 log_warn(LD_DIR,
3212 "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
3213 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3214 " T="I64_FORMAT". "
3215 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3216 casename, Etotal, Mtotal,
3217 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3218 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3219 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3220 valid = 0;
3222 if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
3223 log_warn(LD_DIR,
3224 "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
3225 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3226 " T="I64_FORMAT". "
3227 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3228 casename, Etotal, Gtotal,
3229 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3230 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3231 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3232 valid = 0;
3234 if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
3235 log_warn(LD_DIR,
3236 "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
3237 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
3238 " T="I64_FORMAT". "
3239 "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
3240 casename, Mtotal, Gtotal,
3241 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
3242 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
3243 Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
3244 valid = 0;
3249 if (valid)
3250 log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
3251 casename);
3253 return valid;
3256 /** Parse and extract all SR commits from <b>tokens</b> and place them in
3257 * <b>ns</b>. */
3258 static void
3259 extract_shared_random_commits(networkstatus_t *ns, smartlist_t *tokens)
3261 smartlist_t *chunks = NULL;
3263 tor_assert(ns);
3264 tor_assert(tokens);
3265 /* Commits are only present in a vote. */
3266 tor_assert(ns->type == NS_TYPE_VOTE);
3268 ns->sr_info.commits = smartlist_new();
3270 smartlist_t *commits = find_all_by_keyword(tokens, K_COMMIT);
3271 /* It's normal that a vote might contain no commits even if it participates
3272 * in the SR protocol. Don't treat it as an error. */
3273 if (commits == NULL) {
3274 goto end;
3277 /* Parse the commit. We do NO validation of number of arguments or ordering
3278 * for forward compatibility, it's the parse commit job to inform us if it's
3279 * supported or not. */
3280 chunks = smartlist_new();
3281 SMARTLIST_FOREACH_BEGIN(commits, directory_token_t *, tok) {
3282 /* Extract all arguments and put them in the chunks list. */
3283 for (int i = 0; i < tok->n_args; i++) {
3284 smartlist_add(chunks, tok->args[i]);
3286 sr_commit_t *commit = sr_parse_commit(chunks);
3287 smartlist_clear(chunks);
3288 if (commit == NULL) {
3289 /* Get voter identity so we can warn that this dirauth vote contains
3290 * commit we can't parse. */
3291 networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
3292 tor_assert(voter);
3293 log_warn(LD_DIR, "SR: Unable to parse commit %s from vote of voter %s.",
3294 escaped(tok->object_body),
3295 hex_str(voter->identity_digest,
3296 sizeof(voter->identity_digest)));
3297 /* Commitment couldn't be parsed. Continue onto the next commit because
3298 * this one could be unsupported for instance. */
3299 continue;
3301 /* Add newly created commit object to the vote. */
3302 smartlist_add(ns->sr_info.commits, commit);
3303 } SMARTLIST_FOREACH_END(tok);
3305 end:
3306 smartlist_free(chunks);
3307 smartlist_free(commits);
3310 /** Check if a shared random value of type <b>srv_type</b> is in
3311 * <b>tokens</b>. If there is, parse it and set it to <b>srv_out</b>. Return
3312 * -1 on failure, 0 on success. The resulting srv is allocated on the heap and
3313 * it's the responsibility of the caller to free it. */
3314 static int
3315 extract_one_srv(smartlist_t *tokens, directory_keyword srv_type,
3316 sr_srv_t **srv_out)
3318 int ret = -1;
3319 directory_token_t *tok;
3320 sr_srv_t *srv = NULL;
3321 smartlist_t *chunks;
3323 tor_assert(tokens);
3325 chunks = smartlist_new();
3326 tok = find_opt_by_keyword(tokens, srv_type);
3327 if (!tok) {
3328 /* That's fine, no SRV is allowed. */
3329 ret = 0;
3330 goto end;
3332 for (int i = 0; i < tok->n_args; i++) {
3333 smartlist_add(chunks, tok->args[i]);
3335 srv = sr_parse_srv(chunks);
3336 if (srv == NULL) {
3337 log_warn(LD_DIR, "SR: Unparseable SRV %s", escaped(tok->object_body));
3338 goto end;
3340 /* All is good. */
3341 *srv_out = srv;
3342 ret = 0;
3343 end:
3344 smartlist_free(chunks);
3345 return ret;
3348 /** Extract any shared random values found in <b>tokens</b> and place them in
3349 * the networkstatus <b>ns</b>. */
3350 static void
3351 extract_shared_random_srvs(networkstatus_t *ns, smartlist_t *tokens)
3353 const char *voter_identity;
3354 networkstatus_voter_info_t *voter;
3356 tor_assert(ns);
3357 tor_assert(tokens);
3358 /* Can be only one of them else code flow. */
3359 tor_assert(ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS);
3361 if (ns->type == NS_TYPE_VOTE) {
3362 voter = smartlist_get(ns->voters, 0);
3363 tor_assert(voter);
3364 voter_identity = hex_str(voter->identity_digest,
3365 sizeof(voter->identity_digest));
3366 } else {
3367 /* Consensus has multiple voters so no specific voter. */
3368 voter_identity = "consensus";
3371 /* We extract both, and on error everything is stopped because it means
3372 * the vote is malformed for the shared random value(s). */
3373 if (extract_one_srv(tokens, K_PREVIOUS_SRV, &ns->sr_info.previous_srv) < 0) {
3374 log_warn(LD_DIR, "SR: Unable to parse previous SRV from %s",
3375 voter_identity);
3376 /* Maybe we have a chance with the current SRV so let's try it anyway. */
3378 if (extract_one_srv(tokens, K_CURRENT_SRV, &ns->sr_info.current_srv) < 0) {
3379 log_warn(LD_DIR, "SR: Unable to parse current SRV from %s",
3380 voter_identity);
3384 /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
3385 * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
3386 networkstatus_t *
3387 networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
3388 networkstatus_type_t ns_type)
3390 smartlist_t *tokens = smartlist_new();
3391 smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
3392 networkstatus_voter_info_t *voter = NULL;
3393 networkstatus_t *ns = NULL;
3394 common_digests_t ns_digests;
3395 uint8_t sha3_as_signed[DIGEST256_LEN];
3396 const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
3397 directory_token_t *tok;
3398 struct in_addr in;
3399 int i, inorder, n_signatures = 0;
3400 memarea_t *area = NULL, *rs_area = NULL;
3401 consensus_flavor_t flav = FLAV_NS;
3402 char *last_kwd=NULL;
3404 tor_assert(s);
3406 if (eos_out)
3407 *eos_out = NULL;
3409 if (router_get_networkstatus_v3_hashes(s, &ns_digests) ||
3410 router_get_networkstatus_v3_sha3_as_signed(sha3_as_signed, s)<0) {
3411 log_warn(LD_DIR, "Unable to compute digest of network-status");
3412 goto err;
3415 area = memarea_new();
3416 end_of_header = find_start_of_next_routerstatus(s);
3417 if (tokenize_string(area, s, end_of_header, tokens,
3418 (ns_type == NS_TYPE_CONSENSUS) ?
3419 networkstatus_consensus_token_table :
3420 networkstatus_token_table, 0)) {
3421 log_warn(LD_DIR, "Error tokenizing network-status header");
3422 goto err;
3425 ns = tor_malloc_zero(sizeof(networkstatus_t));
3426 memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
3427 memcpy(&ns->digest_sha3_as_signed, sha3_as_signed, sizeof(sha3_as_signed));
3429 tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
3430 tor_assert(tok);
3431 if (tok->n_args > 1) {
3432 int flavor = networkstatus_parse_flavor_name(tok->args[1]);
3433 if (flavor < 0) {
3434 log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
3435 escaped(tok->args[1]));
3436 goto err;
3438 ns->flavor = flav = flavor;
3440 if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
3441 log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
3442 goto err;
3445 if (ns_type != NS_TYPE_CONSENSUS) {
3446 const char *end_of_cert = NULL;
3447 if (!(cert = strstr(s, "\ndir-key-certificate-version")))
3448 goto err;
3449 ++cert;
3450 ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
3451 if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
3452 goto err;
3455 tok = find_by_keyword(tokens, K_VOTE_STATUS);
3456 tor_assert(tok->n_args);
3457 if (!strcmp(tok->args[0], "vote")) {
3458 ns->type = NS_TYPE_VOTE;
3459 } else if (!strcmp(tok->args[0], "consensus")) {
3460 ns->type = NS_TYPE_CONSENSUS;
3461 } else if (!strcmp(tok->args[0], "opinion")) {
3462 ns->type = NS_TYPE_OPINION;
3463 } else {
3464 log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
3465 escaped(tok->args[0]));
3466 goto err;
3468 if (ns_type != ns->type) {
3469 log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
3470 goto err;
3473 if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
3474 tok = find_by_keyword(tokens, K_PUBLISHED);
3475 if (parse_iso_time(tok->args[0], &ns->published))
3476 goto err;
3478 ns->supported_methods = smartlist_new();
3479 tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
3480 if (tok) {
3481 for (i=0; i < tok->n_args; ++i)
3482 smartlist_add_strdup(ns->supported_methods, tok->args[i]);
3483 } else {
3484 smartlist_add_strdup(ns->supported_methods, "1");
3486 } else {
3487 tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
3488 if (tok) {
3489 int num_ok;
3490 ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
3491 &num_ok, NULL);
3492 if (!num_ok)
3493 goto err;
3494 } else {
3495 ns->consensus_method = 1;
3499 if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_CLIENT_PROTOCOLS)))
3500 ns->recommended_client_protocols = tor_strdup(tok->args[0]);
3501 if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_RELAY_PROTOCOLS)))
3502 ns->recommended_relay_protocols = tor_strdup(tok->args[0]);
3503 if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_CLIENT_PROTOCOLS)))
3504 ns->required_client_protocols = tor_strdup(tok->args[0]);
3505 if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_RELAY_PROTOCOLS)))
3506 ns->required_relay_protocols = tor_strdup(tok->args[0]);
3508 tok = find_by_keyword(tokens, K_VALID_AFTER);
3509 if (parse_iso_time(tok->args[0], &ns->valid_after))
3510 goto err;
3512 tok = find_by_keyword(tokens, K_FRESH_UNTIL);
3513 if (parse_iso_time(tok->args[0], &ns->fresh_until))
3514 goto err;
3516 tok = find_by_keyword(tokens, K_VALID_UNTIL);
3517 if (parse_iso_time(tok->args[0], &ns->valid_until))
3518 goto err;
3520 tok = find_by_keyword(tokens, K_VOTING_DELAY);
3521 tor_assert(tok->n_args >= 2);
3523 int ok;
3524 ns->vote_seconds =
3525 (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
3526 if (!ok)
3527 goto err;
3528 ns->dist_seconds =
3529 (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
3530 if (!ok)
3531 goto err;
3533 if (ns->valid_after +
3534 (get_options()->TestingTorNetwork ?
3535 MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) > ns->fresh_until) {
3536 log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
3537 goto err;
3539 if (ns->valid_after +
3540 (get_options()->TestingTorNetwork ?
3541 MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL)*2 > ns->valid_until) {
3542 log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
3543 goto err;
3545 if (ns->vote_seconds < MIN_VOTE_SECONDS) {
3546 log_warn(LD_DIR, "Vote seconds is too short");
3547 goto err;
3549 if (ns->dist_seconds < MIN_DIST_SECONDS) {
3550 log_warn(LD_DIR, "Dist seconds is too short");
3551 goto err;
3554 if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
3555 ns->client_versions = tor_strdup(tok->args[0]);
3557 if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
3558 ns->server_versions = tor_strdup(tok->args[0]);
3562 smartlist_t *package_lst = find_all_by_keyword(tokens, K_PACKAGE);
3563 ns->package_lines = smartlist_new();
3564 if (package_lst) {
3565 SMARTLIST_FOREACH(package_lst, directory_token_t *, t,
3566 smartlist_add_strdup(ns->package_lines, t->args[0]));
3568 smartlist_free(package_lst);
3571 tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
3572 ns->known_flags = smartlist_new();
3573 inorder = 1;
3574 for (i = 0; i < tok->n_args; ++i) {
3575 smartlist_add_strdup(ns->known_flags, tok->args[i]);
3576 if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
3577 log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
3578 inorder = 0;
3581 if (!inorder) {
3582 log_warn(LD_DIR, "known-flags not in order");
3583 goto err;
3585 if (ns->type != NS_TYPE_CONSENSUS &&
3586 smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
3587 /* If we allowed more than 64 flags in votes, then parsing them would make
3588 * us invoke undefined behavior whenever we used 1<<flagnum to do a
3589 * bit-shift. This is only for votes and opinions: consensus users don't
3590 * care about flags they don't recognize, and so don't build a bitfield
3591 * for them. */
3592 log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
3593 goto err;
3596 tok = find_opt_by_keyword(tokens, K_PARAMS);
3597 if (tok) {
3598 int any_dups = 0;
3599 inorder = 1;
3600 ns->net_params = smartlist_new();
3601 for (i = 0; i < tok->n_args; ++i) {
3602 int ok=0;
3603 char *eq = strchr(tok->args[i], '=');
3604 size_t eq_pos;
3605 if (!eq) {
3606 log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
3607 goto err;
3609 eq_pos = eq-tok->args[i];
3610 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
3611 if (!ok) {
3612 log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
3613 goto err;
3615 if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
3616 log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
3617 inorder = 0;
3619 if (last_kwd && eq_pos == strlen(last_kwd) &&
3620 fast_memeq(last_kwd, tok->args[i], eq_pos)) {
3621 log_warn(LD_DIR, "Duplicate value for %s parameter",
3622 escaped(tok->args[i]));
3623 any_dups = 1;
3625 tor_free(last_kwd);
3626 last_kwd = tor_strndup(tok->args[i], eq_pos);
3627 smartlist_add_strdup(ns->net_params, tok->args[i]);
3629 if (!inorder) {
3630 log_warn(LD_DIR, "params not in order");
3631 goto err;
3633 if (any_dups) {
3634 log_warn(LD_DIR, "Duplicate in parameters");
3635 goto err;
3639 ns->voters = smartlist_new();
3641 SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
3642 tok = _tok;
3643 if (tok->tp == K_DIR_SOURCE) {
3644 tor_assert(tok->n_args >= 6);
3646 if (voter)
3647 smartlist_add(ns->voters, voter);
3648 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
3649 voter->sigs = smartlist_new();
3650 if (ns->type != NS_TYPE_CONSENSUS)
3651 memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
3653 voter->nickname = tor_strdup(tok->args[0]);
3654 if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
3655 base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
3656 tok->args[1], HEX_DIGEST_LEN)
3657 != sizeof(voter->identity_digest)) {
3658 log_warn(LD_DIR, "Error decoding identity digest %s in "
3659 "network-status document.", escaped(tok->args[1]));
3660 goto err;
3662 if (ns->type != NS_TYPE_CONSENSUS &&
3663 tor_memneq(ns->cert->cache_info.identity_digest,
3664 voter->identity_digest, DIGEST_LEN)) {
3665 log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
3666 goto err;
3668 if (ns->type != NS_TYPE_CONSENSUS) {
3669 if (authority_cert_is_blacklisted(ns->cert)) {
3670 log_warn(LD_DIR, "Rejecting vote signature made with blacklisted "
3671 "signing key %s",
3672 hex_str(ns->cert->signing_key_digest, DIGEST_LEN));
3673 goto err;
3676 voter->address = tor_strdup(tok->args[2]);
3677 if (!tor_inet_aton(tok->args[3], &in)) {
3678 log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
3679 escaped(tok->args[3]));
3680 goto err;
3682 voter->addr = ntohl(in.s_addr);
3683 int ok;
3684 voter->dir_port = (uint16_t)
3685 tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
3686 if (!ok)
3687 goto err;
3688 voter->or_port = (uint16_t)
3689 tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
3690 if (!ok)
3691 goto err;
3692 } else if (tok->tp == K_CONTACT) {
3693 if (!voter || voter->contact) {
3694 log_warn(LD_DIR, "contact element is out of place.");
3695 goto err;
3697 voter->contact = tor_strdup(tok->args[0]);
3698 } else if (tok->tp == K_VOTE_DIGEST) {
3699 tor_assert(ns->type == NS_TYPE_CONSENSUS);
3700 tor_assert(tok->n_args >= 1);
3701 if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
3702 log_warn(LD_DIR, "vote-digest element is out of place.");
3703 goto err;
3705 if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
3706 base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
3707 tok->args[0], HEX_DIGEST_LEN)
3708 != sizeof(voter->vote_digest)) {
3709 log_warn(LD_DIR, "Error decoding vote digest %s in "
3710 "network-status consensus.", escaped(tok->args[0]));
3711 goto err;
3714 } SMARTLIST_FOREACH_END(_tok);
3715 if (voter) {
3716 smartlist_add(ns->voters, voter);
3717 voter = NULL;
3719 if (smartlist_len(ns->voters) == 0) {
3720 log_warn(LD_DIR, "Missing dir-source elements in a networkstatus.");
3721 goto err;
3722 } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
3723 log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
3724 goto err;
3727 if (ns->type != NS_TYPE_CONSENSUS &&
3728 (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
3729 int bad = 1;
3730 if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
3731 networkstatus_voter_info_t *voter_0 = smartlist_get(ns->voters, 0);
3732 if (base16_decode(voter_0->legacy_id_digest, DIGEST_LEN,
3733 tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN)
3734 bad = 1;
3735 else
3736 bad = 0;
3738 if (bad) {
3739 log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
3740 escaped(tok->args[0]));
3744 /* If this is a vote document, check if information about the shared
3745 randomness protocol is included, and extract it. */
3746 if (ns->type == NS_TYPE_VOTE) {
3747 /* Does this authority participates in the SR protocol? */
3748 tok = find_opt_by_keyword(tokens, K_SR_FLAG);
3749 if (tok) {
3750 ns->sr_info.participate = 1;
3751 /* Get the SR commitments and reveals from the vote. */
3752 extract_shared_random_commits(ns, tokens);
3755 /* For both a vote and consensus, extract the shared random values. */
3756 if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS) {
3757 extract_shared_random_srvs(ns, tokens);
3760 /* Parse routerstatus lines. */
3761 rs_tokens = smartlist_new();
3762 rs_area = memarea_new();
3763 s = end_of_header;
3764 ns->routerstatus_list = smartlist_new();
3766 while (!strcmpstart(s, "r ")) {
3767 if (ns->type != NS_TYPE_CONSENSUS) {
3768 vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3769 if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
3770 rs, 0, 0)) {
3771 smartlist_add(ns->routerstatus_list, rs);
3772 } else {
3773 vote_routerstatus_free(rs);
3775 } else {
3776 routerstatus_t *rs;
3777 if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
3778 NULL, NULL,
3779 ns->consensus_method,
3780 flav))) {
3781 /* Use exponential-backoff scheduling when downloading microdescs */
3782 rs->dl_status.backoff = DL_SCHED_RANDOM_EXPONENTIAL;
3783 smartlist_add(ns->routerstatus_list, rs);
3787 for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
3788 routerstatus_t *rs1, *rs2;
3789 if (ns->type != NS_TYPE_CONSENSUS) {
3790 vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
3791 vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
3792 rs1 = &a->status; rs2 = &b->status;
3793 } else {
3794 rs1 = smartlist_get(ns->routerstatus_list, i-1);
3795 rs2 = smartlist_get(ns->routerstatus_list, i);
3797 if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
3798 >= 0) {
3799 log_warn(LD_DIR, "Networkstatus entries not sorted by identity digest");
3800 goto err;
3803 if (ns_type != NS_TYPE_CONSENSUS) {
3804 digest256map_t *ed_id_map = digest256map_new();
3805 SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, vote_routerstatus_t *,
3806 vrs) {
3807 if (! vrs->has_ed25519_listing ||
3808 tor_mem_is_zero((const char *)vrs->ed25519_id, DIGEST256_LEN))
3809 continue;
3810 if (digest256map_get(ed_id_map, vrs->ed25519_id) != NULL) {
3811 log_warn(LD_DIR, "Vote networkstatus ed25519 identities were not "
3812 "unique");
3813 digest256map_free(ed_id_map, NULL);
3814 goto err;
3816 digest256map_set(ed_id_map, vrs->ed25519_id, (void*)1);
3817 } SMARTLIST_FOREACH_END(vrs);
3818 digest256map_free(ed_id_map, NULL);
3821 /* Parse footer; check signature. */
3822 footer_tokens = smartlist_new();
3823 if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
3824 ++end_of_footer;
3825 else
3826 end_of_footer = s + strlen(s);
3827 if (tokenize_string(area,s, end_of_footer, footer_tokens,
3828 networkstatus_vote_footer_token_table, 0)) {
3829 log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
3830 goto err;
3834 int found_sig = 0;
3835 SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
3836 tok = _tok;
3837 if (tok->tp == K_DIRECTORY_SIGNATURE)
3838 found_sig = 1;
3839 else if (found_sig) {
3840 log_warn(LD_DIR, "Extraneous token after first directory-signature");
3841 goto err;
3843 } SMARTLIST_FOREACH_END(_tok);
3846 if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
3847 if (tok != smartlist_get(footer_tokens, 0)) {
3848 log_warn(LD_DIR, "Misplaced directory-footer token");
3849 goto err;
3853 tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
3854 if (tok) {
3855 ns->weight_params = smartlist_new();
3856 for (i = 0; i < tok->n_args; ++i) {
3857 int ok=0;
3858 char *eq = strchr(tok->args[i], '=');
3859 if (!eq) {
3860 log_warn(LD_DIR, "Bad element '%s' in weight params",
3861 escaped(tok->args[i]));
3862 goto err;
3864 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
3865 if (!ok) {
3866 log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
3867 goto err;
3869 smartlist_add_strdup(ns->weight_params, tok->args[i]);
3873 SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
3874 char declared_identity[DIGEST_LEN];
3875 networkstatus_voter_info_t *v;
3876 document_signature_t *sig;
3877 const char *id_hexdigest = NULL;
3878 const char *sk_hexdigest = NULL;
3879 digest_algorithm_t alg = DIGEST_SHA1;
3880 tok = _tok;
3881 if (tok->tp != K_DIRECTORY_SIGNATURE)
3882 continue;
3883 tor_assert(tok->n_args >= 2);
3884 if (tok->n_args == 2) {
3885 id_hexdigest = tok->args[0];
3886 sk_hexdigest = tok->args[1];
3887 } else {
3888 const char *algname = tok->args[0];
3889 int a;
3890 id_hexdigest = tok->args[1];
3891 sk_hexdigest = tok->args[2];
3892 a = crypto_digest_algorithm_parse_name(algname);
3893 if (a<0) {
3894 log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
3895 escaped(algname));
3896 continue;
3898 alg = a;
3901 if (!tok->object_type ||
3902 strcmp(tok->object_type, "SIGNATURE") ||
3903 tok->object_size < 128 || tok->object_size > 512) {
3904 log_warn(LD_DIR, "Bad object type or length on directory-signature");
3905 goto err;
3908 if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
3909 base16_decode(declared_identity, sizeof(declared_identity),
3910 id_hexdigest, HEX_DIGEST_LEN)
3911 != sizeof(declared_identity)) {
3912 log_warn(LD_DIR, "Error decoding declared identity %s in "
3913 "network-status document.", escaped(id_hexdigest));
3914 goto err;
3916 if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
3917 log_warn(LD_DIR, "ID on signature on network-status document does "
3918 "not match any declared directory source.");
3919 goto err;
3921 sig = tor_malloc_zero(sizeof(document_signature_t));
3922 memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
3923 sig->alg = alg;
3924 if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
3925 base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
3926 sk_hexdigest, HEX_DIGEST_LEN)
3927 != sizeof(sig->signing_key_digest)) {
3928 log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
3929 "network-status document.", escaped(sk_hexdigest));
3930 tor_free(sig);
3931 goto err;
3934 if (ns->type != NS_TYPE_CONSENSUS) {
3935 if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
3936 DIGEST_LEN)) {
3937 log_warn(LD_DIR, "Digest mismatch between declared and actual on "
3938 "network-status vote.");
3939 tor_free(sig);
3940 goto err;
3944 if (voter_get_sig_by_algorithm(v, sig->alg)) {
3945 /* We already parsed a vote with this algorithm from this voter. Use the
3946 first one. */
3947 log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
3948 "that contains two signatures from the same voter with the same "
3949 "algorithm. Ignoring the second signature.");
3950 tor_free(sig);
3951 continue;
3954 if (ns->type != NS_TYPE_CONSENSUS) {
3955 if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
3956 tok, ns->cert->signing_key, 0,
3957 "network-status document")) {
3958 tor_free(sig);
3959 goto err;
3961 sig->good_signature = 1;
3962 } else {
3963 if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
3964 tor_free(sig);
3965 goto err;
3967 sig->signature = tor_memdup(tok->object_body, tok->object_size);
3968 sig->signature_len = (int) tok->object_size;
3970 smartlist_add(v->sigs, sig);
3972 ++n_signatures;
3973 } SMARTLIST_FOREACH_END(_tok);
3975 if (! n_signatures) {
3976 log_warn(LD_DIR, "No signatures on networkstatus document.");
3977 goto err;
3978 } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
3979 log_warn(LD_DIR, "Received more than one signature on a "
3980 "network-status vote.");
3981 goto err;
3984 if (eos_out)
3985 *eos_out = end_of_footer;
3987 goto done;
3988 err:
3989 dump_desc(s_dup, "v3 networkstatus");
3990 networkstatus_vote_free(ns);
3991 ns = NULL;
3992 done:
3993 if (tokens) {
3994 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
3995 smartlist_free(tokens);
3997 if (voter) {
3998 if (voter->sigs) {
3999 SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
4000 document_signature_free(sig));
4001 smartlist_free(voter->sigs);
4003 tor_free(voter->nickname);
4004 tor_free(voter->address);
4005 tor_free(voter->contact);
4006 tor_free(voter);
4008 if (rs_tokens) {
4009 SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
4010 smartlist_free(rs_tokens);
4012 if (footer_tokens) {
4013 SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
4014 smartlist_free(footer_tokens);
4016 if (area) {
4017 DUMP_AREA(area, "v3 networkstatus");
4018 memarea_drop_all(area);
4020 if (rs_area)
4021 memarea_drop_all(rs_area);
4022 tor_free(last_kwd);
4024 return ns;
4027 /** Return the common_digests_t that holds the digests of the
4028 * <b>flavor_name</b>-flavored networkstatus according to the detached
4029 * signatures document <b>sigs</b>, allocating a new common_digests_t as
4030 * neeeded. */
4031 static common_digests_t *
4032 detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
4034 common_digests_t *d = strmap_get(sigs->digests, flavor_name);
4035 if (!d) {
4036 d = tor_malloc_zero(sizeof(common_digests_t));
4037 strmap_set(sigs->digests, flavor_name, d);
4039 return d;
4042 /** Return the list of signatures of the <b>flavor_name</b>-flavored
4043 * networkstatus according to the detached signatures document <b>sigs</b>,
4044 * allocating a new common_digests_t as neeeded. */
4045 static smartlist_t *
4046 detached_get_signatures(ns_detached_signatures_t *sigs,
4047 const char *flavor_name)
4049 smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
4050 if (!sl) {
4051 sl = smartlist_new();
4052 strmap_set(sigs->signatures, flavor_name, sl);
4054 return sl;
4057 /** Parse a detached v3 networkstatus signature document between <b>s</b> and
4058 * <b>eos</b> and return the result. Return -1 on failure. */
4059 ns_detached_signatures_t *
4060 networkstatus_parse_detached_signatures(const char *s, const char *eos)
4062 /* XXXX there is too much duplicate shared between this function and
4063 * networkstatus_parse_vote_from_string(). */
4064 directory_token_t *tok;
4065 memarea_t *area = NULL;
4066 common_digests_t *digests;
4068 smartlist_t *tokens = smartlist_new();
4069 ns_detached_signatures_t *sigs =
4070 tor_malloc_zero(sizeof(ns_detached_signatures_t));
4071 sigs->digests = strmap_new();
4072 sigs->signatures = strmap_new();
4074 if (!eos)
4075 eos = s + strlen(s);
4077 area = memarea_new();
4078 if (tokenize_string(area,s, eos, tokens,
4079 networkstatus_detached_signature_token_table, 0)) {
4080 log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
4081 goto err;
4084 /* Grab all the digest-like tokens. */
4085 SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
4086 const char *algname;
4087 digest_algorithm_t alg;
4088 const char *flavor;
4089 const char *hexdigest;
4090 size_t expected_length, digest_length;
4092 tok = _tok;
4094 if (tok->tp == K_CONSENSUS_DIGEST) {
4095 algname = "sha1";
4096 alg = DIGEST_SHA1;
4097 flavor = "ns";
4098 hexdigest = tok->args[0];
4099 } else if (tok->tp == K_ADDITIONAL_DIGEST) {
4100 int a = crypto_digest_algorithm_parse_name(tok->args[1]);
4101 if (a<0) {
4102 log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
4103 continue;
4105 alg = (digest_algorithm_t) a;
4106 flavor = tok->args[0];
4107 algname = tok->args[1];
4108 hexdigest = tok->args[2];
4109 } else {
4110 continue;
4113 digest_length = crypto_digest_algorithm_get_length(alg);
4114 expected_length = digest_length * 2; /* hex encoding */
4116 if (strlen(hexdigest) != expected_length) {
4117 log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
4118 "networkstatus signatures");
4119 goto err;
4121 digests = detached_get_digests(sigs, flavor);
4122 tor_assert(digests);
4123 if (!tor_mem_is_zero(digests->d[alg], digest_length)) {
4124 log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
4125 "signatures document", flavor, algname);
4126 continue;
4128 if (base16_decode(digests->d[alg], digest_length,
4129 hexdigest, strlen(hexdigest)) != (int) digest_length) {
4130 log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
4131 "networkstatus signatures");
4132 goto err;
4134 } SMARTLIST_FOREACH_END(_tok);
4136 tok = find_by_keyword(tokens, K_VALID_AFTER);
4137 if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
4138 log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
4139 goto err;
4142 tok = find_by_keyword(tokens, K_FRESH_UNTIL);
4143 if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
4144 log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
4145 goto err;
4148 tok = find_by_keyword(tokens, K_VALID_UNTIL);
4149 if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
4150 log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
4151 goto err;
4154 SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
4155 const char *id_hexdigest;
4156 const char *sk_hexdigest;
4157 const char *algname;
4158 const char *flavor;
4159 digest_algorithm_t alg;
4161 char id_digest[DIGEST_LEN];
4162 char sk_digest[DIGEST_LEN];
4163 smartlist_t *siglist;
4164 document_signature_t *sig;
4165 int is_duplicate;
4167 tok = _tok;
4168 if (tok->tp == K_DIRECTORY_SIGNATURE) {
4169 tor_assert(tok->n_args >= 2);
4170 flavor = "ns";
4171 algname = "sha1";
4172 id_hexdigest = tok->args[0];
4173 sk_hexdigest = tok->args[1];
4174 } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
4175 tor_assert(tok->n_args >= 4);
4176 flavor = tok->args[0];
4177 algname = tok->args[1];
4178 id_hexdigest = tok->args[2];
4179 sk_hexdigest = tok->args[3];
4180 } else {
4181 continue;
4185 int a = crypto_digest_algorithm_parse_name(algname);
4186 if (a<0) {
4187 log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
4188 continue;
4190 alg = (digest_algorithm_t) a;
4193 if (!tok->object_type ||
4194 strcmp(tok->object_type, "SIGNATURE") ||
4195 tok->object_size < 128 || tok->object_size > 512) {
4196 log_warn(LD_DIR, "Bad object type or length on directory-signature");
4197 goto err;
4200 if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
4201 base16_decode(id_digest, sizeof(id_digest),
4202 id_hexdigest, HEX_DIGEST_LEN) != sizeof(id_digest)) {
4203 log_warn(LD_DIR, "Error decoding declared identity %s in "
4204 "network-status vote.", escaped(id_hexdigest));
4205 goto err;
4207 if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
4208 base16_decode(sk_digest, sizeof(sk_digest),
4209 sk_hexdigest, HEX_DIGEST_LEN) != sizeof(sk_digest)) {
4210 log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
4211 "network-status vote.", escaped(sk_hexdigest));
4212 goto err;
4215 siglist = detached_get_signatures(sigs, flavor);
4216 is_duplicate = 0;
4217 SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
4218 if (dsig->alg == alg &&
4219 tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
4220 tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
4221 is_duplicate = 1;
4224 if (is_duplicate) {
4225 log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
4226 "found.");
4227 continue;
4230 sig = tor_malloc_zero(sizeof(document_signature_t));
4231 sig->alg = alg;
4232 memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
4233 memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
4234 if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
4235 tor_free(sig);
4236 goto err;
4238 sig->signature = tor_memdup(tok->object_body, tok->object_size);
4239 sig->signature_len = (int) tok->object_size;
4241 smartlist_add(siglist, sig);
4242 } SMARTLIST_FOREACH_END(_tok);
4244 goto done;
4245 err:
4246 ns_detached_signatures_free(sigs);
4247 sigs = NULL;
4248 done:
4249 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
4250 smartlist_free(tokens);
4251 if (area) {
4252 DUMP_AREA(area, "detached signatures");
4253 memarea_drop_all(area);
4255 return sigs;
4258 /** Parse the addr policy in the string <b>s</b> and return it. If
4259 * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
4260 * ADDR_POLICY_REJECT) for items that specify no action.
4262 * Returns NULL on policy errors.
4264 * Set *<b>malformed_list</b> to true if the entire policy list should be
4265 * discarded. Otherwise, set it to false, and only this item should be ignored
4266 * on error - the rest of the policy list can continue to be processed and
4267 * used.
4269 * The addr_policy_t returned by this function can have its address set to
4270 * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
4271 * of AF_INET and AF_INET6 items.
4273 MOCK_IMPL(addr_policy_t *,
4274 router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
4275 int *malformed_list))
4277 directory_token_t *tok = NULL;
4278 const char *cp, *eos;
4279 /* Longest possible policy is
4280 * "accept6 [ffff:ffff:..255]/128:10000-65535",
4281 * which contains a max-length IPv6 address, plus 26 characters.
4282 * But note that there can be an arbitrary amount of space between the
4283 * accept and the address:mask/port element.
4284 * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
4285 * IPv6 address. But making the buffer shorter might cause valid long lines,
4286 * which parsed in previous versions, to fail to parse in new versions.
4287 * (These lines would have to have excessive amounts of whitespace.) */
4288 char line[TOR_ADDR_BUF_LEN*2 + 32];
4289 addr_policy_t *r;
4290 memarea_t *area = NULL;
4292 tor_assert(malformed_list);
4293 *malformed_list = 0;
4295 s = eat_whitespace(s);
4296 /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
4297 * and ":" (port separator) are ambiguous */
4298 if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
4299 if (tor_snprintf(line, sizeof(line), "%s %s",
4300 assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
4301 log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
4302 return NULL;
4304 cp = line;
4305 tor_strlower(line);
4306 } else { /* assume an already well-formed address policy line */
4307 cp = s;
4310 eos = cp + strlen(cp);
4311 area = memarea_new();
4312 tok = get_next_token(area, &cp, eos, routerdesc_token_table);
4313 if (tok->tp == ERR_) {
4314 log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
4315 goto err;
4317 if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
4318 tok->tp != K_REJECT && tok->tp != K_REJECT6) {
4319 log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
4320 goto err;
4323 /* Use the extended interpretation of accept/reject *,
4324 * expanding it into an IPv4 wildcard and an IPv6 wildcard.
4325 * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
4326 r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
4327 if (!r) {
4328 goto err;
4331 /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
4332 * AF_UNSPEC addresses are only permitted on the accept/reject field type.
4333 * Unlike descriptors, torrcs exit policy accept/reject can be followed by
4334 * either an IPv4 or IPv6 address. */
4335 if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
4336 tor_addr_family(&r->addr) != AF_INET6) {
4337 /* This is a non-fatal error, just ignore this one entry. */
4338 *malformed_list = 0;
4339 log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
4340 "exit policy. Ignoring, but continuing to parse rules. (Use "
4341 "accept/reject with IPv4 addresses.)",
4342 tok->n_args == 1 ? tok->args[0] : "");
4343 addr_policy_free(r);
4344 r = NULL;
4345 goto done;
4348 goto done;
4349 err:
4350 *malformed_list = 1;
4351 r = NULL;
4352 done:
4353 token_clear(tok);
4354 if (area) {
4355 DUMP_AREA(area, "policy item");
4356 memarea_drop_all(area);
4358 return r;
4361 /** Add an exit policy stored in the token <b>tok</b> to the router info in
4362 * <b>router</b>. Return 0 on success, -1 on failure. */
4363 static int
4364 router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
4366 addr_policy_t *newe;
4367 /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
4368 newe = router_parse_addr_policy(tok, 0);
4369 if (!newe)
4370 return -1;
4371 if (! router->exit_policy)
4372 router->exit_policy = smartlist_new();
4374 /* Ensure that in descriptors, accept/reject fields are followed by
4375 * IPv4 addresses, and accept6/reject6 fields are followed by
4376 * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
4377 * accept/reject followed by IPv6. */
4378 if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
4379 tor_addr_family(&newe->addr) == AF_INET)
4381 ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
4382 tor_addr_family(&newe->addr) == AF_INET6)) {
4383 /* There's nothing the user can do about other relays' descriptors,
4384 * so we don't provide usage advice here. */
4385 log_warn(LD_DIR, "Mismatch between field type and address type in exit "
4386 "policy '%s'. Discarding entire router descriptor.",
4387 tok->n_args == 1 ? tok->args[0] : "");
4388 addr_policy_free(newe);
4389 return -1;
4392 smartlist_add(router->exit_policy, newe);
4394 return 0;
4397 /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
4398 * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
4399 * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
4400 * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
4401 * policies */
4402 static addr_policy_t *
4403 router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
4405 addr_policy_t newe;
4406 char *arg;
4408 tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
4409 tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
4411 if (tok->n_args != 1)
4412 return NULL;
4413 arg = tok->args[0];
4415 if (!strcmpstart(arg,"private"))
4416 return router_parse_addr_policy_private(tok);
4418 memset(&newe, 0, sizeof(newe));
4420 if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
4421 newe.policy_type = ADDR_POLICY_REJECT;
4422 else
4423 newe.policy_type = ADDR_POLICY_ACCEPT;
4425 /* accept6/reject6 * produces an IPv6 wildcard address only.
4426 * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
4427 if ((fmt_flags & TAPMP_EXTENDED_STAR)
4428 && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
4429 fmt_flags |= TAPMP_STAR_IPV6_ONLY;
4432 if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
4433 &newe.prt_min, &newe.prt_max) < 0) {
4434 log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
4435 return NULL;
4438 return addr_policy_get_canonical_entry(&newe);
4441 /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
4442 * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
4443 * router descriptors until earlier versions are obsolete.
4445 * accept/reject and accept6/reject6 private all produce rules for both
4446 * IPv4 and IPv6 addresses.
4448 static addr_policy_t *
4449 router_parse_addr_policy_private(directory_token_t *tok)
4451 const char *arg;
4452 uint16_t port_min, port_max;
4453 addr_policy_t result;
4455 arg = tok->args[0];
4456 if (strcmpstart(arg, "private"))
4457 return NULL;
4459 arg += strlen("private");
4460 arg = (char*) eat_whitespace(arg);
4461 if (!arg || *arg != ':')
4462 return NULL;
4464 if (parse_port_range(arg+1, &port_min, &port_max)<0)
4465 return NULL;
4467 memset(&result, 0, sizeof(result));
4468 if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
4469 result.policy_type = ADDR_POLICY_REJECT;
4470 else
4471 result.policy_type = ADDR_POLICY_ACCEPT;
4472 result.is_private = 1;
4473 result.prt_min = port_min;
4474 result.prt_max = port_max;
4476 if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
4477 log_warn(LD_GENERAL,
4478 "'%s' expands into rules which apply to all private IPv4 and "
4479 "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
4480 "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
4483 return addr_policy_get_canonical_entry(&result);
4486 /** Log and exit if <b>t</b> is malformed */
4487 void
4488 assert_addr_policy_ok(smartlist_t *lst)
4490 if (!lst) return;
4491 SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
4492 tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
4493 t->policy_type == ADDR_POLICY_ACCEPT);
4494 tor_assert(t->prt_min <= t->prt_max);
4498 /** Return a newly allocated smartlist of all accept or reject tokens in
4499 * <b>s</b>.
4501 static smartlist_t *
4502 find_all_exitpolicy(smartlist_t *s)
4504 smartlist_t *out = smartlist_new();
4505 SMARTLIST_FOREACH(s, directory_token_t *, t,
4506 if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
4507 t->tp == K_REJECT || t->tp == K_REJECT6)
4508 smartlist_add(out,t));
4509 return out;
4512 /** Helper function for <b>router_get_hash_impl</b>: given <b>s</b>,
4513 * <b>s_len</b>, <b>start_str</b>, <b>end_str</b>, and <b>end_c</b> with the
4514 * same semantics as in that function, set *<b>start_out</b> (inclusive) and
4515 * *<b>end_out</b> (exclusive) to the boundaries of the string to be hashed.
4517 * Return 0 on success and -1 on failure.
4519 static int
4520 router_get_hash_impl_helper(const char *s, size_t s_len,
4521 const char *start_str,
4522 const char *end_str, char end_c,
4523 int log_severity,
4524 const char **start_out, const char **end_out)
4526 const char *start, *end;
4527 start = tor_memstr(s, s_len, start_str);
4528 if (!start) {
4529 log_fn(log_severity,LD_DIR,
4530 "couldn't find start of hashed material \"%s\"",start_str);
4531 return -1;
4533 if (start != s && *(start-1) != '\n') {
4534 log_fn(log_severity,LD_DIR,
4535 "first occurrence of \"%s\" is not at the start of a line",
4536 start_str);
4537 return -1;
4539 end = tor_memstr(start+strlen(start_str),
4540 s_len - (start-s) - strlen(start_str), end_str);
4541 if (!end) {
4542 log_fn(log_severity,LD_DIR,
4543 "couldn't find end of hashed material \"%s\"",end_str);
4544 return -1;
4546 end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
4547 if (!end) {
4548 log_fn(log_severity,LD_DIR,
4549 "couldn't find EOL");
4550 return -1;
4552 ++end;
4554 *start_out = start;
4555 *end_out = end;
4556 return 0;
4559 /** Compute the digest of the substring of <b>s</b> taken from the first
4560 * occurrence of <b>start_str</b> through the first instance of c after the
4561 * first subsequent occurrence of <b>end_str</b>; store the 20-byte or 32-byte
4562 * result in <b>digest</b>; return 0 on success.
4564 * If no such substring exists, return -1.
4566 static int
4567 router_get_hash_impl(const char *s, size_t s_len, char *digest,
4568 const char *start_str,
4569 const char *end_str, char end_c,
4570 digest_algorithm_t alg)
4572 const char *start=NULL, *end=NULL;
4573 if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,LOG_WARN,
4574 &start,&end)<0)
4575 return -1;
4577 return router_compute_hash_final(digest, start, end-start, alg);
4580 /** Compute the digest of the <b>len</b>-byte directory object at
4581 * <b>start</b>, using <b>alg</b>. Store the result in <b>digest</b>, which
4582 * must be long enough to hold it. */
4583 MOCK_IMPL(STATIC int,
4584 router_compute_hash_final,(char *digest,
4585 const char *start, size_t len,
4586 digest_algorithm_t alg))
4588 if (alg == DIGEST_SHA1) {
4589 if (crypto_digest(digest, start, len) < 0) {
4590 log_warn(LD_BUG,"couldn't compute digest");
4591 return -1;
4593 } else {
4594 if (crypto_digest256(digest, start, len, alg) < 0) {
4595 log_warn(LD_BUG,"couldn't compute digest");
4596 return -1;
4600 return 0;
4603 /** As router_get_hash_impl, but compute all hashes. */
4604 static int
4605 router_get_hashes_impl(const char *s, size_t s_len, common_digests_t *digests,
4606 const char *start_str,
4607 const char *end_str, char end_c)
4609 const char *start=NULL, *end=NULL;
4610 if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,LOG_WARN,
4611 &start,&end)<0)
4612 return -1;
4614 if (crypto_common_digests(digests, start, end-start)) {
4615 log_warn(LD_BUG,"couldn't compute digests");
4616 return -1;
4619 return 0;
4622 /** Assuming that s starts with a microdesc, return the start of the
4623 * *NEXT* one. Return NULL on "not found." */
4624 static const char *
4625 find_start_of_next_microdesc(const char *s, const char *eos)
4627 int started_with_annotations;
4628 s = eat_whitespace_eos(s, eos);
4629 if (!s)
4630 return NULL;
4632 #define CHECK_LENGTH() STMT_BEGIN \
4633 if (s+32 > eos) \
4634 return NULL; \
4635 STMT_END
4637 #define NEXT_LINE() STMT_BEGIN \
4638 s = memchr(s, '\n', eos-s); \
4639 if (!s || s+1 >= eos) \
4640 return NULL; \
4641 s++; \
4642 STMT_END
4644 CHECK_LENGTH();
4646 started_with_annotations = (*s == '@');
4648 if (started_with_annotations) {
4649 /* Start by advancing to the first non-annotation line. */
4650 while (*s == '@')
4651 NEXT_LINE();
4653 CHECK_LENGTH();
4655 /* Now we should be pointed at an onion-key line. If we are, then skip
4656 * it. */
4657 if (!strcmpstart(s, "onion-key"))
4658 NEXT_LINE();
4660 /* Okay, now we're pointed at the first line of the microdescriptor which is
4661 not an annotation or onion-key. The next line that _is_ an annotation or
4662 onion-key is the start of the next microdescriptor. */
4663 while (s+32 < eos) {
4664 if (*s == '@' || !strcmpstart(s, "onion-key"))
4665 return s;
4666 NEXT_LINE();
4668 return NULL;
4670 #undef CHECK_LENGTH
4671 #undef NEXT_LINE
4674 /** Parse as many microdescriptors as are found from the string starting at
4675 * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
4676 * annotations we recognize and ignore ones we don't.
4678 * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
4679 * descriptor in the body field of each microdesc_t.
4681 * Return all newly parsed microdescriptors in a newly allocated
4682 * smartlist_t. If <b>invalid_disgests_out</b> is provided, add a SHA256
4683 * microdesc digest to it for every microdesc that we found to be badly
4684 * formed. (This may cause duplicates) */
4685 smartlist_t *
4686 microdescs_parse_from_string(const char *s, const char *eos,
4687 int allow_annotations,
4688 saved_location_t where,
4689 smartlist_t *invalid_digests_out)
4691 smartlist_t *tokens;
4692 smartlist_t *result;
4693 microdesc_t *md = NULL;
4694 memarea_t *area;
4695 const char *start = s;
4696 const char *start_of_next_microdesc;
4697 int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
4698 const int copy_body = (where != SAVED_IN_CACHE);
4700 directory_token_t *tok;
4702 if (!eos)
4703 eos = s + strlen(s);
4705 s = eat_whitespace_eos(s, eos);
4706 area = memarea_new();
4707 result = smartlist_new();
4708 tokens = smartlist_new();
4710 while (s < eos) {
4711 int okay = 0;
4713 start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
4714 if (!start_of_next_microdesc)
4715 start_of_next_microdesc = eos;
4717 md = tor_malloc_zero(sizeof(microdesc_t));
4719 const char *cp = tor_memstr(s, start_of_next_microdesc-s,
4720 "onion-key");
4721 const int no_onion_key = (cp == NULL);
4722 if (no_onion_key) {
4723 cp = s; /* So that we have *some* junk to put in the body */
4726 md->bodylen = start_of_next_microdesc - cp;
4727 md->saved_location = where;
4728 if (copy_body)
4729 md->body = tor_memdup_nulterm(cp, md->bodylen);
4730 else
4731 md->body = (char*)cp;
4732 md->off = cp - start;
4733 crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
4734 if (no_onion_key) {
4735 log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Malformed or truncated descriptor");
4736 goto next;
4740 if (tokenize_string(area, s, start_of_next_microdesc, tokens,
4741 microdesc_token_table, flags)) {
4742 log_warn(LD_DIR, "Unparseable microdescriptor");
4743 goto next;
4746 if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
4747 if (parse_iso_time(tok->args[0], &md->last_listed)) {
4748 log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
4749 goto next;
4753 tok = find_by_keyword(tokens, K_ONION_KEY);
4754 if (!crypto_pk_public_exponent_ok(tok->key)) {
4755 log_warn(LD_DIR,
4756 "Relay's onion key had invalid exponent.");
4757 goto next;
4759 md->onion_pkey = tok->key;
4760 tok->key = NULL;
4762 if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
4763 curve25519_public_key_t k;
4764 tor_assert(tok->n_args >= 1);
4765 if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
4766 log_warn(LD_DIR, "Bogus ntor-onion-key in microdesc");
4767 goto next;
4769 md->onion_curve25519_pkey =
4770 tor_memdup(&k, sizeof(curve25519_public_key_t));
4773 smartlist_t *id_lines = find_all_by_keyword(tokens, K_ID);
4774 if (id_lines) {
4775 SMARTLIST_FOREACH_BEGIN(id_lines, directory_token_t *, t) {
4776 tor_assert(t->n_args >= 2);
4777 if (!strcmp(t->args[0], "ed25519")) {
4778 if (md->ed25519_identity_pkey) {
4779 log_warn(LD_DIR, "Extra ed25519 key in microdesc");
4780 smartlist_free(id_lines);
4781 goto next;
4783 ed25519_public_key_t k;
4784 if (ed25519_public_from_base64(&k, t->args[1])<0) {
4785 log_warn(LD_DIR, "Bogus ed25519 key in microdesc");
4786 smartlist_free(id_lines);
4787 goto next;
4789 md->ed25519_identity_pkey = tor_memdup(&k, sizeof(k));
4791 } SMARTLIST_FOREACH_END(t);
4792 smartlist_free(id_lines);
4796 smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
4797 if (a_lines) {
4798 find_single_ipv6_orport(a_lines, &md->ipv6_addr, &md->ipv6_orport);
4799 smartlist_free(a_lines);
4803 if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
4804 int i;
4805 md->family = smartlist_new();
4806 for (i=0;i<tok->n_args;++i) {
4807 if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
4808 log_warn(LD_DIR, "Illegal nickname %s in family line",
4809 escaped(tok->args[i]));
4810 goto next;
4812 smartlist_add_strdup(md->family, tok->args[i]);
4816 if ((tok = find_opt_by_keyword(tokens, K_P))) {
4817 md->exit_policy = parse_short_policy(tok->args[0]);
4819 if ((tok = find_opt_by_keyword(tokens, K_P6))) {
4820 md->ipv6_exit_policy = parse_short_policy(tok->args[0]);
4823 smartlist_add(result, md);
4824 okay = 1;
4826 md = NULL;
4827 next:
4828 if (! okay && invalid_digests_out) {
4829 smartlist_add(invalid_digests_out,
4830 tor_memdup(md->digest, DIGEST256_LEN));
4832 microdesc_free(md);
4833 md = NULL;
4835 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
4836 memarea_clear(area);
4837 smartlist_clear(tokens);
4838 s = start_of_next_microdesc;
4841 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
4842 memarea_drop_all(area);
4843 smartlist_free(tokens);
4845 return result;
4848 /** Extract a Tor version from a <b>platform</b> line from a router
4849 * descriptor, and place the result in <b>router_version</b>.
4851 * Return 1 on success, -1 on parsing failure, and 0 if the
4852 * platform line does not indicate some version of Tor.
4854 * If <b>strict</b> is non-zero, finding any weird version components
4855 * (like negative numbers) counts as a parsing failure.
4858 tor_version_parse_platform(const char *platform,
4859 tor_version_t *router_version,
4860 int strict)
4862 char tmp[128];
4863 char *s, *s2, *start;
4865 if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; say 0. */
4866 return 0;
4868 start = (char *)eat_whitespace(platform+3);
4869 if (!*start) return -1;
4870 s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
4871 s2 = (char*)eat_whitespace(s);
4872 if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
4873 s = (char*)find_whitespace(s2);
4875 if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
4876 return -1;
4877 strlcpy(tmp, start, s-start+1);
4879 if (tor_version_parse(tmp, router_version)<0) {
4880 log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
4881 return -1;
4884 if (strict) {
4885 if (router_version->major < 0 ||
4886 router_version->minor < 0 ||
4887 router_version->micro < 0 ||
4888 router_version->patchlevel < 0 ||
4889 router_version->svn_revision < 0) {
4890 return -1;
4894 return 1;
4897 /** Parse the Tor version of the platform string <b>platform</b>,
4898 * and compare it to the version in <b>cutoff</b>. Return 1 if
4899 * the router is at least as new as the cutoff, else return 0.
4902 tor_version_as_new_as(const char *platform, const char *cutoff)
4904 tor_version_t cutoff_version, router_version;
4905 int r;
4906 tor_assert(platform);
4908 if (tor_version_parse(cutoff, &cutoff_version)<0) {
4909 log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
4910 return 0;
4913 r = tor_version_parse_platform(platform, &router_version, 0);
4914 if (r == 0) {
4915 /* nonstandard Tor; be safe and say yes */
4916 return 1;
4917 } else if (r < 0) {
4918 /* unparseable version; be safe and say yes. */
4919 return 1;
4922 /* Here's why we don't need to do any special handling for svn revisions:
4923 * - If neither has an svn revision, we're fine.
4924 * - If the router doesn't have an svn revision, we can't assume that it
4925 * is "at least" any svn revision, so we need to return 0.
4926 * - If the target version doesn't have an svn revision, any svn revision
4927 * (or none at all) is good enough, so return 1.
4928 * - If both target and router have an svn revision, we compare them.
4931 return tor_version_compare(&router_version, &cutoff_version) >= 0;
4934 /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
4935 * Return 0 on success, -1 on failure. */
4937 tor_version_parse(const char *s, tor_version_t *out)
4939 char *eos=NULL;
4940 const char *cp=NULL;
4941 int ok = 1;
4942 /* Format is:
4943 * "Tor " ? NUM dot NUM [ dot NUM [ ( pre | rc | dot ) NUM ] ] [ - tag ]
4945 tor_assert(s);
4946 tor_assert(out);
4948 memset(out, 0, sizeof(tor_version_t));
4949 out->status = VER_RELEASE;
4950 if (!strcasecmpstart(s, "Tor "))
4951 s += 4;
4953 cp = s;
4955 #define NUMBER(m) \
4956 do { \
4957 if (!cp || *cp < '0' || *cp > '9') \
4958 return -1; \
4959 out->m = (int)tor_parse_uint64(cp, 10, 0, INT32_MAX, &ok, &eos); \
4960 if (!ok) \
4961 return -1; \
4962 if (!eos || eos == cp) \
4963 return -1; \
4964 cp = eos; \
4965 } while (0)
4967 #define DOT() \
4968 do { \
4969 if (*cp != '.') \
4970 return -1; \
4971 ++cp; \
4972 } while (0)
4974 NUMBER(major);
4975 DOT();
4976 NUMBER(minor);
4977 if (*cp == 0)
4978 return 0;
4979 else if (*cp == '-')
4980 goto status_tag;
4981 DOT();
4982 NUMBER(micro);
4984 /* Get status */
4985 if (*cp == 0) {
4986 return 0;
4987 } else if (*cp == '.') {
4988 ++cp;
4989 } else if (*cp == '-') {
4990 goto status_tag;
4991 } else if (0==strncmp(cp, "pre", 3)) {
4992 out->status = VER_PRE;
4993 cp += 3;
4994 } else if (0==strncmp(cp, "rc", 2)) {
4995 out->status = VER_RC;
4996 cp += 2;
4997 } else {
4998 return -1;
5001 NUMBER(patchlevel);
5003 status_tag:
5004 /* Get status tag. */
5005 if (*cp == '-' || *cp == '.')
5006 ++cp;
5007 eos = (char*) find_whitespace(cp);
5008 if (eos-cp >= (int)sizeof(out->status_tag))
5009 strlcpy(out->status_tag, cp, sizeof(out->status_tag));
5010 else {
5011 memcpy(out->status_tag, cp, eos-cp);
5012 out->status_tag[eos-cp] = 0;
5014 cp = eat_whitespace(eos);
5016 if (!strcmpstart(cp, "(r")) {
5017 cp += 2;
5018 out->svn_revision = (int) strtol(cp,&eos,10);
5019 } else if (!strcmpstart(cp, "(git-")) {
5020 char *close_paren = strchr(cp, ')');
5021 int hexlen;
5022 char digest[DIGEST_LEN];
5023 if (! close_paren)
5024 return -1;
5025 cp += 5;
5026 if (close_paren-cp > HEX_DIGEST_LEN)
5027 return -1;
5028 hexlen = (int)(close_paren-cp);
5029 memwipe(digest, 0, sizeof(digest));
5030 if ( hexlen == 0 || (hexlen % 2) == 1)
5031 return -1;
5032 if (base16_decode(digest, hexlen/2, cp, hexlen) != hexlen/2)
5033 return -1;
5034 memcpy(out->git_tag, digest, hexlen/2);
5035 out->git_tag_len = hexlen/2;
5038 return 0;
5039 #undef NUMBER
5040 #undef DOT
5043 /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
5044 * b. */
5046 tor_version_compare(tor_version_t *a, tor_version_t *b)
5048 int i;
5049 tor_assert(a);
5050 tor_assert(b);
5052 /* We take this approach to comparison to ensure the same (bogus!) behavior
5053 * on all inputs as we would have seen before bug #21278 was fixed. The
5054 * only important difference here is that this method doesn't cause
5055 * a signed integer underflow.
5057 #define CMP(field) do { \
5058 unsigned aval = (unsigned) a->field; \
5059 unsigned bval = (unsigned) b->field; \
5060 int result = (int) (aval - bval); \
5061 if (result < 0) \
5062 return -1; \
5063 else if (result > 0) \
5064 return 1; \
5065 } while (0)
5067 CMP(major);
5068 CMP(minor);
5069 CMP(micro);
5070 CMP(status);
5071 CMP(patchlevel);
5072 if ((i = strcmp(a->status_tag, b->status_tag)))
5073 return i;
5074 CMP(svn_revision);
5075 CMP(git_tag_len);
5076 if (a->git_tag_len)
5077 return fast_memcmp(a->git_tag, b->git_tag, a->git_tag_len);
5078 else
5079 return 0;
5081 #undef CMP
5084 /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
5087 tor_version_same_series(tor_version_t *a, tor_version_t *b)
5089 tor_assert(a);
5090 tor_assert(b);
5091 return ((a->major == b->major) &&
5092 (a->minor == b->minor) &&
5093 (a->micro == b->micro));
5096 /** Helper: Given pointers to two strings describing tor versions, return -1
5097 * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
5098 * Used to sort a list of versions. */
5099 static int
5100 compare_tor_version_str_ptr_(const void **_a, const void **_b)
5102 const char *a = *_a, *b = *_b;
5103 int ca, cb;
5104 tor_version_t va, vb;
5105 ca = tor_version_parse(a, &va);
5106 cb = tor_version_parse(b, &vb);
5107 /* If they both parse, compare them. */
5108 if (!ca && !cb)
5109 return tor_version_compare(&va,&vb);
5110 /* If one parses, it comes first. */
5111 if (!ca && cb)
5112 return -1;
5113 if (ca && !cb)
5114 return 1;
5115 /* If neither parses, compare strings. Also, the directory server admin
5116 ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
5117 return strcmp(a,b);
5120 /** Sort a list of string-representations of versions in ascending order. */
5121 void
5122 sort_version_list(smartlist_t *versions, int remove_duplicates)
5124 smartlist_sort(versions, compare_tor_version_str_ptr_);
5126 if (remove_duplicates)
5127 smartlist_uniq(versions, compare_tor_version_str_ptr_, tor_free_);
5130 /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
5131 * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
5132 * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
5133 * encrypted introduction points to the newly allocated
5134 * *<b>intro_points_encrypted_out</b>, their encrypted size to
5135 * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
5136 * to *<b>encoded_size_out</b>, and a pointer to the possibly next
5137 * descriptor to *<b>next_out</b>; return 0 for success (including validation)
5138 * and -1 for failure.
5140 * If <b>as_hsdir</b> is 1, we're parsing this as an HSDir, and we should
5141 * be strict about time formats.
5144 rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
5145 char *desc_id_out,
5146 char **intro_points_encrypted_out,
5147 size_t *intro_points_encrypted_size_out,
5148 size_t *encoded_size_out,
5149 const char **next_out, const char *desc,
5150 int as_hsdir)
5152 rend_service_descriptor_t *result =
5153 tor_malloc_zero(sizeof(rend_service_descriptor_t));
5154 char desc_hash[DIGEST_LEN];
5155 const char *eos;
5156 smartlist_t *tokens = smartlist_new();
5157 directory_token_t *tok;
5158 char secret_id_part[DIGEST_LEN];
5159 int i, version, num_ok=1;
5160 smartlist_t *versions;
5161 char public_key_hash[DIGEST_LEN];
5162 char test_desc_id[DIGEST_LEN];
5163 memarea_t *area = NULL;
5164 const int strict_time_fmt = as_hsdir;
5166 tor_assert(desc);
5167 /* Check if desc starts correctly. */
5168 if (strncmp(desc, "rendezvous-service-descriptor ",
5169 strlen("rendezvous-service-descriptor "))) {
5170 log_info(LD_REND, "Descriptor does not start correctly.");
5171 goto err;
5173 /* Compute descriptor hash for later validation. */
5174 if (router_get_hash_impl(desc, strlen(desc), desc_hash,
5175 "rendezvous-service-descriptor ",
5176 "\nsignature", '\n', DIGEST_SHA1) < 0) {
5177 log_warn(LD_REND, "Couldn't compute descriptor hash.");
5178 goto err;
5180 /* Determine end of string. */
5181 eos = strstr(desc, "\nrendezvous-service-descriptor ");
5182 if (!eos)
5183 eos = desc + strlen(desc);
5184 else
5185 eos = eos + 1;
5186 /* Check length. */
5187 if (eos-desc > REND_DESC_MAX_SIZE) {
5188 /* XXXX+ If we are parsing this descriptor as a server, this
5189 * should be a protocol warning. */
5190 log_warn(LD_REND, "Descriptor length is %d which exceeds "
5191 "maximum rendezvous descriptor size of %d bytes.",
5192 (int)(eos-desc), REND_DESC_MAX_SIZE);
5193 goto err;
5195 /* Tokenize descriptor. */
5196 area = memarea_new();
5197 if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
5198 log_warn(LD_REND, "Error tokenizing descriptor.");
5199 goto err;
5201 /* Set next to next descriptor, if available. */
5202 *next_out = eos;
5203 /* Set length of encoded descriptor. */
5204 *encoded_size_out = eos - desc;
5205 /* Check min allowed length of token list. */
5206 if (smartlist_len(tokens) < 7) {
5207 log_warn(LD_REND, "Impossibly short descriptor.");
5208 goto err;
5210 /* Parse base32-encoded descriptor ID. */
5211 tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
5212 tor_assert(tok == smartlist_get(tokens, 0));
5213 tor_assert(tok->n_args == 1);
5214 if (!rend_valid_descriptor_id(tok->args[0])) {
5215 log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
5216 goto err;
5218 if (base32_decode(desc_id_out, DIGEST_LEN,
5219 tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
5220 log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
5221 tok->args[0]);
5222 goto err;
5224 /* Parse descriptor version. */
5225 tok = find_by_keyword(tokens, R_VERSION);
5226 tor_assert(tok->n_args == 1);
5227 result->version =
5228 (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
5229 if (result->version != 2 || !num_ok) {
5230 /* If it's <2, it shouldn't be under this format. If the number
5231 * is greater than 2, we bumped it because we broke backward
5232 * compatibility. See how version numbers in our other formats
5233 * work. */
5234 log_warn(LD_REND, "Unrecognized descriptor version: %s",
5235 escaped(tok->args[0]));
5236 goto err;
5238 /* Parse public key. */
5239 tok = find_by_keyword(tokens, R_PERMANENT_KEY);
5240 result->pk = tok->key;
5241 tok->key = NULL; /* Prevent free */
5242 /* Parse secret ID part. */
5243 tok = find_by_keyword(tokens, R_SECRET_ID_PART);
5244 tor_assert(tok->n_args == 1);
5245 if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
5246 strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
5247 log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
5248 goto err;
5250 if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
5251 log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
5252 tok->args[0]);
5253 goto err;
5255 /* Parse publication time -- up-to-date check is done when storing the
5256 * descriptor. */
5257 tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
5258 tor_assert(tok->n_args == 1);
5259 if (parse_iso_time_(tok->args[0], &result->timestamp,
5260 strict_time_fmt, 0) < 0) {
5261 log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
5262 goto err;
5264 /* Parse protocol versions. */
5265 tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
5266 tor_assert(tok->n_args == 1);
5267 versions = smartlist_new();
5268 smartlist_split_string(versions, tok->args[0], ",",
5269 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5270 for (i = 0; i < smartlist_len(versions); i++) {
5271 version = (int) tor_parse_long(smartlist_get(versions, i),
5272 10, 0, INT_MAX, &num_ok, NULL);
5273 if (!num_ok) /* It's a string; let's ignore it. */
5274 continue;
5275 if (version >= REND_PROTOCOL_VERSION_BITMASK_WIDTH)
5276 /* Avoid undefined left-shift behaviour. */
5277 continue;
5278 result->protocols |= 1 << version;
5280 SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
5281 smartlist_free(versions);
5282 /* Parse encrypted introduction points. Don't verify. */
5283 tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
5284 if (tok) {
5285 if (strcmp(tok->object_type, "MESSAGE")) {
5286 log_warn(LD_DIR, "Bad object type: introduction points should be of "
5287 "type MESSAGE");
5288 goto err;
5290 *intro_points_encrypted_out = tor_memdup(tok->object_body,
5291 tok->object_size);
5292 *intro_points_encrypted_size_out = tok->object_size;
5293 } else {
5294 *intro_points_encrypted_out = NULL;
5295 *intro_points_encrypted_size_out = 0;
5297 /* Parse and verify signature. */
5298 tok = find_by_keyword(tokens, R_SIGNATURE);
5299 if (check_signature_token(desc_hash, DIGEST_LEN, tok, result->pk, 0,
5300 "v2 rendezvous service descriptor") < 0)
5301 goto err;
5302 /* Verify that descriptor ID belongs to public key and secret ID part. */
5303 if (crypto_pk_get_digest(result->pk, public_key_hash) < 0) {
5304 log_warn(LD_REND, "Unable to compute rend descriptor public key digest");
5305 goto err;
5307 rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
5308 secret_id_part);
5309 if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
5310 log_warn(LD_REND, "Parsed descriptor ID does not match "
5311 "computed descriptor ID.");
5312 goto err;
5314 goto done;
5315 err:
5316 rend_service_descriptor_free(result);
5317 result = NULL;
5318 done:
5319 if (tokens) {
5320 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
5321 smartlist_free(tokens);
5323 if (area)
5324 memarea_drop_all(area);
5325 *parsed_out = result;
5326 if (result)
5327 return 0;
5328 return -1;
5331 /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
5332 * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
5333 * write the result to a newly allocated string that is pointed to by
5334 * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
5335 * Return 0 if decryption was successful and -1 otherwise. */
5337 rend_decrypt_introduction_points(char **ipos_decrypted,
5338 size_t *ipos_decrypted_size,
5339 const char *descriptor_cookie,
5340 const char *ipos_encrypted,
5341 size_t ipos_encrypted_size)
5343 tor_assert(ipos_encrypted);
5344 tor_assert(descriptor_cookie);
5345 if (ipos_encrypted_size < 2) {
5346 log_warn(LD_REND, "Size of encrypted introduction points is too "
5347 "small.");
5348 return -1;
5350 if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
5351 char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
5352 session_key[CIPHER_KEY_LEN], *dec;
5353 int declen, client_blocks;
5354 size_t pos = 0, len, client_entries_len;
5355 crypto_digest_t *digest;
5356 crypto_cipher_t *cipher;
5357 client_blocks = (int) ipos_encrypted[1];
5358 client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
5359 REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
5360 if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
5361 log_warn(LD_REND, "Size of encrypted introduction points is too "
5362 "small.");
5363 return -1;
5365 memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
5366 digest = crypto_digest_new();
5367 crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
5368 crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
5369 crypto_digest_get_digest(digest, client_id,
5370 REND_BASIC_AUTH_CLIENT_ID_LEN);
5371 crypto_digest_free(digest);
5372 for (pos = 2; pos < 2 + client_entries_len;
5373 pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
5374 if (tor_memeq(ipos_encrypted + pos, client_id,
5375 REND_BASIC_AUTH_CLIENT_ID_LEN)) {
5376 /* Attempt to decrypt introduction points. */
5377 cipher = crypto_cipher_new(descriptor_cookie);
5378 if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
5379 + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
5380 CIPHER_KEY_LEN) < 0) {
5381 log_warn(LD_REND, "Could not decrypt session key for client.");
5382 crypto_cipher_free(cipher);
5383 return -1;
5385 crypto_cipher_free(cipher);
5387 len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
5388 dec = tor_malloc_zero(len + 1);
5389 declen = crypto_cipher_decrypt_with_iv(session_key, dec, len,
5390 ipos_encrypted + 2 + client_entries_len,
5391 ipos_encrypted_size - 2 - client_entries_len);
5393 if (declen < 0) {
5394 log_warn(LD_REND, "Could not decrypt introduction point string.");
5395 tor_free(dec);
5396 return -1;
5398 if (fast_memcmpstart(dec, declen, "introduction-point ")) {
5399 log_warn(LD_REND, "Decrypted introduction points don't "
5400 "look like we could parse them.");
5401 tor_free(dec);
5402 continue;
5404 *ipos_decrypted = dec;
5405 *ipos_decrypted_size = declen;
5406 return 0;
5409 log_warn(LD_REND, "Could not decrypt introduction points. Please "
5410 "check your authorization for this service!");
5411 return -1;
5412 } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
5413 char *dec;
5414 int declen;
5415 if (ipos_encrypted_size < CIPHER_IV_LEN + 2) {
5416 log_warn(LD_REND, "Size of encrypted introduction points is too "
5417 "small.");
5418 return -1;
5420 dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1 + 1);
5422 declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec,
5423 ipos_encrypted_size -
5424 CIPHER_IV_LEN - 1,
5425 ipos_encrypted + 1,
5426 ipos_encrypted_size - 1);
5428 if (declen < 0) {
5429 log_warn(LD_REND, "Decrypting introduction points failed!");
5430 tor_free(dec);
5431 return -1;
5433 *ipos_decrypted = dec;
5434 *ipos_decrypted_size = declen;
5435 return 0;
5436 } else {
5437 log_warn(LD_REND, "Unknown authorization type number: %d",
5438 ipos_encrypted[0]);
5439 return -1;
5443 /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
5444 * length <b>intro_points_encoded_size</b> and write the result to the
5445 * descriptor in <b>parsed</b>; return the number of successfully parsed
5446 * introduction points or -1 in case of a failure. */
5448 rend_parse_introduction_points(rend_service_descriptor_t *parsed,
5449 const char *intro_points_encoded,
5450 size_t intro_points_encoded_size)
5452 const char *current_ipo, *end_of_intro_points;
5453 smartlist_t *tokens = NULL;
5454 directory_token_t *tok;
5455 rend_intro_point_t *intro;
5456 extend_info_t *info;
5457 int result, num_ok=1;
5458 memarea_t *area = NULL;
5459 tor_assert(parsed);
5460 /** Function may only be invoked once. */
5461 tor_assert(!parsed->intro_nodes);
5462 if (!intro_points_encoded || intro_points_encoded_size == 0) {
5463 log_warn(LD_REND, "Empty or zero size introduction point list");
5464 goto err;
5466 /* Consider one intro point after the other. */
5467 current_ipo = intro_points_encoded;
5468 end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
5469 tokens = smartlist_new();
5470 parsed->intro_nodes = smartlist_new();
5471 area = memarea_new();
5473 while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
5474 "introduction-point ")) {
5475 /* Determine end of string. */
5476 const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
5477 "\nintroduction-point ");
5478 if (!eos)
5479 eos = end_of_intro_points;
5480 else
5481 eos = eos+1;
5482 tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
5483 /* Free tokens and clear token list. */
5484 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
5485 smartlist_clear(tokens);
5486 memarea_clear(area);
5487 /* Tokenize string. */
5488 if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
5489 log_warn(LD_REND, "Error tokenizing introduction point");
5490 goto err;
5492 /* Advance to next introduction point, if available. */
5493 current_ipo = eos;
5494 /* Check minimum allowed length of introduction point. */
5495 if (smartlist_len(tokens) < 5) {
5496 log_warn(LD_REND, "Impossibly short introduction point.");
5497 goto err;
5499 /* Allocate new intro point and extend info. */
5500 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
5501 info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
5502 /* Parse identifier. */
5503 tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
5504 if (base32_decode(info->identity_digest, DIGEST_LEN,
5505 tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
5506 log_warn(LD_REND, "Identity digest contains illegal characters: %s",
5507 tok->args[0]);
5508 rend_intro_point_free(intro);
5509 goto err;
5511 /* Write identifier to nickname. */
5512 info->nickname[0] = '$';
5513 base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
5514 info->identity_digest, DIGEST_LEN);
5515 /* Parse IP address. */
5516 tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
5517 if (tor_addr_parse(&info->addr, tok->args[0])<0) {
5518 log_warn(LD_REND, "Could not parse introduction point address.");
5519 rend_intro_point_free(intro);
5520 goto err;
5522 if (tor_addr_family(&info->addr) != AF_INET) {
5523 log_warn(LD_REND, "Introduction point address was not ipv4.");
5524 rend_intro_point_free(intro);
5525 goto err;
5528 /* Parse onion port. */
5529 tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
5530 info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
5531 &num_ok,NULL);
5532 if (!info->port || !num_ok) {
5533 log_warn(LD_REND, "Introduction point onion port %s is invalid",
5534 escaped(tok->args[0]));
5535 rend_intro_point_free(intro);
5536 goto err;
5538 /* Parse onion key. */
5539 tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
5540 if (!crypto_pk_public_exponent_ok(tok->key)) {
5541 log_warn(LD_REND,
5542 "Introduction point's onion key had invalid exponent.");
5543 rend_intro_point_free(intro);
5544 goto err;
5546 info->onion_key = tok->key;
5547 tok->key = NULL; /* Prevent free */
5548 /* Parse service key. */
5549 tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
5550 if (!crypto_pk_public_exponent_ok(tok->key)) {
5551 log_warn(LD_REND,
5552 "Introduction point key had invalid exponent.");
5553 rend_intro_point_free(intro);
5554 goto err;
5556 intro->intro_key = tok->key;
5557 tok->key = NULL; /* Prevent free */
5558 /* Add extend info to list of introduction points. */
5559 smartlist_add(parsed->intro_nodes, intro);
5561 result = smartlist_len(parsed->intro_nodes);
5562 goto done;
5564 err:
5565 result = -1;
5567 done:
5568 /* Free tokens and clear token list. */
5569 if (tokens) {
5570 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
5571 smartlist_free(tokens);
5573 if (area)
5574 memarea_drop_all(area);
5576 return result;
5579 /** Parse the content of a client_key file in <b>ckstr</b> and add
5580 * rend_authorized_client_t's for each parsed client to
5581 * <b>parsed_clients</b>. Return the number of parsed clients as result
5582 * or -1 for failure. */
5584 rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
5586 int result = -1;
5587 smartlist_t *tokens;
5588 directory_token_t *tok;
5589 const char *current_entry = NULL;
5590 memarea_t *area = NULL;
5591 char *err_msg = NULL;
5592 if (!ckstr || strlen(ckstr) == 0)
5593 return -1;
5594 tokens = smartlist_new();
5595 /* Begin parsing with first entry, skipping comments or whitespace at the
5596 * beginning. */
5597 area = memarea_new();
5598 current_entry = eat_whitespace(ckstr);
5599 while (!strcmpstart(current_entry, "client-name ")) {
5600 rend_authorized_client_t *parsed_entry;
5601 /* Determine end of string. */
5602 const char *eos = strstr(current_entry, "\nclient-name ");
5603 if (!eos)
5604 eos = current_entry + strlen(current_entry);
5605 else
5606 eos = eos + 1;
5607 /* Free tokens and clear token list. */
5608 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
5609 smartlist_clear(tokens);
5610 memarea_clear(area);
5611 /* Tokenize string. */
5612 if (tokenize_string(area, current_entry, eos, tokens,
5613 client_keys_token_table, 0)) {
5614 log_warn(LD_REND, "Error tokenizing client keys file.");
5615 goto err;
5617 /* Advance to next entry, if available. */
5618 current_entry = eos;
5619 /* Check minimum allowed length of token list. */
5620 if (smartlist_len(tokens) < 2) {
5621 log_warn(LD_REND, "Impossibly short client key entry.");
5622 goto err;
5624 /* Parse client name. */
5625 tok = find_by_keyword(tokens, C_CLIENT_NAME);
5626 tor_assert(tok == smartlist_get(tokens, 0));
5627 tor_assert(tok->n_args == 1);
5629 if (!rend_valid_client_name(tok->args[0])) {
5630 log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
5631 "between 1 and %d, and valid characters are "
5632 "[A-Za-z0-9+-_].)", tok->args[0], REND_CLIENTNAME_MAX_LEN);
5633 goto err;
5635 /* Check if client name is duplicate. */
5636 if (strmap_get(parsed_clients, tok->args[0])) {
5637 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
5638 "duplicate client name: '%s'. Ignoring.", tok->args[0]);
5639 goto err;
5641 parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
5642 parsed_entry->client_name = tor_strdup(tok->args[0]);
5643 strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
5644 /* Parse client key. */
5645 tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
5646 if (tok) {
5647 parsed_entry->client_key = tok->key;
5648 tok->key = NULL; /* Prevent free */
5651 /* Parse descriptor cookie. */
5652 tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
5653 tor_assert(tok->n_args == 1);
5654 if (rend_auth_decode_cookie(tok->args[0], parsed_entry->descriptor_cookie,
5655 NULL, &err_msg) < 0) {
5656 tor_assert(err_msg);
5657 log_warn(LD_REND, "%s", err_msg);
5658 tor_free(err_msg);
5659 goto err;
5662 result = strmap_size(parsed_clients);
5663 goto done;
5664 err:
5665 result = -1;
5666 done:
5667 /* Free tokens and clear token list. */
5668 SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
5669 smartlist_free(tokens);
5670 if (area)
5671 memarea_drop_all(area);
5672 return result;
5675 /** Called on startup; right now we just handle scanning the unparseable
5676 * descriptor dumps, but hang anything else we might need to do in the
5677 * future here as well.
5679 void
5680 routerparse_init(void)
5683 * Check both if the sandbox is active and whether it's configured; no
5684 * point in loading all that if we won't be able to use it after the
5685 * sandbox becomes active.
5687 if (!(sandbox_is_active() || get_options()->Sandbox)) {
5688 dump_desc_init();
5692 /** Clean up all data structures used by routerparse.c at exit */
5693 void
5694 routerparse_free_all(void)
5696 dump_desc_fifo_cleanup();