args[i])); goto err; } } } else if (tok) { int i; for (i=0; i < tok->n_args; ++i) { if (!strcmp(tok->args[i], "Exit")) rs->is_exit = 1; else if (!strcmp(tok->args[i], "Stable")) rs->is_stable = 1; else if (!strcmp(tok->args[i], "Fast")) rs->is_fast = 1; else if (!strcmp(tok->args[i], "Running")) rs->is_running = 1; else if (!strcmp(tok->args[i], "Named")) rs->is_named = 1; else if (!strcmp(tok->args[i], "Valid")) rs->is_valid = 1; else if (!strcmp(tok->args[i], "V2Dir")) rs->is_v2_dir = 1; else if (!strcmp(tok->args[i], "Guard")) rs->is_possible_guard = 1; else if (!strcmp(tok->args[i], "BadExit")) rs->is_bad_exit = 1; else if (!strcmp(tok->args[i], "BadDirectory")) rs->is_bad_directory = 1; else if (!strcmp(tok->args[i], "Authority")) rs->is_authority = 1; else if (!strcmp(tok->args[i], "Unnamed") && consensus_method >= 2) { /* Unnamed is computed right by consensus method 2 and later. */ rs->is_unnamed = 1; } else if (!strcmp(tok->args[i], "HSDir")) { rs->is_hs_dir = 1; } } } if ((tok = find_first_by_keyword(tokens, K_V))) { tor_assert(tok->n_args == 1); rs->version_known = 1; if (strcmpstart(tok->args[0], "Tor ")) { rs->version_supports_begindir = 1; rs->version_supports_extrainfo_upload = 1; } else { rs->version_supports_begindir = tor_version_as_new_as(tok->args[0], "0.1.2.2-alpha"); rs->version_supports_extrainfo_upload = tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)"); rs->version_supports_v3_dir = tor_version_as_new_as(tok->args[0], "0.2.0.8-alpha"); } if (vote_rs) { vote_rs->version = tok->args[0]; tok->args[0] = NULL; /* suppress free() */ } } if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME)) rs->is_named = 0; goto done; err: if (rs && !vote_rs) routerstatus_free(rs); rs = NULL; done: SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t)); smartlist_clear(tokens); *s = eos; return rs; } /** Helper to sort a smartlist of pointers to routerstatus_t */ static int _compare_routerstatus_entries(const void **_a, const void **_b) { const routerstatus_t *a = *_a, *b = *_b; return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN); } /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */ static void _free_duplicate_routerstatus_entry(void *e) { log_warn(LD_DIR, "Network-status has two entries for the same router. " "Dropping one."); routerstatus_free(e); } /** Given a v2 network-status object in s, try to * parse it and return the result. Return NULL on failure. Check the * signature of the network status, but do not (yet) check the signing key for * authority. */ networkstatus_v2_t * networkstatus_v2_parse_from_string(const char *s) { const char *eos; smartlist_t *tokens = smartlist_create(); smartlist_t *footer_tokens = smartlist_create(); networkstatus_v2_t *ns = NULL; char ns_digest[DIGEST_LEN]; char tmp_digest[DIGEST_LEN]; struct in_addr in; directory_token_t *tok; int i; if (router_get_networkstatus_v2_hash(s, ns_digest)) { log_warn(LD_DIR, "Unable to compute digest of network-status"); goto err; } eos = find_start_of_next_routerstatus(s); if (tokenize_string(s, eos, tokens, netstatus_token_table,0)) { log_warn(LD_DIR, "Error tokenizing network-status header."); goto err; } ns = tor_malloc_zero(sizeof(networkstatus_v2_t)); memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN); tok = find_first_by_keyword(tokens, K_NETWORK_STATUS_VERSION); tor_assert(tok && tok->n_args >= 1); if (strcmp(tok->args[0], "2")) { log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was " "%s", escaped(tok->args[0])); goto err; } tok = find_first_by_keyword(tokens, K_DIR_SOURCE); tor_assert(tok); tor_assert(tok->n_args >= 3); ns->source_address = tok->args[0]; tok->args[0] = NULL; if (tor_inet_aton(tok->args[1], &in) == 0) { log_warn(LD_DIR, "Error parsing network-status source address %s", escaped(tok->args[1])); goto err; } ns->source_addr = ntohl(in.s_addr); ns->source_dirport = (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL); if (ns->source_dirport == 0) { log_warn(LD_DIR, "Directory source without dirport; skipping."); goto err; } tok = find_first_by_keyword(tokens, K_FINGERPRINT); tor_assert(tok); tor_assert(tok->n_args); if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) { log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s", escaped(tok->args[0])); goto err; } if ((tok = find_first_by_keyword(tokens, K_CONTACT))) { tor_assert(tok->n_args); ns->contact = tok->args[0]; tok->args[0] = NULL; } tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY); tor_assert(tok && tok->key); ns->signing_key = tok->key; tok->key = NULL; if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) { log_warn(LD_DIR, "Couldn't compute signing key digest"); goto err; } if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) { log_warn(LD_DIR, "network-status fingerprint did not match dir-signing-key"); goto err; } if ((tok = find_first_by_keyword(tokens, K_DIR_OPTIONS))) { for (i=0; i < tok->n_args; ++i) { if (!strcmp(tok->args[i], "Names")) ns->binds_names = 1; if (!strcmp(tok->args[i], "Versions")) ns->recommends_versions = 1; if (!strcmp(tok->args[i], "BadExits")) ns->lists_bad_exits = 1; if (!strcmp(tok->args[i], "BadDirectories")) ns->lists_bad_directories = 1; } } if (ns->recommends_versions) { if (!(tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) { log_warn(LD_DIR, "Missing client-versions"); } ns->client_versions = tok->args[0]; tok->args[0] = NULL; if (!(tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS)) || tok->n_args<1) { log_warn(LD_DIR, "Missing server-versions on versioning directory"); goto err; } ns->server_versions = tok->args[0]; tok->args[0] = NULL; } tok = find_first_by_keyword(tokens, K_PUBLISHED); tor_assert(tok); tor_assert(tok->n_args == 1); if (parse_iso_time(tok->args[0], &ns->published_on) < 0) { goto err; } ns->entries = smartlist_create(); s = eos; SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t)); smartlist_clear(tokens); while (!strcmpstart(s, "r ")) { routerstatus_t *rs; if ((rs = routerstatus_parse_entry_from_string(&s, tokens, NULL, NULL, 0))) smartlist_add(ns->entries, rs); } smartlist_sort(ns->entries, _compare_routerstatus_entries); smartlist_uniq(ns->entries, _compare_routerstatus_entries, _free_duplicate_routerstatus_entry); if (tokenize_string(s, NULL, footer_tokens, dir_footer_token_table,0)) { log_warn(LD_DIR, "Error tokenizing network-status footer."); goto err; } if (smartlist_len(footer_tokens) < 1) { log_warn(LD_DIR, "Too few items in network-status footer."); goto err; } tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1); if (tok->tp != K_DIRECTORY_SIGNATURE) { log_warn(LD_DIR, "Expected network-status footer to end with a signature."); goto err; } note_crypto_pk_op(VERIFY_DIR); if (check_signature_token(ns_digest, tok, ns->signing_key, 0, "network-status") < 0) goto err; goto done; err: if (ns) networkstatus_v2_free(ns); ns = NULL; done: SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t)); smartlist_free(tokens); SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t)); smartlist_free(footer_tokens); return ns; } /** Parse a v3 networkstatus vote (if is_vote is true) or a v3 * networkstatus consensus (if is_vote is false) from s, and * return the result. Return NULL on failure. */ networkstatus_vote_t * networkstatus_parse_vote_from_string(const char *s, const char **eos_out, int is_vote) { smartlist_t *tokens = smartlist_create(); smartlist_t *rs_tokens = NULL, *footer_tokens = NULL; networkstatus_voter_info_t *voter = NULL; networkstatus_vote_t *ns = NULL; char ns_digest[DIGEST_LEN]; const char *cert, *end_of_header, *end_of_footer; directory_token_t *tok; int ok; struct in_addr in; int i, inorder, n_signatures = 0; if (router_get_networkstatus_v3_hash(s, ns_digest)) { log_warn(LD_DIR, "Unable to compute digest of network-status"); goto err; } end_of_header = find_start_of_next_routerstatus(s); if (tokenize_string(s, end_of_header, tokens, is_vote ? networkstatus_vote_token_table : networkstatus_consensus_token_table, 0)) { log_warn(LD_DIR, "Error tokenizing network-status vote header."); goto err; } ns = tor_malloc_zero(sizeof(networkstatus_vote_t)); memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN); if (is_vote) { const char *end_of_cert = NULL; if (!(cert = strstr(s, "\ndir-key-certificate-version"))) goto err; ++cert; ns->cert = authority_cert_parse_from_string(cert, &end_of_cert); if (!ns->cert || !end_of_cert || end_of_cert > end_of_header) goto err; } tok = find_first_by_keyword(tokens, K_VOTE_STATUS); tor_assert(tok); tor_assert(tok->n_args); if (!strcmp(tok->args[0], "vote")) { ns->is_vote = 1; } else if (!strcmp(tok->args[0], "consensus")) { ns->is_vote = 0; } else { log_warn(LD_DIR, "Unrecognized vote status %s in network-status", escaped(tok->args[0])); goto err; } if (!bool_eq(ns->is_vote, is_vote)) { log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus."); goto err; } if (ns->is_vote) { tok = find_first_by_keyword(tokens, K_PUBLISHED); if (parse_iso_time(tok->args[0], &ns->published)) goto err; ns->supported_methods = smartlist_create(); tok = find_first_by_keyword(tokens, K_CONSENSUS_METHODS); if (tok) { for (i=0; i < tok->n_args; ++i) smartlist_add(ns->supported_methods, tok->args[i]); tok->n_args = 0; /* Prevent double free. */ } else { smartlist_add(ns->supported_methods, tor_strdup("1")); } } else { tok = find_first_by_keyword(tokens, K_CONSENSUS_METHOD); if (tok) { ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX, &ok, NULL); if (!ok) goto err; } else { ns->consensus_method = 1; } } tok = find_first_by_keyword(tokens, K_VALID_AFTER); if (parse_iso_time(tok->args[0], &ns->valid_after)) goto err; tok = find_first_by_keyword(tokens, K_FRESH_UNTIL); if (parse_iso_time(tok->args[0], &ns->fresh_until)) goto err; tok = find_first_by_keyword(tokens, K_VALID_UNTIL); if (parse_iso_time(tok->args[0], &ns->valid_until)) goto err; tok = find_first_by_keyword(tokens, K_VOTING_DELAY); tor_assert(tok->n_args >= 2); ns->vote_seconds = (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL); if (!ok) goto err; ns->dist_seconds = (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL); if (!ok) goto err; if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) { log_warn(LD_DIR, "Vote/consensus freshness interval is too short"); goto err; } if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) { log_warn(LD_DIR, "Vote/consensus liveness interval is too short"); goto err; } if (ns->vote_seconds < MIN_VOTE_SECONDS) { log_warn(LD_DIR, "Vote seconds is too short"); goto err; } if (ns->dist_seconds < MIN_DIST_SECONDS) { log_warn(LD_DIR, "Dist seconds is too short"); goto err; } if ((tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) { ns->client_versions = tok->args[0]; tok->args[0] = NULL; } if ((tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS))) { ns->server_versions = tok->args[0]; tok->args[0] = NULL; } tok = find_first_by_keyword(tokens, K_KNOWN_FLAGS); ns->known_flags = smartlist_create(); inorder = 1; for (i = 0; i < tok->n_args; ++i) { smartlist_add(ns->known_flags, tok->args[i]); if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) { log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]); inorder = 0; } } tok->n_args = 0; /* suppress free of args members, but not of args itself. */ if (!inorder) { log_warn(LD_DIR, "known-flags not in order"); goto err; } ns->voters = smartlist_create(); SMARTLIST_FOREACH(tokens, directory_token_t *, _tok, { tok = _tok; if (tok->tp == K_DIR_SOURCE) { tor_assert(tok->n_args >= 6); if (voter) smartlist_add(ns->voters, voter); voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t)); if (is_vote) memcpy(voter->vote_digest, ns_digest, DIGEST_LEN); voter->nickname = tor_strdup(tok->args[0]); if (strlen(tok->args[1]) != HEX_DIGEST_LEN || base16_decode(voter->identity_digest, sizeof(voter->identity_digest), tok->args[1], HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding identity digest %s in " "network-status vote.", escaped(tok->args[1])); goto err; } if (is_vote && memcmp(ns->cert->cache_info.identity_digest, voter->identity_digest, DIGEST_LEN)) { log_warn(LD_DIR,"Mismatch between identities in certificate and vote"); goto err; } voter->address = tor_strdup(tok->args[2]); if (!tor_inet_aton(tok->args[3], &in)) { log_warn(LD_DIR, "Error decoding IP address %s in network-status.", escaped(tok->args[3])); goto err; } voter->addr = ntohl(in.s_addr); voter->dir_port = (uint64_t) (int) tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL); if (!ok) goto err; voter->or_port = (uint64_t) (int) tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL); if (!ok) goto err; } else if (tok->tp == K_CONTACT) { if (!voter || voter->contact) { log_warn(LD_DIR, "contact element is out of place."); goto err; } voter->contact = tor_strdup(tok->args[0]); } else if (tok->tp == K_VOTE_DIGEST) { tor_assert(!is_vote); tor_assert(tok->n_args >= 1); if (!voter || ! tor_digest_is_zero(voter->vote_digest)) { log_warn(LD_DIR, "vote-digest element is out of place."); goto err; } if (strlen(tok->args[0]) != HEX_DIGEST_LEN || base16_decode(voter->vote_digest, sizeof(voter->vote_digest), tok->args[0], HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding vote digest %s in " "network-status consensus.", escaped(tok->args[1])); goto err; } } }); if (voter) { smartlist_add(ns->voters, voter); voter = NULL; } if (smartlist_len(ns->voters) == 0) { log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus."); goto err; } else if (is_vote && smartlist_len(ns->voters) != 1) { log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus."); goto err; } /* Parse routerstatus lines. */ rs_tokens = smartlist_create(); s = end_of_header; ns->routerstatus_list = smartlist_create(); while (!strcmpstart(s, "r ")) { if (is_vote) { vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t)); if (routerstatus_parse_entry_from_string(&s, tokens, ns, rs, 0)) smartlist_add(ns->routerstatus_list, rs); else { tor_free(rs->version); tor_free(rs); } } else { routerstatus_t *rs; if ((rs = routerstatus_parse_entry_from_string(&s, tokens, NULL, NULL, ns->consensus_method))) smartlist_add(ns->routerstatus_list, rs); } } for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) { routerstatus_t *rs1, *rs2; if (is_vote) { vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1); vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i); rs1 = &a->status; rs2 = &b->status; } else { rs1 = smartlist_get(ns->routerstatus_list, i-1); rs2 = smartlist_get(ns->routerstatus_list, i); } if (memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN) >= 0) { log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity " "digest"); goto err; } } /* Parse footer; check signature. */ footer_tokens = smartlist_create(); if ((end_of_footer = strstr(s, "\nnetwork-status-version "))) ++end_of_footer; else end_of_footer = s + strlen(s); if (tokenize_string(s, end_of_footer, footer_tokens, networkstatus_vote_footer_token_table, 0)) { log_warn(LD_DIR, "Error tokenizing network-status vote footer."); goto err; } SMARTLIST_FOREACH(footer_tokens, directory_token_t *, _tok, { char declared_identity[DIGEST_LEN]; networkstatus_voter_info_t *v; tok = _tok; if (tok->tp != K_DIRECTORY_SIGNATURE) continue; tor_assert(tok->n_args >= 2); if (!tok->object_type || strcmp(tok->object_type, "SIGNATURE") || tok->object_size < 128 || tok->object_size > 512) { log_warn(LD_DIR, "Bad object type or length on directory-signature"); goto err; } if (strlen(tok->args[0]) != HEX_DIGEST_LEN || base16_decode(declared_identity, sizeof(declared_identity), tok->args[0], HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding declared identity %s in " "network-status vote.", escaped(tok->args[0])); goto err; } if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) { log_warn(LD_DIR, "ID on signature on network-status vote does not match" "any declared directory source."); goto err; } if (strlen(tok->args[1]) != HEX_DIGEST_LEN || base16_decode(v->signing_key_digest, sizeof(v->signing_key_digest), tok->args[1], HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding declared digest %s in " "network-status vote.", escaped(tok->args[1])); goto err; } if (is_vote) { if (memcmp(declared_identity, ns->cert->cache_info.identity_digest, DIGEST_LEN)) { log_warn(LD_DIR, "Digest mismatch between declared and actual on " "network-status vote."); goto err; } } if (is_vote) { if (check_signature_token(ns_digest, tok, ns->cert->signing_key, 0, "network-status vote")) goto err; v->good_signature = 1; } else { v->signature = tor_memdup(tok->object_body, tok->object_size); v->signature_len = tok->object_size; } ++n_signatures; }); if (! n_signatures) { log_warn(LD_DIR, "No signatures on networkstatus vote."); goto err; } if (eos_out) *eos_out = end_of_footer; goto done; err: if (ns) networkstatus_vote_free(ns); ns = NULL; done: if (tokens) { SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t)); smartlist_free(tokens); } if (voter) { tor_free(voter->nickname); tor_free(voter->address); tor_free(voter->contact); tor_free(voter->signature); tor_free(voter); } if (rs_tokens) { SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_free(t)); smartlist_free(rs_tokens); } if (footer_tokens) { SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t)); smartlist_free(footer_tokens); } return ns; } /** Parse a detached v3 networkstatus signature document between s and * eos and return the result. Return -1 on failure. */ ns_detached_signatures_t * networkstatus_parse_detached_signatures(const char *s, const char *eos) { /* XXXX020 there is too much duplicate code here. */ directory_token_t *tok; smartlist_t *tokens = smartlist_create(); ns_detached_signatures_t *sigs = tor_malloc_zero(sizeof(ns_detached_signatures_t)); if (!eos) eos = s + strlen(s); if (tokenize_string(s, eos, tokens, networkstatus_detached_signature_token_table, 0)) { log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures"); goto err; } tok = find_first_by_keyword(tokens, K_CONSENSUS_DIGEST); if (strlen(tok->args[0]) != HEX_DIGEST_LEN) { log_warn(LD_DIR, "Wrong length on consensus-digest in detached " "networkstatus signatures"); goto err; } if (base16_decode(sigs->networkstatus_digest, DIGEST_LEN, tok->args[0], strlen(tok->args[0])) < 0) { log_warn(LD_DIR, "Bad encoding on on consensus-digest in detached " "networkstatus signatures"); goto err; } tok = find_first_by_keyword(tokens, K_VALID_AFTER); if (parse_iso_time(tok->args[0], &sigs->valid_after)) { log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures"); goto err; } tok = find_first_by_keyword(tokens, K_FRESH_UNTIL); if (parse_iso_time(tok->args[0], &sigs->fresh_until)) { log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures"); goto err; } tok = find_first_by_keyword(tokens, K_VALID_UNTIL); if (parse_iso_time(tok->args[0], &sigs->valid_until)) { log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures"); goto err; } sigs->signatures = smartlist_create(); SMARTLIST_FOREACH(tokens, directory_token_t *, _tok, { char id_digest[DIGEST_LEN]; char sk_digest[DIGEST_LEN]; networkstatus_voter_info_t *voter; tok = _tok; if (tok->tp != K_DIRECTORY_SIGNATURE) continue; tor_assert(tok->n_args >= 2); if (!tok->object_type || strcmp(tok->object_type, "SIGNATURE") || tok->object_size < 128 || tok->object_size > 512) { log_warn(LD_DIR, "Bad object type or length on directory-signature"); goto err; } if (strlen(tok->args[0]) != HEX_DIGEST_LEN || base16_decode(id_digest, sizeof(id_digest), tok->args[0], HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding declared identity %s in " "network-status vote.", escaped(tok->args[0])); goto err; } if (strlen(tok->args[1]) != HEX_DIGEST_LEN || base16_decode(sk_digest, sizeof(sk_digest), tok->args[1], HEX_DIGEST_LEN) < 0) { log_warn(LD_DIR, "Error decoding declared identity %s in " "network-status vote.", escaped(tok->args[1])); goto err; } voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t)); memcpy(voter->identity_digest, id_digest, DIGEST_LEN); memcpy(voter->signing_key_digest, sk_digest, DIGEST_LEN); voter->signature = tor_memdup(tok->object_body, tok->object_size); voter->signature_len = tok->object_size; smartlist_add(sigs->signatures, voter); }); goto done; err: ns_detached_signatures_free(sigs); sigs = NULL; done: SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t)); return sigs; } /** Parse the addr policy in the string s and return it. If * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or * ADDR_POLICY_REJECT) for items that specify no action. */ addr_policy_t * router_parse_addr_policy_from_string(const char *s, int assume_action) { directory_token_t *tok = NULL; const char *cp, *eos; /* Longest possible policy is "accept ffff:ffff:..255/ffff:...255:0-65535". * But note that there can be an arbitrary amount of space between the * accept and the address:mask/port element. */ char line[TOR_ADDR_BUF_LEN*2 + 32]; addr_policy_t *r; s = eat_whitespace(s); if ((*s == '*' || TOR_ISDIGIT(*s)) && assume_action >= 0) { if (tor_snprintf(line, sizeof(line), "%s %s", assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) { log_warn(LD_DIR, "Policy %s is too long.", escaped(s)); return NULL; } cp = line; tor_strlower(line); } else { /* assume an already well-formed address policy line */ cp = s; } eos = cp + strlen(cp); tok = get_next_token(&cp, eos, routerdesc_token_table); if (tok->tp == _ERR) { log_warn(LD_DIR, "Error reading address policy: %s", tok->error); goto err; } if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) { log_warn(LD_DIR, "Expected 'accept' or 'reject'."); goto err; } /* Now that we've gotten an addr policy, add it to the router. */ r = router_parse_addr_policy(tok); goto done; err: r = NULL; done: token_free(tok); return r; } /** Add an exit policy stored in the token tok to the router info in * router. Return 0 on success, -1 on failure. */ static int router_add_exit_policy(routerinfo_t *router, directory_token_t *tok) { addr_policy_t *newe, **tmpe; newe = router_parse_addr_policy(tok); if (!newe) return -1; for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next)) ; *tmpe = newe; return 0; } /** Given a K_ACCEPT or K_REJECT token and a router, create and return * a new exit_policy_t corresponding to the token. */ static addr_policy_t * router_parse_addr_policy(directory_token_t *tok) { addr_policy_t *newe; char *arg; char buf[POLICY_BUF_LEN]; tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT); if (tok->n_args != 1) return NULL; arg = tok->args[0]; if (!strcmpstart(arg,"private")) return router_parse_addr_policy_private(tok); newe = tor_malloc_zero(sizeof(addr_policy_t)); newe->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT : ADDR_POLICY_ACCEPT; if (parse_addr_and_port_range(arg, &newe->addr, &newe->maskbits, &newe->prt_min, &newe->prt_max)) goto policy_read_failed; if (policy_write_item(buf, sizeof(buf), newe) < 0) goto policy_read_failed; newe->string = tor_strdup(buf); return newe; policy_read_failed: log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg)); tor_free(newe); return NULL; } /** Parse an exit policy line of the format "accept/reject private:...". * This didn't exist until Tor 0.1.1.15, so nobody should generate it in * router descriptors until earlier versions are obsolete. */ static addr_policy_t * router_parse_addr_policy_private(directory_token_t *tok) { static const char *private_nets[] = { "0.0.0.0/8", "169.254.0.0/16", "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",NULL }; char *arg; addr_policy_t *result, **nextp; int net; uint16_t port_min, port_max; arg = tok->args[0]; if (strcmpstart(arg, "private")) return NULL; arg += strlen("private"); arg = (char*) eat_whitespace(arg); if (!arg || *arg != ':') return NULL; if (parse_port_range(arg+1, &port_min, &port_max)<0) return NULL; nextp = &result; for (net = 0; private_nets[net]; ++net) { size_t len; *nextp = tor_malloc_zero(sizeof(addr_policy_t)); (*nextp)->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT : ADDR_POLICY_ACCEPT; len = strlen(arg)+strlen(private_nets[net])+16; (*nextp)->string = tor_malloc(len+1); tor_snprintf((*nextp)->string, len, "%s %s%s", tok->tp == K_REJECT ? "reject" : "accept", private_nets[net], arg); if (parse_addr_and_port_range((*nextp)->string + 7, &(*nextp)->addr, &(*nextp)->maskbits, &(*nextp)->prt_min, &(*nextp)->prt_max)) { log_warn(LD_BUG, "Couldn't parse an address range we generated!"); return NULL; } nextp = &(*nextp)->next; } return result; } /** Log and exit if t is malformed */ void assert_addr_policy_ok(addr_policy_t *t) { addr_policy_t *t2; while (t) { tor_assert(t->policy_type == ADDR_POLICY_REJECT || t->policy_type == ADDR_POLICY_ACCEPT); tor_assert(t->prt_min <= t->prt_max); t2 = router_parse_addr_policy_from_string(t->string, -1); tor_assert(t2); tor_assert(t2->policy_type == t->policy_type); tor_assert(t2->addr == t->addr); tor_assert(t2->maskbits == t->maskbits); tor_assert(t2->prt_min == t->prt_min); tor_assert(t2->prt_max == t->prt_max); tor_assert(!strcmp(t2->string, t->string)); tor_assert(t2->next == NULL); addr_policy_free(t2); t = t->next; } } /* * Low-level tokenizer for router descriptors and directories. */ /** Free all resources allocated for tok */ static void token_free(directory_token_t *tok) { int i; tor_assert(tok); if (tok->args) { for (i = 0; i < tok->n_args; ++i) { tor_free(tok->args[i]); } tor_free(tok->args); } tor_free(tok->object_type); tor_free(tok->object_body); tor_free(tok->error); if (tok->key) crypto_free_pk_env(tok->key); tor_free(tok); } #define RET_ERR(msg) \ STMT_BEGIN \ if (tok) token_free(tok); \ tok = tor_malloc_zero(sizeof(directory_token_t)); \ tok->tp = _ERR; \ tok->error = tor_strdup(msg); \ goto done_tokenizing; \ STMT_END static INLINE directory_token_t * token_check_object(const char *kwd, directory_token_t *tok, obj_syntax o_syn) { char ebuf[128]; switch (o_syn) { case NO_OBJ: if (tok->object_body) { tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd); RET_ERR(ebuf); } if (tok->key) { tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd); RET_ERR(ebuf); } break; case NEED_OBJ: if (!tok->object_body) { tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd); RET_ERR(ebuf); } break; case NEED_KEY_1024: if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) { tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits", kwd, (int)crypto_pk_keysize(tok->key)); RET_ERR(ebuf); } /* fall through */ case NEED_KEY: if (!tok->key) { tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd); } break; case OBJ_OK: break; } done_tokenizing: return tok; } /** Helper function: read the next token from *s, advance *s to the end of the * token, and return the parsed token. Parse *s according to the list * of tokens in table. */ static directory_token_t * get_next_token(const char **s, const char *eos, token_rule_t *table) { const char *next, *eol, *obstart; int i, j, allocated, obname_len; directory_token_t *tok; obj_syntax o_syn = NO_OBJ; char ebuf[128]; const char *kwd = ""; #define RET_ERR(msg) \ STMT_BEGIN \ if (tok) token_free(tok); \ tok = tor_malloc_zero(sizeof(directory_token_t)); \ tok->tp = _ERR; \ tok->error = tor_strdup(msg); \ goto done_tokenizing; \ STMT_END tok = tor_malloc_zero(sizeof(directory_token_t)); tok->tp = _ERR; /* Set *s to first token, eol to end-of-line, next to after first token */ *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */ eol = memchr(*s, '\n', eos-*s); if (!eol) eol = eos; next = find_whitespace_eos(*s, eol); if (!strcmp_len(*s, "opt", next-*s)) { /* Skip past an "opt" at the start of the line. */ *s = eat_whitespace_eos_no_nl(next, eol); next = find_whitespace_eos(*s, eol); } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */ RET_ERR("Unexpected EOF"); } /* Search the table for the appropriate entry. (I tried a binary search * instead, but it wasn't any faster.) */ for (i = 0; table[i].t ; ++i) { if (!strcmp_len(*s, table[i].t, next-*s)) { /* We've found the keyword. */ kwd = table[i].t; tok->tp = table[i].v; o_syn = table[i].os; *s = eat_whitespace_eos_no_nl(next, eol); next = find_whitespace_eos(*s, eol); /* We go ahead whether there are arguments or not, so that tok->args is * always set if we want arguments. */ if (table[i].concat_args) { /* The keyword takes the line as a single argument */ tok->args = tor_malloc(sizeof(char*)); tok->args[0] = tor_strndup(*s,eol-*s); /* Grab everything on line */ tok->n_args = 1; } else { /* This keyword takes multiple arguments. */ j = 0; allocated = 16; tok->args = tor_malloc(sizeof(char*)*allocated); while (*s < eol) { /* While not at eol, store the next token */ if (j == allocated) { allocated *= 2; tok->args = tor_realloc(tok->args,sizeof(char*)*allocated); } tok->args[j++] = tor_strndup(*s, next-*s); *s = eat_whitespace_eos_no_nl(next, eol); /* eat intra-line ws */ next = find_whitespace_eos(*s, eol); /* find end of token at *s */ } tok->n_args = j; } if (tok->n_args < table[i].min_args) { tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd); RET_ERR(ebuf); } else if (tok->n_args > table[i].max_args) { tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd); RET_ERR(ebuf); } break; } } if (tok->tp == _ERR) { /* No keyword matched; call it an "K_opt" or "A_unrecognized" */ if (**s == '@') tok->tp = _A_UNKNOWN; else tok->tp = K_OPT; tok->args = tor_malloc(sizeof(char*)); tok->args[0] = tor_strndup(*s, eol-*s); tok->n_args = 1; o_syn = OBJ_OK; } /* Check whether there's an object present */ *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */ eol = memchr(*s, '\n', eos-*s); if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */ goto check_object; obstart = *s; /* Set obstart to start of object spec */ if (*s+11 >= eol-5 || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */ strcmp_len(eol-5, "-----", 5)) { /* nuls or invalid endings */ RET_ERR("Malformed object: bad begin line"); } tok->object_type = tor_strndup(*s+11, eol-*s-16); obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */ *s = eol+1; /* Set *s to possible start of object data (could be eos) */ /* Go to the end of the object */ next = tor_memstr(*s, eos-*s, "-----END "); if (!next) { RET_ERR("Malformed object: missing object end line"); } eol = memchr(next, '\n', eos-next); if (!eol) /* end-of-line marker, or eos if there's no '\n' */ eol = eos; /* Validate the ending tag, which should be 9 + NAME + 5 + eol */ if (eol-next != 9+obname_len+5 || strcmp_len(next+9, tok->object_type, obname_len) || strcmp_len(eol-5, "-----", 5)) { snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s", tok->object_type); ebuf[sizeof(ebuf)-1] = '\0'; RET_ERR(ebuf); } if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a key... */ tok->key = crypto_new_pk_env(); if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart)) RET_ERR("Couldn't parse public key."); } else { /* If it's something else, try to base64-decode it */ int r; tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */ r = base64_decode(tok->object_body, next-*s, *s, next-*s); if (r<0) RET_ERR("Malformed object: bad base64-encoded data"); tok->object_size = r; } *s = eol; check_object: tok = token_check_object(kwd, tok, o_syn); done_tokenizing: return tok; #undef RET_ERR } /** Read all tokens from a string between start and end, and add * them to out. Parse according to the token rules in table. * Caller must free tokens in out. */ static int tokenize_string(const char *start, const char *end, smartlist_t *out, token_rule_t *table, int flags) { const char **s; directory_token_t *tok = NULL; int counts[_NIL]; int i; int first_nonannotation; int prev_len = smartlist_len(out); s = &start; if (!end) end = start+strlen(start); for (i = 0; i < _NIL; ++i) counts[i] = 0; while (*s < end && (!tok || tok->tp != _EOF)) { tok = get_next_token(s, end, table); if (tok->tp == _ERR) { log_warn(LD_DIR, "parse error: %s", tok->error); token_free(tok); return -1; } ++counts[tok->tp]; smartlist_add(out, tok); *s = eat_whitespace_eos(*s, end); } if (flags & TS_NOCHECK) return 0; if ((flags & TS_ANNOTATIONS_OK)) { first_nonannotation = -1; for (i = 0; i < smartlist_len(out); ++i) { tok = smartlist_get(out, i); if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) { first_nonannotation = i; break; } } if (first_nonannotation < 0) { log_warn(LD_DIR, "parse error: item contains only annotations"); return -1; } for (i=first_nonannotation; i < smartlist_len(out); ++i) { tok = smartlist_get(out, i); if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) { log_warn(LD_DIR, "parse error: Annotations mixed with keywords"); return -1; } } if ((flags & TS_NO_NEW_ANNOTATIONS)) { if (first_nonannotation != prev_len) { log_warn(LD_DIR, "parse error: Unexpectd annotations."); return -1; } } } else { for (i=0; i < smartlist_len(out); ++i) { tok = smartlist_get(out, i); if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) { log_warn(LD_DIR, "parse error: no annotations allowed."); return -1; } } first_nonannotation = 0; } for (i = 0; table[i].t; ++i) { if (counts[table[i].v] < table[i].min_cnt) { log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t); return -1; } if (counts[table[i].v] > table[i].max_cnt) { log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t); return -1; } if (table[i].pos & AT_START) { if (smartlist_len(out) < 1 || (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) { log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t); return -1; } } if (table[i].pos & AT_END) { if (smartlist_len(out) < 1 || (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) { log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t); return -1; } } } return 0; } /** Find the first token in s whose keyword is keyword; return * NULL if no such keyword is found. */ static directory_token_t * find_first_by_keyword(smartlist_t *s, directory_keyword keyword) { SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t); return NULL; } /** Return a newly allocated smartlist of all accept or reject tokens in * s. */ static smartlist_t * find_all_exitpolicy(smartlist_t *s) { smartlist_t *out = smartlist_create(); SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == K_ACCEPT || t->tp == K_REJECT) smartlist_add(out,t)); return out; } /** Compute the SHA-1 digest of the substring of s taken from the first * occurrence of start_str through the first instance of c after the * first subsequent occurrence of end_str; store the 20-byte result in * digest; return 0 on success. * * If no such substring exists, return -1. */ static int router_get_hash_impl(const char *s, char *digest, const char *start_str, const char *end_str, char end_c) { char *start, *end; start = strstr(s, start_str); if (!start) { log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str); return -1; } if (start != s && *(start-1) != '\n') { log_warn(LD_DIR, "first occurrence of \"%s\" is not at the start of a line", start_str); return -1; } end = strstr(start+strlen(start_str), end_str); if (!end) { log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str); return -1; } end = strchr(end+strlen(end_str), end_c); if (!end) { log_warn(LD_DIR,"couldn't find EOL"); return -1; } ++end; if (crypto_digest(digest, start, end-start)) { log_warn(LD_BUG,"couldn't compute digest"); return -1; } return 0; } /** Parse the Tor version of the platform string platform, * and compare it to the version in cutoff. Return 1 if * the router is at least as new as the cutoff, else return 0. */ int tor_version_as_new_as(const char *platform, const char *cutoff) { tor_version_t cutoff_version, router_version; char *s, *s2, *start; char tmp[128]; tor_assert(platform); if (tor_version_parse(cutoff, &cutoff_version)<0) { log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff); return 0; } if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */ return 1; start = (char *)eat_whitespace(platform+3); if (!*start) return 0; s = (char *)find_whitespace(start); /* also finds '\0', which is fine */ s2 = (char*)eat_whitespace(s); if (!strcmpstart(s2, "(r")) s = (char*)find_whitespace(s2); if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */ return 0; strlcpy(tmp, start, s-start+1); if (tor_version_parse(tmp, &router_version)<0) { log_info(LD_DIR,"Router version '%s' unparseable.",tmp); return 1; /* be safe and say yes */ } /* Here's why we don't need to do any special handling for svn revisions: * - If neither has an svn revision, we're fine. * - If the router doesn't have an svn revision, we can't assume that it * is "at least" any svn revision, so we need to return 0. * - If the target version doesn't have an svn revision, any svn revision * (or none at all) is good enough, so return 1. * - If both target and router have an svn revision, we compare them. */ return tor_version_compare(&router_version, &cutoff_version) >= 0; } /** Parse a tor version from s, and store the result in out. * Return 0 on success, -1 on failure. */ int tor_version_parse(const char *s, tor_version_t *out) { char *eos=NULL; const char *cp=NULL; /* Format is: * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ] */ tor_assert(s); tor_assert(out); memset(out, 0, sizeof(tor_version_t)); if (!strcasecmpstart(s, "Tor ")) s += 4; /* Get major. */ out->major = strtol(s,&eos,10); if (!eos || eos==s || *eos != '.') return -1; cp = eos+1; /* Get minor */ out->minor = strtol(cp,&eos,10); if (!eos || eos==cp || *eos != '.') return -1; cp = eos+1; /* Get micro */ out->micro = strtol(cp,&eos,10); if (!eos || eos==cp) return -1; if (!*eos) { out->status = VER_RELEASE; out->patchlevel = 0; return 0; } cp = eos; /* Get status */ if (*cp == '.') { out->status = VER_RELEASE; ++cp; } else if (0==strncmp(cp, "pre", 3)) { out->status = VER_PRE; cp += 3; } else if (0==strncmp(cp, "rc", 2)) { out->status = VER_RC; cp += 2; } else { return -1; } /* Get patchlevel */ out->patchlevel = strtol(cp,&eos,10); if (!eos || eos==cp) return -1; cp = eos; /* Get status tag. */ if (*cp == '-' || *cp == '.') ++cp; eos = (char*) find_whitespace(cp); if (eos-cp >= (int)sizeof(out->status_tag)) strlcpy(out->status_tag, cp, sizeof(out->status_tag)); else { memcpy(out->status_tag, cp, eos-cp); out->status_tag[eos-cp] = 0; } cp = eat_whitespace(eos); if (!strcmpstart(cp, "(r")) { cp += 2; out->svn_revision = strtol(cp,&eos,10); } return 0; } /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a > * b. */ int tor_version_compare(tor_version_t *a, tor_version_t *b) { int i; tor_assert(a); tor_assert(b); if ((i = a->major - b->major)) return i; else if ((i = a->minor - b->minor)) return i; else if ((i = a->micro - b->micro)) return i; else if ((i = a->status - b->status)) return i; else if ((i = a->patchlevel - b->patchlevel)) return i; else if ((i = strcmp(a->status_tag, b->status_tag))) return i; else return a->svn_revision - b->svn_revision; } /** Return true iff versions a and b belong to the same series. */ static int tor_version_same_series(tor_version_t *a, tor_version_t *b) { tor_assert(a); tor_assert(b); return ((a->major == b->major) && (a->minor == b->minor) && (a->micro == b->micro)); } /** Helper: Given pointers to two strings describing tor versions, return -1 * if _a precedes _b, 1 if _b preceeds _a, and 0 if they are equivalent. * Used to sort a list of versions. */ static int _compare_tor_version_str_ptr(const void **_a, const void **_b) { const char *a = *_a, *b = *_b; int ca, cb; tor_version_t va, vb; ca = tor_version_parse(a, &va); cb = tor_version_parse(b, &vb); /* If they both parse, compare them. */ if (!ca && !cb) return tor_version_compare(&va,&vb); /* If one parses, it comes first. */ if (!ca && cb) return -1; if (ca && !cb) return 1; /* If neither parses, compare strings. Also, the directory server admin ** needs to be smacked upside the head. But Tor is tolerant and gentle. */ return strcmp(a,b); } /** Sort a list of string-representations of versions in ascending order. */ void sort_version_list(smartlist_t *versions, int remove_duplicates) { smartlist_sort(versions, _compare_tor_version_str_ptr); if (remove_duplicates) smartlist_uniq(versions, _compare_tor_version_str_ptr, _tor_free); } /** Parse and validate the ASCII-encoded v2 descriptor in desc, * write the parsed descriptor to the newly allocated *parsed_out, the * binary descriptor ID of length DIGEST_LEN to desc_id_out, the * encrypted introduction points to the newly allocated * *intro_points_encrypted_out, their encrypted size to * *intro_points_encrypted_size_out, the size of the encoded descriptor * to *encoded_size_out, and a pointer to the possibly next * descriptor to *next_out; return 0 for success (including validation) * and -1 for failure. */ int rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out, char *desc_id_out, char **intro_points_encrypted_out, size_t *intro_points_encrypted_size_out, size_t *encoded_size_out, const char **next_out, const char *desc) { rend_service_descriptor_t *result = tor_malloc_zero(sizeof(rend_service_descriptor_t)); char desc_hash[DIGEST_LEN]; const char *eos; smartlist_t *tokens = smartlist_create(); directory_token_t *tok; char secret_id_part[DIGEST_LEN]; int i, version; smartlist_t *versions; char public_key_hash[DIGEST_LEN]; char test_desc_id[DIGEST_LEN]; tor_assert(desc); /* Check if desc starts correctly. */ if (strncmp(desc, "rendezvous-service-descriptor ", strlen("rendezvous-service-descriptor "))) { log_info(LD_REND, "Descriptor does not start correctly."); goto err; } /* Compute descriptor hash for later validation. */ if (router_get_hash_impl(desc, desc_hash, "rendezvous-service-descriptor ", "\nsignature", '\n') < 0) { log_warn(LD_REND, "Couldn't compute descriptor hash."); goto err; } /* Determine end of string. */ eos = strstr(desc, "\nrendezvous-service-descriptor "); if (!eos) eos = desc + strlen(desc); else eos = eos + 1; /* Tokenize descriptor. */ if (tokenize_string(desc, eos, tokens, desc_token_table, 0)) { log_warn(LD_REND, "Error tokenizing descriptor."); goto err; } /* Set next to next descriptor, if available. */ *next_out = eos; /* Set length of encoded descriptor. */ *encoded_size_out = eos - desc; /* Check min allowed length of token list. */ if (smartlist_len(tokens) < 8) { log_warn(LD_REND, "Impossibly short descriptor."); goto err; } /* Parse base32-encoded descriptor ID. */ tok = find_first_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR); tor_assert(tok); tor_assert(tok == smartlist_get(tokens, 0)); tor_assert(tok->n_args == 1); if (strlen(tok->args[0]) != REND_DESC_ID_V2_LEN_BASE32 || strspn(tok->args[0], BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) { log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]); goto err; } if (base32_decode(desc_id_out, DIGEST_LEN, tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) { log_warn(LD_REND, "Descriptor ID contains illegal characters: %s", tok->args[0]); goto err; } /* Parse descriptor version. */ tok = find_first_by_keyword(tokens, R_VERSION); tor_assert(tok); tor_assert(tok->n_args == 1); result->version = atoi(tok->args[0]); if (result->version < 2) { /*XXXX020 what if > 2? */ /* Good question: should higher versions * be rejected by directories? -KL */ log_warn(LD_REND, "Wrong descriptor version: %d", result->version); goto err; } /* Parse public key. */ tok = find_first_by_keyword(tokens, R_PERMANENT_KEY); tor_assert(tok); result->pk = tok->key; tok->key = NULL; /* Prevent free */ /* Parse secret ID part. */ tok = find_first_by_keyword(tokens, R_SECRET_ID_PART); tor_assert(tok); tor_assert(tok->n_args == 1); if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 || strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) { log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]); goto err; } if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) { log_warn(LD_REND, "Secret ID part contains illegal characters: %s", tok->args[0]); goto err; } /* Parse publication time -- up-to-date check is done when storing the * descriptor. */ tok = find_first_by_keyword(tokens, R_PUBLICATION_TIME); tor_assert(tok); tor_assert(tok->n_args == 1); if (parse_iso_time(tok->args[0], &result->timestamp) < 0) { log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]); goto err; } /* Parse protocol versions. */ tok = find_first_by_keyword(tokens, R_PROTOCOL_VERSIONS); tor_assert(tok); tor_assert(tok->n_args == 1); versions = smartlist_create(); smartlist_split_string(versions, tok->args[0], ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0); for (i = 0; i < smartlist_len(versions); i++) { /* XXXX020 validate the numbers here. */ version = atoi(smartlist_get(versions, i)); result->protocols |= 1 << version; } SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp)); smartlist_free(versions); /* Parse encrypted introduction points. Don't verify. */ tok = find_first_by_keyword(tokens, R_INTRODUCTION_POINTS); tor_assert(tok); /* XXXX020 make sure it's "BEGIN MESSAGE", not "BEGIN SOMETHINGELSE" */ *intro_points_encrypted_out = tok->object_body; *intro_points_encrypted_size_out = tok->object_size; tok->object_body = NULL; /* Prevent free. */ /* Parse and verify signature. */ tok = find_first_by_keyword(tokens, R_SIGNATURE); tor_assert(tok); note_crypto_pk_op(VERIFY_RTR); if (check_signature_token(desc_hash, tok, result->pk, 0, "v2 rendezvous service descriptor") < 0) goto err; /* Verify that descriptor ID belongs to public key and secret ID part. */ crypto_pk_get_digest(result->pk, public_key_hash); rend_get_descriptor_id_bytes(test_desc_id, public_key_hash, secret_id_part); if (memcmp(desc_id_out, test_desc_id, DIGEST_LEN)) { log_warn(LD_REND, "Parsed descriptor ID does not match " "computed descriptor ID."); goto err; } goto done; err: if (result) rend_service_descriptor_free(result); result = NULL; done: if (tokens) { SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t)); smartlist_free(tokens); } *parsed_out = result; if (result) return 0; return -1; } /** Decrypt and decode the introduction points in * intro_points_encrypted of length * intro_points_encrypted_size using descriptor_cookie * (which may also be NULL if no decryption, but only parsing is * required), parse the introduction points, and write the result to * parsed; return the number of successfully parsed introduction * points or -1 in case of a failure. */ int rend_decrypt_introduction_points(rend_service_descriptor_t *parsed, const char *descriptor_cookie, const char *intro_points_encrypted, size_t intro_points_encrypted_size) { char *ipos_decrypted = NULL; const char **current_ipo; smartlist_t *intropoints; smartlist_t *tokens; int i; directory_token_t *tok; extend_info_t *info; struct in_addr ip; int result; tor_assert(parsed); tor_assert(intro_points_encrypted); tor_assert(intro_points_encrypted_size > 0); /* Decrypt introduction points, if required. */ if (descriptor_cookie) { crypto_cipher_env_t *cipher; int unenclen; ipos_decrypted = tor_malloc_zero(intro_points_encrypted_size - 16); cipher = crypto_create_init_cipher(descriptor_cookie, 0); unenclen = crypto_cipher_decrypt_with_iv(cipher, ipos_decrypted, intro_points_encrypted_size - 16, intro_points_encrypted, intro_points_encrypted_size); crypto_free_cipher_env(cipher); if (unenclen < 0) { tor_free(ipos_decrypted); return -1; } intro_points_encrypted = ipos_decrypted; intro_points_encrypted_size = unenclen; } /* Consider one intro point after the other. */ current_ipo = (const char **)&intro_points_encrypted; intropoints = smartlist_create(); tokens = smartlist_create(); if (parsed->intro_keys) { log_warn(LD_BUG, "Parsing list of introduction points for the same " "hidden service, twice."); } else { parsed->intro_keys = strmap_new(); } while (!strcmpstart(*current_ipo, "introduction-point ")) { /* Determine end of string. */ const char *eos = strstr(*current_ipo, "\nintroduction-point "); if (!eos) eos = *current_ipo+strlen(*current_ipo); else eos = eos+1; /* Free tokens and clear token list. */ SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t)); smartlist_clear(tokens); /* Tokenize string. */ if (tokenize_string(*current_ipo, eos, tokens, ipo_token_table, 0)) { log_warn(LD_REND, "Error tokenizing introduction point."); goto err; } /* Advance to next introduction point, if available. */ *current_ipo = eos; /* Check minimum allowed length of introduction point. */ if (smartlist_len(tokens) < 5) { log_warn(LD_REND, "Impossibly short introduction point."); goto err; } /* Allocate new extend info. */ info = tor_malloc_zero(sizeof(extend_info_t)); /* Parse identifier. */ tok = find_first_by_keyword(tokens, R_IPO_IDENTIFIER); tor_assert(tok); if (base32_decode(info->identity_digest, DIGEST_LEN, tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) { log_warn(LD_REND, "Identity digest contains illegal characters: %s", tok->args[0]); tor_free(info); goto err; } /* Write identifier to nickname. */ info->nickname[0] = '$'; base16_encode(info->nickname + 1, sizeof(info->nickname) - 1, info->identity_digest, DIGEST_LEN); /* Parse IP address. */ tok = find_first_by_keyword(tokens, R_IPO_IP_ADDRESS); if (tor_inet_aton(tok->args[0], &ip) == 0) { log_warn(LD_REND, "Could not parse IP address."); tor_free(info); goto err; } info->addr = ntohl(ip.s_addr); /* Parse onion port. */ tok = find_first_by_keyword(tokens, R_IPO_ONION_PORT); /* XXXX020 validate range. */ info->port = (uint16_t) atoi(tok->args[0]); /* Parse onion key. */ tok = find_first_by_keyword(tokens, R_IPO_ONION_KEY); info->onion_key = tok->key; tok->key = NULL; /* Prevent free */ /* Parse service key. */ tok = find_first_by_keyword(tokens, R_IPO_SERVICE_KEY); strmap_set(parsed->intro_keys, info->nickname, tok->key); tok->key = NULL; /* Prevent free */ /* Add extend info to list of introduction points. */ smartlist_add(intropoints, info); } /* Write extend infos to descriptor. */ /* XXXX020 what if intro_points (&tc) are already set? */ parsed->n_intro_points = smartlist_len(intropoints); parsed->intro_point_extend_info = tor_malloc_zero(sizeof(extend_info_t *) * parsed->n_intro_points); parsed->intro_points = tor_malloc_zero(sizeof(char *) * parsed->n_intro_points); i = 0; SMARTLIST_FOREACH(intropoints, extend_info_t *, ipo, { parsed->intro_points[i] = tor_strdup(ipo->nickname); parsed->intro_point_extend_info[i++] = ipo; }); result = parsed->n_intro_points; goto done; err: result = -1; done: /* Free tokens and clear token list. */ SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t)); smartlist_free(tokens); return result; }