Example #1
0
static void
test_crypto_curve25519_persist(void *arg)
{
  curve25519_keypair_t keypair, keypair2;
  char *fname = tor_strdup(get_fname("curve25519_keypair"));
  char *tag = NULL;
  char *content = NULL;
  const char *cp;
  struct stat st;
  size_t taglen;

  (void)arg;

  tt_int_op(0,==,curve25519_keypair_generate(&keypair, 0));

  tt_int_op(0,==,curve25519_keypair_write_to_file(&keypair, fname, "testing"));
  tt_int_op(0,==,curve25519_keypair_read_from_file(&keypair2, &tag, fname));
  tt_str_op(tag,==,"testing");
  tor_free(tag);

  test_memeq(keypair.pubkey.public_key,
             keypair2.pubkey.public_key,
             CURVE25519_PUBKEY_LEN);
  test_memeq(keypair.seckey.secret_key,
             keypair2.seckey.secret_key,
             CURVE25519_SECKEY_LEN);

  content = read_file_to_str(fname, RFTS_BIN, &st);
  tt_assert(content);
  taglen = strlen("== c25519v1: testing ==");
  tt_int_op(st.st_size, ==, 32+CURVE25519_PUBKEY_LEN+CURVE25519_SECKEY_LEN);
  tt_assert(fast_memeq(content, "== c25519v1: testing ==", taglen));
  tt_assert(tor_mem_is_zero(content+taglen, 32-taglen));
  cp = content + 32;
  test_memeq(keypair.seckey.secret_key,
             cp,
             CURVE25519_SECKEY_LEN);
  cp += CURVE25519_SECKEY_LEN;
  test_memeq(keypair.pubkey.public_key,
             cp,
             CURVE25519_SECKEY_LEN);

  tor_free(fname);
  fname = tor_strdup(get_fname("bogus_keypair"));

  tt_int_op(-1, ==, curve25519_keypair_read_from_file(&keypair2, &tag, fname));
  tor_free(tag);

  content[69] ^= 0xff;
  tt_int_op(0, ==, write_bytes_to_file(fname, content, (size_t)st.st_size, 1));
  tt_int_op(-1, ==, curve25519_keypair_read_from_file(&keypair2, &tag, fname));

 done:
  tor_free(fname);
  tor_free(content);
  tor_free(tag);
}
Example #2
0
static void
test_ext_or_init_auth(void *arg)
{
  or_options_t *options = get_options_mutable();
  const char *fn;
  char *cp = NULL;
  struct stat st;
  char cookie0[32];
  (void)arg;

  /* Check default filename location */
  tor_free(options->DataDirectory);
  options->DataDirectory = tor_strdup("foo");
  cp = get_ext_or_auth_cookie_file_name();
  tt_str_op(cp, OP_EQ, "foo"PATH_SEPARATOR"extended_orport_auth_cookie");
  tor_free(cp);

  /* Shouldn't be initialized already, or our tests will be a bit
   * meaningless */
  ext_or_auth_cookie = tor_malloc_zero(32);
  tt_assert(tor_mem_is_zero((char*)ext_or_auth_cookie, 32));

  /* Now make sure we use a temporary file */
  fn = get_fname("ext_cookie_file");
  options->ExtORPortCookieAuthFile = tor_strdup(fn);
  cp = get_ext_or_auth_cookie_file_name();
  tt_str_op(cp, OP_EQ, fn);
  tor_free(cp);

  /* Test the initialization function with a broken
     write_bytes_to_file(). See if the problem is handled properly. */
  MOCK(write_bytes_to_file, write_bytes_to_file_fail);
  tt_int_op(-1, OP_EQ, init_ext_or_cookie_authentication(1));
  tt_int_op(ext_or_auth_cookie_is_set, OP_EQ, 0);
  UNMOCK(write_bytes_to_file);

  /* Now do the actual initialization. */
  tt_int_op(0, OP_EQ, init_ext_or_cookie_authentication(1));
  tt_int_op(ext_or_auth_cookie_is_set, OP_EQ, 1);
  cp = read_file_to_str(fn, RFTS_BIN, &st);
  tt_ptr_op(cp, OP_NE, NULL);
  tt_u64_op((uint64_t)st.st_size, OP_EQ, 64);
  tt_mem_op(cp,OP_EQ, "! Extended ORPort Auth Cookie !\x0a", 32);
  tt_mem_op(cp+32,OP_EQ, ext_or_auth_cookie, 32);
  memcpy(cookie0, ext_or_auth_cookie, 32);
  tt_assert(!tor_mem_is_zero((char*)ext_or_auth_cookie, 32));

  /* Operation should be idempotent. */
  tt_int_op(0, OP_EQ, init_ext_or_cookie_authentication(1));
  tt_mem_op(cookie0,OP_EQ, ext_or_auth_cookie, 32);

 done:
  tor_free(cp);
  ext_orport_free_all();
}
Example #3
0
/* Test helper function: Make sure that a bridge line gets parsed
 * properly. Also make sure that the resulting bridge_line_t structure
 * has its fields set correctly. */
