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