#define RENDSERVICE_PRIVATE
#include "core/or/or.h"
#include "app/config/config.h"
#include "core/mainloop/mainloop.h"
#include "core/or/circuitbuild.h"
#include "core/or/circuitlist.h"
#include "core/or/circuituse.h"
#include "core/or/policies.h"
#include "core/or/relay.h"
#include "core/or/crypt_path.h"
#include "feature/client/circpathbias.h"
#include "feature/control/control_events.h"
#include "feature/dirclient/dirclient.h"
#include "feature/dircommon/directory.h"
#include "feature/hs/hs_common.h"
#include "feature/hs/hs_config.h"
#include "feature/hs_common/replaycache.h"
#include "feature/keymgt/loadkey.h"
#include "feature/nodelist/describe.h"
#include "feature/nodelist/networkstatus.h"
#include "feature/nodelist/nickname.h"
#include "feature/nodelist/node_select.h"
#include "feature/nodelist/nodelist.h"
#include "feature/nodelist/routerset.h"
#include "feature/rend/rendclient.h"
#include "feature/rend/rendcommon.h"
#include "feature/rend/rendparse.h"
#include "feature/rend/rendservice.h"
#include "feature/stats/predict_ports.h"
#include "lib/crypt_ops/crypto_dh.h"
#include "lib/crypt_ops/crypto_rand.h"
#include "lib/crypt_ops/crypto_util.h"
#include "lib/encoding/confline.h"
#include "lib/net/resolve.h"
#include "core/or/cpath_build_state_st.h"
#include "core/or/crypt_path_st.h"
#include "core/or/crypt_path_reference_st.h"
#include "core/or/edge_connection_st.h"
#include "core/or/extend_info_st.h"
#include "feature/hs/hs_opts_st.h"
#include "feature/nodelist/networkstatus_st.h"
#include "core/or/origin_circuit_st.h"
#include "feature/rend/rend_authorized_client_st.h"
#include "feature/rend/rend_encoded_v2_service_descriptor_st.h"
#include "feature/rend/rend_intro_point_st.h"
#include "feature/rend/rend_service_descriptor_st.h"
#include "feature/nodelist/routerstatus_st.h"
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
struct rend_service_t;
static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
const char *pk_digest);
static rend_intro_point_t *find_intro_point(origin_circuit_t *circ);
static rend_intro_point_t *find_expiring_intro_point(
struct rend_service_t *service, origin_circuit_t *circ);
static extend_info_t *find_rp_for_intro(
const rend_intro_cell_t *intro,
char **err_msg_out);
static int intro_point_accepted_intro_count(rend_intro_point_t *intro);
static int intro_point_should_expire_now(rend_intro_point_t *intro,
time_t now);
static int rend_service_derive_key_digests(struct rend_service_t *s);
static int rend_service_load_keys(struct rend_service_t *s);
static int rend_service_load_auth_keys(struct rend_service_t *s,
const char *hfname);
static struct rend_service_t *rend_service_get_by_pk_digest(
const char* digest);
static struct rend_service_t *rend_service_get_by_service_id(const char *id);
static const char *rend_service_escaped_dir(
const struct rend_service_t *s);
static ssize_t rend_service_parse_intro_for_v0_or_v1(
rend_intro_cell_t *intro,
const uint8_t *buf,
size_t plaintext_len,
char **err_msg_out);
static ssize_t rend_service_parse_intro_for_v2(
rend_intro_cell_t *intro,
const uint8_t *buf,
size_t plaintext_len,
char **err_msg_out);
static ssize_t rend_service_parse_intro_for_v3(
rend_intro_cell_t *intro,
const uint8_t *buf,
size_t plaintext_len,
char **err_msg_out);
static int rend_service_check_private_dir(const or_options_t *options,
const rend_service_t *s,
int create);
static const smartlist_t* rend_get_service_list(
const smartlist_t* substitute_service_list);
static smartlist_t* rend_get_service_list_mutable(
smartlist_t* substitute_service_list);
static int rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted);
static const char *private_key_fname = "private_key";
static const char *hostname_fname = "hostname";
static const char *client_keys_fname = "client_keys";
static const char *sos_poison_fname = "onion_service_non_anonymous";
static smartlist_t *rend_service_list = NULL;
static smartlist_t *rend_service_staging_list = NULL;
static void
log_once_deprecation_warning(void)
{
static bool logged_once = false;
if (!logged_once) {
log_warn(LD_REND, "DEPRECATED: Onion service version 2 are deprecated. "
"Please use version 3 which is the default now. "
"Currently, version 2 is planned to be obsolete in "
"the Tor version 0.4.6 stable series.");
logged_once = true;
}
}
#define WARN_ONCE_DEPRECATION() log_once_deprecation_warning()
static const smartlist_t*
rend_get_service_list(const smartlist_t* substitute_service_list)
{
return rend_get_service_list_mutable((smartlist_t*)substitute_service_list);
}
static smartlist_t*
rend_get_service_list_mutable(smartlist_t* substitute_service_list)
{
if (substitute_service_list) {
return substitute_service_list;
}
if (BUG(!rend_service_list)) {
return NULL;
}
return rend_service_list;
}
static unsigned int
rend_service_is_ephemeral(const struct rend_service_t *s)
{
return (s->directory == NULL);
}
static const char *
rend_service_escaped_dir(const struct rend_service_t *s)
{
return rend_service_is_ephemeral(s) ? "[EPHEMERAL]" : escaped(s->directory);
}
int
rend_num_services(void)
{
if (!rend_service_list)
return 0;
return smartlist_len(rend_service_list);
}
void
rend_authorized_client_free_(rend_authorized_client_t *client)
{
if (!client)
return;
if (client->client_key)
crypto_pk_free(client->client_key);
if (client->client_name)
memwipe(client->client_name, 0, strlen(client->client_name));
tor_free(client->client_name);
memwipe(client->descriptor_cookie, 0, sizeof(client->descriptor_cookie));
tor_free(client);
}
static void
rend_authorized_client_free_void(void *authorized_client)
{
rend_authorized_client_free_(authorized_client);
}
STATIC void
rend_service_free_(rend_service_t *service)
{
if (!service)
return;
tor_free(service->directory);
if (service->ports) {
SMARTLIST_FOREACH(service->ports, rend_service_port_config_t*, p,
rend_service_port_config_free(p));
smartlist_free(service->ports);
}
if (service->private_key)
crypto_pk_free(service->private_key);
if (service->intro_nodes) {
SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
rend_intro_point_free(intro););
smartlist_free(service->intro_nodes);
}
if (service->expiring_nodes) {
SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *, intro,
rend_intro_point_free(intro););
smartlist_free(service->expiring_nodes);
}
rend_service_descriptor_free(service->desc);
if (service->clients) {
SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
rend_authorized_client_free(c););
smartlist_free(service->clients);
}
if (service->accepted_intro_dh_parts) {
replaycache_free(service->accepted_intro_dh_parts);
}
tor_free(service);
}
void
rend_service_free_staging_list(void)
{
if (rend_service_staging_list) {
SMARTLIST_FOREACH(rend_service_staging_list, rend_service_t*, ptr,
rend_service_free(ptr));
smartlist_free(rend_service_staging_list);
rend_service_staging_list = NULL;
}
}
void
rend_service_free_all(void)
{
if (rend_service_list) {
SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
rend_service_free(ptr));
smartlist_free(rend_service_list);
rend_service_list = NULL;
}
rend_service_free_staging_list();
}
void
rend_service_init(void)
{
tor_assert(!rend_service_list);
tor_assert(!rend_service_staging_list);
rend_service_list = smartlist_new();
rend_service_staging_list = smartlist_new();
}
static int
rend_validate_service(const smartlist_t *service_list,
const rend_service_t *service)
{
tor_assert(service_list);
tor_assert(service);
if (service->max_streams_per_circuit < 0) {
log_warn(LD_CONFIG, "Hidden service (%s) configured with negative max "
"streams per circuit.",
rend_service_escaped_dir(service));
goto invalid;
}
if (service->max_streams_close_circuit < 0 ||
service->max_streams_close_circuit > 1) {
log_warn(LD_CONFIG, "Hidden service (%s) configured with invalid "
"max streams handling.",
rend_service_escaped_dir(service));
goto invalid;
}
if (service->auth_type != REND_NO_AUTH &&
(!service->clients || smartlist_len(service->clients) == 0)) {
log_warn(LD_CONFIG, "Hidden service (%s) with client authorization but "
"no clients.",
rend_service_escaped_dir(service));
goto invalid;
}
if (!service->ports || !smartlist_len(service->ports)) {
log_warn(LD_CONFIG, "Hidden service (%s) with no ports configured.",
rend_service_escaped_dir(service));
goto invalid;
}
return 0;
invalid:
return -1;
}
static int
rend_add_service(smartlist_t *service_list, rend_service_t *service)
{
int i;
rend_service_port_config_t *p;
tor_assert(service);
smartlist_t *s_list = rend_get_service_list_mutable(service_list);
if (BUG(!s_list)) {
rend_service_free(service);
return -1;
}
service->intro_nodes = smartlist_new();
service->expiring_nodes = smartlist_new();
log_debug(LD_REND,"Configuring service with directory %s",
rend_service_escaped_dir(service));
for (i = 0; i < smartlist_len(service->ports); ++i) {
p = smartlist_get(service->ports, i);
if (!(p->is_unix_addr)) {
log_debug(LD_REND,
"Service maps port %d to %s",
p->virtual_port,
fmt_addrport(&p->real_addr, p->real_port));
} else {
#ifdef HAVE_SYS_UN_H
log_debug(LD_REND,
"Service maps port %d to socket at \"%s\"",
p->virtual_port, p->unix_addr);
#else
log_warn(LD_BUG,
"Service maps port %d to an AF_UNIX socket, but we "
"have no AF_UNIX support on this platform. This is "
"probably a bug.",
p->virtual_port);
rend_service_free(service);
return -1;
#endif
}
}
tor_assert(s_list);
smartlist_add(s_list, service);
if (s_list == rend_service_list) {
hs_service_map_has_changed();
}
return 0;
}
static rend_service_port_config_t *
rend_service_port_config_new(const char *socket_path)
{
if (!socket_path)
return tor_malloc_zero(sizeof(rend_service_port_config_t) + 1);
const size_t pathlen = strlen(socket_path) + 1;
rend_service_port_config_t *conf =
tor_malloc_zero(sizeof(rend_service_port_config_t) + pathlen);
memcpy(conf->unix_addr, socket_path, pathlen);
conf->is_unix_addr = 1;
return conf;
}
rend_service_port_config_t *
rend_service_parse_port_config(const char *string, const char *sep,
char **err_msg_out)
{
smartlist_t *sl;
int virtport;
int realport = 0;
uint16_t p;
tor_addr_t addr;
rend_service_port_config_t *result = NULL;
unsigned int is_unix_addr = 0;
const char *socket_path = NULL;
char *err_msg = NULL;
char *addrport = NULL;
sl = smartlist_new();
smartlist_split_string(sl, string, sep,
SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
if (smartlist_len(sl) < 1 || BUG(smartlist_len(sl) > 2)) {
err_msg = tor_strdup("Bad syntax in hidden service port configuration.");
goto err;
}
virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
if (!virtport) {
tor_asprintf(&err_msg, "Missing or invalid port %s in hidden service "
"port configuration", escaped(smartlist_get(sl,0)));
goto err;
}
if (smartlist_len(sl) == 1) {
realport = virtport;
tor_addr_from_ipv4h(&addr, 0x7F000001u);
} else {
int ret;
const char *addrport_element = smartlist_get(sl,1);
const char *rest = NULL;
int is_unix;
ret = port_cfg_line_extract_addrport(addrport_element, &addrport,
&is_unix, &rest);
if (ret < 0) {
tor_asprintf(&err_msg, "Couldn't process address <%s> from hidden "
"service configuration", addrport_element);
goto err;
}
if (rest && strlen(rest)) {
err_msg = tor_strdup("HiddenServicePort parse error: invalid port "
"mapping");
goto err;
}
if (is_unix) {
socket_path = addrport;
is_unix_addr = 1;
} else if (strchr(addrport, ':') || strchr(addrport, '.')) {
if (tor_addr_port_lookup(addrport, &addr, &p)<0) {
err_msg = tor_strdup("Unparseable address in hidden service port "
"configuration.");
goto err;
}
realport = p?p:virtport;
} else {
realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
if (!realport) {
tor_asprintf(&err_msg, "Unparseable or out-of-range port %s in "
"hidden service port configuration.",
escaped(addrport));
goto err;
}
tor_addr_from_ipv4h(&addr, 0x7F000001u);
}
}
result = rend_service_port_config_new(socket_path);
result->virtual_port = virtport;
result->is_unix_addr = is_unix_addr;
if (!is_unix_addr) {
result->real_port = realport;
tor_addr_copy(&result->real_addr, &addr);
result->unix_addr[0] = '\0';
}
err:
tor_free(addrport);
if (err_msg_out != NULL) {
*err_msg_out = err_msg;
} else {
tor_free(err_msg);
}
SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
smartlist_free(sl);
return result;
}
void
rend_service_port_config_free_(rend_service_port_config_t *p)
{
tor_free(p);
}
static void
copy_service_on_prunning(rend_service_t *dst, rend_service_t *src)
{
tor_assert(dst);
tor_assert(src);
dst->desc_is_dirty = src->desc_is_dirty;
dst->next_upload_time = src->next_upload_time;
dst->accepted_intro_dh_parts = src->accepted_intro_dh_parts;
src->accepted_intro_dh_parts = NULL;
dst->intro_period_started = src->intro_period_started;
dst->n_intro_circuits_launched = src->n_intro_circuits_launched;
dst->n_intro_points_wanted = src->n_intro_points_wanted;
}
STATIC void
rend_service_prune_list_impl_(void)
{
origin_circuit_t *ocirc = NULL;
smartlist_t *surviving_services, *old_service_list, *new_service_list;
tor_assert(rend_service_staging_list);
old_service_list = rend_service_list;
new_service_list = rend_service_staging_list;
rend_service_list = new_service_list;
rend_service_staging_list = NULL;
if (!old_service_list) {
return;
}
surviving_services = smartlist_new();
SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
if (rend_service_is_ephemeral(old)) {
SMARTLIST_DEL_CURRENT(old_service_list, old);
smartlist_add(surviving_services, old);
smartlist_add(new_service_list, old);
}
} SMARTLIST_FOREACH_END(old);
SMARTLIST_FOREACH_BEGIN(new_service_list, rend_service_t *, new) {
SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
if (rend_service_is_ephemeral(new) || rend_service_is_ephemeral(old) ||
strcmp(old->directory, new->directory)) {
continue;
}
smartlist_add_all(new->intro_nodes, old->intro_nodes);
smartlist_clear(old->intro_nodes);
smartlist_add_all(new->expiring_nodes, old->expiring_nodes);
smartlist_clear(old->expiring_nodes);
copy_service_on_prunning(new, old);
smartlist_add(surviving_services, old);
break;
} SMARTLIST_FOREACH_END(old);
} SMARTLIST_FOREACH_END(new);
while ((ocirc = circuit_get_next_intro_circ(ocirc, false))) {
int keep_it = 0;
if (ocirc->rend_data == NULL) {
continue;
}
SMARTLIST_FOREACH_BEGIN(surviving_services, const rend_service_t *, s) {
if (rend_circuit_pk_digest_eq(ocirc, (uint8_t *) s->pk_digest)) {
keep_it = 1;
break;
}
} SMARTLIST_FOREACH_END(s);
if (keep_it) {
continue;
}
log_info(LD_REND, "Closing intro point %s for service %s.",
safe_str_client(extend_info_describe(
ocirc->build_state->chosen_exit)),
safe_str_client(rend_data_get_address(ocirc->rend_data)));
circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
}
smartlist_free(surviving_services);
hs_service_map_has_changed();
}
void
rend_service_prune_list(void)
{
smartlist_t *old_service_list = rend_service_list;
if (!rend_service_staging_list) {
rend_service_staging_list = smartlist_new();
}
rend_service_prune_list_impl_();
if (old_service_list) {
SMARTLIST_FOREACH(old_service_list, rend_service_t *, s,
rend_service_free(s));
smartlist_free(old_service_list);
}
}
static void
service_config_shadow_copy(rend_service_t *service,
hs_service_config_t *config)
{
tor_assert(service);
tor_assert(config);
service->directory = tor_strdup(config->directory_path);
service->dir_group_readable = config->dir_group_readable;
service->allow_unknown_ports = config->allow_unknown_ports;
service->max_streams_per_circuit = (int) config->max_streams_per_rdv_circuit;
if (BUG(config->max_streams_per_rdv_circuit >
HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT)) {
service->max_streams_per_circuit = HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT;
}
service->max_streams_close_circuit = config->max_streams_close_circuit;
service->n_intro_points_wanted = config->num_intro_points;
smartlist_add_all(service->ports, config->ports);
smartlist_free(config->ports);
config->ports = NULL;
}
int
rend_config_service(const hs_opts_t *hs_opts,
const or_options_t *options,
hs_service_config_t *config)
{
rend_service_t *service = NULL;
tor_assert(options);
tor_assert(hs_opts);
tor_assert(config);
WARN_ONCE_DEPRECATION();
if (rend_service_staging_list == NULL) {
rend_service_staging_list = smartlist_new();
}
service = tor_malloc_zero(sizeof(rend_service_t));
service->intro_period_started = time(NULL);
service->ports = smartlist_new();
service_config_shadow_copy(service, config);
if (hs_opts->HiddenServiceNumIntroductionPoints > NUM_INTRO_POINTS_MAX) {
log_warn(LD_CONFIG, "HiddenServiceNumIntroductionPoints must be "
"between 0 and %d, not %d.",
NUM_INTRO_POINTS_MAX,
hs_opts->HiddenServiceNumIntroductionPoints);
goto err;
}
service->n_intro_points_wanted = hs_opts->HiddenServiceNumIntroductionPoints;
log_info(LD_CONFIG, "HiddenServiceNumIntroductionPoints=%d for %s",
service->n_intro_points_wanted, escaped(service->directory));
if (hs_opts->HiddenServiceAuthorizeClient) {
smartlist_t *type_names_split, *clients;
const char *authname;
type_names_split = smartlist_new();
smartlist_split_string(type_names_split,
hs_opts->HiddenServiceAuthorizeClient, " ", 0, 2);
if (smartlist_len(type_names_split) < 1) {
log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
"should have been prevented when parsing the "
"configuration.");
smartlist_free(type_names_split);
goto err;
}
authname = smartlist_get(type_names_split, 0);
if (!strcasecmp(authname, "basic")) {
service->auth_type = REND_BASIC_AUTH;
} else if (!strcasecmp(authname, "stealth")) {
service->auth_type = REND_STEALTH_AUTH;
} else {
log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
"unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
"are recognized.",
(char *) smartlist_get(type_names_split, 0));
SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
smartlist_free(type_names_split);
goto err;
}
service->clients = smartlist_new();
if (smartlist_len(type_names_split) < 2) {
log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
"auth-type '%s', but no client names.",
service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
smartlist_free(type_names_split);
goto err;
}
clients = smartlist_new();
smartlist_split_string(clients, smartlist_get(type_names_split, 1),
",", SPLIT_SKIP_SPACE, 0);
SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
smartlist_free(type_names_split);
{
int num_clients = smartlist_len(clients);
smartlist_sort_strings(clients);
smartlist_uniq_strings(clients);
if (smartlist_len(clients) < num_clients) {
log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
"duplicate client name(s); removing.",
num_clients - smartlist_len(clients));
}
}
SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name) {
rend_authorized_client_t *client;
if (!rend_valid_client_name(client_name)) {
log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
"illegal client name: '%s'. Names must be "
"between 1 and %d characters and contain "
"only [A-Za-z0-9+_-].",
client_name, REND_CLIENTNAME_MAX_LEN);
SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
smartlist_free(clients);
goto err;
}
client = tor_malloc_zero(sizeof(rend_authorized_client_t));
client->client_name = tor_strdup(client_name);
smartlist_add(service->clients, client);
log_debug(LD_REND, "Adding client name '%s'", client_name);
} SMARTLIST_FOREACH_END(client_name);
SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
smartlist_free(clients);
if ((service->auth_type == REND_BASIC_AUTH &&
smartlist_len(service->clients) > 512) ||
(service->auth_type == REND_STEALTH_AUTH &&
smartlist_len(service->clients) > 16)) {
log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
"client authorization entries, but only a "
"maximum of %d entries is allowed for "
"authorization type '%s'.",
smartlist_len(service->clients),
service->auth_type == REND_BASIC_AUTH ? 512 : 16,
service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
goto err;
}
}
if (rend_validate_service(rend_service_staging_list, service) < 0) {
goto err;
}
if (rend_add_service(rend_service_staging_list, service) < 0) {
service = NULL;
goto err;
}
return 0;
err:
rend_service_free(service);
return -1;
}
hs_service_add_ephemeral_status_t
rend_service_add_ephemeral(crypto_pk_t *pk,
smartlist_t *ports,
int max_streams_per_circuit,
int max_streams_close_circuit,
rend_auth_type_t auth_type,
smartlist_t *auth_clients,
char **service_id_out)
{
*service_id_out = NULL;
rend_service_t *s = tor_malloc_zero(sizeof(rend_service_t));
s->directory = NULL;
s->private_key = pk;
s->auth_type = auth_type;
s->clients = auth_clients;
s->ports = ports;
s->intro_period_started = time(NULL);
s->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
s->max_streams_per_circuit = max_streams_per_circuit;
s->max_streams_close_circuit = max_streams_close_circuit;
if (rend_service_derive_key_digests(s) < 0) {
rend_service_free(s);
return RSAE_BADPRIVKEY;
}
if (!s->ports || smartlist_len(s->ports) == 0) {
log_warn(LD_CONFIG, "At least one VIRTPORT/TARGET must be specified.");
rend_service_free(s);
return RSAE_BADVIRTPORT;
}
if (s->auth_type != REND_NO_AUTH &&
(!s->clients || smartlist_len(s->clients) == 0)) {
log_warn(LD_CONFIG, "At least one authorized client must be specified.");
rend_service_free(s);
return RSAE_BADAUTH;
}
if (rend_service_get_by_pk_digest(s->pk_digest)) {
log_warn(LD_CONFIG, "Onion Service private key collides with an "
"existing service.");
rend_service_free(s);
return RSAE_ADDREXISTS;
}
if (rend_service_get_by_service_id(s->service_id)) {
log_warn(LD_CONFIG, "Onion Service id collides with an existing service.");
rend_service_free(s);
return RSAE_ADDREXISTS;
}
if (rend_add_service(NULL, s)) {
return RSAE_INTERNAL;
}
*service_id_out = tor_strdup(s->service_id);
log_debug(LD_CONFIG, "Added ephemeral Onion Service: %s", s->service_id);
return RSAE_OKAY;
}
int
rend_service_del_ephemeral(const char *service_id)
{
rend_service_t *s;
if (!rend_valid_v2_service_id(service_id)) {
log_warn(LD_CONFIG, "Requested malformed Onion Service id for removal.");
return -1;
}
if ((s = rend_service_get_by_service_id(service_id)) == NULL) {
log_warn(LD_CONFIG, "Requested non-existent Onion Service id for "
"removal.");
return -1;
}
if (!rend_service_is_ephemeral(s)) {
log_warn(LD_CONFIG, "Requested non-ephemeral Onion Service for removal.");
return -1;
}
SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
if (!circ->marked_for_close &&
(circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
if (oc->rend_data == NULL ||
!rend_circuit_pk_digest_eq(oc, (uint8_t *) s->pk_digest)) {
continue;
}
log_debug(LD_REND, "Closing intro point %s for service %s.",
safe_str_client(extend_info_describe(
oc->build_state->chosen_exit)),
rend_data_get_address(oc->rend_data));
circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
}
} SMARTLIST_FOREACH_END(circ);
smartlist_remove(rend_service_list, s);
hs_service_map_has_changed();
rend_service_free(s);
log_debug(LD_CONFIG, "Removed ephemeral Onion Service: %s", service_id);
return 0;
}
#define INTRO_CIRC_RETRY_PERIOD_SLOP 10
static void
rend_log_intro_limit(const rend_service_t *service, int min_severity)
{
int exceeded_limit = (service->n_intro_circuits_launched >=
rend_max_intro_circs_per_period(
service->n_intro_points_wanted));
int severity = min_severity;
if (exceeded_limit) {
severity = LOG_WARN;
}
time_t intro_period_elapsed = time(NULL) - service->intro_period_started;
tor_assert_nonfatal(intro_period_elapsed >= 0);
{
char *msg;
static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
if ((msg = rate_limit_log(&rlimit, approx_time()))) {
log_fn(severity, LD_REND,
"Hidden service %s %s %d intro points in the last %d seconds. "
"Intro circuit launches are limited to %d per %d seconds.%s",
service->service_id,
exceeded_limit ? "exceeded launch limit with" : "launched",
service->n_intro_circuits_launched,
(int)intro_period_elapsed,
rend_max_intro_circs_per_period(service->n_intro_points_wanted),
INTRO_CIRC_RETRY_PERIOD, msg);
rend_service_dump_stats(severity);
tor_free(msg);
}
}
}
static void
rend_service_update_descriptor(rend_service_t *service)
{
rend_service_descriptor_t *d;
int i;
rend_service_descriptor_free(service->desc);
service->desc = NULL;
d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
d->pk = crypto_pk_dup_key(service->private_key);
d->timestamp = time(NULL);
d->timestamp -= d->timestamp % 3600;
d->intro_nodes = smartlist_new();
d->protocols = (1 << 2) + (1 << 3);
for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
rend_intro_point_t *intro_desc;
intro_svc->listed_in_last_desc = 0;
if (!intro_svc->circuit_established) {
continue;
}
intro_svc->listed_in_last_desc = 1;
intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
if (intro_svc->intro_key)
intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
smartlist_add(d->intro_nodes, intro_desc);
if (intro_svc->time_published == -1) {
intro_svc->time_published = time(NULL);
}
}
unsigned int have_intro = (unsigned int)smartlist_len(d->intro_nodes);
if (have_intro != service->n_intro_points_wanted) {
int severity;
if (have_intro < service->n_intro_points_wanted ||
have_intro > NUM_INTRO_POINTS_MAX) {
severity = LOG_WARN;
} else {
severity = LOG_NOTICE;
}
log_fn(severity, LD_REND, "Hidden service %s wanted %d intro points, but "
"descriptor was updated with %d instead.",
service->service_id,
service->n_intro_points_wanted, have_intro);
rend_log_intro_limit(service, severity);
}
}
static char *
rend_service_path(const rend_service_t *service, const char *file_name)
{
tor_assert(service->directory);
return hs_path_from_filename(service->directory, file_name);
}
STATIC char *
rend_service_sos_poison_path(const rend_service_t *service)
{
return rend_service_path(service, sos_poison_fname);
}
static int
service_is_single_onion_poisoned(const rend_service_t *service)
{
char *poison_fname = NULL;
file_status_t fstatus;
if (BUG(!service)) {
return 0;
}
if (rend_service_is_ephemeral(service)) {
return 0;
}
poison_fname = rend_service_sos_poison_path(service);
fstatus = file_status(poison_fname);
tor_free(poison_fname);
if (fstatus == FN_FILE || fstatus == FN_EMPTY) {
return 1;
}
return 0;
}
static int
rend_service_private_key_exists(const rend_service_t *service)
{
char *private_key_path = rend_service_path(service, private_key_fname);
const file_status_t private_key_status = file_status(private_key_path);
tor_free(private_key_path);
return private_key_status == FN_FILE;
}
STATIC int
rend_service_verify_single_onion_poison(const rend_service_t* s,
const or_options_t* options)
{
if (BUG(!s)) {
return -1;
}
if (BUG(rend_service_is_ephemeral(s))) {
return -1;
}
if (BUG(!s->directory)) {
return -1;
}
if (!rend_service_private_key_exists(s)) {
return 0;
}
if (service_is_single_onion_poisoned(s) !=
rend_service_non_anonymous_mode_enabled(options)) {
return -1;
}
return 0;
}
static int
poison_new_single_onion_hidden_service_dir_impl(const rend_service_t *service,
const or_options_t* options)
{
if (BUG(!service)) {
return -1;
}
tor_assert(rend_service_non_anonymous_mode_enabled(options));
int fd;
int retval = -1;
char *poison_fname = NULL;
if (rend_service_is_ephemeral(service)) {
log_info(LD_REND, "Ephemeral HS started in non-anonymous mode.");
return 0;
}
if (rend_service_private_key_exists(service)) {
log_warn(LD_BUG, "Tried to single onion poison a service directory after "
"the private key was created.");
return -1;
}
if (BUG(hs_check_service_private_dir(options->User, service->directory,
service->dir_group_readable, 0) < 0))
return -1;
poison_fname = rend_service_sos_poison_path(service);
switch (file_status(poison_fname)) {
case FN_DIR:
case FN_ERROR:
log_warn(LD_FS, "Can't read single onion poison file \"%s\"",
poison_fname);
goto done;
case FN_FILE:
case FN_EMPTY:
log_debug(LD_FS, "Tried to re-poison a single onion poisoned file \"%s\"",
poison_fname);
break;
case FN_NOENT:
fd = tor_open_cloexec(poison_fname, O_RDWR|O_CREAT|O_TRUNC, 0600);
if (fd < 0) {
log_warn(LD_FS, "Could not create single onion poison file %s",
poison_fname);
goto done;
}
close(fd);
break;
default:
tor_assert(0);
}
retval = 0;
done:
tor_free(poison_fname);
return retval;
}
STATIC int
rend_service_poison_new_single_onion_dir(const rend_service_t *s,
const or_options_t* options)
{
if (BUG(!s)) {
return -1;
}
tor_assert(rend_service_non_anonymous_mode_enabled(options));
if (BUG(rend_service_is_ephemeral(s))) {
return -1;
}
if (BUG(!s->directory)) {
return -1;
}
if (!rend_service_private_key_exists(s)) {
if (poison_new_single_onion_hidden_service_dir_impl(s, options)
< 0) {
return -1;
}
}
return 0;
}
int
rend_service_key_on_disk(const char *directory_path)
{
int ret = 0;
char *fname;
crypto_pk_t *pk = NULL;
tor_assert(directory_path);
fname = hs_path_from_filename(directory_path, private_key_fname);
pk = init_key_from_file(fname, 0, LOG_DEBUG, NULL);
if (pk) {
ret = 1;
}
crypto_pk_free(pk);
tor_free(fname);
return ret;
}
int
rend_service_load_all_keys(const smartlist_t *service_list)
{
const smartlist_t *s_list = rend_get_service_list(service_list);
if (BUG(!s_list)) {
return -1;
}
SMARTLIST_FOREACH_BEGIN(s_list, rend_service_t *, s) {
if (s->private_key)
continue;
log_info(LD_REND, "Loading hidden-service keys from %s",
rend_service_escaped_dir(s));
if (rend_service_load_keys(s) < 0)
return -1;
} SMARTLIST_FOREACH_END(s);
return 0;
}
static void
rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s)
{
tor_assert(lst);
tor_assert(s);
tor_assert(s->directory);
smartlist_add(lst, rend_service_path(s, private_key_fname));
smartlist_add(lst, rend_service_path(s, hostname_fname));
smartlist_add(lst, rend_service_path(s, client_keys_fname));
smartlist_add(lst, rend_service_sos_poison_path(s));
}
void
rend_services_add_filenames_to_lists(smartlist_t *open_lst,
smartlist_t *stat_lst)
{
if (!rend_service_list)
return;
SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
if (!rend_service_is_ephemeral(s)) {
rend_service_add_filenames_to_list(open_lst, s);
smartlist_add_strdup(stat_lst, s->directory);
}
} SMARTLIST_FOREACH_END(s);
}
static int
rend_service_derive_key_digests(struct rend_service_t *s)
{
if (rend_get_service_id(s->private_key, s->service_id)<0) {
log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
return -1;
}
if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
log_warn(LD_BUG, "Couldn't compute hash of public key.");
return -1;
}
return 0;
}
static int
rend_service_check_private_dir(const or_options_t *options,
const rend_service_t *s,
int create)
{
if (BUG(!s)) {
return -1;
}
if (hs_check_service_private_dir(options->User, s->directory,
s->dir_group_readable, create) < 0) {
return -1;
}
if (rend_service_verify_single_onion_poison(s, options) < 0) {
log_warn(LD_GENERAL, "We are configured with "
"HiddenServiceNonAnonymousMode %d, but the hidden "
"service key in directory %s was created in %s mode. "
"This is not allowed.",
rend_service_non_anonymous_mode_enabled(options) ? 1 : 0,
rend_service_escaped_dir(s),
rend_service_non_anonymous_mode_enabled(options) ?
"an anonymous" : "a non-anonymous"
);
return -1;
}
if (create && rend_service_non_anonymous_mode_enabled(options)) {
static int logged_warning = 0;
if (rend_service_poison_new_single_onion_dir(s, options) < 0) {
log_warn(LD_GENERAL,"Failed to mark new hidden services as non-anonymous"
".");
return -1;
}
if (!logged_warning) {
log_notice(LD_REND, "The configured onion service directories have been "
"used in single onion mode. They can not be used for "
"anonymous hidden services.");
logged_warning = 1;
}
}
return 0;
}
static int
rend_service_load_keys(rend_service_t *s)
{
char *fname = NULL;
char buf[128];
if (rend_service_check_private_dir(get_options(), s, 1) < 0)
goto err;
fname = rend_service_path(s, private_key_fname);
s->private_key = init_key_from_file(fname, 1, LOG_ERR, NULL);
if (!s->private_key)
goto err;
if (rend_service_derive_key_digests(s) < 0)
goto err;
tor_free(fname);
fname = rend_service_path(s, hostname_fname);
tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
if (write_str_to_file(fname,buf,0)<0) {
log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
goto err;
}
#ifndef _WIN32
if (s->dir_group_readable) {
if (chmod(fname, 0640))
log_warn(LD_FS,"Unable to make hidden hostname file %s group-readable.",
fname);
}
#endif
if (s->auth_type != REND_NO_AUTH) {
if (rend_service_load_auth_keys(s, fname) < 0) {
goto err;
}
}
int r = 0;
goto done;
err:
r = -1;
done:
memwipe(buf, 0, sizeof(buf));
tor_free(fname);
return r;
}
static int
rend_service_load_auth_keys(rend_service_t *s, const char *hfname)
{
int r = 0;
char *cfname = NULL;
char *client_keys_str = NULL;
strmap_t *parsed_clients = strmap_new();
FILE *cfile, *hfile;
open_file_t *open_cfile = NULL, *open_hfile = NULL;
char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
char service_id[16+1];
char buf[1500];
cfname = rend_service_path(s, client_keys_fname);
client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
if (client_keys_str) {
if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
log_warn(LD_CONFIG, "Previously stored client_keys file could not "
"be parsed.");
goto err;
} else {
log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
strmap_size(parsed_clients));
}
}
if (!(cfile = start_writing_to_stdio_file(cfname,
OPEN_FLAGS_REPLACE | O_TEXT,
0600, &open_cfile))) {
log_warn(LD_CONFIG, "Could not open client_keys file %s",
escaped(cfname));
goto err;
}
if (!(hfile = start_writing_to_stdio_file(hfname,
OPEN_FLAGS_REPLACE | O_TEXT,
0600, &open_hfile))) {
log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(hfname));
goto err;
}
SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client) {
rend_authorized_client_t *parsed =
strmap_get(parsed_clients, client->client_name);
int written;
size_t len;
if (parsed) {
memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
REND_DESC_COOKIE_LEN);
} else {
crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
}
if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
(char *) client->descriptor_cookie,
REND_DESC_COOKIE_LEN, 0) < 0) {
log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
goto err;
}
if (parsed && parsed->client_key) {
client->client_key = crypto_pk_dup_key(parsed->client_key);
} else if (s->auth_type == REND_STEALTH_AUTH) {
crypto_pk_t *prkey = NULL;
if (!(prkey = crypto_pk_new())) {
log_warn(LD_BUG,"Error constructing client key");
goto err;
}
if (crypto_pk_generate_key(prkey)) {
log_warn(LD_BUG,"Error generating client key");
crypto_pk_free(prkey);
goto err;
}
if (! crypto_pk_is_valid_private_key(prkey)) {
log_warn(LD_BUG,"Generated client key seems invalid");
crypto_pk_free(prkey);
goto err;
}
client->client_key = prkey;
}
written = tor_snprintf(buf, sizeof(buf),
"client-name %s\ndescriptor-cookie %s\n",
client->client_name, desc_cook_out);
if (written < 0) {
log_warn(LD_BUG, "Could not write client entry.");
goto err;
}
if (client->client_key) {
char *client_key_out = NULL;
if (crypto_pk_write_private_key_to_string(client->client_key,
&client_key_out, &len) != 0) {
log_warn(LD_BUG, "Internal error: "
"crypto_pk_write_private_key_to_string() failed.");
goto err;
}
if (rend_get_service_id(client->client_key, service_id)<0) {
log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
memwipe(client_key_out, 0, len);
tor_free(client_key_out);
goto err;
}
written = tor_snprintf(buf + written, sizeof(buf) - written,
"client-key\n%s", client_key_out);
memwipe(client_key_out, 0, len);
tor_free(client_key_out);
if (written < 0) {
log_warn(LD_BUG, "Could not write client entry.");
goto err;
}
} else {
strlcpy(service_id, s->service_id, sizeof(service_id));
}
if (fputs(buf, cfile) < 0) {
log_warn(LD_FS, "Could not append client entry to file: %s",
strerror(errno));
goto err;
}
char *encoded_cookie = rend_auth_encode_cookie(client->descriptor_cookie,
s->auth_type);
if (!encoded_cookie) {
log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
goto err;
}
tor_snprintf(buf, sizeof(buf), "%s.onion %s # client: %s\n",
service_id, encoded_cookie, client->client_name);
memwipe(encoded_cookie, 0, strlen(encoded_cookie));
tor_free(encoded_cookie);
if (fputs(buf, hfile)<0) {
log_warn(LD_FS, "Could not append host entry to file: %s",
strerror(errno));
goto err;
}
} SMARTLIST_FOREACH_END(client);
finish_writing_to_file(open_cfile);
finish_writing_to_file(open_hfile);
goto done;
err:
r = -1;
if (open_cfile)
abort_writing_to_file(open_cfile);
if (open_hfile)
abort_writing_to_file(open_hfile);
done:
if (client_keys_str) {
memwipe(client_keys_str, 0, strlen(client_keys_str));
tor_free(client_keys_str);
}
strmap_free(parsed_clients, rend_authorized_client_free_void);
if (cfname) {
memwipe(cfname, 0, strlen(cfname));
tor_free(cfname);
}
memwipe(buf, 0, sizeof(buf));
memwipe(desc_cook_out, 0, sizeof(desc_cook_out));
memwipe(service_id, 0, sizeof(service_id));
return r;
}
static rend_service_t *
rend_service_get_by_pk_digest(const char* digest)
{
SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
if (tor_memeq(s->pk_digest,digest,DIGEST_LEN))
return s);
return NULL;
}
static struct rend_service_t *
rend_service_get_by_service_id(const char *id)
{
tor_assert(strlen(id) == REND_SERVICE_ID_LEN_BASE32);
SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s, {
if (tor_memeq(s->service_id, id, REND_SERVICE_ID_LEN_BASE32))
return s;
});
return NULL;
}
static int
rend_check_authorization(rend_service_t *service,
const char *descriptor_cookie,
size_t cookie_len)
{
rend_authorized_client_t *auth_client = NULL;
tor_assert(service);
tor_assert(descriptor_cookie);
if (!service->clients) {
log_warn(LD_BUG, "Can't check authorization for a service that has no "
"authorized clients configured.");
return 0;
}
if (cookie_len != REND_DESC_COOKIE_LEN) {
log_info(LD_REND, "Descriptor cookie is %lu bytes, but we expected "
"%lu bytes. Dropping cell.",
(unsigned long)cookie_len, (unsigned long)REND_DESC_COOKIE_LEN);
return 0;
}
SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
if (tor_memeq(client->descriptor_cookie, descriptor_cookie,
REND_DESC_COOKIE_LEN)) {
auth_client = client;
break;
}
});
if (!auth_client) {
char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
descriptor_cookie, REND_DESC_COOKIE_LEN, 0);
log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
"Dropping cell!",
descriptor_cookie_base64);
return 0;
}
log_info(LD_REND, "Client %s authorized for service %s.",
auth_client->client_name, service->service_id);
return 1;
}
static int
rend_service_use_direct_connection(const or_options_t* options,
const extend_info_t* ei)
{
return (rend_service_allow_non_anonymous_connection(options) &&
fascist_firewall_allows_address_addr(&ei->addr, ei->port,
FIREWALL_OR_CONNECTION, 0, 0));
}
static int
rend_service_use_direct_connection_node(const or_options_t* options,
const node_t* node)
{
return (rend_service_allow_non_anonymous_connection(options) &&
fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0));
}
int
rend_service_receive_introduction(origin_circuit_t *circuit,
const uint8_t *request,
size_t request_len)
{
int status = 0, result;
const or_options_t *options = get_options();
char *err_msg = NULL;
int err_msg_severity = LOG_WARN;
const char *stage_descr = NULL, *rend_pk_digest;
int reason = END_CIRC_REASON_TORPROTOCOL;
char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
rend_service_t *service = NULL;
rend_intro_point_t *intro_point = NULL;
crypto_pk_t *intro_key = NULL;
rend_intro_cell_t *parsed_req = NULL;
extend_info_t *rp = NULL;
char buf[RELAY_PAYLOAD_SIZE];
char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
int i;
crypto_dh_t *dh = NULL;
origin_circuit_t *launched = NULL;
crypt_path_t *cpath = NULL;
char hexcookie[9];
int circ_needs_uptime;
time_t now = time(NULL);
time_t elapsed;
int replay;
ssize_t keylen;
if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) {
log_warn(LD_PROTOCOL,
"Got an INTRODUCE2 over a non-introduction circuit %u.",
(unsigned) circuit->base_.n_circ_id);
goto err;
}
assert_circ_anonymity_ok(circuit, options);
tor_assert(circuit->rend_data);
rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
rend_pk_digest, REND_SERVICE_ID_LEN);
service = rend_service_get_by_pk_digest(rend_pk_digest);
if (!service) {
log_warn(LD_BUG,
"Internal error: Got an INTRODUCE2 cell on an intro "
"circ for an unrecognized service %s.",
escaped(serviceid));
goto err;
}
intro_point = find_intro_point(circuit);
if (intro_point == NULL) {
intro_point = find_expiring_intro_point(service, circuit);
if (intro_point == NULL) {
log_warn(LD_BUG,
"Internal error: Got an INTRODUCE2 cell on an "
"intro circ (for service %s) with no corresponding "
"rend_intro_point_t.",
escaped(serviceid));
goto err;
}
}
log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %u.",
escaped(serviceid), (unsigned)circuit->base_.n_circ_id);
intro_key = circuit->intro_key;
tor_free(err_msg);
stage_descr = NULL;
stage_descr = "early parsing";
parsed_req =
rend_service_begin_parse_intro(request, request_len, 2, &err_msg);
if (!parsed_req) {
goto log_error;
} else if (err_msg) {
log_info(LD_REND, "%s on circ %u.", err_msg,
(unsigned)circuit->base_.n_circ_id);
tor_free(err_msg);
}
if (!service->accepted_intro_dh_parts) {
service->accepted_intro_dh_parts =
replaycache_new(REND_REPLAY_TIME_INTERVAL,
REND_REPLAY_TIME_INTERVAL);
}
if (!intro_point->accepted_intro_rsa_parts) {
intro_point->accepted_intro_rsa_parts = replaycache_new(0, 0);
}
keylen = crypto_pk_keysize(intro_key);
replay = replaycache_add_test_and_elapsed(
intro_point->accepted_intro_rsa_parts,
parsed_req->ciphertext, MIN(parsed_req->ciphertext_len, keylen),
&elapsed);
if (replay) {
log_warn(LD_REND,
"Possible replay detected! We received an "
"INTRODUCE2 cell with same PK-encrypted part %d "
"seconds ago. Dropping cell.",
(int)elapsed);
goto err;
}
stage_descr = "decryption";
result = rend_service_decrypt_intro(parsed_req, intro_key, &err_msg);
if (result < 0) {
goto log_error;
} else if (err_msg) {
log_info(LD_REND, "%s on circ %u.", err_msg,
(unsigned)circuit->base_.n_circ_id);
tor_free(err_msg);
}
stage_descr = "late parsing";
result = rend_service_parse_intro_plaintext(parsed_req, &err_msg);
if (result < 0) {
goto log_error;
} else if (err_msg) {
log_info(LD_REND, "%s on circ %u.", err_msg,
(unsigned)circuit->base_.n_circ_id);
tor_free(err_msg);
}
stage_descr = "late validation";
result = rend_service_validate_intro_late(parsed_req, &err_msg);
if (result < 0) {
goto log_error;
} else if (err_msg) {
log_info(LD_REND, "%s on circ %u.", err_msg,
(unsigned)circuit->base_.n_circ_id);
tor_free(err_msg);
}
stage_descr = NULL;
++(intro_point->accepted_introduce2_count);
rp = find_rp_for_intro(parsed_req, &err_msg);
if (!rp) {
err_msg_severity = LOG_PROTOCOL_WARN;
goto log_error;
}
if (options->StrictNodes &&
routerset_contains_extendinfo(options->ExcludeNodes, rp)) {
log_warn(LD_REND, "Client asked to rendezvous at a relay that we "
"exclude, and StrictNodes is set. Refusing service.");
reason = END_CIRC_REASON_INTERNAL;
goto err;
}
base16_encode(hexcookie, 9, (const char *)(parsed_req->rc), 4);
replay = replaycache_add_test_and_elapsed(
service->accepted_intro_dh_parts,
parsed_req->dh, DH1024_KEY_LEN,
&elapsed);
if (replay) {
log_info(LD_REND, "We received an "
"INTRODUCE2 cell with same first part of "
"Diffie-Hellman handshake %d seconds ago. Dropping "
"cell.",
(int) elapsed);
goto err;
}
if (service->clients) {
if (parsed_req->version == 3 && parsed_req->u.v3.auth_len > 0) {
if (rend_check_authorization(service,
(const char*)parsed_req->u.v3.auth_data,
parsed_req->u.v3.auth_len)) {
log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
} else {
log_info(LD_REND, "The authorization data that are contained in "
"the INTRODUCE2 cell are invalid. Dropping cell.");
reason = END_CIRC_REASON_CONNECTFAILED;
goto err;
}
} else {
log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
"data, but we require client authorization. Dropping cell.");
reason = END_CIRC_REASON_CONNECTFAILED;
goto err;
}
}
dh = crypto_dh_new(DH_TYPE_REND);
if (!dh || crypto_dh_generate_public(dh)<0) {
log_warn(LD_BUG,"Internal error: couldn't build DH state "
"or generate public key.");
reason = END_CIRC_REASON_INTERNAL;
goto err;
}
if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh,
(char *)(parsed_req->dh),
DH1024_KEY_LEN, keys,
DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
reason = END_CIRC_REASON_INTERNAL;
goto err;
}
circ_needs_uptime = hs_service_requires_uptime_circ(service->ports);
rep_hist_note_used_internal(now, circ_needs_uptime, 1);
int max_rend_failures=hs_get_service_max_rend_failures();
for (i=0;i<max_rend_failures;i++) {
int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
if (rend_service_use_direct_connection(options, rp) && i == 0) {
flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
}
launched = circuit_launch_by_extend_info(
CIRCUIT_PURPOSE_S_CONNECT_REND, rp, flags);
if (launched)
break;
}
if (!launched) {
log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
"point %s for service %s.",
safe_str_client(extend_info_describe(rp)),
serviceid);
reason = END_CIRC_REASON_CONNECTFAILED;
goto err;
}
log_info(LD_REND,
"Accepted intro; launching circuit to %s "
"(cookie %s) for service %s.",
safe_str_client(extend_info_describe(rp)),
hexcookie, serviceid);
tor_assert(launched->build_state);
launched->rend_data =
rend_data_service_create(service->service_id, rend_pk_digest,
parsed_req->rc, service->auth_type);
launched->build_state->service_pending_final_cpath_ref =
tor_malloc_zero(sizeof(crypt_path_reference_t));
launched->build_state->service_pending_final_cpath_ref->refcount = 1;
launched->build_state->service_pending_final_cpath_ref->cpath = cpath =
tor_malloc_zero(sizeof(crypt_path_t));
cpath->magic = CRYPT_PATH_MAGIC;
launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
cpath->rend_dh_handshake_state = dh;
dh = NULL;
if (cpath_init_circuit_crypto(cpath,
keys+DIGEST_LEN, sizeof(keys)-DIGEST_LEN,
1, 0)<0)
goto err;
memcpy(cpath->rend_circ_nonce, keys, DIGEST_LEN);
goto done;
log_error:
if (!err_msg) {
if (stage_descr) {
tor_asprintf(&err_msg,
"unknown %s error for INTRODUCE2", stage_descr);
} else {
err_msg = tor_strdup("unknown error for INTRODUCE2");
}
}
log_fn(err_msg_severity, LD_REND, "%s on circ %u", err_msg,
(unsigned)circuit->base_.n_circ_id);
err:
status = -1;
if (dh) crypto_dh_free(dh);
if (launched) {
circuit_mark_for_close(TO_CIRCUIT(launched), reason);
}
tor_free(err_msg);
done:
memwipe(keys, 0, sizeof(keys));
memwipe(buf, 0, sizeof(buf));
memwipe(serviceid, 0, sizeof(serviceid));
memwipe(hexcookie, 0, sizeof(hexcookie));
rend_service_free_intro(parsed_req);
extend_info_free(rp);
return status;
}
static extend_info_t *
find_rp_for_intro(const rend_intro_cell_t *intro,
char **err_msg_out)
{
extend_info_t *rp = NULL;
char *err_msg = NULL;
const char *rp_nickname = NULL;
const node_t *node = NULL;
if (!intro) {
if (err_msg_out)
err_msg = tor_strdup("Bad parameters to find_rp_for_intro()");
goto err;
}
if (intro->version == 0 || intro->version == 1) {
rp_nickname = (const char *)(intro->u.v0_v1.rp);
node = node_get_by_nickname(rp_nickname, NNF_NO_WARN_UNNAMED);
if (!node) {
if (err_msg_out) {
tor_asprintf(&err_msg,
"Couldn't find router %s named in INTRODUCE2 cell",
escaped_safe_str_client(rp_nickname));
}
goto err;
}
const int allow_direct = rend_service_allow_non_anonymous_connection(
get_options());
rp = extend_info_from_node(node, allow_direct);
if (!rp) {
if (err_msg_out) {
tor_asprintf(&err_msg,
"Couldn't build extend_info_t for router %s named "
"in INTRODUCE2 cell",
escaped_safe_str_client(rp_nickname));
}
goto err;
}
} else if (intro->version == 2) {
rp = extend_info_dup(intro->u.v2.extend_info);
} else if (intro->version == 3) {
rp = extend_info_dup(intro->u.v3.extend_info);
} else {
if (err_msg_out) {
tor_asprintf(&err_msg,
"Unknown version %d in INTRODUCE2 cell",
(int)(intro->version));
}
goto err;
}
tor_assert(rp);
if (!extend_info_addr_is_allowed(&rp->addr)) {
if (err_msg_out) {
tor_asprintf(&err_msg,
"Relay IP in INTRODUCE2 cell is private address.");
}
extend_info_free(rp);
rp = NULL;
goto err;
}
goto done;
err:
if (err_msg_out)
*err_msg_out = err_msg;
else
tor_free(err_msg);
done:
return rp;
}
void
rend_service_free_intro_(rend_intro_cell_t *request)
{
if (!request) {
return;
}
tor_free(request->ciphertext);
request->ciphertext_len = 0;
if (request->plaintext) {
memwipe(request->plaintext, 0, request->plaintext_len);
tor_free(request->plaintext);
request->plaintext_len = 0;
}
if (request->parsed) {
switch (request->version) {
case 0:
case 1:
break;
case 2:
extend_info_free(request->u.v2.extend_info);
request->u.v2.extend_info = NULL;
break;
case 3:
if (request->u.v3.auth_data) {
memwipe(request->u.v3.auth_data, 0, request->u.v3.auth_len);
tor_free(request->u.v3.auth_data);
}
extend_info_free(request->u.v3.extend_info);
request->u.v3.extend_info = NULL;
break;
default:
log_info(LD_BUG,
"rend_service_free_intro() saw unknown protocol "
"version %d.",
request->version);
}
}
memwipe(request, 0, sizeof(*request));
tor_free(request);
}
rend_intro_cell_t *
rend_service_begin_parse_intro(const uint8_t *request,
size_t request_len,
uint8_t type,
char **err_msg_out)
{
rend_intro_cell_t *rv = NULL;
char *err_msg = NULL;
if (!request || request_len <= 0) goto err;
if (!(type == 1 || type == 2)) goto err;
if (request_len <
(DIGEST_LEN + REND_COOKIE_LEN + (MAX_NICKNAME_LEN + 1) +
DH1024_KEY_LEN + 42)) {
if (err_msg_out) {
tor_asprintf(&err_msg,
"got a truncated INTRODUCE%d cell",
(int)type);
}
goto err;
}
rv = tor_malloc_zero(sizeof(*rv));
rv->type = type;
memcpy(rv->pk, request, DIGEST_LEN);
rv->ciphertext = tor_malloc(request_len - DIGEST_LEN);
memcpy(rv->ciphertext, request + DIGEST_LEN, request_len - DIGEST_LEN);
rv->ciphertext_len = request_len - DIGEST_LEN;
goto done;
err:
rend_service_free_intro(rv);
rv = NULL;
if (err_msg_out && !err_msg) {
tor_asprintf(&err_msg,
"unknown INTRODUCE%d error",
(int)type);
}
done:
if (err_msg_out) *err_msg_out = err_msg;
else tor_free(err_msg);
return rv;
}
static ssize_t
rend_service_parse_intro_for_v0_or_v1(
rend_intro_cell_t *intro,
const uint8_t *buf,
size_t plaintext_len,
char **err_msg_out)
{
const char *rp_nickname, *endptr;
size_t nickname_field_len, ver_specific_len;
if (intro->version == 1) {
ver_specific_len = MAX_HEX_NICKNAME_LEN + 2;
rp_nickname = ((const char *)buf) + 1;
nickname_field_len = MAX_HEX_NICKNAME_LEN + 1;
} else if (intro->version == 0) {
ver_specific_len = MAX_NICKNAME_LEN + 1;
rp_nickname = (const char *)buf;
nickname_field_len = MAX_NICKNAME_LEN + 1;
} else {
if (err_msg_out)
tor_asprintf(err_msg_out,
"rend_service_parse_intro_for_v0_or_v1() called with "
"bad version %d on INTRODUCE%d cell (this is a bug)",
intro->version,
(int)(intro->type));
goto err;
}
if (plaintext_len < ver_specific_len) {
if (err_msg_out)
tor_asprintf(err_msg_out,
"short plaintext of encrypted part in v1 INTRODUCE%d "
"cell (%lu bytes, needed %lu)",
(int)(intro->type),
(unsigned long)plaintext_len,
(unsigned long)ver_specific_len);
goto err;
}
endptr = memchr(rp_nickname, 0, nickname_field_len);
if (!endptr || endptr == rp_nickname) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"couldn't find a nul-padded nickname in "
"INTRODUCE%d cell",
(int)(intro->type));
}
goto err;
}
if ((intro->version == 0 &&
!is_legal_nickname(rp_nickname)) ||
(intro->version == 1 &&
!is_legal_nickname_or_hexdigest(rp_nickname))) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"bad nickname in INTRODUCE%d cell",
(int)(intro->type));
}
goto err;
}
memcpy(intro->u.v0_v1.rp, rp_nickname, endptr - rp_nickname + 1);
return ver_specific_len;
err:
return -1;
}
static ssize_t
rend_service_parse_intro_for_v2(
rend_intro_cell_t *intro,
const uint8_t *buf,
size_t plaintext_len,
char **err_msg_out)
{
unsigned int klen;
extend_info_t *extend_info = NULL;
ssize_t ver_specific_len;
if (!(intro->version == 2 ||
intro->version == 3)) {
if (err_msg_out)
tor_asprintf(err_msg_out,
"rend_service_parse_intro_for_v2() called with "
"bad version %d on INTRODUCE%d cell (this is a bug)",
intro->version,
(int)(intro->type));
goto err;
}
if (plaintext_len < 7 + DIGEST_LEN + 2) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"truncated plaintext of encrypted parted of "
"version %d INTRODUCE%d cell",
intro->version,
(int)(intro->type));
}
goto err;
}
extend_info = tor_malloc_zero(sizeof(extend_info_t));
tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf + 1));
extend_info->port = ntohs(get_uint16(buf + 5));
memcpy(extend_info->identity_digest, buf + 7, DIGEST_LEN);
extend_info->nickname[0] = '$';
base16_encode(extend_info->nickname + 1, sizeof(extend_info->nickname) - 1,
extend_info->identity_digest, DIGEST_LEN);
klen = ntohs(get_uint16(buf + 7 + DIGEST_LEN));
if (plaintext_len < 7 + DIGEST_LEN + 2 + klen) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"truncated plaintext of encrypted parted of "
"version %d INTRODUCE%d cell",
intro->version,
(int)(intro->type));
}
goto err;
}
extend_info->onion_key =
crypto_pk_asn1_decode((const char *)(buf + 7 + DIGEST_LEN + 2), klen);
if (!extend_info->onion_key) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"error decoding onion key in version %d "
"INTRODUCE%d cell",
intro->version,
(intro->type));
}
goto err;
}
if (128 != crypto_pk_keysize(extend_info->onion_key)) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"invalid onion key size in version %d INTRODUCE%d cell",
intro->version,
(intro->type));
}
goto err;
}
ver_specific_len = 7+DIGEST_LEN+2+klen;
if (intro->version == 2) intro->u.v2.extend_info = extend_info;
else intro->u.v3.extend_info = extend_info;
return ver_specific_len;
err:
extend_info_free(extend_info);
return -1;
}
static ssize_t
rend_service_parse_intro_for_v3(
rend_intro_cell_t *intro,
const uint8_t *buf,
size_t plaintext_len,
char **err_msg_out)
{
ssize_t adjust, v2_ver_specific_len, ts_offset;
if (intro->version != 3) {
if (err_msg_out)
tor_asprintf(err_msg_out,
"rend_service_parse_intro_for_v3() called with "
"bad version %d on INTRODUCE%d cell (this is a bug)",
intro->version,
(int)(intro->type));
goto err;
}
if (plaintext_len < 4) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"truncated plaintext of encrypted parted of "
"version %d INTRODUCE%d cell",
intro->version,
(int)(intro->type));
}
goto err;
}
intro->u.v3.auth_type = buf[1];
if (intro->u.v3.auth_type != REND_NO_AUTH) {
intro->u.v3.auth_len = ntohs(get_uint16(buf + 2));
ts_offset = 4 + intro->u.v3.auth_len;
} else {
intro->u.v3.auth_len = 0;
ts_offset = 2;
}
if (intro->u.v3.auth_type == REND_BASIC_AUTH ||
intro->u.v3.auth_type == REND_STEALTH_AUTH) {
if (intro->u.v3.auth_len != REND_DESC_COOKIE_LEN) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"wrong auth data size %d for INTRODUCE%d cell, "
"should be %d",
(int)(intro->u.v3.auth_len),
(int)(intro->type),
REND_DESC_COOKIE_LEN);
}
goto err;
}
}
if (plaintext_len < (size_t)(ts_offset)+4) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"truncated plaintext of encrypted parted of "
"version %d INTRODUCE%d cell",
intro->version,
(int)(intro->type));
}
goto err;
}
if (intro->u.v3.auth_type != REND_NO_AUTH &&
intro->u.v3.auth_len > 0) {
intro->u.v3.auth_data = tor_malloc(intro->u.v3.auth_len);
memcpy(intro->u.v3.auth_data, buf + 4, intro->u.v3.auth_len);
}
adjust = 3 + ts_offset;
v2_ver_specific_len =
rend_service_parse_intro_for_v2(intro,
buf + adjust, plaintext_len - adjust,
err_msg_out);
if (v2_ver_specific_len >= 0) return v2_ver_specific_len + adjust;
else return v2_ver_specific_len;
err:
return -1;
}
static ssize_t
(*intro_version_handlers[])(
rend_intro_cell_t *,
const uint8_t *,
size_t,
char **) =
{ rend_service_parse_intro_for_v0_or_v1,
rend_service_parse_intro_for_v0_or_v1,
rend_service_parse_intro_for_v2,
rend_service_parse_intro_for_v3 };
int
rend_service_decrypt_intro(
rend_intro_cell_t *intro,
crypto_pk_t *key,
char **err_msg_out)
{
char *err_msg = NULL;
uint8_t key_digest[DIGEST_LEN];
char service_id[REND_SERVICE_ID_LEN_BASE32+1];
ssize_t key_len;
uint8_t buf[RELAY_PAYLOAD_SIZE];
int result, status = -1;
if (!intro || !key) {
if (err_msg_out) {
err_msg =
tor_strdup("rend_service_decrypt_intro() called with bad "
"parameters");
}
status = -2;
goto err;
}
if (!(intro->ciphertext) || intro->ciphertext_len <= 0) {
if (err_msg_out) {
tor_asprintf(&err_msg,
"rend_intro_cell_t was missing ciphertext for "
"INTRODUCE%d cell",
(int)(intro->type));
}
status = -3;
goto err;
}
if (crypto_pk_get_digest(key, (char *)key_digest) < 0) {
if (err_msg_out)
*err_msg_out = tor_strdup("Couldn't compute RSA digest.");
log_warn(LD_BUG, "Couldn't compute key digest.");
status = -7;
goto err;
}
if (tor_memneq(key_digest, intro->pk, DIGEST_LEN)) {
if (err_msg_out) {
base32_encode(service_id, REND_SERVICE_ID_LEN_BASE32 + 1,
(char*)(intro->pk), REND_SERVICE_ID_LEN);
tor_asprintf(&err_msg,
"got an INTRODUCE%d cell for the wrong service (%s)",
(int)(intro->type),
escaped(service_id));
}
status = -4;
goto err;
}
key_len = crypto_pk_keysize(key);
if (intro->ciphertext_len < key_len) {
if (err_msg_out) {
tor_asprintf(&err_msg,
"got an INTRODUCE%d cell with a truncated PK-encrypted "
"part",
(int)(intro->type));
}
status = -5;
goto err;
}
result =
crypto_pk_obsolete_private_hybrid_decrypt(
key, (char *)buf, sizeof(buf),
(const char *)(intro->ciphertext), intro->ciphertext_len,
PK_PKCS1_OAEP_PADDING, 1);
if (result < 0) {
if (err_msg_out) {
tor_asprintf(&err_msg,
"couldn't decrypt INTRODUCE%d cell",
(int)(intro->type));
}
status = -6;
goto err;
}
intro->plaintext_len = result;
intro->plaintext = tor_malloc(intro->plaintext_len);
memcpy(intro->plaintext, buf, intro->plaintext_len);
status = 0;
goto done;
err:
if (err_msg_out && !err_msg) {
tor_asprintf(&err_msg,
"unknown INTRODUCE%d error decrypting encrypted part",
intro ? (int)(intro->type) : -1);
}
done:
if (err_msg_out) *err_msg_out = err_msg;
else tor_free(err_msg);
memwipe(buf, 0, sizeof(buf));
memwipe(key_digest, 0, sizeof(key_digest));
memwipe(service_id, 0, sizeof(service_id));
return status;
}
int
rend_service_parse_intro_plaintext(
rend_intro_cell_t *intro,
char **err_msg_out)
{
char *err_msg = NULL;
ssize_t ver_specific_len, ver_invariant_len;
uint8_t version;
int status = -1;
if (!intro) {
if (err_msg_out) {
err_msg =
tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
"rend_intro_cell_t");
}
status = -2;
goto err;
}
if (!(intro->plaintext) || intro->plaintext_len <= 0) {
if (err_msg_out) {
err_msg = tor_strdup("rend_intro_cell_t was missing plaintext");
}
status = -3;
goto err;
}
version = intro->plaintext[0];
if (version > 3) version = 0;
intro->version = version;
ver_specific_len =
intro_version_handlers[version](intro,
intro->plaintext, intro->plaintext_len,
&err_msg);
if (ver_specific_len < 0) {
status = -4;
goto err;
}
ver_invariant_len = intro->plaintext_len - ver_specific_len;
if (ver_invariant_len < REND_COOKIE_LEN + DH1024_KEY_LEN) {
tor_asprintf(&err_msg,
"decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
(int)(intro->type),
(long)(intro->plaintext_len));
status = -5;
goto err;
} else if (ver_invariant_len > REND_COOKIE_LEN + DH1024_KEY_LEN) {
tor_asprintf(&err_msg,
"decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
(int)(intro->type),
(long)(intro->plaintext_len));
status = -6;
goto err;
} else {
memcpy(intro->rc,
intro->plaintext + ver_specific_len,
REND_COOKIE_LEN);
memcpy(intro->dh,
intro->plaintext + ver_specific_len + REND_COOKIE_LEN,
DH1024_KEY_LEN);
}
intro->parsed = 1;
status = 0;
goto done;
err:
if (err_msg_out && !err_msg) {
tor_asprintf(&err_msg,
"unknown INTRODUCE%d error parsing encrypted part",
intro ? (int)(intro->type) : -1);
}
done:
if (err_msg_out) *err_msg_out = err_msg;
else tor_free(err_msg);
return status;
}
int
rend_service_validate_intro_late(const rend_intro_cell_t *intro,
char **err_msg_out)
{
int status = 0;
if (!intro) {
if (err_msg_out)
*err_msg_out =
tor_strdup("NULL intro cell passed to "
"rend_service_validate_intro_late()");
status = -1;
goto err;
}
if (intro->version == 3 && intro->parsed) {
if (!(intro->u.v3.auth_type == REND_NO_AUTH ||
intro->u.v3.auth_type == REND_BASIC_AUTH ||
intro->u.v3.auth_type == REND_STEALTH_AUTH)) {
if (err_msg_out)
tor_asprintf(err_msg_out,
"unknown authorization type %d",
intro->u.v3.auth_type);
}
}
err:
return status;
}
void
rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
{
origin_circuit_t *newcirc;
cpath_build_state_t *newstate, *oldstate;
const char *rend_pk_digest;
rend_service_t *service = NULL;
int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
tor_assert(oldcirc->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
oldstate = oldcirc->build_state;
tor_assert(oldstate);
if (oldstate->service_pending_final_cpath_ref == NULL) {
log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
"Initiator will retry.");
return;
}
log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
safe_str(extend_info_describe(oldstate->chosen_exit)));
rend_pk_digest = (char *) rend_data_get_pk_digest(oldcirc->rend_data, NULL);
service = rend_service_get_by_pk_digest(rend_pk_digest);
if (!service) {
char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
rend_pk_digest, REND_SERVICE_ID_LEN);
log_warn(LD_BUG, "Internal error: Trying to relaunch a rendezvous circ "
"for an unrecognized service %s.",
safe_str_client(serviceid));
return;
}
if (hs_service_requires_uptime_circ(service->ports)) {
flags |= CIRCLAUNCH_NEED_UPTIME;
}
newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
oldstate->chosen_exit, flags);
if (!newcirc) {
log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
safe_str(extend_info_describe(oldstate->chosen_exit)));
return;
}
newstate = newcirc->build_state;
tor_assert(newstate);
newstate->failure_count = oldstate->failure_count+1;
newstate->expiry_time = oldstate->expiry_time;
newstate->service_pending_final_cpath_ref =
oldstate->service_pending_final_cpath_ref;
++(newstate->service_pending_final_cpath_ref->refcount);
newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
}
static int
rend_service_launch_establish_intro(rend_service_t *service,
rend_intro_point_t *intro)
{
origin_circuit_t *launched;
int flags = CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL;
const or_options_t *options = get_options();
extend_info_t *launch_ei = intro->extend_info;
extend_info_t *direct_ei = NULL;
if (rend_service_allow_non_anonymous_connection(options) &&
intro->circuit_retries == 0) {
const node_t *node = node_get_by_id(launch_ei->identity_digest);
if (BUG(!node)) {
return -1;
}
if (rend_service_use_direct_connection_node(options, node)) {
direct_ei = extend_info_from_node(node, 1);
if (BUG(!direct_ei)) {
return -1;
}
flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
launch_ei = direct_ei;
}
}
tor_assert(launch_ei);
tor_assert(tor_memeq(intro->extend_info->identity_digest,
launch_ei->identity_digest,
DIGEST_LEN));
log_info(LD_REND,
"Launching circuit to introduction point %s%s%s for service %s",
safe_str_client(extend_info_describe(intro->extend_info)),
direct_ei ? " via direct address " : "",
direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : "",
service->service_id);
rep_hist_note_used_internal(time(NULL), 1, 0);
++service->n_intro_circuits_launched;
launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
launch_ei, flags);
if (!launched) {
log_info(LD_REND,
"Can't launch circuit to establish introduction at %s%s%s.",
safe_str_client(extend_info_describe(intro->extend_info)),
direct_ei ? " via direct address " : "",
direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : ""
);
extend_info_free(direct_ei);
return -1;
}
tor_assert(tor_memeq(intro->extend_info->identity_digest,
launched->build_state->chosen_exit->identity_digest,
DIGEST_LEN));
launched->rend_data = rend_data_service_create(service->service_id,
service->pk_digest, NULL,
service->auth_type);
launched->intro_key = crypto_pk_dup_key(intro->intro_key);
if (launched->base_.state == CIRCUIT_STATE_OPEN)
rend_service_intro_has_opened(launched);
extend_info_free(direct_ei);
return 0;
}
static unsigned int
count_established_intro_points(const rend_service_t *service)
{
unsigned int num = 0;
SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
num += intro->circuit_established
);
return num;
}
static unsigned int
count_intro_point_circuits(const rend_service_t *service)
{
unsigned int num_ipos = 0;
SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
if (!circ->marked_for_close &&
circ->state == CIRCUIT_STATE_OPEN &&
(circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
if (oc->rend_data &&
rend_circuit_pk_digest_eq(oc, (uint8_t *) service->pk_digest)) {
num_ipos++;
}
}
}
SMARTLIST_FOREACH_END(circ);
return num_ipos;
}
ssize_t
rend_service_encode_establish_intro_cell(char *cell_body_out,
size_t cell_body_out_len,
crypto_pk_t *intro_key,
const char *rend_circ_nonce)
{
int retval = -1;
int r;
int len = 0;
char auth[DIGEST_LEN + 9];
tor_assert(intro_key);
tor_assert(rend_circ_nonce);
r = crypto_pk_asn1_encode(intro_key, cell_body_out+2,
RELAY_PAYLOAD_SIZE-2);
if (r < 0) {
log_warn(LD_BUG, "Internal error; failed to establish intro point.");
goto err;
}
len = r;
set_uint16(cell_body_out, htons((uint16_t)len));
len += 2;
memcpy(auth, rend_circ_nonce, DIGEST_LEN);
memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
if (crypto_digest(cell_body_out+len, auth, DIGEST_LEN+9))
goto err;
len += 20;
r = crypto_pk_private_sign_digest(intro_key, cell_body_out+len,
cell_body_out_len - len,
cell_body_out, len);
if (r<0) {
log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
goto err;
}
len += r;
retval = len;
err:
memwipe(auth, 0, sizeof(auth));
return retval;
}
void
rend_service_intro_has_opened(origin_circuit_t *circuit)
{
rend_service_t *service;
char buf[RELAY_PAYLOAD_SIZE];
char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
unsigned int expiring_nodes_len, num_ip_circuits, valid_ip_circuits = 0;
int reason = END_CIRC_REASON_TORPROTOCOL;
const char *rend_pk_digest;
tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
assert_circ_anonymity_ok(circuit, get_options());
tor_assert(circuit->cpath);
tor_assert(circuit->rend_data);
rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
rend_pk_digest, REND_SERVICE_ID_LEN);
service = rend_service_get_by_pk_digest(rend_pk_digest);
if (!service) {
log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %u.",
safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
reason = END_CIRC_REASON_NOSUCHSERVICE;
goto err;
}
expiring_nodes_len = (unsigned int) smartlist_len(service->expiring_nodes);
num_ip_circuits = count_intro_point_circuits(service);
if (num_ip_circuits > expiring_nodes_len) {
valid_ip_circuits = num_ip_circuits - expiring_nodes_len;
}
if (valid_ip_circuits > service->n_intro_points_wanted) {
const or_options_t *options = get_options();
rend_intro_point_t *intro = find_intro_point(circuit);
if (intro != NULL) {
smartlist_remove(service->intro_nodes, intro);
rend_intro_point_free(intro);
}
if (options->ExcludeNodes) {
log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
"circuit, but we already have enough. Closing it.");
reason = END_CIRC_REASON_NONE;
goto err;
} else {
tor_assert(circuit->build_state->is_internal);
log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
"circuit, but we already have enough. Redefining purpose to "
"general; leaving as internal.");
if (circuit_should_use_vanguards(TO_CIRCUIT(circuit)->purpose)) {
circuit_change_purpose(TO_CIRCUIT(circuit),
CIRCUIT_PURPOSE_HS_VANGUARDS);
} else {
circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_C_GENERAL);
}
{
rend_data_free(circuit->rend_data);
circuit->rend_data = NULL;
}
{
crypto_pk_t *intro_key = circuit->intro_key;
circuit->intro_key = NULL;
crypto_pk_free(intro_key);
}
circuit_has_opened(circuit);
goto done;
}
}
log_info(LD_REND,
"Established circuit %u as introduction point for service %s",
(unsigned)circuit->base_.n_circ_id, serviceid);
circuit_log_path(LOG_INFO, LD_REND, circuit);
{
ssize_t len;
len = rend_service_encode_establish_intro_cell(buf, sizeof(buf),
circuit->intro_key,
circuit->cpath->prev->rend_circ_nonce);
if (len < 0) {
reason = END_CIRC_REASON_INTERNAL;
goto err;
}
if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
RELAY_COMMAND_ESTABLISH_INTRO,
buf, len, circuit->cpath->prev)<0) {
log_info(LD_GENERAL,
"Couldn't send introduction request for service %s on circuit %u",
serviceid, (unsigned)circuit->base_.n_circ_id);
goto done;
}
}
pathbias_count_use_attempt(circuit);
goto done;
err:
circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
done:
memwipe(buf, 0, sizeof(buf));
memwipe(serviceid, 0, sizeof(serviceid));
return;
}
int
rend_service_intro_established(origin_circuit_t *circuit,
const uint8_t *request,
size_t request_len)
{
rend_service_t *service;
rend_intro_point_t *intro;
char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
(void) request;
(void) request_len;
tor_assert(circuit->rend_data);
const char *rend_pk_digest =
(char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
log_warn(LD_PROTOCOL,
"received INTRO_ESTABLISHED cell on non-intro circuit.");
goto err;
}
service = rend_service_get_by_pk_digest(rend_pk_digest);
if (!service) {
log_warn(LD_REND, "Unknown service on introduction circuit %u.",
(unsigned)circuit->base_.n_circ_id);
goto err;
}
base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
rend_pk_digest, REND_SERVICE_ID_LEN);
intro = find_intro_point(circuit);
if (intro == NULL) {
log_warn(LD_REND,
"Introduction circuit established without a rend_intro_point_t "
"object for service %s on circuit %u",
safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
goto err;
}
intro->circuit_established = 1;
service->desc_is_dirty = time(NULL);
circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO);
log_info(LD_REND,
"Received INTRO_ESTABLISHED cell on circuit %u for service %s",
(unsigned)circuit->base_.n_circ_id, serviceid);
pathbias_mark_use_success(circuit);
return 0;
err:
circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
return -1;
}
void
rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
{
rend_service_t *service;
char buf[RELAY_PAYLOAD_SIZE];
crypt_path_t *hop;
char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
char hexcookie[9];
int reason;
const char *rend_cookie, *rend_pk_digest;
tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
tor_assert(circuit->cpath);
tor_assert(circuit->build_state);
assert_circ_anonymity_ok(circuit, get_options());
tor_assert(circuit->rend_data);
rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data,
NULL);
rend_cookie = circuit->rend_data->rend_cookie;
circuit->base_.timestamp_dirty = time(NULL);
pathbias_count_use_attempt(circuit);
hop = circuit->build_state->service_pending_final_cpath_ref->cpath;
base16_encode(hexcookie,9, rend_cookie,4);
base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
rend_pk_digest, REND_SERVICE_ID_LEN);
log_info(LD_REND,
"Done building circuit %u to rendezvous with "
"cookie %s for service %s",
(unsigned)circuit->base_.n_circ_id, hexcookie, serviceid);
circuit_log_path(LOG_INFO, LD_REND, circuit);
circuit->hs_circ_has_timed_out = 0;
if (hop == NULL) {
log_info(LD_REND, "Another rend circ has already reached this rend point; "
"closing this rend circ.");
reason = END_CIRC_REASON_NONE;
goto err;
}
circuit->build_state->pending_final_cpath = hop;
circuit->build_state->service_pending_final_cpath_ref->cpath = NULL;
service = rend_service_get_by_pk_digest(rend_pk_digest);
if (!service) {
log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
"rendezvous circuit.");
reason = END_CIRC_REASON_INTERNAL;
goto err;
}
memcpy(buf, rend_cookie, REND_COOKIE_LEN);
if (crypto_dh_get_public(hop->rend_dh_handshake_state,
buf+REND_COOKIE_LEN, DH1024_KEY_LEN)<0) {
log_warn(LD_GENERAL,"Couldn't get DH public key.");
reason = END_CIRC_REASON_INTERNAL;
goto err;
}
memcpy(buf+REND_COOKIE_LEN+DH1024_KEY_LEN, hop->rend_circ_nonce,
DIGEST_LEN);
if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
RELAY_COMMAND_RENDEZVOUS1,
buf, HS_LEGACY_RENDEZVOUS_CELL_SIZE,
circuit->cpath->prev)<0) {
log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
goto done;
}
crypto_dh_free(hop->rend_dh_handshake_state);
hop->rend_dh_handshake_state = NULL;
hop->state = CPATH_STATE_OPEN;
hop->package_window = circuit_initial_package_window();
hop->deliver_window = CIRCWINDOW_START;
cpath_extend_linked_list(&circuit->cpath, hop);
circuit->build_state->pending_final_cpath = NULL;
circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_REND_JOINED);
goto done;
err:
circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
done:
memwipe(buf, 0, sizeof(buf));
memwipe(serviceid, 0, sizeof(serviceid));
memwipe(hexcookie, 0, sizeof(hexcookie));
return;
}
static origin_circuit_t *
find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
{
origin_circuit_t *circ = NULL;
tor_assert(intro);
while ((circ = circuit_get_next_by_pk_and_purpose(circ,
(uint8_t *) pk_digest, CIRCUIT_PURPOSE_S_INTRO))) {
if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
intro->extend_info->identity_digest, DIGEST_LEN) &&
circ->rend_data) {
return circ;
}
}
circ = NULL;
while ((circ = circuit_get_next_by_pk_and_purpose(circ,
(uint8_t *) pk_digest,
CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
intro->extend_info->identity_digest, DIGEST_LEN) &&
circ->rend_data) {
return circ;
}
}
return NULL;
}
static rend_intro_point_t *
find_expiring_intro_point(rend_service_t *service, origin_circuit_t *circ)
{
tor_assert(service);
tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *,
intro_point,
if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
return intro_point;
});
return NULL;
}
static rend_intro_point_t *
find_intro_point(origin_circuit_t *circ)
{
const char *serviceid;
rend_service_t *service = NULL;
tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
tor_assert(circ->rend_data);
serviceid = rend_data_get_address(circ->rend_data);
SMARTLIST_FOREACH(rend_service_list, rend_service_t *, s,
if (tor_memeq(s->service_id, serviceid, REND_SERVICE_ID_LEN_BASE32)) {
service = s;
break;
});
if (service == NULL) return NULL;
SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro_point,
if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
return intro_point;
});
return NULL;
}
void
directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
smartlist_t *descs, smartlist_t *hs_dirs,
const char *service_id, int seconds_valid)
{
int i, j, failed_upload = 0;
smartlist_t *responsible_dirs = smartlist_new();
smartlist_t *successful_uploads = smartlist_new();
routerstatus_t *hs_dir;
for (i = 0; i < smartlist_len(descs); i++) {
rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
if (hs_dirs && smartlist_len(hs_dirs) > 0) {
smartlist_add_all(responsible_dirs, hs_dirs);
} else {
if (hid_serv_get_responsible_directories(responsible_dirs,
desc->desc_id) < 0) {
log_warn(LD_REND, "Could not determine the responsible hidden service "
"directories to post descriptors to.");
control_event_hs_descriptor_upload(service_id,
"UNKNOWN",
"UNKNOWN", NULL);
goto done;
}
}
for (j = 0; j < smartlist_len(responsible_dirs); j++) {
char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
char *hs_dir_ip;
const node_t *node;
rend_data_t *rend_data;
hs_dir = smartlist_get(responsible_dirs, j);
if (smartlist_contains_digest(renddesc->successful_uploads,
hs_dir->identity_digest))
continue;
node = node_get_by_id(hs_dir->identity_digest);
if (!node || !node_has_preferred_descriptor(node,0)) {
log_info(LD_REND, "Not launching upload for for v2 descriptor to "
"hidden service directory %s; we don't have its "
"router descriptor. Queuing for later upload.",
safe_str_client(routerstatus_describe(hs_dir)));
failed_upload = -1;
continue;
}
rend_data = rend_data_client_create(service_id, desc->desc_id, NULL,
REND_NO_AUTH);
directory_request_t *req =
directory_request_new(DIR_PURPOSE_UPLOAD_RENDDESC_V2);
directory_request_set_routerstatus(req, hs_dir);
directory_request_set_indirection(req, DIRIND_ANONYMOUS);
directory_request_set_payload(req,
desc->desc_str, strlen(desc->desc_str));
directory_request_set_rend_query(req, rend_data);
directory_initiate_request(req);
directory_request_free(req);
rend_data_free(rend_data);
base32_encode(desc_id_base32, sizeof(desc_id_base32),
desc->desc_id, DIGEST_LEN);
hs_dir_ip = tor_dup_ip(hs_dir->addr);
if (hs_dir_ip) {
log_info(LD_REND, "Launching upload for v2 descriptor for "
"service '%s' with descriptor ID '%s' with validity "
"of %d seconds to hidden service directory '%s' on "
"%s:%d.",
safe_str_client(service_id),
safe_str_client(desc_id_base32),
seconds_valid,
hs_dir->nickname,
hs_dir_ip,
hs_dir->or_port);
tor_free(hs_dir_ip);
}
control_event_hs_descriptor_upload(service_id,
hs_dir->identity_digest,
desc_id_base32, NULL);
if (!smartlist_contains_digest(successful_uploads,
hs_dir->identity_digest))
smartlist_add(successful_uploads, hs_dir->identity_digest);
}
smartlist_clear(responsible_dirs);
}
if (!failed_upload) {
if (renddesc->successful_uploads) {
SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
smartlist_free(renddesc->successful_uploads);
renddesc->successful_uploads = NULL;
}
renddesc->all_uploads_performed = 1;
} else {
if (!renddesc->successful_uploads)
renddesc->successful_uploads = smartlist_new();
SMARTLIST_FOREACH(successful_uploads, const char *, c, {
if (!smartlist_contains_digest(renddesc->successful_uploads, c)) {
char *hsdir_id = tor_memdup(c, DIGEST_LEN);
smartlist_add(renddesc->successful_uploads, hsdir_id);
}
});
}
done:
smartlist_free(responsible_dirs);
smartlist_free(successful_uploads);
}
static void
upload_service_descriptor(rend_service_t *service)
{
time_t now = time(NULL);
int rendpostperiod;
char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
int uploaded = 0;
rendpostperiod = get_options()->RendPostPeriod;
networkstatus_t *c = networkstatus_get_latest_consensus();
if (c && smartlist_len(c->routerstatus_list) > 0) {
int seconds_valid, i, j, num_descs;
smartlist_t *descs = smartlist_new();
smartlist_t *client_cookies = smartlist_new();
num_descs = service->auth_type == REND_STEALTH_AUTH ?
smartlist_len(service->clients) : 1;
for (j = 0; j < num_descs; j++) {
crypto_pk_t *client_key = NULL;
rend_authorized_client_t *client = NULL;
smartlist_clear(client_cookies);
switch (service->auth_type) {
case REND_NO_AUTH:
break;
case REND_BASIC_AUTH:
SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
cl, smartlist_add(client_cookies, cl->descriptor_cookie));
break;
case REND_STEALTH_AUTH:
client = smartlist_get(service->clients, j);
client_key = client->client_key;
smartlist_add(client_cookies, client->descriptor_cookie);
break;
}
seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
now, 0,
service->auth_type,
client_key,
client_cookies);
if (seconds_valid < 0) {
log_warn(LD_BUG, "Internal error: couldn't encode service "
"descriptor; not uploading.");
smartlist_free(descs);
smartlist_free(client_cookies);
return;
}
rend_get_service_id(service->desc->pk, serviceid);
if (get_options()->PublishHidServDescriptors) {
log_info(LD_REND, "Launching upload for hidden service %s",
serviceid);
directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
seconds_valid);
}
for (i = 0; i < smartlist_len(descs); i++)
rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
smartlist_clear(descs);
if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
> rendpostperiod)
service->next_upload_time = now + rendpostperiod;
else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
service->next_upload_time = now + seconds_valid + 1;
else
service->next_upload_time = now + seconds_valid -
REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
now, 1,
service->auth_type,
client_key,
client_cookies);
if (seconds_valid < 0) {
log_warn(LD_BUG, "Internal error: couldn't encode service "
"descriptor; not uploading.");
smartlist_free(descs);
smartlist_free(client_cookies);
return;
}
if (get_options()->PublishHidServDescriptors) {
directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
seconds_valid);
}
for (i = 0; i < smartlist_len(descs); i++)
rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
smartlist_clear(descs);
}
}
smartlist_free(descs);
smartlist_free(client_cookies);
uploaded = 1;
if (get_options()->PublishHidServDescriptors) {
log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
} else {
log_info(LD_REND, "Successfully stored created v2 rend descriptors!");
}
}
if (!uploaded)
service->next_upload_time = now + 60;
service->desc_is_dirty = 0;
}
static int
intro_point_accepted_intro_count(rend_intro_point_t *intro)
{
return intro->accepted_introduce2_count;
}
static int
intro_point_should_expire_now(rend_intro_point_t *intro,
time_t now)
{
tor_assert(intro != NULL);
if (intro->time_published == -1) {
return 0;
}
if (intro_point_accepted_intro_count(intro) >=
intro->max_introductions) {
return 1;
}
if (intro->time_to_expire == -1) {
int intro_point_lifetime_seconds =
crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS,
INTRO_POINT_LIFETIME_MAX_SECONDS);
intro->time_to_expire = now + intro_point_lifetime_seconds;
return 0;
}
return (now >= intro->time_to_expire);
}
static void
remove_invalid_intro_points(rend_service_t *service,
smartlist_t *exclude_nodes,
smartlist_t *retry_nodes, time_t now)
{
tor_assert(service);
SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
intro) {
origin_circuit_t *intro_circ =
find_intro_circuit(intro, service->pk_digest);
if (intro_circ) {
continue;
}
SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
rend_intro_point_free(intro);
} SMARTLIST_FOREACH_END(intro);
SMARTLIST_FOREACH_BEGIN(service->intro_nodes, rend_intro_point_t *,
intro) {
const node_t *node =
node_get_by_id(intro->extend_info->identity_digest);
origin_circuit_t *intro_circ =
find_intro_circuit(intro, service->pk_digest);
if (node && exclude_nodes) {
smartlist_add(exclude_nodes, (void*) node);
}
if (intro_circ == NULL) {
log_info(LD_REND, "Attempting to retry on %s as intro point for %s"
" (circuit disappeared).",
safe_str_client(extend_info_describe(intro->extend_info)),
safe_str_client(service->service_id));
intro->circuit_established = 0;
if (node == NULL ||
intro->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES) {
rend_intro_point_free(intro);
SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
continue;
}
if (retry_nodes) {
smartlist_add(retry_nodes, intro);
}
}
if (intro_point_should_expire_now(intro, now)) {
log_info(LD_REND, "Expiring %s as intro point for %s.",
safe_str_client(extend_info_describe(intro->extend_info)),
safe_str_client(service->service_id));
if (retry_nodes) {
smartlist_remove(retry_nodes, intro);
}
smartlist_add(service->expiring_nodes, intro);
SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
intro->circuit_established = 0;
}
} SMARTLIST_FOREACH_END(intro);
}
void
rend_service_desc_has_uploaded(const rend_data_t *rend_data)
{
rend_service_t *service;
const char *onion_address;
tor_assert(rend_data);
onion_address = rend_data_get_address(rend_data);
service = rend_service_get_by_service_id(onion_address);
if (service == NULL) {
return;
}
SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
intro) {
origin_circuit_t *intro_circ =
find_intro_circuit(intro, service->pk_digest);
if (intro_circ != NULL) {
circuit_mark_for_close(TO_CIRCUIT(intro_circ),
END_CIRC_REASON_FINISHED);
}
SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
rend_intro_point_free(intro);
} SMARTLIST_FOREACH_END(intro);
}
static int
rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted)
{
tor_assert(n_intro_points_wanted <= NUM_INTRO_POINTS_MAX);
return ((n_intro_points_wanted + NUM_INTRO_POINTS_EXTRA) * 2);
}
void
rend_consider_services_intro_points(time_t now)
{
int i;
const or_options_t *options = get_options();
const int allow_direct = rend_service_allow_non_anonymous_connection(
get_options());
smartlist_t *exclude_nodes;
smartlist_t *retry_nodes;
if (!have_completed_a_circuit())
return;
exclude_nodes = smartlist_new();
retry_nodes = smartlist_new();
SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, service) {
int r;
unsigned int n_intro_points_to_open;
unsigned int intro_nodes_len;
smartlist_clear(exclude_nodes);
smartlist_clear(retry_nodes);
remove_invalid_intro_points(service, exclude_nodes, retry_nodes, now);
if (now > service->intro_period_started + INTRO_CIRC_RETRY_PERIOD) {
rend_log_intro_limit(service, LOG_INFO);
service->intro_period_started = now;
service->n_intro_circuits_launched = 0;
} else if (service->n_intro_circuits_launched >=
rend_max_intro_circs_per_period(
service->n_intro_points_wanted)) {
rend_log_intro_limit(service, LOG_WARN);
continue;
}
SMARTLIST_FOREACH_BEGIN(retry_nodes, rend_intro_point_t *, intro) {
r = rend_service_launch_establish_intro(service, intro);
if (r < 0) {
log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
safe_str_client(extend_info_describe(intro->extend_info)),
safe_str_client(service->service_id));
smartlist_remove(service->intro_nodes, intro);
rend_intro_point_free(intro);
continue;
}
intro->circuit_retries++;
} SMARTLIST_FOREACH_END(intro);
intro_nodes_len = (unsigned int) smartlist_len(service->intro_nodes);
if (intro_nodes_len >= service->n_intro_points_wanted) {
continue;
}
n_intro_points_to_open = service->n_intro_points_wanted - intro_nodes_len;
if (intro_nodes_len == 0) {
n_intro_points_to_open += NUM_INTRO_POINTS_EXTRA;
}
for (i = 0; i < (int) n_intro_points_to_open; i++) {
const node_t *node;
rend_intro_point_t *intro;
router_crn_flags_t flags = CRN_NEED_UPTIME|CRN_NEED_DESC;
router_crn_flags_t direct_flags = flags;
direct_flags |= CRN_PREF_ADDR;
direct_flags |= CRN_DIRECT_CONN;
node = router_choose_random_node(exclude_nodes,
options->ExcludeNodes,
allow_direct ? direct_flags : flags);
if (allow_direct && !node) {
log_info(LD_REND,
"Unable to find an intro point that we can connect to "
"directly for %s, falling back to a 3-hop path.",
safe_str_client(service->service_id));
node = router_choose_random_node(exclude_nodes,
options->ExcludeNodes, flags);
}
if (!node) {
log_warn(LD_REND,
"We only have %d introduction points established for %s; "
"wanted %u.",
smartlist_len(service->intro_nodes),
safe_str_client(service->service_id),
n_intro_points_to_open);
break;
}
smartlist_add(exclude_nodes, (void*)node);
intro = tor_malloc_zero(sizeof(rend_intro_point_t));
intro->extend_info = extend_info_from_node(node, 0);
if (BUG(intro->extend_info == NULL)) {
tor_free(intro);
break;
}
intro->intro_key = crypto_pk_new();
const int fail = crypto_pk_generate_key(intro->intro_key);
tor_assert(!fail);
intro->time_published = -1;
intro->time_to_expire = -1;
intro->max_introductions =
crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
smartlist_add(service->intro_nodes, intro);
log_info(LD_REND, "Picked router %s as an intro point for %s.",
safe_str_client(node_describe(node)),
safe_str_client(service->service_id));
r = rend_service_launch_establish_intro(service, intro);
if (r < 0) {
log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
safe_str_client(extend_info_describe(intro->extend_info)),
safe_str_client(service->service_id));
}
}
} SMARTLIST_FOREACH_END(service);
smartlist_free(exclude_nodes);
smartlist_free(retry_nodes);
}
#define MIN_REND_INITIAL_POST_DELAY (30)
#define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
void
rend_consider_services_upload(time_t now)
{
int i;
rend_service_t *service;
const or_options_t *options = get_options();
int rendpostperiod = options->RendPostPeriod;
int rendinitialpostdelay = (options->TestingTorNetwork ?
MIN_REND_INITIAL_POST_DELAY_TESTING :
MIN_REND_INITIAL_POST_DELAY);
for (i=0; i < smartlist_len(rend_service_list); ++i) {
service = smartlist_get(rend_service_list, i);
if (!service->next_upload_time) {
service->next_upload_time =
now + rendinitialpostdelay + crypto_rand_int(2*rendpostperiod);
if (rend_service_reveal_startup_time(options)) {
service->next_upload_time = now + rendinitialpostdelay;
}
}
unsigned int intro_points_ready =
count_established_intro_points(service) >=
service->n_intro_points_wanted;
if (intro_points_ready &&
(service->next_upload_time < now ||
(service->desc_is_dirty &&
service->desc_is_dirty < now-rendinitialpostdelay))) {
rend_service_update_descriptor(service);
upload_service_descriptor(service);
}
}
}
static int consider_republishing_rend_descriptors = 1;
void
rend_hsdir_routers_changed(void)
{
consider_republishing_rend_descriptors = 1;
}
void
rend_consider_descriptor_republication(void)
{
int i;
rend_service_t *service;
if (!consider_republishing_rend_descriptors)
return;
consider_republishing_rend_descriptors = 0;
if (!get_options()->PublishHidServDescriptors)
return;
for (i=0; i < smartlist_len(rend_service_list); ++i) {
service = smartlist_get(rend_service_list, i);
if (service->desc && !service->desc->all_uploads_performed) {
upload_service_descriptor(service);
}
}
}
void
rend_service_dump_stats(int severity)
{
rend_service_t *service;
rend_intro_point_t *intro;
const char *safe_name;
origin_circuit_t *circ;
for (int i = 0; i < smartlist_len(rend_service_list); ++i) {
service = smartlist_get(rend_service_list, i);
tor_log(severity, LD_GENERAL, "Service configured in %s:",
rend_service_escaped_dir(service));
for (int j = 0; j < smartlist_len(service->intro_nodes); ++j) {
intro = smartlist_get(service->intro_nodes, j);
safe_name = safe_str_client(intro->extend_info->nickname);
circ = find_intro_circuit(intro, service->pk_digest);
if (!circ) {
tor_log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
j, safe_name);
continue;
}
tor_log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
j, safe_name, circuit_state_to_string(circ->base_.state));
}
}
}
int
rend_service_set_connection_addr_port(edge_connection_t *conn,
origin_circuit_t *circ)
{
rend_service_t *service;
char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
const char *rend_pk_digest;
tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
tor_assert(circ->rend_data);
log_debug(LD_REND,"beginning to hunt for addr/port");
rend_pk_digest = (char *) rend_data_get_pk_digest(circ->rend_data, NULL);
base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
rend_pk_digest, REND_SERVICE_ID_LEN);
service = rend_service_get_by_pk_digest(rend_pk_digest);
if (!service) {
log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
"rendezvous circuit %u; closing.",
serviceid, (unsigned)circ->base_.n_circ_id);
return -2;
}
if (service->max_streams_per_circuit > 0) {
#define MAX_STREAM_WARN_INTERVAL 600
static struct ratelim_t stream_ratelim =
RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
if (circ->rend_data->nr_streams >= service->max_streams_per_circuit) {
log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
"Maximum streams per circuit limit reached on rendezvous "
"circuit %u; %s. Circuit has %d out of %d streams.",
(unsigned)circ->base_.n_circ_id,
service->max_streams_close_circuit ?
"closing circuit" :
"ignoring open stream request",
circ->rend_data->nr_streams,
service->max_streams_per_circuit);
return service->max_streams_close_circuit ? -2 : -1;
}
}
if (hs_set_conn_addr_port(service->ports, conn) == 0) {
return 0;
}
log_info(LD_REND,
"No virtual port mapping exists for port %d on service %s",
conn->base_.port, serviceid);
if (service->allow_unknown_ports)
return -1;
else
return -2;
}
static int
rend_service_non_anonymous_mode_consistent(const or_options_t *options)
{
return (!! options->HiddenServiceSingleHopMode ==
!! options->HiddenServiceNonAnonymousMode);
}
int
rend_service_allow_non_anonymous_connection(const or_options_t *options)
{
tor_assert(rend_service_non_anonymous_mode_consistent(options));
return options->HiddenServiceSingleHopMode ? 1 : 0;
}
int
rend_service_reveal_startup_time(const or_options_t *options)
{
tor_assert(rend_service_non_anonymous_mode_consistent(options));
return rend_service_non_anonymous_mode_enabled(options);
}
int
rend_service_non_anonymous_mode_enabled(const or_options_t *options)
{
tor_assert(rend_service_non_anonymous_mode_consistent(options));
return options->HiddenServiceNonAnonymousMode ? 1 : 0;
}
#ifdef TOR_UNIT_TESTS
STATIC void
set_rend_service_list(smartlist_t *new_list)
{
rend_service_list = new_list;
}
STATIC void
set_rend_rend_service_staging_list(smartlist_t *new_list)
{
rend_service_staging_list = new_list;
}
#endif