static void
good_bridge_line_test(const char *string, const char *test_addrport,
                      const char *test_digest, const char *test_transport,
                      const smartlist_t *test_socks_args)
{
  char *tmp = NULL;
  bridge_line_t *bridge_line = parse_bridge_line(string);
  test_assert(bridge_line);

  /* test addrport */
  tmp = tor_strdup(fmt_addrport(&bridge_line->addr, bridge_line->port));
  test_streq(test_addrport, tmp);
  tor_free(tmp);

  /* If we were asked to validate a digest, but we did not get a
     digest after parsing, we failed. */
  if (test_digest && tor_digest_is_zero(bridge_line->digest))
    test_assert(0);

  /* If we were not asked to validate a digest, and we got a digest
     after parsing, we failed again. */
  if (!test_digest && !tor_digest_is_zero(bridge_line->digest))
    test_assert(0);

  /* If we were asked to validate a digest, and we got a digest after
     parsing, make sure it's correct. */
  if (test_digest) {
    tmp = tor_strdup(hex_str(bridge_line->digest, DIGEST_LEN));
    tor_strlower(tmp);
    test_streq(test_digest, tmp);
    tor_free(tmp);
  }

  /* If we were asked to validate a transport name, make sure tha it
     matches with the transport name that was parsed. */
  if (test_transport && !bridge_line->transport_name)
    test_assert(0);
  if (!test_transport && bridge_line->transport_name)
    test_assert(0);
  if (test_transport)
    test_streq(test_transport, bridge_line->transport_name);

  /* Validate the SOCKS argument smartlist. */
  if (test_socks_args && !bridge_line->socks_args)
    test_assert(0);
  if (!test_socks_args && bridge_line->socks_args)
    test_assert(0);
  if (test_socks_args)
    test_assert(smartlist_strings_eq(test_socks_args,
                                     bridge_line->socks_args));

 done:
  tor_free(tmp);
  bridge_line_free(bridge_line);
}
Example #4
0
/** Helper: parse the config string and strdup into key/value
 * strings. Set *result to the list, or NULL if parsing the string
 * failed.  Return 0 on success, -1 on failure. Warn and ignore any
 * misformatted lines.
 *
 * If <b>extended</b> is set, then treat keys beginning with / and with + as
 * indicating "clear" and "append" respectively. */
int
config_get_lines(const char *string, config_line_t **result, int extended)
{
  config_line_t *list = NULL, **next;
  char *k, *v;
  const char *parse_err;

  next = &list;
  do {
    k = v = NULL;
    string = parse_config_line_from_str_verbose(string, &k, &v, &parse_err);
    if (!string) {
      log_warn(LD_CONFIG, "Error while parsing configuration: %s",
               parse_err?parse_err:"<unknown>");
      config_free_lines(list);
      tor_free(k);
      tor_free(v);
      return -1;
    }
    if (k && v) {
      unsigned command = CONFIG_LINE_NORMAL;
      if (extended) {
        if (k[0] == '+') {
          char *k_new = tor_strdup(k+1);
          tor_free(k);
          k = k_new;
          command = CONFIG_LINE_APPEND;
        } else if (k[0] == '/') {
          char *k_new = tor_strdup(k+1);
          tor_free(k);
          k = k_new;
          tor_free(v);
          v = tor_strdup("");
          command = CONFIG_LINE_CLEAR;
        }
      }
      /* This list can get long, so we keep a pointer to the end of it
       * rather than using config_line_append over and over and getting
       * n^2 performance. */
      *next = tor_malloc_zero(sizeof(config_line_t));
      (*next)->key = k;
      (*next)->value = v;
      (*next)->next = NULL;
      (*next)->command = command;
      next = &((*next)->next);
    } else {
      tor_free(k);
      tor_free(v);
    }
  } while (*string);

  *result = list;
  return 0;
}
static void
test_conn_edge_ap_handshake_rewrite_and_attach_closes_conn_for_excluded_exit(void *data)
{
  entry_connection_t *conn = entry_connection_new(CONN_TYPE_AP, AF_INET);
  addressmap_init();
  origin_circuit_t *circuit = NULL;
  crypt_path_t *path = NULL;
  (void) data;

  MOCK(get_options, get_options_mock);
  MOCK(connection_ap_handshake_rewrite, connection_ap_handshake_rewrite_mock);
  MOCK(connection_mark_unattached_ap_, connection_mark_unattached_ap_mock);
  MOCK(node_get_by_nickname, node_get_by_nickname_mock);

  init_rewrite_mock();
  init_exit_node_mock();
  init_mock_options();

  rewrite_mock->should_close = 0;
  rewrite_mock->exit_source = ADDRMAPSRC_NONE;
  SET_SOCKS_ADDRESS(conn->socks_request, "http://www.wellformed.exit");
  conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  strlcpy(exit_node_mock->rs->nickname, "wellformed", MAX_NICKNAME_LEN+1);

  options_mock->AllowDotExit = 1;
  options_mock->StrictNodes = 0;
  options_mock->SafeLogging_ = SAFELOG_SCRUB_NONE;

  excluded_nodes = routerset_new();
  smartlist_add(excluded_nodes->list, tor_strdup("wellformed"));
  strmap_set(excluded_nodes->names, tor_strdup("wellformed"), exit_node_mock);
  options_mock->ExcludeExitNodes = excluded_nodes;

  int prev_log = setup_capture_of_logs(LOG_INFO);
  int res = connection_ap_handshake_rewrite_and_attach(conn, circuit, path);

  tt_int_op(unattachment_reason_spy, OP_EQ, END_STREAM_REASON_TORPROTOCOL);
  tt_int_op(res, OP_EQ, -1);
  tt_str_op(mock_saved_log_at(-1), OP_EQ, "Excluded relay in exit address 'http://www.exit'. Refusing.\n");

  done:
    UNMOCK(get_options);
    UNMOCK(connection_ap_handshake_rewrite);
    UNMOCK(connection_mark_unattached_ap_);
    UNMOCK(node_get_by_nickname);

    destroy_rewrite_mock();
    destroy_mock_options();
    destroy_exit_node_mock();
    tor_free(excluded_nodes);
    tor_free(circuit);
    tor_free(path);
    teardown_capture_of_logs(prev_log);
}
Example #6
0
static void
test_pt_get_transport_options(void *arg)
{
  char **execve_args;
  smartlist_t *transport_list = smartlist_new();
  managed_proxy_t *mp;
  or_options_t *options = get_options_mutable();
  char *opt_str = NULL;
  config_line_t *cl = NULL;
  (void)arg;

  execve_args = tor_malloc(sizeof(char*)*2);
  execve_args[0] = tor_strdup("cheeseshop");
  execve_args[1] = NULL;

  mp = managed_proxy_create(transport_list, execve_args, 1);
  tt_ptr_op(mp, OP_NE, NULL);
  opt_str = get_transport_options_for_server_proxy(mp);
  tt_ptr_op(opt_str, OP_EQ, NULL);

  smartlist_add_strdup(mp->transports_to_launch, "gruyere");
  smartlist_add_strdup(mp->transports_to_launch, "roquefort");
  smartlist_add_strdup(mp->transports_to_launch, "stnectaire");

  tt_assert(options);

  cl = tor_malloc_zero(sizeof(config_line_t));
  cl->value = tor_strdup("gruyere melty=10 hardness=se;ven");
  options->ServerTransportOptions = cl;

  cl = tor_malloc_zero(sizeof(config_line_t));
  cl->value = tor_strdup("stnectaire melty=4 hardness=three");
  cl->next = options->ServerTransportOptions;
  options->ServerTransportOptions = cl;

  cl = tor_malloc_zero(sizeof(config_line_t));
  cl->value = tor_strdup("pepperjack melty=12 hardness=five");
  cl->next = options->ServerTransportOptions;
  options->ServerTransportOptions = cl;

  opt_str = get_transport_options_for_server_proxy(mp);
  tt_str_op(opt_str, OP_EQ,
            "gruyere:melty=10;gruyere:hardness=se\\;ven;"
            "stnectaire:melty=4;stnectaire:hardness=three");

 done:
  tor_free(opt_str);
  config_free_lines(cl);
  managed_proxy_destroy(mp, 0);
  smartlist_free(transport_list);
}
Example #7
0
/** Helper function: called whenever the client sends a resolve request to our
 * controller.  We need to eventually answer the request <b>req</b>.
 * Returns 0 if the controller will be getting (or has gotten) an event in
 * response; -1 if we couldn't launch the request.
 */
