Tor  0.4.5.0-alpha-dev
control_cmd.c
Go to the documentation of this file.
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2  * Copyright (c) 2007-2020, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
4 
5 /**
6  * \file control_cmd.c
7  * \brief Implement various commands for Tor's control-socket interface.
8  **/
9 
10 #define CONTROL_MODULE_PRIVATE
11 #define CONTROL_CMD_PRIVATE
12 #define CONTROL_EVENTS_PRIVATE
13 
14 #include "core/or/or.h"
15 #include "app/config/config.h"
16 #include "lib/confmgt/confmgt.h"
17 #include "app/main/main.h"
19 #include "core/or/circuitbuild.h"
20 #include "core/or/circuitlist.h"
21 #include "core/or/circuituse.h"
23 #include "core/or/circuitstats.h"
24 #include "core/or/extendinfo.h"
26 #include "feature/client/dnsserv.h"
31 #include "feature/control/control_hs.h"
33 #include "feature/control/control_getinfo.h"
35 #include "feature/hs/hs_control.h"
41 #include "feature/rend/rendparse.h"
45 #include "lib/encoding/confline.h"
46 #include "lib/encoding/kvline.h"
47 
59 
61 
63  const control_cmd_args_t *args,
64  int use_defaults);
65 
66 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
67  * finished authentication and is accepting commands. */
68 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
69 
70 /**
71  * Release all storage held in <b>args</b>
72  **/
73 void
75 {
76  if (! args)
77  return;
78 
79  if (args->args) {
80  SMARTLIST_FOREACH(args->args, char *, c, tor_free(c));
81  smartlist_free(args->args);
82  }
83  config_free_lines(args->kwargs);
84  tor_free(args->cmddata);
85 
86  tor_free(args);
87 }
88 
89 /** Erase all memory held in <b>args</b>. */
90 void
92 {
93  if (!args)
94  return;
95 
96  if (args->args) {
97  SMARTLIST_FOREACH(args->args, char *, c, memwipe(c, 0, strlen(c)));
98  }
99  for (config_line_t *line = args->kwargs; line; line = line->next) {
100  memwipe(line->key, 0, strlen(line->key));
101  memwipe(line->value, 0, strlen(line->value));
102  }
103  if (args->cmddata)
104  memwipe(args->cmddata, 0, args->cmddata_len);
105 }
106 
107 /**
108  * Return true iff any element of the NULL-terminated <b>array</b> matches
109  * <b>kwd</b>. Case-insensitive.
110  **/
111 static bool
112 string_array_contains_keyword(const char **array, const char *kwd)
113 {
114  for (unsigned i = 0; array[i]; ++i) {
115  if (! strcasecmp(array[i], kwd))
116  return true;
117  }
118  return false;
119 }
120 
121 /** Helper for argument parsing: check whether the keyword arguments just
122  * parsed in <b>result</b> were well-formed according to <b>syntax</b>.
123  *
124  * On success, return 0. On failure, return -1 and set *<b>error_out</b>
125  * to a newly allocated error string.
126  **/
127 static int
129  const control_cmd_syntax_t *syntax,
130  char **error_out)
131 {
132  if (result->kwargs == NULL) {
133  tor_asprintf(error_out, "Cannot parse keyword argument(s)");
134  return -1;
135  }
136 
137  if (! syntax->allowed_keywords) {
138  /* All keywords are permitted. */
139  return 0;
140  }
141 
142  /* Check for unpermitted arguments */
143  const config_line_t *line;
144  for (line = result->kwargs; line; line = line->next) {
146  line->key)) {
147  tor_asprintf(error_out, "Unrecognized keyword argument %s",
148  escaped(line->key));
149  return -1;
150  }
151  }
152 
153  return 0;
154 }
155 
156 /**
157  * Helper: parse the arguments to a command according to <b>syntax</b>. On
158  * success, set *<b>error_out</b> to NULL and return a newly allocated
159  * control_cmd_args_t. On failure, set *<b>error_out</b> to newly allocated
160  * error string, and return NULL.
161  **/
164  const control_cmd_syntax_t *syntax,
165  size_t body_len,
166  const char *body,
167  char **error_out)
168 {
169  *error_out = NULL;
170  control_cmd_args_t *result = tor_malloc_zero(sizeof(control_cmd_args_t));
171  const char *cmdline;
172  char *cmdline_alloc = NULL;
173  tor_assert(syntax->max_args < INT_MAX || syntax->max_args == UINT_MAX);
174 
175  result->command = command;
176 
177  if (syntax->store_raw_body) {
178  tor_assert(body[body_len] == 0);
179  result->raw_body = body;
180  }
181 
182  const char *eol = memchr(body, '\n', body_len);
183  if (syntax->want_cmddata) {
184  if (! eol || (eol+1) == body+body_len) {
185  *error_out = tor_strdup("Empty body");
186  goto err;
187  }
188  cmdline_alloc = tor_memdup_nulterm(body, eol-body);
189  cmdline = cmdline_alloc;
190  ++eol;
191  result->cmddata_len = read_escaped_data(eol, (body+body_len)-eol,
192  &result->cmddata);
193  } else {
194  if (eol && (eol+1) != body+body_len) {
195  *error_out = tor_strdup("Unexpected body");
196  goto err;
197  }
198  cmdline = body;
199  }
200 
201  result->args = smartlist_new();
202  smartlist_split_string(result->args, cmdline, " ",
203  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,
204  (int)(syntax->max_args+1));
205  size_t n_args = smartlist_len(result->args);
206  if (n_args < syntax->min_args) {
207  tor_asprintf(error_out, "Need at least %u argument(s)",
208  syntax->min_args);
209  goto err;
210  } else if (n_args > syntax->max_args && ! syntax->accept_keywords) {
211  tor_asprintf(error_out, "Cannot accept more than %u argument(s)",
212  syntax->max_args);
213  goto err;
214  }
215 
216  if (n_args > syntax->max_args) {
217  /* We have extra arguments after the positional arguments, and we didn't
218  treat them as an error, so they must count as keyword arguments: Either
219  K=V pairs, or flags, or both. */
220  tor_assert(n_args == syntax->max_args + 1);
221  tor_assert(syntax->accept_keywords);
222  char *remainder = smartlist_pop_last(result->args);
223  result->kwargs = kvline_parse(remainder, syntax->kvline_flags);
224  tor_free(remainder);
225  if (kvline_check_keyword_args(result, syntax, error_out) < 0) {
226  goto err;
227  }
228  }
229 
230  tor_assert_nonfatal(*error_out == NULL);
231  goto done;
232  err:
233  tor_assert_nonfatal(*error_out != NULL);
234  control_cmd_args_free(result);
235  done:
236  tor_free(cmdline_alloc);
237  return result;
238 }
239 
240 /**
241  * Return true iff <b>lines</b> contains <b>flags</b> as a no-value
242  * (keyword-only) entry.
243  **/
244 static bool
245 config_lines_contain_flag(const config_line_t *lines, const char *flag)
246 {
247  const config_line_t *line = config_line_find_case(lines, flag);
248  return line && !strcmp(line->value, "");
249 }
250 
251 static const control_cmd_syntax_t setconf_syntax = {
252  .max_args=0,
253  .accept_keywords=true,
254  .kvline_flags=KV_OMIT_VALS|KV_QUOTED,
255 };
256 
257 /** Called when we receive a SETCONF message: parse the body and try
258  * to update our configuration. Reply with a DONE or ERROR message.
259  * Modifies the contents of body.*/
260 static int
262  const control_cmd_args_t *args)
263 {
264  return control_setconf_helper(conn, args, 0);
265 }
266 
267 static const control_cmd_syntax_t resetconf_syntax = {
268  .max_args=0,
269  .accept_keywords=true,
270  .kvline_flags=KV_OMIT_VALS|KV_QUOTED,
271 };
272 
273 /** Called when we receive a RESETCONF message: parse the body and try
274  * to update our configuration. Reply with a DONE or ERROR message.
275  * Modifies the contents of body. */
276 static int
278  const control_cmd_args_t *args)
279 {
280  return control_setconf_helper(conn, args, 1);
281 }
282 
283 static const control_cmd_syntax_t getconf_syntax = {
284  .max_args=UINT_MAX
285 };
286 
287 /** Called when we receive a GETCONF message. Parse the request, and
288  * reply with a CONFVALUE or an ERROR message */
289 static int
291  const control_cmd_args_t *args)
292 {
293  const smartlist_t *questions = args->args;
294  smartlist_t *answers = smartlist_new();
295  smartlist_t *unrecognized = smartlist_new();
296  const or_options_t *options = get_options();
297 
298  SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
299  if (!option_is_recognized(q)) {
300  control_reply_add_printf(unrecognized, 552,
301  "Unrecognized configuration key \"%s\"", q);
302  } else {
303  config_line_t *answer = option_get_assignment(options,q);
304  if (!answer) {
305  const char *name = option_get_canonical_name(q);
306  control_reply_add_one_kv(answers, 250, KV_OMIT_VALS, name, "");
307  }
308 
309  while (answer) {
310  config_line_t *next;
311  control_reply_add_one_kv(answers, 250, KV_RAW, answer->key,
312  answer->value);
313  next = answer->next;
314  tor_free(answer->key);
315  tor_free(answer->value);
316  tor_free(answer);
317  answer = next;
318  }
319  }
320  } SMARTLIST_FOREACH_END(q);
321 
322  if (smartlist_len(unrecognized)) {
323  control_write_reply_lines(conn, unrecognized);
324  } else if (smartlist_len(answers)) {
325  control_write_reply_lines(conn, answers);
326  } else {
327  send_control_done(conn);
328  }
329 
330  control_reply_free(answers);
331  control_reply_free(unrecognized);
332  return 0;
333 }
334 
335 static const control_cmd_syntax_t loadconf_syntax = {
336  .want_cmddata = true
337 };
338 
339 /** Called when we get a +LOADCONF message. */
340 static int
342  const control_cmd_args_t *args)
343 {
344  setopt_err_t retval;
345  char *errstring = NULL;
346 
347  retval = options_init_from_string(NULL, args->cmddata,
348  CMD_RUN_TOR, NULL, &errstring);
349 
350  if (retval != SETOPT_OK)
351  log_warn(LD_CONTROL,
352  "Controller gave us config file that didn't validate: %s",
353  errstring);
354 
355 #define SEND_ERRMSG(code, msg) \
356  control_printf_endreply(conn, code, msg "%s%s", \
357  errstring ? ": " : "", \
358  errstring ? errstring : "")
359  switch (retval) {
360  case SETOPT_ERR_PARSE:
361  SEND_ERRMSG(552, "Invalid config file");
362  break;
363  case SETOPT_ERR_TRANSITION:
364  SEND_ERRMSG(553, "Transition not allowed");
365  break;
366  case SETOPT_ERR_SETTING:
367  SEND_ERRMSG(553, "Unable to set option");
368  break;
369  case SETOPT_ERR_MISC:
370  default:
371  SEND_ERRMSG(550, "Unable to load config");
372  break;
373  case SETOPT_OK:
374  send_control_done(conn);
375  break;
376  }
377 #undef SEND_ERRMSG
378  tor_free(errstring);
379  return 0;
380 }
381 
382 static const control_cmd_syntax_t setevents_syntax = {
383  .max_args = UINT_MAX
384 };
385 
386 /** Called when we get a SETEVENTS message: update conn->event_mask,
387  * and reply with DONE or ERROR. */
388 static int
390  const control_cmd_args_t *args)
391 {
392  int event_code;
393  event_mask_t event_mask = 0;
394  const smartlist_t *events = args->args;
395 
396  SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
397  {
398  if (!strcasecmp(ev, "EXTENDED") ||
399  !strcasecmp(ev, "AUTHDIR_NEWDESCS")) {
400  log_warn(LD_CONTROL, "The \"%s\" SETEVENTS argument is no longer "
401  "supported.", ev);
402  continue;
403  } else {
404  int i;
405  event_code = -1;
406 
407  for (i = 0; control_event_table[i].event_name != NULL; ++i) {
408  if (!strcasecmp(ev, control_event_table[i].event_name)) {
409  event_code = control_event_table[i].event_code;
410  break;
411  }
412  }
413 
414  if (event_code == -1) {
415  control_printf_endreply(conn, 552, "Unrecognized event \"%s\"", ev);
416  return 0;
417  }
418  }
419  event_mask |= (((event_mask_t)1) << event_code);
420  }
421  SMARTLIST_FOREACH_END(ev);
422 
423  conn->event_mask = event_mask;
424 
426  send_control_done(conn);
427  return 0;
428 }
429 
430 static const control_cmd_syntax_t saveconf_syntax = {
431  .max_args = 0,
432  .accept_keywords = true,
433  .kvline_flags=KV_OMIT_VALS,
434 };
435 
436 /** Called when we get a SAVECONF command. Try to flush the current options to
437  * disk, and report success or failure. */
438 static int
440  const control_cmd_args_t *args)
441 {
442  bool force = config_lines_contain_flag(args->kwargs, "FORCE");
443  const or_options_t *options = get_options();
444  if ((!force && options->IncludeUsed) || options_save_current() < 0) {
445  control_write_endreply(conn, 551,
446  "Unable to write configuration to disk.");
447  } else {
448  send_control_done(conn);
449  }
450  return 0;
451 }
452 
453 static const control_cmd_syntax_t signal_syntax = {
454  .min_args = 1,
455  .max_args = 1,
456 };
457 
458 /** Called when we get a SIGNAL command. React to the provided signal, and
459  * report success or failure. (If the signal results in a shutdown, success
460  * may not be reported.) */
461 static int
463  const control_cmd_args_t *args)
464 {
465  int sig = -1;
466  int i;
467 
468  tor_assert(smartlist_len(args->args) == 1);
469  const char *s = smartlist_get(args->args, 0);
470 
471  for (i = 0; signal_table[i].signal_name != NULL; ++i) {
472  if (!strcasecmp(s, signal_table[i].signal_name)) {
473  sig = signal_table[i].sig;
474  break;
475  }
476  }
477 
478  if (sig < 0)
479  control_printf_endreply(conn, 552, "Unrecognized signal code \"%s\"", s);
480  if (sig < 0)
481  return 0;
482 
483  send_control_done(conn);
484  /* Flush the "done" first if the signal might make us shut down. */
485  if (sig == SIGTERM || sig == SIGINT)
486  connection_flush(TO_CONN(conn));
487 
488  activate_signal(sig);
489 
490  return 0;
491 }
492 
493 static const control_cmd_syntax_t takeownership_syntax = {
494  .max_args = UINT_MAX, // This should probably become zero. XXXXX
495 };
496 
497 /** Called when we get a TAKEOWNERSHIP command. Mark this connection
498  * as an owning connection, so that we will exit if the connection
499  * closes. */
500 static int
502  const control_cmd_args_t *args)
503 {
504  (void)args;
505 
507 
508  log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
509  "Tor instance.",
510  (int)(conn->base_.s));
511 
512  send_control_done(conn);
513  return 0;
514 }
515 
516 static const control_cmd_syntax_t dropownership_syntax = {
517  .max_args = UINT_MAX, // This should probably become zero. XXXXX
518 };
519 
520 /** Called when we get a DROPOWNERSHIP command. Mark this connection
521  * as a non-owning connection, so that we will not exit if the connection
522  * closes. */
523 static int
525  const control_cmd_args_t *args)
526 {
527  (void)args;
528 
530 
531  log_info(LD_CONTROL, "Control connection %d has dropped ownership of this "
532  "Tor instance.",
533  (int)(conn->base_.s));
534 
535  send_control_done(conn);
536  return 0;
537 }
538 
539 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
540 static origin_circuit_t *
541 get_circ(const char *id)
542 {
543  uint32_t n_id;
544  int ok;
545  n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
546  if (!ok)
547  return NULL;
548  return circuit_get_by_global_id(n_id);
549 }
550 
551 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
552 static entry_connection_t *
553 get_stream(const char *id)
554 {
555  uint64_t n_id;
556  int ok;
557  connection_t *conn;
558  n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
559  if (!ok)
560  return NULL;
561  conn = connection_get_by_global_id(n_id);
562  if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
563  return NULL;
564  return TO_ENTRY_CONN(conn);
565 }
566 
567 /** Helper for setconf and resetconf. Acts like setconf, except
568  * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
569  * contents of body.
570  */
571 static int
573  const control_cmd_args_t *args,
574  int use_defaults)
575 {
576  setopt_err_t opt_err;
577  char *errstring = NULL;
578  const unsigned flags =
579  CAL_CLEAR_FIRST | (use_defaults ? CAL_USE_DEFAULTS : 0);
580 
581  // We need a copy here, since confmgt.c wants to canonicalize cases.
582  config_line_t *lines = config_lines_dup(args->kwargs);
583 
584  opt_err = options_trial_assign(lines, flags, &errstring);
585  {
586 #define SEND_ERRMSG(code, msg) \
587  control_printf_endreply(conn, code, msg ": %s", errstring);
588 
589  switch (opt_err) {
590  case SETOPT_ERR_MISC:
591  SEND_ERRMSG(552, "Unrecognized option");
592  break;
593  case SETOPT_ERR_PARSE:
594  SEND_ERRMSG(513, "Unacceptable option value");
595  break;
596  case SETOPT_ERR_TRANSITION:
597  SEND_ERRMSG(553, "Transition not allowed");
598  break;
599  case SETOPT_ERR_SETTING:
600  default:
601  SEND_ERRMSG(553, "Unable to set option");
602  break;
603  case SETOPT_OK:
604  config_free_lines(lines);
605  send_control_done(conn);
606  return 0;
607  }
608 #undef SEND_ERRMSG
609  log_warn(LD_CONTROL,
610  "Controller gave us config lines that didn't validate: %s",
611  errstring);
612  config_free_lines(lines);
613  tor_free(errstring);
614  return 0;
615  }
616 }
617 
618 /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
619  * containing funny characters. */
620 static int
622 {
623  if (!strcmpstart(addr, "*."))
624  return address_is_invalid_destination(addr+2, 1);
625  else
626  return address_is_invalid_destination(addr, 1);
627 }
628 
629 static const control_cmd_syntax_t mapaddress_syntax = {
630  // no positional arguments are expected
631  .max_args=0,
632  // an arbitrary number of K=V entries are supported.
633  .accept_keywords=true,
634 };
635 
636 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
637  * and report success or failure. */
638 static int
640  const control_cmd_args_t *args)
641 {
642  smartlist_t *reply;
643  char *r;
644  size_t sz;
645 
646  reply = smartlist_new();
647  const config_line_t *line;
648  for (line = args->kwargs; line; line = line->next) {
649  const char *from = line->key;
650  const char *to = line->value;
651  {
654  "512-syntax error: invalid address '%s'", to);
655  log_warn(LD_CONTROL,
656  "Skipping invalid argument '%s' in MapAddress msg", to);
657  } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
658  !strcmp(from, "::")) {
659  const char type =
660  !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
661  (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
662  const char *address = addressmap_register_virtual_address(
663  type, tor_strdup(to));
664  if (!address) {
666  "451-resource exhausted: skipping '%s=%s'", from,to);
667  log_warn(LD_CONTROL,
668  "Unable to allocate address for '%s' in MapAddress msg",
669  safe_str_client(to));
670  } else {
671  smartlist_add_asprintf(reply, "250-%s=%s", address, to);
672  }
673  } else {
674  const char *msg;
675  if (addressmap_register_auto(from, to, 1,
676  ADDRMAPSRC_CONTROLLER, &msg) < 0) {
678  "512-syntax error: invalid address mapping "
679  " '%s=%s': %s", from, to, msg);
680  log_warn(LD_CONTROL,
681  "Skipping invalid argument '%s=%s' in MapAddress msg: %s",
682  from, to, msg);
683  } else {
684  smartlist_add_asprintf(reply, "250-%s=%s", from, to);
685  }
686  }
687  }
688  }
689 
690  if (smartlist_len(reply)) {
691  ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
692  r = smartlist_join_strings(reply, "\r\n", 1, &sz);
693  connection_buf_add(r, sz, TO_CONN(conn));
694  tor_free(r);
695  } else {
696  control_write_endreply(conn, 512, "syntax error: "
697  "not enough arguments to mapaddress.");
698  }
699 
700  SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
701  smartlist_free(reply);
702  return 0;
703 }
704 
705 /** Given a string, convert it to a circuit purpose. */
706 static uint8_t
707 circuit_purpose_from_string(const char *string)
708 {
709  if (!strcasecmpstart(string, "purpose="))
710  string += strlen("purpose=");
711 
712  if (!strcasecmp(string, "general"))
714  else if (!strcasecmp(string, "controller"))
716  else
718 }
719 
720 static const control_cmd_syntax_t extendcircuit_syntax = {
721  .min_args=1,
722  .max_args=1, // see note in function
723  .accept_keywords=true,
724  .kvline_flags=KV_OMIT_VALS
725 };
726 
727 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
728  * circuit, and report success or failure. */
729 static int
731  const control_cmd_args_t *args)
732 {
733  smartlist_t *router_nicknames=smartlist_new(), *nodes=NULL;
734  origin_circuit_t *circ = NULL;
735  uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
736  const config_line_t *kwargs = args->kwargs;
737  const char *circ_id = smartlist_get(args->args, 0);
738  const char *path_str = NULL;
739  char *path_str_alloc = NULL;
740 
741  /* The syntax for this command is unfortunate. The second argument is
742  optional, and is a comma-separated list long-format fingerprints, which
743  can (historically!) contain an equals sign.
744 
745  Here we check the second argument to see if it's a path, and if so we
746  remove it from the kwargs list and put it in path_str.
747  */
748  if (kwargs) {
749  const config_line_t *arg1 = kwargs;
750  if (!strcmp(arg1->value, "")) {
751  path_str = arg1->key;
752  kwargs = kwargs->next;
753  } else if (arg1->key[0] == '$') {
754  tor_asprintf(&path_str_alloc, "%s=%s", arg1->key, arg1->value);
755  path_str = path_str_alloc;
756  kwargs = kwargs->next;
757  }
758  }
759 
760  const config_line_t *purpose_line = config_line_find_case(kwargs, "PURPOSE");
761  bool zero_circ = !strcmp("0", circ_id);
762 
763  if (purpose_line) {
764  intended_purpose = circuit_purpose_from_string(purpose_line->value);
765  if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
766  control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
767  purpose_line->value);
768  goto done;
769  }
770  }
771 
772  if (zero_circ) {
773  if (!path_str) {
774  // "EXTENDCIRCUIT 0" with no path.
775  circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
776  if (!circ) {
777  control_write_endreply(conn, 551, "Couldn't start circuit");
778  } else {
779  control_printf_endreply(conn, 250, "EXTENDED %lu",
780  (unsigned long)circ->global_identifier);
781  }
782  goto done;
783  }
784  }
785 
786  if (!zero_circ && !(circ = get_circ(circ_id))) {
787  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
788  goto done;
789  }
790 
791  if (!path_str) {
792  control_write_endreply(conn, 512, "syntax error: path required.");
793  goto done;
794  }
795 
796  smartlist_split_string(router_nicknames, path_str, ",", 0, 0);
797 
798  nodes = smartlist_new();
799  bool first_node = zero_circ;
800  SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
801  const node_t *node = node_get_by_nickname(n, 0);
802  if (!node) {
803  control_printf_endreply(conn, 552, "No such router \"%s\"", n);
804  goto done;
805  }
806  if (!node_has_preferred_descriptor(node, first_node)) {
807  control_printf_endreply(conn, 552, "No descriptor for \"%s\"", n);
808  goto done;
809  }
810  smartlist_add(nodes, (void*)node);
811  first_node = false;
812  } SMARTLIST_FOREACH_END(n);
813 
814  if (!smartlist_len(nodes)) {
815  control_write_endreply(conn, 512, "No router names provided");
816  goto done;
817  }
818 
819  if (zero_circ) {
820  /* start a new circuit */
821  circ = origin_circuit_init(intended_purpose, 0);
822  }
823 
824  /* now circ refers to something that is ready to be extended */
825  first_node = zero_circ;
826  SMARTLIST_FOREACH(nodes, const node_t *, node,
827  {
828  extend_info_t *info = extend_info_from_node(node, first_node);
829  if (!info) {
830  tor_assert_nonfatal(first_node);
831  log_warn(LD_CONTROL,
832  "controller tried to connect to a node that lacks a suitable "
833  "descriptor, or which doesn't have any "
834  "addresses that are allowed by the firewall configuration; "
835  "circuit marked for closing.");
836  circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
837  control_write_endreply(conn, 551, "Couldn't start circuit");
838  goto done;
839  }
840  circuit_append_new_exit(circ, info);
841  if (circ->build_state->desired_path_len > 1) {
842  circ->build_state->onehop_tunnel = 0;
843  }
844  extend_info_free(info);
845  first_node = 0;
846  });
847 
848  /* now that we've populated the cpath, start extending */
849  if (zero_circ) {
850  int err_reason = 0;
851  if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
852  circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
853  control_write_endreply(conn, 551, "Couldn't start circuit");
854  goto done;
855  }
856  } else {
857  if (circ->base_.state == CIRCUIT_STATE_OPEN ||
858  circ->base_.state == CIRCUIT_STATE_GUARD_WAIT) {
859  int err_reason = 0;
861  if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
862  log_info(LD_CONTROL,
863  "send_next_onion_skin failed; circuit marked for closing.");
864  circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
865  control_write_endreply(conn, 551, "Couldn't send onion skin");
866  goto done;
867  }
868  }
869  }
870 
871  control_printf_endreply(conn, 250, "EXTENDED %lu",
872  (unsigned long)circ->global_identifier);
873  if (zero_circ) /* send a 'launched' event, for completeness */
874  circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
875  done:
876  SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
877  smartlist_free(router_nicknames);
878  smartlist_free(nodes);
879  tor_free(path_str_alloc);
880  return 0;
881 }
882 
883 static const control_cmd_syntax_t setcircuitpurpose_syntax = {
884  .max_args=1,
885  .accept_keywords=true,
886 };
887 
888 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
889  * circuit and it's a valid purpose, change it. */
890 static int
892  const control_cmd_args_t *args)
893 {
894  origin_circuit_t *circ = NULL;
895  uint8_t new_purpose;
896  const char *circ_id = smartlist_get(args->args,0);
897 
898  if (!(circ = get_circ(circ_id))) {
899  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
900  goto done;
901  }
902 
903  {
904  const config_line_t *purp = config_line_find_case(args->kwargs, "PURPOSE");
905  if (!purp) {
906  control_write_endreply(conn, 552, "No purpose given");
907  goto done;
908  }
909  new_purpose = circuit_purpose_from_string(purp->value);
910  if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
911  control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
912  purp->value);
913  goto done;
914  }
915  }
916 
917  circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
918  send_control_done(conn);
919 
920  done:
921  return 0;
922 }
923 
924 static const char *attachstream_keywords[] = {
925  "HOP", NULL
926 };
927 static const control_cmd_syntax_t attachstream_syntax = {
928  .min_args=2, .max_args=2,
929  .accept_keywords=true,
930  .allowed_keywords=attachstream_keywords
931 };
932 
933 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
934  * stream, and report success or failure. */
935 static int
937  const control_cmd_args_t *args)
938 {
939  entry_connection_t *ap_conn = NULL;
940  origin_circuit_t *circ = NULL;
941  crypt_path_t *cpath=NULL;
942  int hop=0, hop_line_ok=1;
943  const char *stream_id = smartlist_get(args->args, 0);
944  const char *circ_id = smartlist_get(args->args, 1);
945  int zero_circ = !strcmp(circ_id, "0");
946  const config_line_t *hoparg = config_line_find_case(args->kwargs, "HOP");
947 
948  if (!(ap_conn = get_stream(stream_id))) {
949  control_printf_endreply(conn, 552, "Unknown stream \"%s\"", stream_id);
950  return 0;
951  } else if (!zero_circ && !(circ = get_circ(circ_id))) {
952  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
953  return 0;
954  } else if (circ) {
955  if (hoparg) {
956  hop = (int) tor_parse_ulong(hoparg->value, 10, 0, INT_MAX,
957  &hop_line_ok, NULL);
958  if (!hop_line_ok) { /* broken hop line */
959  control_printf_endreply(conn, 552, "Bad value hop=%s",
960  hoparg->value);
961  return 0;
962  }
963  }
964  }
965 
966  if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
967  ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
968  ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
969  control_write_endreply(conn, 555,
970  "Connection is not managed by controller.");
971  return 0;
972  }
973 
974  /* Do we need to detach it first? */
975  if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
976  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
977  circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
978  connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
979  /* Un-mark it as ending, since we're going to reuse it. */
980  edge_conn->edge_has_sent_end = 0;
981  edge_conn->end_reason = 0;
982  if (tmpcirc)
983  circuit_detach_stream(tmpcirc, edge_conn);
985  }
986 
987  if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
988  control_write_endreply(conn, 551,
989  "Can't attach stream to non-open origin circuit");
990  return 0;
991  }
992  /* Is this a single hop circuit? */
993  if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
994  control_write_endreply(conn, 551,
995  "Can't attach stream to this one-hop circuit.");
996  return 0;
997  }
998 
999  if (circ && hop>0) {
1000  /* find this hop in the circuit, and set cpath */
1001  cpath = circuit_get_cpath_hop(circ, hop);
1002  if (!cpath) {
1003  control_printf_endreply(conn, 551, "Circuit doesn't have %d hops.", hop);
1004  return 0;
1005  }
1006  }
1007  if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
1008  control_write_endreply(conn, 551, "Unable to attach stream");
1009  return 0;
1010  }
1011  send_control_done(conn);
1012  return 0;
1013 }
1014 
1015 static const char *postdescriptor_keywords[] = {
1016  "cache", "purpose", NULL,
1017 };
1018 
1019 static const control_cmd_syntax_t postdescriptor_syntax = {
1020  .max_args = 0,
1021  .accept_keywords = true,
1022  .allowed_keywords = postdescriptor_keywords,
1023  .want_cmddata = true,
1024 };
1025 
1026 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
1027  * descriptor, and report success or failure. */
1028 static int
1030  const control_cmd_args_t *args)
1031 {
1032  const char *msg=NULL;
1033  uint8_t purpose = ROUTER_PURPOSE_GENERAL;
1034  int cache = 0; /* eventually, we may switch this to 1 */
1035  const config_line_t *line;
1036 
1037  line = config_line_find_case(args->kwargs, "purpose");
1038  if (line) {
1039  purpose = router_purpose_from_string(line->value);
1040  if (purpose == ROUTER_PURPOSE_UNKNOWN) {
1041  control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
1042  line->value);
1043  goto done;
1044  }
1045  }
1046  line = config_line_find_case(args->kwargs, "cache");
1047  if (line) {
1048  if (!strcasecmp(line->value, "no"))
1049  cache = 0;
1050  else if (!strcasecmp(line->value, "yes"))
1051  cache = 1;
1052  else {
1053  control_printf_endreply(conn, 552, "Unknown cache request \"%s\"",
1054  line->value);
1055  goto done;
1056  }
1057  }
1058 
1059  switch (router_load_single_router(args->cmddata, purpose, cache, &msg)) {
1060  case -1:
1061  if (!msg) msg = "Could not parse descriptor";
1062  control_write_endreply(conn, 554, msg);
1063  break;
1064  case 0:
1065  if (!msg) msg = "Descriptor not added";
1066  control_write_endreply(conn, 251, msg);
1067  break;
1068  case 1:
1069  send_control_done(conn);
1070  break;
1071  }
1072 
1073  done:
1074  return 0;
1075 }
1076 
1077 static const control_cmd_syntax_t redirectstream_syntax = {
1078  .min_args = 2,
1079  .max_args = UINT_MAX, // XXX should be 3.
1080 };
1081 
1082 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
1083  * address of the named AP stream, and report success or failure. */
1084 static int
1086  const control_cmd_args_t *cmd_args)
1087 {
1088  entry_connection_t *ap_conn = NULL;
1089  char *new_addr = NULL;
1090  uint16_t new_port = 0;
1091  const smartlist_t *args = cmd_args->args;
1092 
1093  if (!(ap_conn = get_stream(smartlist_get(args, 0)))
1094  || !ap_conn->socks_request) {
1095  control_printf_endreply(conn, 552, "Unknown stream \"%s\"",
1096  (char*)smartlist_get(args, 0));
1097  } else {
1098  int ok = 1;
1099  if (smartlist_len(args) > 2) { /* they included a port too */
1100  new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
1101  10, 1, 65535, &ok, NULL);
1102  }
1103  if (!ok) {
1104  control_printf_endreply(conn, 512, "Cannot parse port \"%s\"",
1105  (char*)smartlist_get(args, 2));
1106  } else {
1107  new_addr = tor_strdup(smartlist_get(args, 1));
1108  }
1109  }
1110 
1111  if (!new_addr)
1112  return 0;
1113 
1114  strlcpy(ap_conn->socks_request->address, new_addr,
1115  sizeof(ap_conn->socks_request->address));
1116  if (new_port)
1117  ap_conn->socks_request->port = new_port;
1118  tor_free(new_addr);
1119  send_control_done(conn);
1120  return 0;
1121 }
1122 
1123 static const control_cmd_syntax_t closestream_syntax = {
1124  .min_args = 2,
1125  .max_args = UINT_MAX, /* XXXX This is the original behavior, but
1126  * maybe we should change the spec. */
1127 };
1128 
1129 /** Called when we get a CLOSESTREAM command; try to close the named stream
1130  * and report success or failure. */
1131 static int
1133  const control_cmd_args_t *cmd_args)
1134 {
1135  entry_connection_t *ap_conn=NULL;
1136  uint8_t reason=0;
1137  int ok;
1138  const smartlist_t *args = cmd_args->args;
1139 
1140  tor_assert(smartlist_len(args) >= 2);
1141 
1142  if (!(ap_conn = get_stream(smartlist_get(args, 0))))
1143  control_printf_endreply(conn, 552, "Unknown stream \"%s\"",
1144  (char*)smartlist_get(args, 0));
1145  else {
1146  reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
1147  &ok, NULL);
1148  if (!ok) {
1149  control_printf_endreply(conn, 552, "Unrecognized reason \"%s\"",
1150  (char*)smartlist_get(args, 1));
1151  ap_conn = NULL;
1152  }
1153  }
1154  if (!ap_conn)
1155  return 0;
1156 
1157  connection_mark_unattached_ap(ap_conn, reason);
1158  send_control_done(conn);
1159  return 0;
1160 }
1161 
1162 static const control_cmd_syntax_t closecircuit_syntax = {
1163  .min_args=1, .max_args=1,
1164  .accept_keywords=true,
1165  .kvline_flags=KV_OMIT_VALS,
1166  // XXXX we might want to exclude unrecognized flags, but for now we
1167  // XXXX just ignore them for backward compatibility.
1168 };
1169 
1170 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
1171  * and report success or failure. */
1172 static int
1174  const control_cmd_args_t *args)
1175 {
1176  const char *circ_id = smartlist_get(args->args, 0);
1177  origin_circuit_t *circ = NULL;
1178 
1179  if (!(circ=get_circ(circ_id))) {
1180  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
1181  return 0;
1182  }
1183 
1184  bool safe = config_lines_contain_flag(args->kwargs, "IfUnused");
1185 
1186  if (!safe || !circ->p_streams) {
1187  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
1188  }
1189 
1190  send_control_done(conn);
1191  return 0;
1192 }
1193 
1194 static const control_cmd_syntax_t resolve_syntax = {
1195  .max_args=0,
1196  .accept_keywords=true,
1197  .kvline_flags=KV_OMIT_VALS,
1198 };
1199 
1200 /** Called when we get a RESOLVE command: start trying to resolve
1201  * the listed addresses. */
1202 static int
1204  const control_cmd_args_t *args)
1205 {
1206  smartlist_t *failed;
1207  int is_reverse = 0;
1208 
1209  if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
1210  log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
1211  "isn't listening for ADDRMAP events. It probably won't see "
1212  "the answer.");
1213  }
1214 
1215  {
1216  const config_line_t *modearg = config_line_find_case(args->kwargs, "mode");
1217  if (modearg && !strcasecmp(modearg->value, "reverse"))
1218  is_reverse = 1;
1219  }
1220  failed = smartlist_new();
1221  for (const config_line_t *line = args->kwargs; line; line = line->next) {
1222  if (!strlen(line->value)) {
1223  const char *addr = line->key;
1224  if (dnsserv_launch_request(addr, is_reverse, conn)<0)
1225  smartlist_add(failed, (char*)addr);
1226  } else {
1227  // XXXX arguably we should reject unrecognized keyword arguments,
1228  // XXXX but the old implementation didn't do that.
1229  }
1230  }
1231 
1232  send_control_done(conn);
1233  SMARTLIST_FOREACH(failed, const char *, arg, {
1234  control_event_address_mapped(arg, arg, time(NULL),
1235  "internal", 0);
1236  });
1237 
1238  smartlist_free(failed);
1239  return 0;
1240 }
1241 
1242 static const control_cmd_syntax_t protocolinfo_syntax = {
1243  .max_args = UINT_MAX
1244 };
1245 
1246 /** Return a comma-separated list of authentication methods for
1247  handle_control_protocolinfo(). Caller must free this string. */
1248 static char *
1250 {
1251  int cookies = options->CookieAuthentication;
1252  char *methods;
1253  int passwd = (options->HashedControlPassword != NULL ||
1254  options->HashedControlSessionPassword != NULL);
1255  smartlist_t *mlist = smartlist_new();
1256 
1257  if (cookies) {
1258  smartlist_add(mlist, (char*)"COOKIE");
1259  smartlist_add(mlist, (char*)"SAFECOOKIE");
1260  }
1261  if (passwd)
1262  smartlist_add(mlist, (char*)"HASHEDPASSWORD");
1263  if (!cookies && !passwd)
1264  smartlist_add(mlist, (char*)"NULL");
1265  methods = smartlist_join_strings(mlist, ",", 0, NULL);
1266  smartlist_free(mlist);
1267 
1268  return methods;
1269 }
1270 
1271 /** Return escaped cookie filename. Caller must free this string.
1272  Return NULL if cookie authentication is disabled. */
1273 static char *
1275 {
1276  char *cfile = NULL, *abs_cfile = NULL, *esc_cfile = NULL;
1277 
1278  if (!options->CookieAuthentication)
1279  return NULL;
1280 
1282  abs_cfile = make_path_absolute(cfile);
1283  esc_cfile = esc_for_log(abs_cfile);
1284  tor_free(cfile);
1285  tor_free(abs_cfile);
1286  return esc_cfile;
1287 }
1288 
1289 /** Compose the auth methods line of a PROTOCOLINFO reply. */
1290 static void
1292 {
1293  const or_options_t *options = get_options();
1294  char *methods = get_authmethods(options);
1295  char *esc_cfile = get_esc_cfile(options);
1296 
1297  control_reply_add_str(reply, 250, "AUTH");
1298  control_reply_append_kv(reply, "METHODS", methods);
1299  if (esc_cfile)
1300  control_reply_append_kv(reply, "COOKIEFILE", esc_cfile);
1301 
1302  tor_free(methods);
1303  tor_free(esc_cfile);
1304 }
1305 
1306 /** Called when we get a PROTOCOLINFO command: send back a reply. */
1307 static int
1309  const control_cmd_args_t *cmd_args)
1310 {
1311  const char *bad_arg = NULL;
1312  const smartlist_t *args = cmd_args->args;
1313  smartlist_t *reply = NULL;
1314 
1315  conn->have_sent_protocolinfo = 1;
1316 
1317  SMARTLIST_FOREACH(args, const char *, arg, {
1318  int ok;
1319  tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
1320  if (!ok) {
1321  bad_arg = arg;
1322  break;
1323  }
1324  });
1325  if (bad_arg) {
1326  control_printf_endreply(conn, 513, "No such version %s",
1327  escaped(bad_arg));
1328  /* Don't tolerate bad arguments when not authenticated. */
1329  if (!STATE_IS_OPEN(TO_CONN(conn)->state))
1330  connection_mark_for_close(TO_CONN(conn));
1331  return 0;
1332  }
1333  reply = smartlist_new();
1334  control_reply_add_str(reply, 250, "PROTOCOLINFO 1");
1335  add_authmethods(reply);
1336  control_reply_add_str(reply, 250, "VERSION");
1337  control_reply_append_kv(reply, "Tor", escaped(VERSION));
1338  control_reply_add_done(reply);
1339 
1340  control_write_reply_lines(conn, reply);
1341  control_reply_free(reply);
1342  return 0;
1343 }
1344 
1345 static const control_cmd_syntax_t usefeature_syntax = {
1346  .max_args = UINT_MAX
1347 };
1348 
1349 /** Called when we get a USEFEATURE command: parse the feature list, and
1350  * set up the control_connection's options properly. */
1351 static int
1353  const control_cmd_args_t *cmd_args)
1354 {
1355  const smartlist_t *args = cmd_args->args;
1356  int bad = 0;
1357  SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
1358  if (!strcasecmp(arg, "VERBOSE_NAMES"))
1359  ;
1360  else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
1361  ;
1362  else {
1363  control_printf_endreply(conn, 552, "Unrecognized feature \"%s\"",
1364  arg);
1365  bad = 1;
1366  break;
1367  }
1368  } SMARTLIST_FOREACH_END(arg);
1369 
1370  if (!bad) {
1371  send_control_done(conn);
1372  }
1373 
1374  return 0;
1375 }
1376 
1377 static const control_cmd_syntax_t dropguards_syntax = {
1378  .max_args = 0,
1379 };
1380 
1381 /** Implementation for the DROPGUARDS command. */
1382 static int
1384  const control_cmd_args_t *args)
1385 {
1386  (void) args; /* We don't take arguments. */
1387 
1388  static int have_warned = 0;
1389  if (! have_warned) {
1390  log_warn(LD_CONTROL, "DROPGUARDS is dangerous; make sure you understand "
1391  "the risks before using it. It may be removed in a future "
1392  "version of Tor.");
1393  have_warned = 1;
1394  }
1395 
1397  send_control_done(conn);
1398 
1399  return 0;
1400 }
1401 
1402 static const control_cmd_syntax_t droptimeouts_syntax = {
1403  .max_args = 0,
1404 };
1405 
1406 /** Implementation for the DROPTIMEOUTS command. */
1407 static int
1409  const control_cmd_args_t *args)
1410 {
1411  (void) args; /* We don't take arguments. */
1412 
1413  static int have_warned = 0;
1414  if (! have_warned) {
1415  log_warn(LD_CONTROL, "DROPTIMEOUTS is dangerous; make sure you understand "
1416  "the risks before using it. It may be removed in a future "
1417  "version of Tor.");
1418  have_warned = 1;
1419  }
1420 
1422  send_control_done(conn);
1424  cbt_control_event_buildtimeout_set(get_circuit_build_times(),
1425  BUILDTIMEOUT_SET_EVENT_RESET);
1426 
1427  return 0;
1428 }
1429 
1430 static const char *hsfetch_keywords[] = {
1431  "SERVER", NULL,
1432 };
1433 static const control_cmd_syntax_t hsfetch_syntax = {
1434  .min_args = 1, .max_args = 1,
1435  .accept_keywords = true,
1436  .allowed_keywords = hsfetch_keywords,
1437 };
1438 
1439 /** Implementation for the HSFETCH command. */
1440 static int
1442  const control_cmd_args_t *args)
1443 
1444 {
1445  char digest[DIGEST_LEN], *desc_id = NULL;
1446  smartlist_t *hsdirs = NULL;
1447  static const char *v2_str = "v2-";
1448  const size_t v2_str_len = strlen(v2_str);
1449  rend_data_t *rend_query = NULL;
1450  ed25519_public_key_t v3_pk;
1451  uint32_t version;
1452  const char *hsaddress = NULL;
1453 
1454  /* Extract the first argument (either HSAddress or DescID). */
1455  const char *arg1 = smartlist_get(args->args, 0);
1456  /* Test if it's an HS address without the .onion part. */
1457  if (rend_valid_v2_service_id(arg1)) {
1458  hsaddress = arg1;
1459  version = HS_VERSION_TWO;
1460  } else if (strcmpstart(arg1, v2_str) == 0 &&
1461  rend_valid_descriptor_id(arg1 + v2_str_len) &&
1462  base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
1464  sizeof(digest)) {
1465  /* We have a well formed version 2 descriptor ID. Keep the decoded value
1466  * of the id. */
1467  desc_id = digest;
1468  version = HS_VERSION_TWO;
1469  } else if (hs_address_is_valid(arg1)) {
1470  hsaddress = arg1;
1471  version = HS_VERSION_THREE;
1472  hs_parse_address(hsaddress, &v3_pk, NULL, NULL);
1473  } else {
1474  control_printf_endreply(conn, 513, "Invalid argument \"%s\"", arg1);
1475  goto done;
1476  }
1477 
1478  for (const config_line_t *line = args->kwargs; line; line = line->next) {
1479  if (!strcasecmp(line->key, "SERVER")) {
1480  const char *server = line->value;
1481 
1482  const node_t *node = node_get_by_hex_id(server, 0);
1483  if (!node) {
1484  control_printf_endreply(conn, 552, "Server \"%s\" not found", server);
1485  goto done;
1486  }
1487  if (!hsdirs) {
1488  /* Stores routerstatus_t cmddata for each specified server. */
1489  hsdirs = smartlist_new();
1490  }
1491  /* Valid server, add it to our local list. */
1492  smartlist_add(hsdirs, node->rs);
1493  } else {
1495  }
1496  }
1497 
1498  if (version == HS_VERSION_TWO) {
1499  rend_query = rend_data_client_create(hsaddress, desc_id, NULL,
1500  REND_NO_AUTH);
1501  if (rend_query == NULL) {
1502  control_write_endreply(conn, 551, "Error creating the HS query");
1503  goto done;
1504  }
1505  }
1506 
1507  /* Using a descriptor ID, we force the user to provide at least one
1508  * hsdir server using the SERVER= option. */
1509  if (desc_id && (!hsdirs || !smartlist_len(hsdirs))) {
1510  control_write_endreply(conn, 512, "SERVER option is required");
1511  goto done;
1512  }
1513 
1514  /* We are about to trigger HSDir fetch so send the OK now because after
1515  * that 650 event(s) are possible so better to have the 250 OK before them
1516  * to avoid out of order replies. */
1517  send_control_done(conn);
1518 
1519  /* Trigger the fetch using the built rend query and possibly a list of HS
1520  * directory to use. This function ignores the client cache thus this will
1521  * always send a fetch command. */
1522  if (version == HS_VERSION_TWO) {
1523  rend_client_fetch_v2_desc(rend_query, hsdirs);
1524  } else if (version == HS_VERSION_THREE) {
1525  hs_control_hsfetch_command(&v3_pk, hsdirs);
1526  }
1527 
1528  done:
1529  /* Contains data pointer that we don't own thus no cleanup. */
1530  smartlist_free(hsdirs);
1531  rend_data_free(rend_query);
1532  return 0;
1533 }
1534 
1535 static const char *hspost_keywords[] = {
1536  "SERVER", "HSADDRESS", NULL
1537 };
1538 static const control_cmd_syntax_t hspost_syntax = {
1539  .min_args = 0, .max_args = 0,
1540  .accept_keywords = true,
1541  .want_cmddata = true,
1542  .allowed_keywords = hspost_keywords
1543 };
1544 
1545 /** Implementation for the HSPOST command. */
1546 static int
1548  const control_cmd_args_t *args)
1549 {
1550  smartlist_t *hs_dirs = NULL;
1551  const char *encoded_desc = args->cmddata;
1552  size_t encoded_desc_len = args->cmddata_len;
1553  const char *onion_address = NULL;
1554  const config_line_t *line;
1555 
1556  for (line = args->kwargs; line; line = line->next) {
1557  if (!strcasecmpstart(line->key, "SERVER")) {
1558  const char *server = line->value;
1559  const node_t *node = node_get_by_hex_id(server, 0);
1560 
1561  if (!node || !node->rs) {
1562  control_printf_endreply(conn, 552, "Server \"%s\" not found",
1563  server);
1564  goto done;
1565  }
1566  /* Valid server, add it to our local list. */
1567  if (!hs_dirs)
1568  hs_dirs = smartlist_new();
1569  smartlist_add(hs_dirs, node->rs);
1570  } else if (!strcasecmpstart(line->key, "HSADDRESS")) {
1571  const char *address = line->value;
1572  if (!hs_address_is_valid(address)) {
1573  control_write_endreply(conn, 512, "Malformed onion address");
1574  goto done;
1575  }
1576  onion_address = address;
1577  } else {
1579  }
1580  }
1581 
1582  /* Handle the v3 case. */
1583  if (onion_address) {
1584  if (hs_control_hspost_command(encoded_desc, onion_address, hs_dirs) < 0) {
1585  control_write_endreply(conn, 554, "Invalid descriptor");
1586  } else {
1587  send_control_done(conn);
1588  }
1589  goto done;
1590  }
1591 
1592  /* From this point on, it is only v2. */
1593 
1594  /* parse it. */
1596  tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
1597  desc->desc_str = tor_memdup_nulterm(encoded_desc, encoded_desc_len);
1598 
1599  rend_service_descriptor_t *parsed = NULL;
1600  char *intro_content = NULL;
1601  size_t intro_size;
1602  size_t encoded_size;
1603  const char *next_desc;
1604  if (!rend_parse_v2_service_descriptor(&parsed, desc->desc_id, &intro_content,
1605  &intro_size, &encoded_size,
1606  &next_desc, desc->desc_str, 1)) {
1607  /* Post the descriptor. */
1608  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1609  if (!rend_get_service_id(parsed->pk, serviceid)) {
1610  smartlist_t *descs = smartlist_new();
1611  smartlist_add(descs, desc);
1612 
1613  /* We are about to trigger HS descriptor upload so send the OK now
1614  * because after that 650 event(s) are possible so better to have the
1615  * 250 OK before them to avoid out of order replies. */
1616  send_control_done(conn);
1617 
1618  /* Trigger the descriptor upload */
1619  directory_post_to_hs_dir(parsed, descs, hs_dirs, serviceid, 0);
1620  smartlist_free(descs);
1621  }
1622 
1623  rend_service_descriptor_free(parsed);
1624  } else {
1625  control_write_endreply(conn, 554, "Invalid descriptor");
1626  }
1627 
1628  tor_free(intro_content);
1629  rend_encoded_v2_service_descriptor_free(desc);
1630  done:
1631  smartlist_free(hs_dirs); /* Contents belong to the rend service code. */
1632  return 0;
1633 }
1634 
1635 /* Helper function for ADD_ONION that adds an ephemeral service depending on
1636  * the given hs_version.
1637  *
1638  * The secret key in pk depends on the hs_version. The ownership of the key
1639  * used in pk is given to the HS subsystem so the caller must stop accessing
1640  * it after.
1641  *
1642  * The port_cfgs is a list of service port. Ownership transferred to service.
1643  * The max_streams refers to the MaxStreams= key.
1644  * The max_streams_close_circuit refers to the MaxStreamsCloseCircuit key.
1645  * The auth_type is the authentication type of the clients in auth_clients.
1646  * The ownership of that list is transferred to the service.
1647  *
1648  * On success (RSAE_OKAY), the address_out points to a newly allocated string
1649  * containing the onion address without the .onion part. On error, address_out
1650  * is untouched. */
1652 add_onion_helper_add_service(int hs_version,
1653  add_onion_secret_key_t *pk,
1654  smartlist_t *port_cfgs, int max_streams,
1655  int max_streams_close_circuit, int auth_type,
1656  smartlist_t *auth_clients, char **address_out)
1657 {
1659 
1660  tor_assert(pk);
1661  tor_assert(port_cfgs);
1662  tor_assert(address_out);
1663 
1664  switch (hs_version) {
1665  case HS_VERSION_TWO:
1666  ret = rend_service_add_ephemeral(pk->v2, port_cfgs, max_streams,
1667  max_streams_close_circuit, auth_type,
1668  auth_clients, address_out);
1669  break;
1670  case HS_VERSION_THREE:
1671  ret = hs_service_add_ephemeral(pk->v3, port_cfgs, max_streams,
1672  max_streams_close_circuit, address_out);
1673  break;
1674  default:
1675  tor_assert_unreached();
1676  }
1677 
1678  return ret;
1679 }
1680 
1681 /** The list of onion services that have been added via ADD_ONION that do not
1682  * belong to any particular control connection.
1683  */
1685 
1686 /**
1687  * Return a list of detached onion services, or NULL if none exist.
1688  **/
1689 smartlist_t *
1691 {
1692  return detached_onion_services;
1693 }
1694 
1695 static const char *add_onion_keywords[] = {
1696  "Port", "Flags", "MaxStreams", "ClientAuth", NULL
1697 };
1698 static const control_cmd_syntax_t add_onion_syntax = {
1699  .min_args = 1, .max_args = 1,
1700  .accept_keywords = true,
1701  .allowed_keywords = add_onion_keywords
1702 };
1703 
1704 /** Called when we get a ADD_ONION command; parse the body, and set up
1705  * the new ephemeral Onion Service. */
1706 static int
1708  const control_cmd_args_t *args)
1709 {
1710  /* Parse all of the arguments that do not involve handling cryptographic
1711  * material first, since there's no reason to touch that at all if any of
1712  * the other arguments are malformed.
1713  */
1714  smartlist_t *port_cfgs = smartlist_new();
1715  smartlist_t *auth_clients = NULL;
1716  smartlist_t *auth_created_clients = NULL;
1717  int discard_pk = 0;
1718  int detach = 0;
1719  int max_streams = 0;
1720  int max_streams_close_circuit = 0;
1721  rend_auth_type_t auth_type = REND_NO_AUTH;
1722  int non_anonymous = 0;
1723  const config_line_t *arg;
1724 
1725  for (arg = args->kwargs; arg; arg = arg->next) {
1726  if (!strcasecmp(arg->key, "Port")) {
1727  /* "Port=VIRTPORT[,TARGET]". */
1729  rend_service_parse_port_config(arg->value, ",", NULL);
1730  if (!cfg) {
1731  control_write_endreply(conn, 512, "Invalid VIRTPORT/TARGET");
1732  goto out;
1733  }
1734  smartlist_add(port_cfgs, cfg);
1735  } else if (!strcasecmp(arg->key, "MaxStreams")) {
1736  /* "MaxStreams=[0..65535]". */
1737  int ok = 0;
1738  max_streams = (int)tor_parse_long(arg->value, 10, 0, 65535, &ok, NULL);
1739  if (!ok) {
1740  control_write_endreply(conn, 512, "Invalid MaxStreams");
1741  goto out;
1742  }
1743  } else if (!strcasecmp(arg->key, "Flags")) {
1744  /* "Flags=Flag[,Flag]", where Flag can be:
1745  * * 'DiscardPK' - If tor generates the keypair, do not include it in
1746  * the response.
1747  * * 'Detach' - Do not tie this onion service to any particular control
1748  * connection.
1749  * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
1750  * exceeded.
1751  * * 'BasicAuth' - Client authorization using the 'basic' method.
1752  * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
1753  * flag is present, tor must be in non-anonymous
1754  * hidden service mode. If this flag is absent,
1755  * tor must be in anonymous hidden service mode.
1756  */
1757  static const char *discard_flag = "DiscardPK";
1758  static const char *detach_flag = "Detach";
1759  static const char *max_s_close_flag = "MaxStreamsCloseCircuit";
1760  static const char *basicauth_flag = "BasicAuth";
1761  static const char *non_anonymous_flag = "NonAnonymous";
1762 
1763  smartlist_t *flags = smartlist_new();
1764  int bad = 0;
1765 
1766  smartlist_split_string(flags, arg->value, ",", SPLIT_IGNORE_BLANK, 0);
1767  if (smartlist_len(flags) < 1) {
1768  control_write_endreply(conn, 512, "Invalid 'Flags' argument");
1769  bad = 1;
1770  }
1771  SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
1772  {
1773  if (!strcasecmp(flag, discard_flag)) {
1774  discard_pk = 1;
1775  } else if (!strcasecmp(flag, detach_flag)) {
1776  detach = 1;
1777  } else if (!strcasecmp(flag, max_s_close_flag)) {
1778  max_streams_close_circuit = 1;
1779  } else if (!strcasecmp(flag, basicauth_flag)) {
1780  auth_type = REND_BASIC_AUTH;
1781  } else if (!strcasecmp(flag, non_anonymous_flag)) {
1782  non_anonymous = 1;
1783  } else {
1784  control_printf_endreply(conn, 512, "Invalid 'Flags' argument: %s",
1785  escaped(flag));
1786  bad = 1;
1787  break;
1788  }
1789  } SMARTLIST_FOREACH_END(flag);
1790  SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
1791  smartlist_free(flags);
1792  if (bad)
1793  goto out;
1794 
1795  } else if (!strcasecmp(arg->key, "ClientAuth")) {
1796  int created = 0;
1797  rend_authorized_client_t *client =
1798  add_onion_helper_clientauth(arg->value, &created, conn);
1799  if (!client) {
1800  goto out;
1801  }
1802 
1803  if (auth_clients != NULL) {
1804  int bad = 0;
1805  SMARTLIST_FOREACH_BEGIN(auth_clients, rend_authorized_client_t *, ac) {
1806  if (strcmp(ac->client_name, client->client_name) == 0) {
1807  bad = 1;
1808  break;
1809  }
1810  } SMARTLIST_FOREACH_END(ac);
1811  if (bad) {
1812  control_write_endreply(conn, 512, "Duplicate name in ClientAuth");
1813  rend_authorized_client_free(client);
1814  goto out;
1815  }
1816  } else {
1817  auth_clients = smartlist_new();
1818  auth_created_clients = smartlist_new();
1819  }
1820  smartlist_add(auth_clients, client);
1821  if (created) {
1822  smartlist_add(auth_created_clients, client);
1823  }
1824  } else {
1826  goto out;
1827  }
1828  }
1829  if (smartlist_len(port_cfgs) == 0) {
1830  control_write_endreply(conn, 512, "Missing 'Port' argument");
1831  goto out;
1832  } else if (auth_type == REND_NO_AUTH && auth_clients != NULL) {
1833  control_write_endreply(conn, 512, "No auth type specified");
1834  goto out;
1835  } else if (auth_type != REND_NO_AUTH && auth_clients == NULL) {
1836  control_write_endreply(conn, 512, "No auth clients specified");
1837  goto out;
1838  } else if ((auth_type == REND_BASIC_AUTH &&
1839  smartlist_len(auth_clients) > 512) ||
1840  (auth_type == REND_STEALTH_AUTH &&
1841  smartlist_len(auth_clients) > 16)) {
1842  control_write_endreply(conn, 512, "Too many auth clients");
1843  goto out;
1844  } else if (non_anonymous != rend_service_non_anonymous_mode_enabled(
1845  get_options())) {
1846  /* If we failed, and the non-anonymous flag is set, Tor must be in
1847  * anonymous hidden service mode.
1848  * The error message changes based on the current Tor config:
1849  * 512 Tor is in anonymous hidden service mode
1850  * 512 Tor is in non-anonymous hidden service mode
1851  * (I've deliberately written them out in full here to aid searchability.)
1852  */
1853  control_printf_endreply(conn, 512,
1854  "Tor is in %sanonymous hidden service " "mode",
1855  non_anonymous ? "" : "non-");
1856  goto out;
1857  }
1858 
1859  /* Parse the "keytype:keyblob" argument. */
1860  int hs_version = 0;
1861  add_onion_secret_key_t pk = { NULL };
1862  const char *key_new_alg = NULL;
1863  char *key_new_blob = NULL;
1864 
1865  const char *onionkey = smartlist_get(args->args, 0);
1866  if (add_onion_helper_keyarg(onionkey, discard_pk,
1867  &key_new_alg, &key_new_blob, &pk, &hs_version,
1868  conn) < 0) {
1869  goto out;
1870  }
1871 
1872  /* Hidden service version 3 don't have client authentication support so if
1873  * ClientAuth was given, send back an error. */
1874  if (hs_version == HS_VERSION_THREE && auth_clients) {
1875  control_write_endreply(conn, 513, "ClientAuth not supported");
1876  goto out;
1877  }
1878 
1879  /* Create the HS, using private key pk, client authentication auth_type,
1880  * the list of auth_clients, and port config port_cfg.
1881  * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
1882  * regardless of success/failure.
1883  */
1884  char *service_id = NULL;
1885  int ret = add_onion_helper_add_service(hs_version, &pk, port_cfgs,
1886  max_streams,
1887  max_streams_close_circuit, auth_type,
1888  auth_clients, &service_id);
1889  port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
1890  auth_clients = NULL; /* so is auth_clients */
1891  switch (ret) {
1892  case RSAE_OKAY:
1893  {
1894  if (detach) {
1898  } else {
1899  if (!conn->ephemeral_onion_services)
1901  smartlist_add(conn->ephemeral_onion_services, service_id);
1902  }
1903 
1904  tor_assert(service_id);
1905  control_printf_midreply(conn, 250, "ServiceID=%s", service_id);
1906  if (key_new_alg) {
1907  tor_assert(key_new_blob);
1908  control_printf_midreply(conn, 250, "PrivateKey=%s:%s",
1909  key_new_alg, key_new_blob);
1910  }
1911  if (auth_created_clients) {
1912  SMARTLIST_FOREACH(auth_created_clients, rend_authorized_client_t *, ac, {
1913  char *encoded = rend_auth_encode_cookie(ac->descriptor_cookie,
1914  auth_type);
1915  tor_assert(encoded);
1916  control_printf_midreply(conn, 250, "ClientAuth=%s:%s",
1917  ac->client_name, encoded);
1918  memwipe(encoded, 0, strlen(encoded));
1919  tor_free(encoded);
1920  });
1921  }
1922 
1923  send_control_done(conn);
1924  break;
1925  }
1926  case RSAE_BADPRIVKEY:
1927  control_write_endreply(conn, 551, "Failed to generate onion address");
1928  break;
1929  case RSAE_ADDREXISTS:
1930  control_write_endreply(conn, 550, "Onion address collision");
1931  break;
1932  case RSAE_BADVIRTPORT:
1933  control_write_endreply(conn, 512, "Invalid VIRTPORT/TARGET");
1934  break;
1935  case RSAE_BADAUTH:
1936  control_write_endreply(conn, 512, "Invalid client authorization");
1937  break;
1938  case RSAE_INTERNAL: FALLTHROUGH;
1939  default:
1940  control_write_endreply(conn, 551, "Failed to add Onion Service");
1941  }
1942  if (key_new_blob) {
1943  memwipe(key_new_blob, 0, strlen(key_new_blob));
1944  tor_free(key_new_blob);
1945  }
1946 
1947  out:
1948  if (port_cfgs) {
1950  rend_service_port_config_free(p));
1951  smartlist_free(port_cfgs);
1952  }
1953 
1954  if (auth_clients) {
1955  SMARTLIST_FOREACH(auth_clients, rend_authorized_client_t *, ac,
1956  rend_authorized_client_free(ac));
1957  smartlist_free(auth_clients);
1958  }
1959  if (auth_created_clients) {
1960  // Do not free entries; they are the same as auth_clients
1961  smartlist_free(auth_created_clients);
1962  }
1963  return 0;
1964 }
1965 
1966 /** Helper function to handle parsing the KeyType:KeyBlob argument to the
1967  * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
1968  * and the private key not discarded, the algorithm and serialized private key,
1969  * or NULL and an optional control protocol error message on failure. The
1970  * caller is responsible for freeing the returned key_new_blob.
1971  *
1972  * Note: The error messages returned are deliberately vague to avoid echoing
1973  * key material.
1974  *
1975  * Note: conn is only used for writing control replies. For testing
1976  * purposes, it can be NULL if control_write_reply() is appropriately
1977  * mocked.
1978  */
1979 STATIC int
1980 add_onion_helper_keyarg(const char *arg, int discard_pk,
1981  const char **key_new_alg_out, char **key_new_blob_out,
1982  add_onion_secret_key_t *decoded_key, int *hs_version,
1983  control_connection_t *conn)
1984 {
1985  smartlist_t *key_args = smartlist_new();
1986  crypto_pk_t *pk = NULL;
1987  const char *key_new_alg = NULL;
1988  char *key_new_blob = NULL;
1989  int ret = -1;
1990 
1991  smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
1992  if (smartlist_len(key_args) != 2) {
1993  control_write_endreply(conn, 512, "Invalid key type/blob");
1994  goto err;
1995  }
1996 
1997  /* The format is "KeyType:KeyBlob". */
1998  static const char *key_type_new = "NEW";
1999  static const char *key_type_best = "BEST";
2000  static const char *key_type_rsa1024 = "RSA1024";
2001  static const char *key_type_ed25519_v3 = "ED25519-V3";
2002 
2003  const char *key_type = smartlist_get(key_args, 0);
2004  const char *key_blob = smartlist_get(key_args, 1);
2005 
2006  if (!strcasecmp(key_type_rsa1024, key_type)) {
2007  /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
2008  pk = crypto_pk_base64_decode_private(key_blob, strlen(key_blob));
2009  if (!pk) {
2010  control_write_endreply(conn, 512, "Failed to decode RSA key");
2011  goto err;
2012  }
2013  if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
2014  crypto_pk_free(pk);
2015  control_write_endreply(conn, 512, "Invalid RSA key size");
2016  goto err;
2017  }
2018  decoded_key->v2 = pk;
2019  *hs_version = HS_VERSION_TWO;
2020  } else if (!strcasecmp(key_type_ed25519_v3, key_type)) {
2021  /* parsing of private ed25519 key */
2022  /* "ED25519-V3:<Base64 Blob>" - Loading a pre-existing ed25519 key. */
2023  ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
2024  if (base64_decode((char *) sk->seckey, sizeof(sk->seckey), key_blob,
2025  strlen(key_blob)) != sizeof(sk->seckey)) {
2026  tor_free(sk);
2027  control_write_endreply(conn, 512, "Failed to decode ED25519-V3 key");
2028  goto err;
2029  }
2030  decoded_key->v3 = sk;
2031  *hs_version = HS_VERSION_THREE;
2032  } else if (!strcasecmp(key_type_new, key_type)) {
2033  /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
2034  if (!strcasecmp(key_type_rsa1024, key_blob)) {
2035  /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
2036  pk = crypto_pk_new();
2037  if (crypto_pk_generate_key(pk)) {
2038  control_printf_endreply(conn, 551, "Failed to generate %s key",
2039  key_type_rsa1024);
2040  goto err;
2041  }
2042  if (!discard_pk) {
2043  if (crypto_pk_base64_encode_private(pk, &key_new_blob)) {
2044  crypto_pk_free(pk);
2045  control_printf_endreply(conn, 551, "Failed to encode %s key",
2046  key_type_rsa1024);
2047  goto err;
2048  }
2049  key_new_alg = key_type_rsa1024;
2050  }
2051  decoded_key->v2 = pk;
2052  *hs_version = HS_VERSION_TWO;
2053  } else if (!strcasecmp(key_type_ed25519_v3, key_blob) ||
2054  !strcasecmp(key_type_best, key_blob)) {
2055  /* "ED25519-V3", ed25519 key, also currently "BEST" by default. */
2056  ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
2057  if (ed25519_secret_key_generate(sk, 1) < 0) {
2058  tor_free(sk);
2059  control_printf_endreply(conn, 551, "Failed to generate %s key",
2060  key_type_ed25519_v3);
2061  goto err;
2062  }
2063  if (!discard_pk) {
2064  ssize_t len = base64_encode_size(sizeof(sk->seckey), 0) + 1;
2065  key_new_blob = tor_malloc_zero(len);
2066  if (base64_encode(key_new_blob, len, (const char *) sk->seckey,
2067  sizeof(sk->seckey), 0) != (len - 1)) {
2068  tor_free(sk);
2069  tor_free(key_new_blob);
2070  control_printf_endreply(conn, 551, "Failed to encode %s key",
2071  key_type_ed25519_v3);
2072  goto err;
2073  }
2074  key_new_alg = key_type_ed25519_v3;
2075  }
2076  decoded_key->v3 = sk;
2077  *hs_version = HS_VERSION_THREE;
2078  } else {
2079  control_write_endreply(conn, 513, "Invalid key type");
2080  goto err;
2081  }
2082  } else {
2083  control_write_endreply(conn, 513, "Invalid key type");
2084  goto err;
2085  }
2086 
2087  /* Succeeded in loading or generating a private key. */
2088  ret = 0;
2089 
2090  err:
2091  SMARTLIST_FOREACH(key_args, char *, cp, {
2092  memwipe(cp, 0, strlen(cp));
2093  tor_free(cp);
2094  });
2095  smartlist_free(key_args);
2096 
2097  *key_new_alg_out = key_new_alg;
2098  *key_new_blob_out = key_new_blob;
2099 
2100  return ret;
2101 }
2102 
2103 /** Helper function to handle parsing a ClientAuth argument to the
2104  * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
2105  * and an optional control protocol error message on failure. The
2106  * caller is responsible for freeing the returned auth_client.
2107  *
2108  * If 'created' is specified, it will be set to 1 when a new cookie has
2109  * been generated.
2110  *
2111  * Note: conn is only used for writing control replies. For testing
2112  * purposes, it can be NULL if control_write_reply() is appropriately
2113  * mocked.
2114  */
2116 add_onion_helper_clientauth(const char *arg, int *created,
2117  control_connection_t *conn)
2118 {
2119  int ok = 0;
2120 
2121  tor_assert(arg);
2122  tor_assert(created);
2123 
2124  smartlist_t *auth_args = smartlist_new();
2125  rend_authorized_client_t *client =
2126  tor_malloc_zero(sizeof(rend_authorized_client_t));
2127  smartlist_split_string(auth_args, arg, ":", 0, 0);
2128  if (smartlist_len(auth_args) < 1 || smartlist_len(auth_args) > 2) {
2129  control_write_endreply(conn, 512, "Invalid ClientAuth syntax");
2130  goto err;
2131  }
2132  client->client_name = tor_strdup(smartlist_get(auth_args, 0));
2133  if (smartlist_len(auth_args) == 2) {
2134  char *decode_err_msg = NULL;
2135  if (rend_auth_decode_cookie(smartlist_get(auth_args, 1),
2136  client->descriptor_cookie,
2137  NULL, &decode_err_msg) < 0) {
2138  tor_assert(decode_err_msg);
2139  control_write_endreply(conn, 512, decode_err_msg);
2140  tor_free(decode_err_msg);
2141  goto err;
2142  }
2143  *created = 0;
2144  } else {
2145  crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
2146  *created = 1;
2147  }
2148 
2149  if (!rend_valid_client_name(client->client_name)) {
2150  control_write_endreply(conn, 512, "Invalid name in ClientAuth");
2151  goto err;
2152  }
2153 
2154  ok = 1;
2155  err:
2156  SMARTLIST_FOREACH(auth_args, char *, item, tor_free(item));
2157  smartlist_free(auth_args);
2158  if (!ok) {
2159  rend_authorized_client_free(client);
2160  client = NULL;
2161  }
2162  return client;
2163 }
2164 
2165 static const control_cmd_syntax_t del_onion_syntax = {
2166  .min_args = 1, .max_args = 1,
2167 };
2168 
2169 /** Called when we get a DEL_ONION command; parse the body, and remove
2170  * the existing ephemeral Onion Service. */
2171 static int
2173  const control_cmd_args_t *cmd_args)
2174 {
2175  int hs_version = 0;
2176  smartlist_t *args = cmd_args->args;
2177  tor_assert(smartlist_len(args) == 1);
2178 
2179  const char *service_id = smartlist_get(args, 0);
2180  if (rend_valid_v2_service_id(service_id)) {
2181  hs_version = HS_VERSION_TWO;
2182  } else if (hs_address_is_valid(service_id)) {
2183  hs_version = HS_VERSION_THREE;
2184  } else {
2185  control_write_endreply(conn, 512, "Malformed Onion Service id");
2186  goto out;
2187  }
2188 
2189  /* Determine if the onion service belongs to this particular control
2190  * connection, or if it is in the global list of detached services. If it
2191  * is in neither, either the service ID is invalid in some way, or it
2192  * explicitly belongs to a different control connection, and an error
2193  * should be returned.
2194  */
2195  smartlist_t *services[2] = {
2198  };
2199  smartlist_t *onion_services = NULL;
2200  int idx = -1;
2201  for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
2202  idx = smartlist_string_pos(services[i], service_id);
2203  if (idx != -1) {
2204  onion_services = services[i];
2205  break;
2206  }
2207  }
2208  if (onion_services == NULL) {
2209  control_write_endreply(conn, 552, "Unknown Onion Service id");
2210  } else {
2211  int ret = -1;
2212  switch (hs_version) {
2213  case HS_VERSION_TWO:
2214  ret = rend_service_del_ephemeral(service_id);
2215  break;
2216  case HS_VERSION_THREE:
2217  ret = hs_service_del_ephemeral(service_id);
2218  break;
2219  default:
2220  /* The ret value will be -1 thus hitting the warning below. This should
2221  * never happen because of the check at the start of the function. */
2222  break;
2223  }
2224  if (ret < 0) {
2225  /* This should *NEVER* fail, since the service is on either the
2226  * per-control connection list, or the global one.
2227  */
2228  log_warn(LD_BUG, "Failed to remove Onion Service %s.",
2229  escaped(service_id));
2231  }
2232 
2233  /* Remove/scrub the service_id from the appropriate list. */
2234  char *cp = smartlist_get(onion_services, idx);
2235  smartlist_del(onion_services, idx);
2236  memwipe(cp, 0, strlen(cp));
2237  tor_free(cp);
2238 
2239  send_control_done(conn);
2240  }
2241 
2242  out:
2243  return 0;
2244 }
2245 
2246 static const control_cmd_syntax_t obsolete_syntax = {
2247  .max_args = UINT_MAX
2248 };
2249 
2250 /**
2251  * Called when we get an obsolete command: tell the controller that it is
2252  * obsolete.
2253  */
2254 static int
2256  const control_cmd_args_t *args)
2257 {
2258  (void)args;
2259  char *command = tor_strdup(conn->current_cmd);
2261  control_printf_endreply(conn, 511, "%s is obsolete.", command);
2262  tor_free(command);
2263  return 0;
2264 }
2265 
2266 /**
2267  * Function pointer to a handler function for a controller command.
2268  **/
2269 typedef int (*handler_fn_t) (control_connection_t *conn,
2270  const control_cmd_args_t *args);
2271 
2272 /**
2273  * Definition for a controller command.
2274  */
2275 typedef struct control_cmd_def_t {
2276  /**
2277  * The name of the command. If the command is multiline, the name must
2278  * begin with "+". This is not case-sensitive. */
2279  const char *name;
2280  /**
2281  * A function to execute the command.
2282  */
2284  /**
2285  * Zero or more CMD_FL_* flags, or'd together.
2286  */
2287  unsigned flags;
2288  /**
2289  * For parsed command: a syntax description.
2290  */
2293 
2294 /**
2295  * Indicates that the command's arguments are sensitive, and should be
2296  * memwiped after use.
2297  */
2298 #define CMD_FL_WIPE (1u<<0)
2300 #ifndef COCCI
2301 /** Macro: declare a command with a one-line argument, a given set of flags,
2302  * and a syntax definition.
2303  **/
2304 #define ONE_LINE(name, flags) \
2305  { \
2306  (#name), \
2307  handle_control_ ##name, \
2308  flags, \
2309  &name##_syntax, \
2310  }
2311 
2312 /**
2313  * Macro: declare a command with a multi-line argument and a given set of
2314  * flags.
2315  **/
2316 #define MULTLINE(name, flags) \
2317  { ("+"#name), \
2318  handle_control_ ##name, \
2319  flags, \
2320  &name##_syntax \
2321  }
2322 
2323 /**
2324  * Macro: declare an obsolete command. (Obsolete commands give a different
2325  * error than non-existent ones.)
2326  **/
2327 #define OBSOLETE(name) \
2328  { #name, \
2329  handle_control_obsolete, \
2330  0, \
2331  &obsolete_syntax, \
2332  }
2333 #endif /* !defined(COCCI) */
2334 
2335 /**
2336  * An array defining all the recognized controller commands.
2337  **/
2339 {
2340  ONE_LINE(setconf, 0),
2341  ONE_LINE(resetconf, 0),
2342  ONE_LINE(getconf, 0),
2343  MULTLINE(loadconf, 0),
2344  ONE_LINE(setevents, 0),
2345  ONE_LINE(authenticate, CMD_FL_WIPE),
2346  ONE_LINE(saveconf, 0),
2347  ONE_LINE(signal, 0),
2348  ONE_LINE(takeownership, 0),
2349  ONE_LINE(dropownership, 0),
2350  ONE_LINE(mapaddress, 0),
2351  ONE_LINE(getinfo, 0),
2352  ONE_LINE(extendcircuit, 0),
2353  ONE_LINE(setcircuitpurpose, 0),
2354  OBSOLETE(setrouterpurpose),
2355  ONE_LINE(attachstream, 0),
2356  MULTLINE(postdescriptor, 0),
2357  ONE_LINE(redirectstream, 0),
2358  ONE_LINE(closestream, 0),
2359  ONE_LINE(closecircuit, 0),
2360  ONE_LINE(usefeature, 0),
2361  ONE_LINE(resolve, 0),
2362  ONE_LINE(protocolinfo, 0),
2363  ONE_LINE(authchallenge, CMD_FL_WIPE),
2364  ONE_LINE(dropguards, 0),
2365  ONE_LINE(droptimeouts, 0),
2366  ONE_LINE(hsfetch, 0),
2367  MULTLINE(hspost, 0),
2368  ONE_LINE(add_onion, CMD_FL_WIPE),
2369  ONE_LINE(del_onion, CMD_FL_WIPE),
2370  ONE_LINE(onion_client_auth_add, CMD_FL_WIPE),
2371  ONE_LINE(onion_client_auth_remove, 0),
2372  ONE_LINE(onion_client_auth_view, 0),
2373 };
2374 
2375 /**
2376  * The number of entries in CONTROL_COMMANDS.
2377  **/
2379 
2380 /**
2381  * Run a single control command, as defined by a control_cmd_def_t,
2382  * with a given set of arguments.
2383  */
2384 static int
2386  control_connection_t *conn,
2387  uint32_t cmd_data_len,
2388  char *args)
2389 {
2390  int rv = 0;
2391 
2392  control_cmd_args_t *parsed_args;
2393  char *err=NULL;
2394  tor_assert(def->syntax);
2395  parsed_args = control_cmd_parse_args(conn->current_cmd,
2396  def->syntax,
2397  cmd_data_len, args,
2398  &err);
2399  if (!parsed_args) {
2400  control_printf_endreply(conn, 512, "Bad arguments to %s: %s",
2401  conn->current_cmd, err?err:"");
2402  tor_free(err);
2403  } else {
2404  if (BUG(err))
2405  tor_free(err);
2406  if (def->handler(conn, parsed_args))
2407  rv = 0;
2408 
2409  if (def->flags & CMD_FL_WIPE)
2410  control_cmd_args_wipe(parsed_args);
2411 
2412  control_cmd_args_free(parsed_args);
2413  }
2414 
2415  if (def->flags & CMD_FL_WIPE)
2416  memwipe(args, 0, cmd_data_len);
2417 
2418  return rv;
2419 }
2420 
2421 /**
2422  * Run a given controller command, as selected by the current_cmd field of
2423  * <b>conn</b>.
2424  */
2425 int
2427  uint32_t cmd_data_len,
2428  char *args)
2429 {
2430  tor_assert(conn);
2431  tor_assert(args);
2432  tor_assert(args[cmd_data_len] == '\0');
2433 
2434  for (unsigned i = 0; i < N_CONTROL_COMMANDS; ++i) {
2435  const control_cmd_def_t *def = &CONTROL_COMMANDS[i];
2436  if (!strcasecmp(conn->current_cmd, def->name)) {
2437  return handle_single_control_command(def, conn, cmd_data_len, args);
2438  }
2439  }
2440 
2441  control_printf_endreply(conn, 510, "Unrecognized command \"%s\"",
2442  conn->current_cmd);
2443 
2444  return 0;
2445 }
2446 
2447 void
2448 control_cmd_free_all(void)
2449 {
2450  if (detached_onion_services) { /* Free the detached onion services */
2452  smartlist_free(detached_onion_services);
2453  }
2454 }
control_connection_t::is_owning_control_connection
unsigned int is_owning_control_connection
Definition: control_connection_st.h:30
CAL_USE_DEFAULTS
#define CAL_USE_DEFAULTS
Definition: confmgt.h:50
control_reply_add_one_kv
void control_reply_add_one_kv(smartlist_t *reply, int code, int flags, const char *key, const char *val)
Definition: control_proto.c:338
handle_control_redirectstream
static int handle_control_redirectstream(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:1085
remove_all_entry_guards
void remove_all_entry_guards(void)
Definition: entrynodes.c:3806
tor_free
#define tor_free(p)
Definition: malloc.h:52
get_circuit_build_times_mutable
circuit_build_times_t * get_circuit_build_times_mutable(void)
Definition: circuitstats.c:86
add_onion_helper_clientauth
STATIC rend_authorized_client_t * add_onion_helper_clientauth(const char *arg, int *created, control_connection_t *conn)
Definition: control_cmd.c:2116
connection_edge.h
Header file for connection_edge.c.
handle_control_resolve
static int handle_control_resolve(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1203
handle_control_droptimeouts
static int handle_control_droptimeouts(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1408
smartlist_split_string
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
Definition: smartlist_split.c:37
control_connection_t::have_sent_protocolinfo
unsigned int have_sent_protocolinfo
Definition: control_connection_st.h:27
or_state_mark_dirty
void or_state_mark_dirty(or_state_t *state, time_t when)
Definition: statefile.c:741
CIRCUIT_STATE_OPEN
#define CIRCUIT_STATE_OPEN
Definition: circuitlist.h:32
rend_encoded_v2_service_descriptor_t::desc_str
char * desc_str
Definition: rend_encoded_v2_service_descriptor_st.h:18
routerinfo.h
Header file for routerinfo.c.
rend_service_del_ephemeral
int rend_service_del_ephemeral(const char *service_id)
Definition: rendservice.c:974
name
const char * name
Definition: config.c:2443
handle_control_mapaddress
static int handle_control_mapaddress(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:639
CAL_CLEAR_FIRST
#define CAL_CLEAR_FIRST
Definition: confmgt.h:59
HS_VERSION_TWO
#define HS_VERSION_TWO
Definition: hs_common.h:24
control_cmd_args_t
Definition: control_cmd_args_st.h:24
control_cmd_def_t::name
const char * name
Definition: control_cmd.c:2279
entry_connection_st.h
Entry connection structure.
memwipe
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:55
N_CONTROL_COMMANDS
static const size_t N_CONTROL_COMMANDS
Definition: control_cmd.c:2378
circuit_send_next_onion_skin
int circuit_send_next_onion_skin(origin_circuit_t *circ)
Definition: circuitbuild.c:904
CIRCUIT_PURPOSE_C_GENERAL
#define CIRCUIT_PURPOSE_C_GENERAL
Definition: circuitlist.h:72
control_connection_t::ephemeral_onion_services
smartlist_t * ephemeral_onion_services
Definition: control_connection_st.h:33
dnsserv.h
Header file for dnsserv.c.
options_save_current
int options_save_current(void)
Definition: config.c:6839
CMD_RUN_TOR
@ CMD_RUN_TOR
Definition: tor_cmdline_mode.h:20
tor_strupper
void tor_strupper(char *s)
Definition: util_string.c:138
or_options_t::HashedControlPassword
struct config_line_t * HashedControlPassword
Definition: or_options_st.h:505
edge_connection_t::edge_has_sent_end
unsigned int edge_has_sent_end
Definition: edge_connection_st.h:67
rend_valid_client_name
int rend_valid_client_name(const char *client_name)
Definition: rendcommon.c:757
handle_control_signal
static int handle_control_signal(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:462
CONTROL_COMMANDS
static const control_cmd_def_t CONTROL_COMMANDS[]
Definition: control_cmd.c:2338
control_connection_t::current_cmd
char * current_cmd
Definition: control_connection_st.h:49
rend_service_descriptor_st.h
Parsed v2 HS descriptor structure.
handle_control_hspost
static int handle_control_hspost(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1547
CIRCLAUNCH_NEED_CAPACITY
#define CIRCLAUNCH_NEED_CAPACITY
Definition: circuituse.h:43
tor_assert
#define tor_assert(expr)
Definition: util_bug.h:102
control.h
Header file for control.c.
rendparse.h
Header file for rendparse.c.
handle_control_command
int handle_control_command(control_connection_t *conn, uint32_t cmd_data_len, char *args)
Definition: control_cmd.c:2426
crypto_pk_new
crypto_pk_t * crypto_pk_new(void)
Definition: crypto_rsa_nss.c:165
confmgt.h
Header for confmgt.c.
LD_BUG
#define LD_BUG
Definition: log.h:86
add_onion_helper_keyarg
STATIC int add_onion_helper_keyarg(const char *arg, int discard_pk, const char **key_new_alg_out, char **key_new_blob_out, add_onion_secret_key_t *decoded_key, int *hs_version, control_connection_t *conn)
Definition: control_cmd.c:1980
control_cmd_syntax_t::want_cmddata
bool want_cmddata
Definition: control_cmd.h:67
cpath_build_state_st.h
Circuit-build-stse structure.
rend_service_port_config_t
Definition: hs_common.h:153
circuituse.h
Header file for circuituse.c.
connection_entry_set_controller_wait
void connection_entry_set_controller_wait(entry_connection_t *conn)
Definition: connection_edge.c:1559
circuit_append_new_exit
int circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
Definition: circuitbuild.c:2062
router_load_single_router
int router_load_single_router(const char *s, uint8_t purpose, int cache, const char **msg)
Definition: routerlist.c:2045
tor_fragile_assert
#define tor_fragile_assert()
Definition: util_bug.h:259
rend_auth_type_t
rend_auth_type_t
Definition: or.h:403
control_proto.h
Header file for control_proto.c.
control_event_address_mapped
int control_event_address_mapped(const char *from, const char *to, time_t expires, const char *error, const int cached)
Definition: control_events.c:1463
hs_service_add_ephemeral
hs_service_add_ephemeral_status_t hs_service_add_ephemeral(ed25519_secret_key_t *sk, smartlist_t *ports, int max_streams_per_rdv_circuit, int max_streams_close_circuit, char **address_out)
Definition: hs_service.c:3644
node_get_by_nickname
const node_t * node_get_by_nickname(const char *nickname, unsigned flags)
Definition: nodelist.c:1004
REND_SERVICE_ID_LEN_BASE32
#define REND_SERVICE_ID_LEN_BASE32
Definition: or.h:332
control_cmd_def_t::flags
unsigned flags
Definition: control_cmd.c:2287
tor_parse_uint64
uint64_t tor_parse_uint64(const char *s, int base, uint64_t min, uint64_t max, int *ok, char **next)
Definition: parse_int.c:110
smartlist_add
void smartlist_add(smartlist_t *sl, void *element)
Definition: smartlist_core.c:117
get_stream
static entry_connection_t * get_stream(const char *id)
Definition: control_cmd.c:553
circuit_launch
origin_circuit_t * circuit_launch(uint8_t purpose, int flags)
Definition: circuituse.c:1951
handle_control_takeownership
static int handle_control_takeownership(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:501
connection_get_by_global_id
connection_t * connection_get_by_global_id(uint64_t id)
Definition: connection.c:4742
rend_encoded_v2_service_descriptor_st.h
Encoded v2 HS descriptor structure.
hs_service_del_ephemeral
int hs_service_del_ephemeral(const char *address)
Definition: hs_service.c:3724
rend_auth_encode_cookie
char * rend_auth_encode_cookie(const uint8_t *cookie_in, rend_auth_type_t auth_type)
Definition: rendcommon.c:894
handle_control_closestream
static int handle_control_closestream(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:1132
control_cmd_syntax_t::max_args
unsigned int max_args
Definition: control_cmd.h:46
circuit_handle_first_hop
int circuit_handle_first_hop(origin_circuit_t *circ)
Definition: circuitbuild.c:540
rend_service_descriptor_t
Definition: rend_service_descriptor_st.h:19
get_detached_onion_services
smartlist_t * get_detached_onion_services(void)
Definition: control_cmd.c:1690
ed25519_secret_key_generate
int ed25519_secret_key_generate(ed25519_secret_key_t *seckey_out, int extra_strong)
Definition: crypto_ed25519.c:168
edge_connection_t::end_reason
uint16_t end_reason
Definition: edge_connection_st.h:54
smartlist_new
smartlist_t * smartlist_new(void)
Definition: smartlist_core.c:26
socks_request_st.h
Client request structure.
send_control_done
void send_control_done(control_connection_t *conn)
Definition: control_proto.c:169
base64_encode
int base64_encode(char *dest, size_t destlen, const char *src, size_t srclen, int flags)
Definition: binascii.c:215
options_init_from_string
setopt_err_t options_init_from_string(const char *cf_defaults, const char *cf, int command, const char *command_arg, char **msg)
Definition: config.c:4535
control_cmd_args_t::kwargs
struct config_line_t * kwargs
Definition: control_cmd_args_st.h:37
tor_parse_long
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition: parse_int.c:59
crypt_path_t
Definition: crypt_path_st.h:47
control_cmd_args_free_
void control_cmd_args_free_(control_cmd_args_t *args)
Definition: control_cmd.c:74
handle_control_dropguards
static int handle_control_dropguards(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1383
MULTLINE
#define MULTLINE(name, flags)
Definition: control_cmd.c:2316
statefile.h
Header for statefile.c.
kvline_check_keyword_args
static int kvline_check_keyword_args(const control_cmd_args_t *result, const control_cmd_syntax_t *syntax, char **error_out)
Definition: control_cmd.c:128
smartlist_pop_last
void * smartlist_pop_last(smartlist_t *sl)
Definition: smartlist_core.c:187
hs_address_is_valid
int hs_address_is_valid(const char *address)
Definition: hs_common.c:974
handle_control_loadconf
static int handle_control_loadconf(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:341
SMARTLIST_FOREACH
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Definition: smartlist_foreach.h:112
get_or_state
or_state_t * get_or_state(void)
Definition: statefile.c:208
handle_control_hsfetch
static int handle_control_hsfetch(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1441
config_lines_dup
config_line_t * config_lines_dup(const config_line_t *inp)
Definition: confline.c:226
base32_decode
int base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:90
handler_fn_t
int(* handler_fn_t)(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:2269
origin_circuit_t::global_identifier
uint32_t global_identifier
Definition: origin_circuit_st.h:240
control_cmd_def_t::syntax
const control_cmd_syntax_t * syntax
Definition: control_cmd.c:2291
rend_client_fetch_v2_desc
int rend_client_fetch_v2_desc(rend_data_t *query, smartlist_t *hsdirs)
Definition: rendclient.c:682
crypto_util.h
Common functions for cryptographic routines.
hs_service_add_ephemeral_status_t
hs_service_add_ephemeral_status_t
Definition: hs_common.h:142
CIRCUIT_PURPOSE_CONTROLLER
#define CIRCUIT_PURPOSE_CONTROLLER
Definition: circuitlist.h:120
control_cmd_args_t::args
struct smartlist_t * args
Definition: control_cmd_args_st.h:33
REND_DESC_ID_V2_LEN_BASE32
#define REND_DESC_ID_V2_LEN_BASE32
Definition: or.h:355
base64_encode_size
size_t base64_encode_size(size_t srclen, int flags)
Definition: binascii.c:166
ENTRY_TO_EDGE_CONN
#define ENTRY_TO_EDGE_CONN(c)
Definition: entry_connection_st.h:102
control_cmd_def_t::handler
handler_fn_t handler
Definition: control_cmd.c:2283
smartlist_string_pos
int smartlist_string_pos(const smartlist_t *sl, const char *element)
Definition: smartlist.c:106
circuitlist.h
Header file for circuitlist.c.
DIGEST_LEN
#define DIGEST_LEN
Definition: digest_sizes.h:20
handle_control_setconf
static int handle_control_setconf(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:261
CONN_TYPE_AP
#define CONN_TYPE_AP
Definition: connection.h:51
AP_CONN_STATE_RESOLVE_WAIT
#define AP_CONN_STATE_RESOLVE_WAIT
Definition: connection_edge.h:53
get_authmethods
static char * get_authmethods(const or_options_t *options)
Definition: control_cmd.c:1249
options_trial_assign
setopt_err_t options_trial_assign(config_line_t *list, unsigned flags, char **msg)
Definition: config.c:2661
RSAE_BADVIRTPORT
@ RSAE_BADVIRTPORT
Definition: hs_common.h:144
address_is_invalid_destination
int address_is_invalid_destination(const char *address, int client)
Definition: addressmap.c:1077
RSAE_BADAUTH
@ RSAE_BADAUTH
Definition: hs_common.h:143
get_controller_cookie_file_name
char * get_controller_cookie_file_name(void)
Definition: control_auth.c:48
control_cmd_args_t::raw_body
const char * raw_body
Definition: control_cmd_args_st.h:49
option_get_canonical_name
const char * option_get_canonical_name(const char *key)
Definition: config.c:2638
TO_ENTRY_CONN
entry_connection_t * TO_ENTRY_CONN(connection_t *c)
Definition: connection_edge.c:202
control_reply_free
#define control_reply_free(r)
Free and null a smartlist of control_reply_line_t.
Definition: control_proto.h:116
handle_control_del_onion
static int handle_control_del_onion(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:2172
or_options_t::HashedControlSessionPassword
struct config_line_t * HashedControlSessionPassword
Definition: or_options_st.h:507
entrynodes.h
Header file for circuitbuild.c.
circuit_get_by_global_id
origin_circuit_t * circuit_get_by_global_id(uint32_t id)
Definition: circuitlist.c:1435
control_auth.h
Header file for control_auth.c.
tor_assert_nonfatal_unreached
#define tor_assert_nonfatal_unreached()
Definition: util_bug.h:176
control_event_table
const struct control_event_t control_event_table[]
Definition: control_events.c:80
node_t
Definition: node_st.h:34
origin_circuit_t
Definition: origin_circuit_st.h:79
handle_control_usefeature
static int handle_control_usefeature(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:1352
LD_CONTROL
#define LD_CONTROL
Definition: log.h:80
connection_edge_end
int connection_edge_end(edge_connection_t *conn, uint8_t reason)
Definition: connection_edge.c:509
AP_CONN_STATE_CONNECT_WAIT
#define AP_CONN_STATE_CONNECT_WAIT
Definition: connection_edge.h:51
add_authmethods
static void add_authmethods(smartlist_t *reply)
Definition: control_cmd.c:1291
control_setconf_helper
static int control_setconf_helper(control_connection_t *conn, const control_cmd_args_t *args, int use_defaults)
Definition: control_cmd.c:572
handle_control_add_onion
static int handle_control_add_onion(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1707
cpath_build_state_t::onehop_tunnel
unsigned int onehop_tunnel
Definition: cpath_build_state_st.h:32
extend_info_from_node
extend_info_t * extend_info_from_node(const node_t *node, int for_direct_connect)
Definition: extendinfo.c:92
control_reply_add_done
void control_reply_add_done(smartlist_t *reply)
Definition: control_proto.c:401
directory_post_to_hs_dir
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)
Definition: rendservice.c:3679
ENTRY_TO_CONN
#define ENTRY_TO_CONN(c)
Definition: or.h:739
ed25519_public_key_t
Definition: crypto_ed25519.h:23
rend_service_descriptor_t::pk
crypto_pk_t * pk
Definition: rend_service_descriptor_st.h:20
RSAE_INTERNAL
@ RSAE_INTERNAL
Definition: hs_common.h:147
escaped
const char * escaped(const char *s)
Definition: escape.c:126
ROUTER_PURPOSE_UNKNOWN
#define ROUTER_PURPOSE_UNKNOWN
Definition: routerinfo_st.h:109
handle_control_getconf
static int handle_control_getconf(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:290
strcmpstart
int strcmpstart(const char *s1, const char *s2)
Definition: util_string.c:206
circuit_change_purpose
void circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
Definition: circuituse.c:3117
smartlist_del
void smartlist_del(smartlist_t *sl, int idx)
Definition: smartlist_core.c:214
control_cmd_syntax_t
Definition: control_cmd.h:36
handle_control_setcircuitpurpose
static int handle_control_setcircuitpurpose(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:891
circuit_purpose_from_string
static uint8_t circuit_purpose_from_string(const char *string)
Definition: control_cmd.c:707
handle_control_postdescriptor
static int handle_control_postdescriptor(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1029
handle_control_extendcircuit
static int handle_control_extendcircuit(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:730
connection_t::marked_for_close
uint16_t marked_for_close
Definition: connection_st.h:149
circuit_t
Definition: circuit_st.h:61
nodelist.h
Header file for nodelist.c.
hs_control_hspost_command
int hs_control_hspost_command(const char *body, const char *onion_address, const smartlist_t *hsdirs_rs)
Definition: hs_control.c:204
rend_valid_v2_service_id
int rend_valid_v2_service_id(const char *query)
Definition: rendcommon.c:725
hs_control.h
Header file containing control port event related code.
routerlist.h
Header file for routerlist.c.
rend_valid_descriptor_id
int rend_valid_descriptor_id(const char *query)
Definition: rendcommon.c:739
rend_service_parse_port_config
rend_service_port_config_t * rend_service_parse_port_config(const char *string, const char *sep, char **err_msg_out)
Definition: rendservice.c:437
origin_circuit_init
origin_circuit_t * origin_circuit_init(uint8_t purpose, int flags)
Definition: circuitbuild.c:449
router_purpose_from_string
uint8_t router_purpose_from_string(const char *s)
Definition: routerinfo.c:97
control_cmd_syntax_t::min_args
unsigned int min_args
Definition: control_cmd.h:41
control_printf_endreply
void control_printf_endreply(control_connection_t *conn, int code, const char *fmt,...)
Definition: control_proto.c:221
routerinfo_st.h
Router descriptor structure.
get_circuit_build_times
const circuit_build_times_t * get_circuit_build_times(void)
Definition: circuitstats.c:79
rendservice.h
Header file for rendservice.c.
circuitstats.h
Header file for circuitstats.c.
make_path_absolute
char * make_path_absolute(const char *fname)
Definition: path.c:261
extendinfo.h
Header for core/or/extendinfo.c.
control_cmd_args_t::command
const char * command
Definition: control_cmd_args_st.h:29
get_esc_cfile
static char * get_esc_cfile(const or_options_t *options)
Definition: control_cmd.c:1274
ed25519_secret_key_t::seckey
uint8_t seckey[ED25519_SECKEY_LEN]
Definition: crypto_ed25519.h:35
command
tor_cmdline_mode_t command
Definition: config.c:2447
connection_ap_handshake_rewrite_and_attach
int connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
Definition: connection_edge.c:2166
control_connection_t::event_mask
uint64_t event_mask
Definition: control_connection_st.h:22
RSAE_BADPRIVKEY
@ RSAE_BADPRIVKEY
Definition: hs_common.h:146
CMD_FL_WIPE
#define CMD_FL_WIPE
Definition: control_cmd.c:2298
connection_t
Definition: connection_st.h:45
connection_t::type
unsigned int type
Definition: connection_st.h:50
ARRAY_LENGTH
#define ARRAY_LENGTH(x)
Definition: compat_compiler.h:222
crypto_rand.h
Common functions for using (pseudo-)random number generators.
entry_connection_t::socks_request
socks_request_t * socks_request
Definition: entry_connection_st.h:27
handle_control_closecircuit
static int handle_control_closecircuit(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1173
crypto_pk_base64_decode_private
crypto_pk_t * crypto_pk_base64_decode_private(const char *str, size_t len)
Definition: crypto_rsa.c:669
control_events.h
Header file for control_events.c.
read_escaped_data
size_t read_escaped_data(const char *data, size_t len, char **out)
Definition: control_proto.c:130
get_options
const or_options_t * get_options(void)
Definition: config.c:928
origin_circuit_t::build_state
cpath_build_state_t * build_state
Definition: origin_circuit_st.h:123
circuitbuild.h
Header file for circuitbuild.c.
addressmap.h
Header for addressmap.c.
control_reply_append_kv
void control_reply_append_kv(smartlist_t *reply, const char *key, const char *val)
Definition: control_proto.c:357
rend_encoded_v2_service_descriptor_t
Definition: rend_encoded_v2_service_descriptor_st.h:16
handle_control_dropownership
static int handle_control_dropownership(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:524
config_lines_contain_flag
static bool config_lines_contain_flag(const config_line_t *lines, const char *flag)
Definition: control_cmd.c:245
control_write_reply_lines
void control_write_reply_lines(control_connection_t *conn, smartlist_t *lines)
Definition: control_proto.c:317
CIRCUIT_PURPOSE_UNKNOWN
#define CIRCUIT_PURPOSE_UNKNOWN
Definition: circuitlist.h:135
address_is_invalid_mapaddress_target
static int address_is_invalid_mapaddress_target(const char *addr)
Definition: control_cmd.c:621
detached_onion_services
static smartlist_t * detached_onion_services
Definition: control_cmd.c:1684
control_cmd_def_t
Definition: control_cmd.c:2275
RSAE_ADDREXISTS
@ RSAE_ADDREXISTS
Definition: hs_common.h:145
connection.h
Header file for connection.c.
rend_parse_v2_service_descriptor
int rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out, char *desc_id_out, char **intro_points_encrypted_out, size_t *intro_points_encrypted_size_out, size_t *encoded_size_out, const char **next_out, const char *desc, int as_hsdir)
Definition: rendparse.c:73
option_get_assignment
config_line_t * option_get_assignment(const or_options_t *options, const char *key)
Definition: config.c:2646
option_is_recognized
int option_is_recognized(const char *key)
Definition: config.c:2630
handle_control_protocolinfo
static int handle_control_protocolinfo(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:1308
kvline_parse
config_line_t * kvline_parse(const char *line, unsigned flags)
Definition: kvline.c:199
control_cmd_syntax_t::accept_keywords
bool accept_keywords
Definition: control_cmd.h:53
confline.h
Header for confline.c.
onionkey
static crypto_pk_t * onionkey
Definition: router.c:105
control_cmd.h
Header file for control_cmd.c.
ADDRMAPSRC_CONTROLLER
@ ADDRMAPSRC_CONTROLLER
Definition: or.h:1037
get_circ
static origin_circuit_t * get_circ(const char *id)
Definition: control_cmd.c:541
STATE_IS_OPEN
#define STATE_IS_OPEN(s)
Definition: control_cmd.c:68
control_reply_add_printf
void control_reply_add_printf(smartlist_t *reply, int code, const char *fmt,...)
Definition: control_proto.c:387
rend_auth_decode_cookie
int rend_auth_decode_cookie(const char *cookie_in, uint8_t *cookie_out, rend_auth_type_t *auth_type_out, char **err_msg_out)
Definition: rendcommon.c:930
main.h
Header file for main.c.
REND_DESC_COOKIE_LEN
#define REND_DESC_COOKIE_LEN
Definition: or.h:367
tor_asprintf
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
rend_authorized_client_st.h
Hidden-service authorized client structure.
rend_service_add_ephemeral
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)
Definition: rendservice.c:906
kvline.h
Header for kvline.c.
SMARTLIST_FOREACH_BEGIN
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
Definition: smartlist_foreach.h:78
addressmap_register_auto
int addressmap_register_auto(const char *from, const char *to, time_t expires, addressmap_entry_source_t addrmap_source, const char **msg)
Definition: config.c:4705
control_cmd_parse_args
STATIC control_cmd_args_t * control_cmd_parse_args(const char *command, const control_cmd_syntax_t *syntax, size_t body_len, const char *body, char **error_out)
Definition: control_cmd.c:163
dnsserv_launch_request
int dnsserv_launch_request(const char *name, int reverse, control_connection_t *control_conn)
Definition: dnsserv.c:210
crypto_pk_t
Definition: crypto_rsa_nss.c:37
HS_VERSION_THREE
#define HS_VERSION_THREE
Definition: hs_common.h:26
rend_data_client_create
rend_data_t * rend_data_client_create(const char *onion_address, const char *desc_id, const char *cookie, rend_auth_type_t auth_type)
Definition: hs_common.c:494
control_cmd_syntax_t::store_raw_body
bool store_raw_body
Definition: control_cmd.h:74
node_st.h
Node information structure.
OBSOLETE
#define OBSOLETE(name)
Definition: control_cmd.c:2327
crypto_pk_base64_encode_private
int crypto_pk_base64_encode_private(const crypto_pk_t *pk, char **priv_out)
Definition: crypto_rsa.c:633
handle_control_saveconf
static int handle_control_saveconf(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:439
control_connection_t
Definition: control_connection_st.h:19
edge_connection_t
Definition: edge_connection_st.h:21
handle_single_control_command
static int handle_single_control_command(const control_cmd_def_t *def, control_connection_t *conn, uint32_t cmd_data_len, char *args)
Definition: control_cmd.c:2385
rend_data_t
Definition: or.h:419
base64_decode
int base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:396
control_write_endreply
void control_write_endreply(control_connection_t *conn, int code, const char *s)
Definition: control_proto.c:214
socks_request_t::address
char address[MAX_SOCKS_ADDR_LEN]
Definition: socks_request_st.h:57
tor_parse_ulong
unsigned long tor_parse_ulong(const char *s, int base, unsigned long min, unsigned long max, int *ok, char **next)
Definition: parse_int.c:78
rend_encoded_v2_service_descriptor_t::desc_id
char desc_id[DIGEST_LEN]
Definition: rend_encoded_v2_service_descriptor_st.h:17
circuit_set_state
void circuit_set_state(circuit_t *circ, uint8_t state)
Definition: circuitlist.c:545
control_printf_midreply
void control_printf_midreply(control_connection_t *conn, int code, const char *fmt,...)
Definition: control_proto.c:240
config_line_t
Definition: confline.h:29
config.h
Header file for config.c.
cpath_build_state_t::desired_path_len
int desired_path_len
Definition: cpath_build_state_st.h:18
connection_t::s
tor_socket_t s
Definition: connection_st.h:96
control_reply_add_str
void control_reply_add_str(smartlist_t *reply, int code, const char *s)
Definition: control_proto.c:375
smartlist_add_asprintf
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
hs_parse_address
int hs_parse_address(const char *address, ed25519_public_key_t *key_out, uint8_t *checksum_out, uint8_t *version_out)
Definition: hs_common.c:958
esc_for_log
char * esc_for_log(const char *s)
Definition: escape.c:30
node_get_by_hex_id
const node_t * node_get_by_hex_id(const char *hex_id, unsigned flags)
Definition: nodelist.c:977
control_cmd_args_t::cmddata
char * cmddata
Definition: control_cmd_args_st.h:45
addressmap_register_virtual_address
const char * addressmap_register_virtual_address(int type, char *new_address)
Definition: addressmap.c:995
circuit_build_times_reset
void circuit_build_times_reset(circuit_build_times_t *cbt)
Definition: circuitstats.c:546
CIRCUIT_STATE_GUARD_WAIT
#define CIRCUIT_STATE_GUARD_WAIT
Definition: circuitlist.h:30
circuit_get_cpath_len
int circuit_get_cpath_len(origin_circuit_t *circ)
Definition: circuitlist.c:2051
origin_circuit_t::p_streams
edge_connection_t * p_streams
Definition: origin_circuit_st.h:84
ROUTER_PURPOSE_GENERAL
#define ROUTER_PURPOSE_GENERAL
Definition: routerinfo_st.h:98
TO_CIRCUIT
#define TO_CIRCUIT(x)
Definition: or.h:965
or_options_t
Definition: or_options_st.h:45
crypto_rand
void crypto_rand(char *to, size_t n)
Definition: crypto_rand.c:477
socks_request_t::port
uint16_t port
Definition: socks_request_st.h:59
crypto_pk_num_bits
int crypto_pk_num_bits(crypto_pk_t *env)
Definition: crypto_rsa_nss.c:340
connection_flush
int connection_flush(connection_t *conn)
Definition: connection.c:4531
TO_CONN
#define TO_CONN(c)
Definition: or.h:736
STATIC
#define STATIC
Definition: testsupport.h:32
handle_control_attachstream
static int handle_control_attachstream(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:936
handle_control_obsolete
static int handle_control_obsolete(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:2255
handle_control_setevents
static int handle_control_setevents(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:389
AP_CONN_STATE_CONTROLLER_WAIT
#define AP_CONN_STATE_CONTROLLER_WAIT
Definition: connection_edge.h:47
control_update_global_event_mask
void control_update_global_event_mask(void)
Definition: control_events.c:207
ed25519_secret_key_t
Definition: crypto_ed25519.h:28
control_cmd_syntax_t::kvline_flags
unsigned kvline_flags
Definition: control_cmd.h:63
entry_connection_t
Definition: entry_connection_st.h:19
handle_control_resetconf
static int handle_control_resetconf(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:277
config_line_find_case
const config_line_t * config_line_find_case(const config_line_t *lines, const char *key)
Definition: confline.c:87
PK_BYTES
#define PK_BYTES
Definition: crypto_rsa.h:24
CIRCUIT_STATE_BUILDING
#define CIRCUIT_STATE_BUILDING
Definition: circuitlist.h:21
origin_circuit_st.h
Origin circuit structure.
setopt_err_t
setopt_err_t
Definition: config.h:48
node_has_preferred_descriptor
int node_has_preferred_descriptor(const node_t *node, int for_direct_connect)
Definition: nodelist.c:1419
circuit_get_by_edge_conn
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
Definition: circuitlist.c:1588
smartlist_t
Definition: smartlist_core.h:26
smartlist_join_strings
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
or_options_t::CookieAuthentication
int CookieAuthentication
Definition: or_options_st.h:509
rendclient.h
Header file for rendclient.c.
control_cmd_args_st.h
Definition for control_cmd_args_t.
circuit_t::state
uint8_t state
Definition: circuit_st.h:110
or_options_t::IncludeUsed
int IncludeUsed
Definition: or_options_st.h:981
control_cmd_args_t::cmddata_len
size_t cmddata_len
Definition: control_cmd_args_st.h:41
rendcommon.h
Header file for rendcommon.c.
RSAE_OKAY
@ RSAE_OKAY
Definition: hs_common.h:148
control_connection_st.h
Controller connection structure.
control_cmd_args_wipe
void control_cmd_args_wipe(control_cmd_args_t *args)
Definition: control_cmd.c:91
string_array_contains_keyword
static bool string_array_contains_keyword(const char **array, const char *kwd)
Definition: control_cmd.c:112
rend_authorized_client_t
Definition: rend_authorized_client_st.h:16
control_cmd_syntax_t::allowed_keywords
const char ** allowed_keywords
Definition: control_cmd.h:58
extend_info_t
Definition: extend_info_st.h:27
strcasecmpstart
int strcasecmpstart(const char *s1, const char *s2)
Definition: util_string.c:216
ONE_LINE
#define ONE_LINE(name, flags)
Definition: control_cmd.c:2304
rend_get_service_id
int rend_get_service_id(crypto_pk_t *pk, char *out)
Definition: rendcommon.c:712
or.h
Master header file for Tor-specific functionality.
circuit_event_status
int circuit_event_status(origin_circuit_t *circ, circuit_status_event_t tp, int reason_code)
Definition: circuitlist.c:501
circuit_detach_stream
void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
Definition: circuituse.c:1393
circuit_get_cpath_hop
crypt_path_t * circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
Definition: circuitlist.c:2087
hs_control_hsfetch_command
void hs_control_hsfetch_command(const ed25519_public_key_t *onion_identity_pk, const smartlist_t *hsdirs)
Definition: hs_control.c:256