int
dnsserv_launch_request(const char *name, int reverse)
{
  entry_connection_t *entry_conn;
  edge_connection_t *conn;
  char *q_name;

  /* Make a new dummy AP connection, and attach the request to it. */
  entry_conn = entry_connection_new(CONN_TYPE_AP, AF_INET);
  conn = ENTRY_TO_EDGE_CONN(entry_conn);
  conn->base_.state = AP_CONN_STATE_RESOLVE_WAIT;

  if (reverse)
    entry_conn->socks_request->command = SOCKS_COMMAND_RESOLVE_PTR;
  else
    entry_conn->socks_request->command = SOCKS_COMMAND_RESOLVE;

  conn->is_dns_request = 1;

  strlcpy(entry_conn->socks_request->address, name,
          sizeof(entry_conn->socks_request->address));

  entry_conn->socks_request->listener_type = CONN_TYPE_CONTROL_LISTENER;
  entry_conn->original_dest_address = tor_strdup(name);
  entry_conn->session_group = SESSION_GROUP_CONTROL_RESOLVE;
  entry_conn->nym_epoch = get_signewnym_epoch();
  entry_conn->isolation_flags = ISO_DEFAULT;

  if (connection_add(TO_CONN(conn))<0) {
    log_warn(LD_APP, "Couldn't register dummy connection for RESOLVE request");
    connection_free(TO_CONN(conn));
    return -1;
  }

  /* Now, unless a controller asked us to leave streams unattached,
  * throw the connection over to get rewritten (which will
  * answer it immediately if it's in the cache, or completely bogus, or
  * automapped), and then attached to a circuit. */
  log_info(LD_APP, "Passing request for %s to rewrite_and_attach.",
           escaped_safe_str_client(name));
  q_name = tor_strdup(name); /* q could be freed in rewrite_and_attach */
  connection_ap_rewrite_and_attach_if_allowed(entry_conn, NULL, NULL);
  /* Now, the connection is marked if it was bad. */

  log_info(LD_APP, "Passed request for %s to rewrite_and_attach_if_allowed.",
           escaped_safe_str_client(q_name));
  tor_free(q_name);
  return 0;
}
Example #8
0
static dir_connection_t *
test_conn_download_status_add_a_connection(const char *resource)
{
  dir_connection_t *conn = DOWNCAST(dir_connection_t,
                                    test_conn_get_connection(
                                                      TEST_CONN_STATE,
                                                      TEST_CONN_TYPE,
                                                      TEST_CONN_RSRC_PURPOSE));

  tt_assert(conn);
  assert_connection_ok(&conn->base_, time(NULL));

  /* Replace the existing resource with the one we want */
  if (resource) {
    if (conn->requested_resource) {
      tor_free(conn->requested_resource);
    }
    conn->requested_resource = tor_strdup(resource);
    assert_connection_ok(&conn->base_, time(NULL));
  }

  return conn;

 done:
  test_conn_get_rsrc_teardown(NULL, conn);
  return NULL;
}
Example #9
0
static void
test_storagedir_empty(void *arg)
{
  char *dirname = tor_strdup(get_fname_rnd("store_dir"));
  storage_dir_t *d = NULL;
  (void)arg;

  tt_int_op(FN_NOENT, OP_EQ, file_status(dirname));

  d = storage_dir_new(dirname, 10);
  tt_assert(d);

  tt_int_op(FN_DIR, OP_EQ, file_status(dirname));

  tt_int_op(0, OP_EQ, smartlist_len(storage_dir_list(d)));
  tt_u64_op(0, OP_EQ, storage_dir_get_usage(d));

  storage_dir_free(d);
  d = storage_dir_new(dirname, 10);
  tt_assert(d);

  tt_int_op(FN_DIR, OP_EQ, file_status(dirname));

  tt_int_op(0, OP_EQ, smartlist_len(storage_dir_list(d)));
  tt_u64_op(0, OP_EQ, storage_dir_get_usage(d));

 done:
  storage_dir_free(d);
  tor_free(dirname);
}
Example #10
0
static void
NS(test_main)(void *arg)
{
  routerset_t *set = NULL;
  int is_empty;
  (void)arg;

  is_empty = routerset_is_empty(set);
  tt_int_op(is_empty, !=, 0);

  set = routerset_new();
  is_empty = routerset_is_empty(set);
  routerset_free(set);
  set = NULL;
  tt_int_op(is_empty, !=, 0);

  set = routerset_new();
  smartlist_add(set->list, tor_strdup("{xx}"));
  is_empty = routerset_is_empty(set);
  routerset_free(set);
  set = NULL;
  tt_int_op(is_empty, ==, 0);

  done:
    ;
}
Example #11
0
static void
NS(test_main)(void *arg)
{
  smartlist_t *out = smartlist_new();
  routerset_t *set = routerset_new();
  int out_len;
  node_t *ent;
  (void)arg;

  NS_MOCK(node_get_by_nickname);

  NS(mock_nickname) = tor_strdup("foo");
  smartlist_add(set->list, NS(mock_nickname));

  routerset_get_all_nodes(out, set, NULL, 0);
  out_len = smartlist_len(out);
  ent = (node_t *)smartlist_get(out, 0);

  smartlist_free(out);
  routerset_free(set);

  tt_int_op(out_len, ==, 1);
  tt_ptr_op(ent, ==, &NS(mock_node));
  tt_int_op(CALLED(node_get_by_nickname), ==, 1);

  done:
    ;
}
Example #12
0
static void
NS(test_main)(void *arg)
{
  routerset_t *set = routerset_new();
  smartlist_t *out = smartlist_new();
  int r;
  (void)arg;

  NS_MOCK(nodelist_get_list);

  smartlist_add(set->country_names, tor_strdup("{xx}"));
  NS(mock_smartlist) = smartlist_new();
  NS(mock_node).is_running = 0;
  smartlist_add(NS(mock_smartlist), (void *)&NS(mock_node));

  routerset_get_all_nodes(out, set, NULL, 1);
  r = smartlist_len(out);
  routerset_free(set);
  smartlist_free(out);
  smartlist_free(NS(mock_smartlist));

  tt_int_op(r, ==, 0);
  tt_int_op(CALLED(nodelist_get_list), ==, 1);

  done:
    ;
}
Example #13
0
static void
NS(test_main)(void *arg)
{
  smartlist_t *out = smartlist_new();
  routerset_t *set = routerset_new();
  int out_len;
  (void)arg;

  NS_MOCK(node_get_by_nickname);

  NS(mock_node).is_running = 0;
  NS(mock_nickname) = "foo";
  smartlist_add(set->list, tor_strdup(NS(mock_nickname)));

  routerset_get_all_nodes(out, set, NULL, 1);
  out_len = smartlist_len(out);

  smartlist_free(out);
  routerset_free(set);

  tt_int_op(out_len, ==, 0);
  tt_int_op(CALLED(node_get_by_nickname), ==, 1);

  done:
    ;
}
Example #14
0
static void
test_storagedir_full(void *arg)
{
  (void)arg;

  char *dirname = tor_strdup(get_fname_rnd("store_dir"));
  storage_dir_t *d = NULL;
  const char str[] = "enemies of the peephole";
  int r;

  d = storage_dir_new(dirname, 3);
  tt_assert(d);

  r = storage_dir_save_string_to_file(d, str, 1, NULL);
  tt_int_op(r, OP_EQ, 0);
  r = storage_dir_save_string_to_file(d, str, 1, NULL);
  tt_int_op(r, OP_EQ, 0);
  r = storage_dir_save_string_to_file(d, str, 1, NULL);
  tt_int_op(r, OP_EQ, 0);

  // These should fail!
  r = storage_dir_save_string_to_file(d, str, 1, NULL);
  tt_int_op(r, OP_EQ, -1);
  r = storage_dir_save_string_to_file(d, str, 1, NULL);
  tt_int_op(r, OP_EQ, -1);

  tt_u64_op(strlen(str) * 3, OP_EQ, storage_dir_get_usage(d));

 done:
  tor_free(dirname);
  storage_dir_free(d);
}
Example #15
0
static void
test_config_write_to_data_subdir(void *arg)
{
  or_options_t* options = get_options_mutable();
  char *datadir;
  char *cp = NULL;
  const char* subdir = "test_stats";
  const char* fname = "test_file";
  const char* str =
      "Lorem ipsum dolor sit amet, consetetur sadipscing\n"
      "elitr, sed diam nonumy eirmod\n"
      "tempor invidunt ut labore et dolore magna aliquyam\n"
      "erat, sed diam voluptua.\n"
      "At vero eos et accusam et justo duo dolores et ea\n"
      "rebum. Stet clita kasd gubergren,\n"
      "no sea takimata sanctus est Lorem ipsum dolor sit amet.\n"
      "Lorem ipsum dolor sit amet,\n"
      "consetetur sadipscing elitr, sed diam nonumy eirmod\n"
      "tempor invidunt ut labore et dolore\n"
      "magna aliquyam erat, sed diam voluptua. At vero eos et\n"
      "accusam et justo duo dolores et\n"
      "ea rebum. Stet clita kasd gubergren, no sea takimata\n"
      "sanctus est Lorem ipsum dolor sit amet.";
  char* filepath = NULL;
  (void)arg;

  tor_free(options->DataDirectory);
  datadir = options->DataDirectory = tor_strdup(get_fname("datadir-1"));
  filepath = get_datadir_fname2(subdir, fname);

#if defined (_WIN32)
  tt_int_op(mkdir(options->DataDirectory), ==, 0);
#else
  tt_int_op(mkdir(options->DataDirectory, 0700), ==, 0);
#endif

  // Write attempt shoudl fail, if subdirectory doesn't exist.
  test_assert(write_to_data_subdir(subdir, fname, str, NULL));
  test_assert(! check_or_create_data_subdir(subdir));

  // Content of file after write attempt should be
  // equal to the original string.
  test_assert(!write_to_data_subdir(subdir, fname, str, NULL));
  cp = read_file_to_str(filepath, 0, NULL);
  test_streq(cp, str);
  tor_free(cp);

  // A second write operation should overwrite the old content.
  test_assert(!write_to_data_subdir(subdir, fname, str, NULL));
  cp = read_file_to_str(filepath, 0, NULL);
  test_streq(cp, str);
  tor_free(cp);

 done:
  (void) unlink(filepath);
  rmdir(options->DataDirectory);
  tor_free(datadir);
  tor_free(filepath);
  tor_free(cp);
}
Example #16
0
static void
NS(test_main)(void *arg)
{
  int retval;
  int made_pending;
  const tor_addr_t *resolved_addr;
  tor_addr_t addr_to_compare;

  (void)arg;

  tor_addr_parse(&addr_to_compare, "8.8.8.8");

  or_circuit_t *on_circ = tor_malloc_zero(sizeof(or_circuit_t));

  edge_connection_t *exitconn = create_valid_exitconn();

  TO_CONN(exitconn)->address = tor_strdup("8.8.8.8");

  retval = dns_resolve_impl(exitconn, 1, on_circ, NULL, &made_pending,
                            NULL);

  resolved_addr = &(exitconn->base_.addr);

  tt_int_op(retval,OP_EQ,1);
  tt_assert(tor_addr_eq(resolved_addr, (const tor_addr_t *)&addr_to_compare));
  tt_int_op(exitconn->address_ttl,OP_EQ,DEFAULT_DNS_TTL);

  done:
  tor_free(on_circ);
  tor_free(TO_CONN(exitconn)->address);
  tor_free(exitconn);
  return;
}
Example #17
0
static void
NS(test_main)(void *arg)
{
  int retval;
  int made_pending;

  edge_connection_t *exitconn = create_valid_exitconn();
  or_circuit_t *on_circ = tor_malloc_zero(sizeof(or_circuit_t));

  (void)arg;

  NS_MOCK(router_my_exit_policy_is_reject_star);

  TO_CONN(exitconn)->address = tor_strdup("invalid#@!.org");

  retval = dns_resolve_impl(exitconn, 1, on_circ, NULL, &made_pending,
                            NULL);

  tt_int_op(retval,OP_EQ,-1);

  done:
  NS_UNMOCK(router_my_exit_policy_is_reject_star);
  tor_free(TO_CONN(exitconn)->address);
  tor_free(exitconn);
  tor_free(on_circ);
  return;
}
Example #18
0
int
sandbox_add_addrinfo(const char* name)
{
  int ret;
  struct addrinfo hints;
  sb_addr_info_t *el = NULL;

  el = tor_malloc(sizeof(sb_addr_info_t));

  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;

  ret = getaddrinfo(name, NULL, &hints, &(el->info));
  if (ret) {
    log_err(LD_BUG,"(Sandbox) failed to getaddrinfo");
    ret = -2;
    tor_free(el);
    goto out;
  }

  el->name = tor_strdup(name);
  el->next = sb_addr_info;
  sb_addr_info = el;

 out:
  return ret;
}
Example #19
0
/** Helper: allocate a new configuration option mapping 'key' to 'val',
 * append it to *<b>lst</b>. */
void
config_line_append(config_line_t **lst,
                   const char *key,
                   const char *val)
{
  config_line_t *newline;

  newline = tor_malloc_zero(sizeof(config_line_t));
  newline->key = tor_strdup(key);
  newline->value = tor_strdup(val);
  newline->next = NULL;
  while (*lst)
    lst = &((*lst)->next);

  (*lst) = newline;
}
Example #20
0
/** Helper: Make a new routerinfo containing the right information for a
 * given vote_routerstatus_t. */
routerinfo_t *
dir_common_generate_ri_from_rs(const vote_routerstatus_t *vrs)
{
  routerinfo_t *r;
  const routerstatus_t *rs = &vrs->status;
  static time_t published = 0;

  r = tor_malloc_zero(sizeof(routerinfo_t));
  r->cert_expiration_time = TIME_MAX;
  memcpy(r->cache_info.identity_digest, rs->identity_digest, DIGEST_LEN);
  memcpy(r->cache_info.signed_descriptor_digest, rs->descriptor_digest,
         DIGEST_LEN);
  r->cache_info.do_not_cache = 1;
  r->cache_info.routerlist_index = -1;
  r->cache_info.signed_descriptor_body =
    tor_strdup("123456789012345678901234567890123");
  r->cache_info.signed_descriptor_len =
    strlen(r->cache_info.signed_descriptor_body);
  r->exit_policy = smartlist_new();
  r->cache_info.published_on = ++published + time(NULL);
  if (rs->has_bandwidth) {
    /*
     * Multiply by 1000 because the routerinfo_t and the routerstatus_t
     * seem to use different units (*sigh*) and because we seem stuck on
     * icky and perverse decimal kilobytes (*double sigh*) - see
     * router_get_advertised_bandwidth_capped() of routerlist.c and
     * routerstatus_format_entry() of dirserv.c.
     */
    r->bandwidthrate = rs->bandwidth_kb * 1000;
    r->bandwidthcapacity = rs->bandwidth_kb * 1000;
  }
  return r;
}
Example #21
0
/* Create a new directory cache descriptor object from a encoded descriptor.
 * On success, return the heap-allocated cache object, otherwise return NULL if
 * we can't decode the descriptor. */
static hs_cache_dir_descriptor_t *
cache_dir_desc_new(const char *desc)
{
  hs_cache_dir_descriptor_t *dir_desc;

  tor_assert(desc);

  dir_desc = tor_malloc_zero(sizeof(hs_cache_dir_descriptor_t));
  dir_desc->plaintext_data =
    tor_malloc_zero(sizeof(hs_desc_plaintext_data_t));
  dir_desc->encoded_desc = tor_strdup(desc);

  if (hs_desc_decode_plaintext(desc, dir_desc->plaintext_data) < 0) {
    log_debug(LD_DIR, "Unable to decode descriptor. Rejecting.");
    goto err;
  }

  /* The blinded pubkey is the indexed key. */
  dir_desc->key = dir_desc->plaintext_data->blinded_pubkey.pubkey;
  dir_desc->created_ts = time(NULL);
  return dir_desc;

 err:
  cache_dir_desc_free(dir_desc);
  return NULL;
}
Example #22
0
static void
test_md_cache_broken(void *data)
{
  or_options_t *options;
  char *fn=NULL;
  microdesc_cache_t *mc = NULL;

  (void)data;

  options = get_options_mutable();
  tt_assert(options);
  tor_free(options->CacheDirectory);
  options->CacheDirectory = tor_strdup(get_fname("md_datadir_test2"));

#ifdef _WIN32
  tt_int_op(0, OP_EQ, mkdir(options->CacheDirectory));
#else
  tt_int_op(0, OP_EQ, mkdir(options->CacheDirectory, 0700));
#endif

  tor_asprintf(&fn, "%s"PATH_SEPARATOR"cached-microdescs",
               options->CacheDirectory);

  write_str_to_file(fn, truncated_md, 1);

  mc = get_microdesc_cache();
  tt_assert(mc);

 done:
  if (options)
    tor_free(options->CacheDirectory);
  tor_free(fn);
  microdesc_free_all();
}
Example #23
0
// Tests if an options with MyFamily fingerprints missing '$' normalises
// them correctly and also ensure it also works with multiple fingerprints
static void
test_config_fix_my_family(void *arg)
{
  char *err = NULL;
  const char *family = "$1111111111111111111111111111111111111111, "
                       "1111111111111111111111111111111111111112, "
                       "$1111111111111111111111111111111111111113";

  or_options_t* options = options_new();
  or_options_t* defaults = options_new();
  (void) arg;

  options_init(options);
  options_init(defaults);
  options->MyFamily = tor_strdup(family);

  options_validate(NULL, options, defaults, 0, &err) ;

  if (err != NULL) {
    TT_FAIL(("options_validate failed: %s", err));
  }

  test_streq(options->MyFamily, "$1111111111111111111111111111111111111111, "
                                "$1111111111111111111111111111111111111112, "
                                "$1111111111111111111111111111111111111113");

  done:
    if (err != NULL) {
      tor_free(err);
    }

    or_options_free(options);
    or_options_free(defaults);
}
Example #24
0
/** See dir_common_construct_vote_1.
 * Produces a vote with slightly different values.
 */
int
dir_common_construct_vote_2(networkstatus_t **vote, authority_cert_t *cert,
                        crypto_pk_t *sign_skey,
                        vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
                        networkstatus_t **vote_out, int *n_vrs,
                        time_t now, int clear_rl)
{
  networkstatus_voter_info_t *voter;

  dir_common_setup_vote(vote, now);
  (*vote)->type = NS_TYPE_VOTE;
  (*vote)->published += 1;
  (*vote)->valid_after = now+1000;
  (*vote)->fresh_until = now+3005;
  (*vote)->valid_until = now+3000;
  (*vote)->vote_seconds = 100;
  (*vote)->dist_seconds = 300;
  smartlist_split_string((*vote)->supported_methods, "1 2 3", NULL, 0, -1);
  smartlist_split_string((*vote)->known_flags,
                         "Authority Exit Fast Guard MadeOfCheese MadeOfTin "
                         "Running Stable V2Dir Valid", 0,
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  voter->nickname = tor_strdup("Voter2");
  voter->address = tor_strdup("2.3.4.5");
  voter->addr = 0x02030405;
  voter->dir_port = 80;
  voter->or_port = 9000;
  voter->contact = tor_strdup("*****@*****.**");
  crypto_pk_get_digest(cert->identity_key, voter->identity_digest);
  /*
   * Set up a vote; generate it; try to parse it.
   */
  smartlist_add((*vote)->voters, voter);
  (*vote)->cert = authority_cert_dup(cert);
  if (! (*vote)->net_params)
    (*vote)->net_params = smartlist_new();
  smartlist_split_string((*vote)->net_params,
                         "bar=2000000000 circuitwindow=20",
                         NULL, 0, 0);
  /* add routerstatuses */
  /* dump the vote and try to parse it. */
  dir_common_add_rs_and_parse(*vote, vote_out, vrs_gen, sign_skey,
                              n_vrs, now, clear_rl);

  return 0;
}
Example #25
0
static void
NS(test_main)(void *arg)
{
  routerset_t *a = routerset_new(), *b = routerset_new();
  int r;
  (void)arg;

  smartlist_add(a->list, tor_strdup("foo"));
  smartlist_add(b->list, tor_strdup("foo"));
  r = routerset_equal(a, b);
  routerset_free(a);
  routerset_free(b);

  tt_int_op(r, ==, 1);
  done:
    ;
}
Example #26
0
int
sandbox_getaddrinfo(const char *name, const char *servname,
                    const struct addrinfo *hints,
                    struct addrinfo **res)
{
  int err;
  struct cached_getaddrinfo_item_t search, *item;

  if (servname != NULL) {
    log_warn(LD_BUG, "called with non-NULL servname");
    return EAI_NONAME;
  }
  if (name == NULL) {
    log_warn(LD_BUG, "called with NULL name");
    return EAI_NONAME;
  }

  *res = NULL;

  memset(&search, 0, sizeof(search));
  search.name = (char *) name;
  search.family = hints ? hints->ai_family : AF_UNSPEC;
  item = HT_FIND(getaddrinfo_cache, &getaddrinfo_cache, &search);

  if (! sandbox_is_active()) {
    /* If the sandbox is not turned on yet, then getaddrinfo and store the
       result. */

    err = getaddrinfo(name, NULL, hints, res);
    log_info(LD_NET,"(Sandbox) getaddrinfo %s.", err ? "failed" : "succeeded");

    if (! item) {
      item = tor_malloc_zero(sizeof(*item));
      item->name = tor_strdup(name);
      item->family = hints ? hints->ai_family : AF_UNSPEC;
      HT_INSERT(getaddrinfo_cache, &getaddrinfo_cache, item);
    }

    if (item->res) {
      freeaddrinfo(item->res);
      item->res = NULL;
    }
    item->res = *res;
    item->err = err;
    return err;
  }

  /* Otherwise, the sanbox is on.  If we have an item, yield its cached
     result. */
  if (item) {
    *res = item->res;
    return item->err;
  }

  /* getting here means something went wrong */
  log_err(LD_BUG,"(Sandbox) failed to get address %s!", name);
  return EAI_NONAME;
}
Example #27
0
File: hibernate.c Project: 4ZM/Tor
/** Helper function: called when we get a GETINFO request for an
 * accounting-related key on the control connection <b>conn</b>.  If we can
 * answer the request for <b>question</b>, then set *<b>answer</b> to a newly
 * allocated string holding the result.  Otherwise, set *<b>answer</b> to
 * NULL. */
int
getinfo_helper_accounting(control_connection_t *conn,
                          const char *question, char **answer,
                          const char **errmsg)
{
  (void) conn;
  (void) errmsg;
  if (!strcmp(question, "accounting/enabled")) {
    *answer = tor_strdup(accounting_is_enabled(get_options()) ? "1" : "0");
  } else if (!strcmp(question, "accounting/hibernating")) {
    if (hibernate_state == HIBERNATE_STATE_DORMANT)
      *answer = tor_strdup("hard");
    else if (hibernate_state == HIBERNATE_STATE_LOWBANDWIDTH)
      *answer = tor_strdup("soft");
    else
      *answer = tor_strdup("awake");
  } else if (!strcmp(question, "accounting/bytes")) {
    *answer = tor_malloc(32);
    tor_snprintf(*answer, 32, U64_FORMAT" "U64_FORMAT,
                 U64_PRINTF_ARG(n_bytes_read_in_interval),
                 U64_PRINTF_ARG(n_bytes_written_in_interval));
  } else if (!strcmp(question, "accounting/bytes-left")) {
    uint64_t limit = get_options()->AccountingMax;
    uint64_t read_left = 0, write_left = 0;
    if (n_bytes_read_in_interval < limit)
      read_left = limit - n_bytes_read_in_interval;
    if (n_bytes_written_in_interval < limit)
      write_left = limit - n_bytes_written_in_interval;
    *answer = tor_malloc(64);
    tor_snprintf(*answer, 64, U64_FORMAT" "U64_FORMAT,
                 U64_PRINTF_ARG(read_left), U64_PRINTF_ARG(write_left));
  } else if (!strcmp(question, "accounting/interval-start")) {
    *answer = tor_malloc(ISO_TIME_LEN+1);
    format_iso_time(*answer, interval_start_time);
  } else if (!strcmp(question, "accounting/interval-wake")) {
    *answer = tor_malloc(ISO_TIME_LEN+1);
    format_iso_time(*answer, interval_wakeup_time);
  } else if (!strcmp(question, "accounting/interval-end")) {
    *answer = tor_malloc(ISO_TIME_LEN+1);
    format_iso_time(*answer, interval_end_time);
  } else {
    *answer = NULL;
  }
  return 0;
}
Example #28
0
/** Mock function for send_control_event_string
 */
static void
send_control_event_string_replacement(uint16_t event, event_format_t which,
                                      const char *msg)
{
  (void) event;
  (void) which;
  tor_free(received_msg);
  received_msg = tor_strdup(msg);
}
Example #29
0
/** See dir_common_construct_vote_1.
 * Produces a vote with slightly different values. Adds a legacy key.
 */
int
dir_common_construct_vote_3(networkstatus_t **vote, authority_cert_t *cert,
                        crypto_pk_t *sign_skey,
                        vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
                        networkstatus_t **vote_out, int *n_vrs,
                        time_t now, int clear_rl)
{
  networkstatus_voter_info_t *voter;

  dir_common_setup_vote(vote, now);
  (*vote)->valid_after = now+1000;
  (*vote)->fresh_until = now+2003;
  (*vote)->valid_until = now+3000;
  (*vote)->vote_seconds = 100;
  (*vote)->dist_seconds = 250;
  smartlist_split_string((*vote)->supported_methods, "1 2 3 4", NULL, 0, -1);
  (*vote)->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
  (*vote)->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
  smartlist_split_string((*vote)->known_flags,
                     "Authority Exit Fast Guard Running Stable V2Dir Valid",
                     0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  voter->nickname = tor_strdup("Voter2");
  voter->address = tor_strdup("3.4.5.6");
  voter->addr = 0x03040506;
  voter->dir_port = 80;
  voter->or_port = 9000;
  voter->contact = tor_strdup("*****@*****.**");
  crypto_pk_get_digest(cert->identity_key, voter->identity_digest);
  memset(voter->legacy_id_digest, (int)'A', DIGEST_LEN);
  /*
   * Set up a vote; generate it; try to parse it.
   */
  smartlist_add((*vote)->voters, voter);
  (*vote)->cert = authority_cert_dup(cert);
  smartlist_split_string((*vote)->net_params, "circuitwindow=80 foo=660",
                         NULL, 0, 0);
  /* add routerstatuses */
  /* dump the vote and try to parse it. */
  dir_common_add_rs_and_parse(*vote, vote_out, vrs_gen, sign_skey,
                              n_vrs, now, clear_rl);

  return 0;
}
Example #30
0
static void
test_pt_get_extrainfo_string(void *arg)
{
  managed_proxy_t *mp1 = NULL, *mp2 = NULL;
  char **argv1, **argv2;
  smartlist_t *t1 = smartlist_new(), *t2 = smartlist_new();
  int r;
  char *s = NULL;
  (void) arg;

  argv1 = tor_malloc_zero(sizeof(char*)*3);
  argv1[0] = tor_strdup("ewige");
  argv1[1] = tor_strdup("Blumenkraft");
  argv1[2] = NULL;
  argv2 = tor_malloc_zero(sizeof(char*)*4);
  argv2[0] = tor_strdup("und");
  argv2[1] = tor_strdup("ewige");
  argv2[2] = tor_strdup("Schlangenkraft");
  argv2[3] = NULL;

  mp1 = managed_proxy_create(t1, argv1, 1);
  mp2 = managed_proxy_create(t2, argv2, 1);

  r = parse_smethod_line("SMETHOD hagbard 127.0.0.1:5555", mp1);
  tt_int_op(r, OP_EQ, 0);
  r = parse_smethod_line("SMETHOD celine 127.0.0.1:1723 ARGS:card=no-enemy",
                         mp2);
  tt_int_op(r, OP_EQ, 0);

  /* Force these proxies to look "completed" or they won't generate output. */
  mp1->conf_state = mp2->conf_state = PT_PROTO_COMPLETED;

  s = pt_get_extra_info_descriptor_string();
  tt_assert(s);
  tt_str_op(s, OP_EQ,
            "transport hagbard 127.0.0.1:5555\n"
            "transport celine 127.0.0.1:1723 card=no-enemy\n");

 done:
  /* XXXX clean up better */
  smartlist_free(t1);
  smartlist_free(t2);
  tor_free(s);
}