tor  0.4.2.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-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 "app/config/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  .max_args=1,
643  .accept_keywords=true,
644 };
645 
648 static int
650  const control_cmd_args_t *args)
651 {
652  smartlist_t *reply;
653  char *r;
654  size_t sz;
655 
656  reply = smartlist_new();
657  const config_line_t *line;
658  for (line = args->kwargs; line; line = line->next) {
659  const char *from = line->key;
660  const char *to = line->value;
661  {
664  "512-syntax error: invalid address '%s'", to);
665  log_warn(LD_CONTROL,
666  "Skipping invalid argument '%s' in MapAddress msg", to);
667  } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
668  !strcmp(from, "::")) {
669  const char type =
670  !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
671  (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
672  const char *address = addressmap_register_virtual_address(
673  type, tor_strdup(to));
674  if (!address) {
676  "451-resource exhausted: skipping '%s=%s'", from,to);
677  log_warn(LD_CONTROL,
678  "Unable to allocate address for '%s' in MapAddress msg",
679  safe_str_client(to));
680  } else {
681  smartlist_add_asprintf(reply, "250-%s=%s", address, to);
682  }
683  } else {
684  const char *msg;
685  if (addressmap_register_auto(from, to, 1,
686  ADDRMAPSRC_CONTROLLER, &msg) < 0) {
688  "512-syntax error: invalid address mapping "
689  " '%s=%s': %s", from, to, msg);
690  log_warn(LD_CONTROL,
691  "Skipping invalid argument '%s=%s' in MapAddress msg: %s",
692  from, to, msg);
693  } else {
694  smartlist_add_asprintf(reply, "250-%s=%s", from, to);
695  }
696  }
697  }
698  }
699 
700  if (smartlist_len(reply)) {
701  ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
702  r = smartlist_join_strings(reply, "\r\n", 1, &sz);
703  connection_buf_add(r, sz, TO_CONN(conn));
704  tor_free(r);
705  } else {
706  const char *response =
707  "512 syntax error: not enough arguments to mapaddress.\r\n";
708  connection_buf_add(response, strlen(response), TO_CONN(conn));
709  }
710 
711  SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
712  smartlist_free(reply);
713  return 0;
714 }
715 
717 static uint8_t
718 circuit_purpose_from_string(const char *string)
719 {
720  if (!strcasecmpstart(string, "purpose="))
721  string += strlen("purpose=");
722 
723  if (!strcasecmp(string, "general"))
725  else if (!strcasecmp(string, "controller"))
727  else
729 }
730 
731 static const control_cmd_syntax_t extendcircuit_syntax = {
732  .min_args=1,
733  .max_args=1, // see note in function
734  .accept_keywords=true,
735  .kvline_flags=KV_OMIT_VALS
736 };
737 
740 static int
742  const control_cmd_args_t *args)
743 {
744  smartlist_t *router_nicknames=smartlist_new(), *nodes=NULL;
745  origin_circuit_t *circ = NULL;
746  uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
747  const config_line_t *kwargs = args->kwargs;
748  const char *circ_id = smartlist_get(args->args, 0);
749  const char *path_str = NULL;
750  char *path_str_alloc = NULL;
751 
752  /* The syntax for this command is unfortunate. The second argument is
753  optional, and is a comma-separated list long-format fingerprints, which
754  can (historically!) contain an equals sign.
755 
756  Here we check the second argument to see if it's a path, and if so we
757  remove it from the kwargs list and put it in path_str.
758  */
759  if (kwargs) {
760  const config_line_t *arg1 = kwargs;
761  if (!strcmp(arg1->value, "")) {
762  path_str = arg1->key;
763  kwargs = kwargs->next;
764  } else if (arg1->key[0] == '$') {
765  tor_asprintf(&path_str_alloc, "%s=%s", arg1->key, arg1->value);
766  path_str = path_str_alloc;
767  kwargs = kwargs->next;
768  }
769  }
770 
771  const config_line_t *purpose_line = config_line_find_case(kwargs, "PURPOSE");
772  bool zero_circ = !strcmp("0", circ_id);
773 
774  if (purpose_line) {
775  intended_purpose = circuit_purpose_from_string(purpose_line->value);
776  if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
777  control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
778  purpose_line->value);
779  goto done;
780  }
781  }
782 
783  if (zero_circ) {
784  if (!path_str) {
785  // "EXTENDCIRCUIT 0" with no path.
786  circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
787  if (!circ) {
788  control_write_endreply(conn, 551, "Couldn't start circuit");
789  } else {
790  control_printf_endreply(conn, 250, "EXTENDED %lu",
791  (unsigned long)circ->global_identifier);
792  }
793  goto done;
794  }
795  }
796 
797  if (!zero_circ && !(circ = get_circ(circ_id))) {
798  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
799  goto done;
800  }
801 
802  if (!path_str) {
803  control_write_endreply(conn, 512, "syntax error: path required.");
804  goto done;
805  }
806 
807  smartlist_split_string(router_nicknames, path_str, ",", 0, 0);
808 
809  nodes = smartlist_new();
810  bool first_node = zero_circ;
811  SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
812  const node_t *node = node_get_by_nickname(n, 0);
813  if (!node) {
814  control_printf_endreply(conn, 552, "No such router \"%s\"", n);
815  goto done;
816  }
817  if (!node_has_preferred_descriptor(node, first_node)) {
818  control_printf_endreply(conn, 552, "No descriptor for \"%s\"", n);
819  goto done;
820  }
821  smartlist_add(nodes, (void*)node);
822  first_node = false;
823  } SMARTLIST_FOREACH_END(n);
824 
825  if (!smartlist_len(nodes)) {
826  control_write_endreply(conn, 512, "No router names provided");
827  goto done;
828  }
829 
830  if (zero_circ) {
831  /* start a new circuit */
832  circ = origin_circuit_init(intended_purpose, 0);
833  }
834 
835  /* now circ refers to something that is ready to be extended */
836  first_node = zero_circ;
837  SMARTLIST_FOREACH(nodes, const node_t *, node,
838  {
839  extend_info_t *info = extend_info_from_node(node, first_node);
840  if (!info) {
841  tor_assert_nonfatal(first_node);
842  log_warn(LD_CONTROL,
843  "controller tried to connect to a node that lacks a suitable "
844  "descriptor, or which doesn't have any "
845  "addresses that are allowed by the firewall configuration; "
846  "circuit marked for closing.");
847  circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
848  connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
849  goto done;
850  }
851  circuit_append_new_exit(circ, info);
852  if (circ->build_state->desired_path_len > 1) {
853  circ->build_state->onehop_tunnel = 0;
854  }
855  extend_info_free(info);
856  first_node = 0;
857  });
858 
859  /* now that we've populated the cpath, start extending */
860  if (zero_circ) {
861  int err_reason = 0;
862  if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
863  circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
864  control_write_endreply(conn, 551, "Couldn't start circuit");
865  goto done;
866  }
867  } else {
868  if (circ->base_.state == CIRCUIT_STATE_OPEN ||
869  circ->base_.state == CIRCUIT_STATE_GUARD_WAIT) {
870  int err_reason = 0;
872  if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
873  log_info(LD_CONTROL,
874  "send_next_onion_skin failed; circuit marked for closing.");
875  circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
876  control_write_endreply(conn, 551, "Couldn't send onion skin");
877  goto done;
878  }
879  }
880  }
881 
882  control_printf_endreply(conn, 250, "EXTENDED %lu",
883  (unsigned long)circ->global_identifier);
884  if (zero_circ) /* send a 'launched' event, for completeness */
885  circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
886  done:
887  SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
888  smartlist_free(router_nicknames);
889  smartlist_free(nodes);
890  tor_free(path_str_alloc);
891  return 0;
892 }
893 
894 static const control_cmd_syntax_t setcircuitpurpose_syntax = {
895  .max_args=1,
896  .accept_keywords=true,
897 };
898 
901 static int
903  const control_cmd_args_t *args)
904 {
905  origin_circuit_t *circ = NULL;
906  uint8_t new_purpose;
907  const char *circ_id = smartlist_get(args->args,0);
908 
909  if (!(circ = get_circ(circ_id))) {
910  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
911  goto done;
912  }
913 
914  {
915  const config_line_t *purp = config_line_find_case(args->kwargs, "PURPOSE");
916  if (!purp) {
917  control_write_endreply(conn, 552, "No purpose given");
918  goto done;
919  }
920  new_purpose = circuit_purpose_from_string(purp->value);
921  if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
922  control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
923  purp->value);
924  goto done;
925  }
926  }
927 
928  circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
929  send_control_done(conn);
930 
931  done:
932  return 0;
933 }
934 
935 static const char *attachstream_keywords[] = {
936  "HOP", NULL
937 };
938 static const control_cmd_syntax_t attachstream_syntax = {
939  .min_args=2, .max_args=2,
940  .accept_keywords=true,
941  .allowed_keywords=attachstream_keywords
942 };
943 
946 static int
948  const control_cmd_args_t *args)
949 {
950  entry_connection_t *ap_conn = NULL;
951  origin_circuit_t *circ = NULL;
952  crypt_path_t *cpath=NULL;
953  int hop=0, hop_line_ok=1;
954  const char *stream_id = smartlist_get(args->args, 0);
955  const char *circ_id = smartlist_get(args->args, 1);
956  int zero_circ = !strcmp(circ_id, "0");
957  const config_line_t *hoparg = config_line_find_case(args->kwargs, "HOP");
958 
959  if (!(ap_conn = get_stream(stream_id))) {
960  control_printf_endreply(conn, 552, "Unknown stream \"%s\"", stream_id);
961  return 0;
962  } else if (!zero_circ && !(circ = get_circ(circ_id))) {
963  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
964  return 0;
965  } else if (circ) {
966  if (hoparg) {
967  hop = (int) tor_parse_ulong(hoparg->value, 10, 0, INT_MAX,
968  &hop_line_ok, NULL);
969  if (!hop_line_ok) { /* broken hop line */
970  control_printf_endreply(conn, 552, "Bad value hop=%s",
971  hoparg->value);
972  return 0;
973  }
974  }
975  }
976 
977  if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
978  ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
979  ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
980  control_write_endreply(conn, 555,
981  "Connection is not managed by controller.");
982  return 0;
983  }
984 
985  /* Do we need to detach it first? */
986  if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
987  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
988  circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
989  connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
990  /* Un-mark it as ending, since we're going to reuse it. */
991  edge_conn->edge_has_sent_end = 0;
992  edge_conn->end_reason = 0;
993  if (tmpcirc)
994  circuit_detach_stream(tmpcirc, edge_conn);
995  CONNECTION_AP_EXPECT_NONPENDING(ap_conn);
996  TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
997  }
998 
999  if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
1000  control_write_endreply(conn, 551,
1001  "Can't attach stream to non-open origin circuit");
1002  return 0;
1003  }
1004  /* Is this a single hop circuit? */
1005  if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
1006  control_write_endreply(conn, 551,
1007  "Can't attach stream to this one-hop circuit.");
1008  return 0;
1009  }
1010 
1011  if (circ && hop>0) {
1012  /* find this hop in the circuit, and set cpath */
1013  cpath = circuit_get_cpath_hop(circ, hop);
1014  if (!cpath) {
1015  control_printf_endreply(conn, 551, "Circuit doesn't have %d hops.", hop);
1016  return 0;
1017  }
1018  }
1019  if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
1020  control_write_endreply(conn, 551, "Unable to attach stream");
1021  return 0;
1022  }
1023  send_control_done(conn);
1024  return 0;
1025 }
1026 
1027 static const char *postdescriptor_keywords[] = {
1028  "cache", "purpose", NULL,
1029 };
1030 
1031 static const control_cmd_syntax_t postdescriptor_syntax = {
1032  .max_args = 0,
1033  .accept_keywords = true,
1034  .allowed_keywords = postdescriptor_keywords,
1035  .want_cmddata = true,
1036 };
1037 
1040 static int
1042  const control_cmd_args_t *args)
1043 {
1044  const char *msg=NULL;
1045  uint8_t purpose = ROUTER_PURPOSE_GENERAL;
1046  int cache = 0; /* eventually, we may switch this to 1 */
1047  const config_line_t *line;
1048 
1049  line = config_line_find_case(args->kwargs, "purpose");
1050  if (line) {
1051  purpose = router_purpose_from_string(line->value);
1052  if (purpose == ROUTER_PURPOSE_UNKNOWN) {
1053  control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
1054  line->value);
1055  goto done;
1056  }
1057  }
1058  line = config_line_find_case(args->kwargs, "cache");
1059  if (line) {
1060  if (!strcasecmp(line->value, "no"))
1061  cache = 0;
1062  else if (!strcasecmp(line->value, "yes"))
1063  cache = 1;
1064  else {
1065  control_printf_endreply(conn, 552, "Unknown cache request \"%s\"",
1066  line->value);
1067  goto done;
1068  }
1069  }
1070 
1071  switch (router_load_single_router(args->cmddata, purpose, cache, &msg)) {
1072  case -1:
1073  if (!msg) msg = "Could not parse descriptor";
1074  control_write_endreply(conn, 554, msg);
1075  break;
1076  case 0:
1077  if (!msg) msg = "Descriptor not added";
1078  control_write_endreply(conn, 251, msg);
1079  break;
1080  case 1:
1081  send_control_done(conn);
1082  break;
1083  }
1084 
1085  done:
1086  return 0;
1087 }
1088 
1089 static const control_cmd_syntax_t redirectstream_syntax = {
1090  .min_args = 2,
1091  .max_args = UINT_MAX, // XXX should be 3.
1092 };
1093 
1096 static int
1098  const control_cmd_args_t *cmd_args)
1099 {
1100  entry_connection_t *ap_conn = NULL;
1101  char *new_addr = NULL;
1102  uint16_t new_port = 0;
1103  const smartlist_t *args = cmd_args->args;
1104 
1105  if (!(ap_conn = get_stream(smartlist_get(args, 0)))
1106  || !ap_conn->socks_request) {
1107  control_printf_endreply(conn, 552, "Unknown stream \"%s\"",
1108  (char*)smartlist_get(args, 0));
1109  } else {
1110  int ok = 1;
1111  if (smartlist_len(args) > 2) { /* they included a port too */
1112  new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
1113  10, 1, 65535, &ok, NULL);
1114  }
1115  if (!ok) {
1116  control_printf_endreply(conn, 512, "Cannot parse port \"%s\"",
1117  (char*)smartlist_get(args, 2));
1118  } else {
1119  new_addr = tor_strdup(smartlist_get(args, 1));
1120  }
1121  }
1122 
1123  if (!new_addr)
1124  return 0;
1125 
1126  strlcpy(ap_conn->socks_request->address, new_addr,
1127  sizeof(ap_conn->socks_request->address));
1128  if (new_port)
1129  ap_conn->socks_request->port = new_port;
1130  tor_free(new_addr);
1131  send_control_done(conn);
1132  return 0;
1133 }
1134 
1135 static const control_cmd_syntax_t closestream_syntax = {
1136  .min_args = 2,
1137  .max_args = UINT_MAX, /* XXXX This is the original behavior, but
1138  * maybe we should change the spec. */
1139 };
1140 
1143 static int
1145  const control_cmd_args_t *cmd_args)
1146 {
1147  entry_connection_t *ap_conn=NULL;
1148  uint8_t reason=0;
1149  int ok;
1150  const smartlist_t *args = cmd_args->args;
1151 
1152  tor_assert(smartlist_len(args) >= 2);
1153 
1154  if (!(ap_conn = get_stream(smartlist_get(args, 0))))
1155  control_printf_endreply(conn, 552, "Unknown stream \"%s\"",
1156  (char*)smartlist_get(args, 0));
1157  else {
1158  reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
1159  &ok, NULL);
1160  if (!ok) {
1161  control_printf_endreply(conn, 552, "Unrecognized reason \"%s\"",
1162  (char*)smartlist_get(args, 1));
1163  ap_conn = NULL;
1164  }
1165  }
1166  if (!ap_conn)
1167  return 0;
1168 
1169  connection_mark_unattached_ap(ap_conn, reason);
1170  send_control_done(conn);
1171  return 0;
1172 }
1173 
1174 static const control_cmd_syntax_t closecircuit_syntax = {
1175  .min_args=1, .max_args=1,
1176  .accept_keywords=true,
1177  .kvline_flags=KV_OMIT_VALS,
1178  // XXXX we might want to exclude unrecognized flags, but for now we
1179  // XXXX just ignore them for backward compatibility.
1180 };
1181 
1184 static int
1186  const control_cmd_args_t *args)
1187 {
1188  const char *circ_id = smartlist_get(args->args, 0);
1189  origin_circuit_t *circ = NULL;
1190 
1191  if (!(circ=get_circ(circ_id))) {
1192  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
1193  return 0;
1194  }
1195 
1196  bool safe = config_lines_contain_flag(args->kwargs, "IfUnused");
1197 
1198  if (!safe || !circ->p_streams) {
1199  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
1200  }
1201 
1202  send_control_done(conn);
1203  return 0;
1204 }
1205 
1206 static const control_cmd_syntax_t resolve_syntax = {
1207  .max_args=0,
1208  .accept_keywords=true,
1209  .kvline_flags=KV_OMIT_VALS,
1210 };
1211 
1214 static int
1216  const control_cmd_args_t *args)
1217 {
1218  smartlist_t *failed;
1219  int is_reverse = 0;
1220 
1221  if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
1222  log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
1223  "isn't listening for ADDRMAP events. It probably won't see "
1224  "the answer.");
1225  }
1226 
1227  {
1228  const config_line_t *modearg = config_line_find_case(args->kwargs, "mode");
1229  if (modearg && !strcasecmp(modearg->value, "reverse"))
1230  is_reverse = 1;
1231  }
1232  failed = smartlist_new();
1233  for (const config_line_t *line = args->kwargs; line; line = line->next) {
1234  if (!strlen(line->value)) {
1235  const char *addr = line->key;
1236  if (dnsserv_launch_request(addr, is_reverse, conn)<0)
1237  smartlist_add(failed, (char*)addr);
1238  } else {
1239  // XXXX arguably we should reject unrecognized keyword arguments,
1240  // XXXX but the old implementation didn't do that.
1241  }
1242  }
1243 
1244  send_control_done(conn);
1245  SMARTLIST_FOREACH(failed, const char *, arg, {
1246  control_event_address_mapped(arg, arg, time(NULL),
1247  "internal", 0);
1248  });
1249 
1250  smartlist_free(failed);
1251  return 0;
1252 }
1253 
1254 static const control_cmd_syntax_t protocolinfo_syntax = {
1255  .max_args = UINT_MAX
1256 };
1257 
1259 static int
1261  const control_cmd_args_t *cmd_args)
1262 {
1263  const char *bad_arg = NULL;
1264  const smartlist_t *args = cmd_args->args;
1265 
1266  conn->have_sent_protocolinfo = 1;
1267 
1268  SMARTLIST_FOREACH(args, const char *, arg, {
1269  int ok;
1270  tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
1271  if (!ok) {
1272  bad_arg = arg;
1273  break;
1274  }
1275  });
1276  if (bad_arg) {
1277  control_printf_endreply(conn, 513, "No such version %s",
1278  escaped(bad_arg));
1279  /* Don't tolerate bad arguments when not authenticated. */
1280  if (!STATE_IS_OPEN(TO_CONN(conn)->state))
1281  connection_mark_for_close(TO_CONN(conn));
1282  goto done;
1283  } else {
1284  const or_options_t *options = get_options();
1285  int cookies = options->CookieAuthentication;
1286  char *cfile = get_controller_cookie_file_name();
1287  char *abs_cfile;
1288  char *esc_cfile;
1289  char *methods;
1290  abs_cfile = make_path_absolute(cfile);
1291  esc_cfile = esc_for_log(abs_cfile);
1292  {
1293  int passwd = (options->HashedControlPassword != NULL ||
1294  options->HashedControlSessionPassword != NULL);
1295  smartlist_t *mlist = smartlist_new();
1296  if (cookies) {
1297  smartlist_add(mlist, (char*)"COOKIE");
1298  smartlist_add(mlist, (char*)"SAFECOOKIE");
1299  }
1300  if (passwd)
1301  smartlist_add(mlist, (char*)"HASHEDPASSWORD");
1302  if (!cookies && !passwd)
1303  smartlist_add(mlist, (char*)"NULL");
1304  methods = smartlist_join_strings(mlist, ",", 0, NULL);
1305  smartlist_free(mlist);
1306  }
1307 
1308  control_write_midreply(conn, 250, "PROTOCOLINFO 1");
1309  control_printf_midreply(conn, 250, "AUTH METHODS=%s%s%s", methods,
1310  cookies?" COOKIEFILE=":"",
1311  cookies?esc_cfile:"");
1312  control_printf_midreply(conn, 250, "VERSION Tor=%s", escaped(VERSION));
1313  send_control_done(conn);
1314 
1315  tor_free(methods);
1316  tor_free(cfile);
1317  tor_free(abs_cfile);
1318  tor_free(esc_cfile);
1319  }
1320  done:
1321  return 0;
1322 }
1323 
1324 static const control_cmd_syntax_t usefeature_syntax = {
1325  .max_args = UINT_MAX
1326 };
1327 
1330 static int
1332  const control_cmd_args_t *cmd_args)
1333 {
1334  const smartlist_t *args = cmd_args->args;
1335  int bad = 0;
1336  SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
1337  if (!strcasecmp(arg, "VERBOSE_NAMES"))
1338  ;
1339  else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
1340  ;
1341  else {
1342  control_printf_endreply(conn, 552, "Unrecognized feature \"%s\"",
1343  arg);
1344  bad = 1;
1345  break;
1346  }
1347  } SMARTLIST_FOREACH_END(arg);
1348 
1349  if (!bad) {
1350  send_control_done(conn);
1351  }
1352 
1353  return 0;
1354 }
1355 
1356 static const control_cmd_syntax_t dropguards_syntax = {
1357  .max_args = 0,
1358 };
1359 
1361 static int
1363  const control_cmd_args_t *args)
1364 {
1365  (void) args; /* We don't take arguments. */
1366 
1367  static int have_warned = 0;
1368  if (! have_warned) {
1369  log_warn(LD_CONTROL, "DROPGUARDS is dangerous; make sure you understand "
1370  "the risks before using it. It may be removed in a future "
1371  "version of Tor.");
1372  have_warned = 1;
1373  }
1374 
1376  send_control_done(conn);
1377 
1378  return 0;
1379 }
1380 
1381 static const char *hsfetch_keywords[] = {
1382  "SERVER", NULL,
1383 };
1384 static const control_cmd_syntax_t hsfetch_syntax = {
1385  .min_args = 1, .max_args = 1,
1386  .accept_keywords = true,
1387  .allowed_keywords = hsfetch_keywords,
1388 };
1389 
1391 static int
1393  const control_cmd_args_t *args)
1394 
1395 {
1396  char digest[DIGEST_LEN], *desc_id = NULL;
1397  smartlist_t *hsdirs = NULL;
1398  static const char *v2_str = "v2-";
1399  const size_t v2_str_len = strlen(v2_str);
1400  rend_data_t *rend_query = NULL;
1401  ed25519_public_key_t v3_pk;
1402  uint32_t version;
1403  const char *hsaddress = NULL;
1404 
1405  /* Extract the first argument (either HSAddress or DescID). */
1406  const char *arg1 = smartlist_get(args->args, 0);
1407  /* Test if it's an HS address without the .onion part. */
1408  if (rend_valid_v2_service_id(arg1)) {
1409  hsaddress = arg1;
1410  version = HS_VERSION_TWO;
1411  } else if (strcmpstart(arg1, v2_str) == 0 &&
1412  rend_valid_descriptor_id(arg1 + v2_str_len) &&
1413  base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
1416  /* We have a well formed version 2 descriptor ID. Keep the decoded value
1417  * of the id. */
1418  desc_id = digest;
1419  version = HS_VERSION_TWO;
1420  } else if (hs_address_is_valid(arg1)) {
1421  hsaddress = arg1;
1422  version = HS_VERSION_THREE;
1423  hs_parse_address(hsaddress, &v3_pk, NULL, NULL);
1424  } else {
1425  control_printf_endreply(conn, 513, "Invalid argument \"%s\"", arg1);
1426  goto done;
1427  }
1428 
1429  for (const config_line_t *line = args->kwargs; line; line = line->next) {
1430  if (!strcasecmp(line->key, "SERVER")) {
1431  const char *server = line->value;
1432 
1433  const node_t *node = node_get_by_hex_id(server, 0);
1434  if (!node) {
1435  control_printf_endreply(conn, 552, "Server \"%s\" not found", server);
1436  goto done;
1437  }
1438  if (!hsdirs) {
1439  /* Stores routerstatus_t cmddata for each specified server. */
1440  hsdirs = smartlist_new();
1441  }
1442  /* Valid server, add it to our local list. */
1443  smartlist_add(hsdirs, node->rs);
1444  } else {
1445  tor_assert_nonfatal_unreached();
1446  }
1447  }
1448 
1449  if (version == HS_VERSION_TWO) {
1450  rend_query = rend_data_client_create(hsaddress, desc_id, NULL,
1451  REND_NO_AUTH);
1452  if (rend_query == NULL) {
1453  control_write_endreply(conn, 551, "Error creating the HS query");
1454  goto done;
1455  }
1456  }
1457 
1458  /* Using a descriptor ID, we force the user to provide at least one
1459  * hsdir server using the SERVER= option. */
1460  if (desc_id && (!hsdirs || !smartlist_len(hsdirs))) {
1461  control_write_endreply(conn, 512, "SERVER option is required");
1462  goto done;
1463  }
1464 
1465  /* We are about to trigger HSDir fetch so send the OK now because after
1466  * that 650 event(s) are possible so better to have the 250 OK before them
1467  * to avoid out of order replies. */
1468  send_control_done(conn);
1469 
1470  /* Trigger the fetch using the built rend query and possibly a list of HS
1471  * directory to use. This function ignores the client cache thus this will
1472  * always send a fetch command. */
1473  if (version == HS_VERSION_TWO) {
1474  rend_client_fetch_v2_desc(rend_query, hsdirs);
1475  } else if (version == HS_VERSION_THREE) {
1476  hs_control_hsfetch_command(&v3_pk, hsdirs);
1477  }
1478 
1479  done:
1480  /* Contains data pointer that we don't own thus no cleanup. */
1481  smartlist_free(hsdirs);
1482  rend_data_free(rend_query);
1483  return 0;
1484 }
1485 
1486 static const char *hspost_keywords[] = {
1487  "SERVER", "HSADDRESS", NULL
1488 };
1489 static const control_cmd_syntax_t hspost_syntax = {
1490  .min_args = 0, .max_args = 0,
1491  .accept_keywords = true,
1492  .want_cmddata = true,
1493  .allowed_keywords = hspost_keywords
1494 };
1495 
1497 static int
1499  const control_cmd_args_t *args)
1500 {
1501  smartlist_t *hs_dirs = NULL;
1502  const char *encoded_desc = args->cmddata;
1503  size_t encoded_desc_len = args->cmddata_len;
1504  const char *onion_address = NULL;
1505  const config_line_t *line;
1506 
1507  for (line = args->kwargs; line; line = line->next) {
1508  if (!strcasecmpstart(line->key, "SERVER")) {
1509  const char *server = line->value;
1510  const node_t *node = node_get_by_hex_id(server, 0);
1511 
1512  if (!node || !node->rs) {
1513  control_printf_endreply(conn, 552, "Server \"%s\" not found",
1514  server);
1515  goto done;
1516  }
1517  /* Valid server, add it to our local list. */
1518  if (!hs_dirs)
1519  hs_dirs = smartlist_new();
1520  smartlist_add(hs_dirs, node->rs);
1521  } else if (!strcasecmpstart(line->key, "HSADDRESS")) {
1522  const char *address = line->value;
1523  if (!hs_address_is_valid(address)) {
1524  control_write_endreply(conn, 512, "Malformed onion address");
1525  goto done;
1526  }
1527  onion_address = address;
1528  } else {
1529  tor_assert_nonfatal_unreached();
1530  }
1531  }
1532 
1533  /* Handle the v3 case. */
1534  if (onion_address) {
1535  if (hs_control_hspost_command(encoded_desc, onion_address, hs_dirs) < 0) {
1536  control_write_endreply(conn, 554, "Invalid descriptor");
1537  } else {
1538  send_control_done(conn);
1539  }
1540  goto done;
1541  }
1542 
1543  /* From this point on, it is only v2. */
1544 
1545  /* parse it. */
1547  tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
1548  desc->desc_str = tor_memdup_nulterm(encoded_desc, encoded_desc_len);
1549 
1550  rend_service_descriptor_t *parsed = NULL;
1551  char *intro_content = NULL;
1552  size_t intro_size;
1553  size_t encoded_size;
1554  const char *next_desc;
1555  if (!rend_parse_v2_service_descriptor(&parsed, desc->desc_id, &intro_content,
1556  &intro_size, &encoded_size,
1557  &next_desc, desc->desc_str, 1)) {
1558  /* Post the descriptor. */
1559  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1560  if (!rend_get_service_id(parsed->pk, serviceid)) {
1561  smartlist_t *descs = smartlist_new();
1562  smartlist_add(descs, desc);
1563 
1564  /* We are about to trigger HS descriptor upload so send the OK now
1565  * because after that 650 event(s) are possible so better to have the
1566  * 250 OK before them to avoid out of order replies. */
1567  send_control_done(conn);
1568 
1569  /* Trigger the descriptor upload */
1570  directory_post_to_hs_dir(parsed, descs, hs_dirs, serviceid, 0);
1571  smartlist_free(descs);
1572  }
1573 
1574  rend_service_descriptor_free(parsed);
1575  } else {
1576  control_write_endreply(conn, 554, "Invalid descriptor");
1577  }
1578 
1579  tor_free(intro_content);
1580  rend_encoded_v2_service_descriptor_free(desc);
1581  done:
1582  smartlist_free(hs_dirs); /* Contents belong to the rend service code. */
1583  return 0;
1584 }
1585 
1586 /* Helper function for ADD_ONION that adds an ephemeral service depending on
1587  * the given hs_version.
1588  *
1589  * The secret key in pk depends on the hs_version. The ownership of the key
1590  * used in pk is given to the HS subsystem so the caller must stop accessing
1591  * it after.
1592  *
1593  * The port_cfgs is a list of service port. Ownership transferred to service.
1594  * The max_streams refers to the MaxStreams= key.
1595  * The max_streams_close_circuit refers to the MaxStreamsCloseCircuit key.
1596  * The auth_type is the authentication type of the clients in auth_clients.
1597  * The ownership of that list is transferred to the service.
1598  *
1599  * On success (RSAE_OKAY), the address_out points to a newly allocated string
1600  * containing the onion address without the .onion part. On error, address_out
1601  * is untouched. */
1603 add_onion_helper_add_service(int hs_version,
1604  add_onion_secret_key_t *pk,
1605  smartlist_t *port_cfgs, int max_streams,
1606  int max_streams_close_circuit, int auth_type,
1607  smartlist_t *auth_clients, char **address_out)
1608 {
1610 
1611  tor_assert(pk);
1612  tor_assert(port_cfgs);
1613  tor_assert(address_out);
1614 
1615  switch (hs_version) {
1616  case HS_VERSION_TWO:
1617  ret = rend_service_add_ephemeral(pk->v2, port_cfgs, max_streams,
1618  max_streams_close_circuit, auth_type,
1619  auth_clients, address_out);
1620  break;
1621  case HS_VERSION_THREE:
1622  ret = hs_service_add_ephemeral(pk->v3, port_cfgs, max_streams,
1623  max_streams_close_circuit, address_out);
1624  break;
1625  default:
1626  tor_assert_unreached();
1627  }
1628 
1629  return ret;
1630 }
1631 
1636 
1640 smartlist_t *
1642 {
1643  return detached_onion_services;
1644 }
1645 
1646 static const char *add_onion_keywords[] = {
1647  "Port", "Flags", "MaxStreams", "ClientAuth", NULL
1648 };
1649 static const control_cmd_syntax_t add_onion_syntax = {
1650  .min_args = 1, .max_args = 1,
1651  .accept_keywords = true,
1652  .allowed_keywords = add_onion_keywords
1653 };
1654 
1657 static int
1659  const control_cmd_args_t *args)
1660 {
1661  /* Parse all of the arguments that do not involve handling cryptographic
1662  * material first, since there's no reason to touch that at all if any of
1663  * the other arguments are malformed.
1664  */
1665  smartlist_t *port_cfgs = smartlist_new();
1666  smartlist_t *auth_clients = NULL;
1667  smartlist_t *auth_created_clients = NULL;
1668  int discard_pk = 0;
1669  int detach = 0;
1670  int max_streams = 0;
1671  int max_streams_close_circuit = 0;
1672  rend_auth_type_t auth_type = REND_NO_AUTH;
1673  int non_anonymous = 0;
1674  const config_line_t *arg;
1675 
1676  for (arg = args->kwargs; arg; arg = arg->next) {
1677  if (!strcasecmp(arg->key, "Port")) {
1678  /* "Port=VIRTPORT[,TARGET]". */
1680  rend_service_parse_port_config(arg->value, ",", NULL);
1681  if (!cfg) {
1682  control_write_endreply(conn, 512, "Invalid VIRTPORT/TARGET");
1683  goto out;
1684  }
1685  smartlist_add(port_cfgs, cfg);
1686  } else if (!strcasecmp(arg->key, "MaxStreams")) {
1687  /* "MaxStreams=[0..65535]". */
1688  int ok = 0;
1689  max_streams = (int)tor_parse_long(arg->value, 10, 0, 65535, &ok, NULL);
1690  if (!ok) {
1691  control_write_endreply(conn, 512, "Invalid MaxStreams");
1692  goto out;
1693  }
1694  } else if (!strcasecmp(arg->key, "Flags")) {
1695  /* "Flags=Flag[,Flag]", where Flag can be:
1696  * * 'DiscardPK' - If tor generates the keypair, do not include it in
1697  * the response.
1698  * * 'Detach' - Do not tie this onion service to any particular control
1699  * connection.
1700  * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
1701  * exceeded.
1702  * * 'BasicAuth' - Client authorization using the 'basic' method.
1703  * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
1704  * flag is present, tor must be in non-anonymous
1705  * hidden service mode. If this flag is absent,
1706  * tor must be in anonymous hidden service mode.
1707  */
1708  static const char *discard_flag = "DiscardPK";
1709  static const char *detach_flag = "Detach";
1710  static const char *max_s_close_flag = "MaxStreamsCloseCircuit";
1711  static const char *basicauth_flag = "BasicAuth";
1712  static const char *non_anonymous_flag = "NonAnonymous";
1713 
1714  smartlist_t *flags = smartlist_new();
1715  int bad = 0;
1716 
1717  smartlist_split_string(flags, arg->value, ",", SPLIT_IGNORE_BLANK, 0);
1718  if (smartlist_len(flags) < 1) {
1719  control_write_endreply(conn, 512, "Invalid 'Flags' argument");
1720  bad = 1;
1721  }
1722  SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
1723  {
1724  if (!strcasecmp(flag, discard_flag)) {
1725  discard_pk = 1;
1726  } else if (!strcasecmp(flag, detach_flag)) {
1727  detach = 1;
1728  } else if (!strcasecmp(flag, max_s_close_flag)) {
1729  max_streams_close_circuit = 1;
1730  } else if (!strcasecmp(flag, basicauth_flag)) {
1731  auth_type = REND_BASIC_AUTH;
1732  } else if (!strcasecmp(flag, non_anonymous_flag)) {
1733  non_anonymous = 1;
1734  } else {
1735  control_printf_endreply(conn, 512, "Invalid 'Flags' argument: %s",
1736  escaped(flag));
1737  bad = 1;
1738  break;
1739  }
1740  } SMARTLIST_FOREACH_END(flag);
1741  SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
1742  smartlist_free(flags);
1743  if (bad)
1744  goto out;
1745 
1746  } else if (!strcasecmp(arg->key, "ClientAuth")) {
1747  char *err_msg = NULL;
1748  int created = 0;
1749  rend_authorized_client_t *client =
1750  add_onion_helper_clientauth(arg->value,
1751  &created, &err_msg);
1752  if (!client) {
1753  if (err_msg) {
1754  connection_write_str_to_buf(err_msg, conn);
1755  tor_free(err_msg);
1756  }
1757  goto out;
1758  }
1759 
1760  if (auth_clients != NULL) {
1761  int bad = 0;
1762  SMARTLIST_FOREACH_BEGIN(auth_clients, rend_authorized_client_t *, ac) {
1763  if (strcmp(ac->client_name, client->client_name) == 0) {
1764  bad = 1;
1765  break;
1766  }
1767  } SMARTLIST_FOREACH_END(ac);
1768  if (bad) {
1769  control_write_endreply(conn, 512, "Duplicate name in ClientAuth");
1770  rend_authorized_client_free(client);
1771  goto out;
1772  }
1773  } else {
1774  auth_clients = smartlist_new();
1775  auth_created_clients = smartlist_new();
1776  }
1777  smartlist_add(auth_clients, client);
1778  if (created) {
1779  smartlist_add(auth_created_clients, client);
1780  }
1781  } else {
1782  tor_assert_nonfatal_unreached();
1783  goto out;
1784  }
1785  }
1786  if (smartlist_len(port_cfgs) == 0) {
1787  control_write_endreply(conn, 512, "Missing 'Port' argument");
1788  goto out;
1789  } else if (auth_type == REND_NO_AUTH && auth_clients != NULL) {
1790  control_write_endreply(conn, 512, "No auth type specified");
1791  goto out;
1792  } else if (auth_type != REND_NO_AUTH && auth_clients == NULL) {
1793  control_write_endreply(conn, 512, "No auth clients specified");
1794  goto out;
1795  } else if ((auth_type == REND_BASIC_AUTH &&
1796  smartlist_len(auth_clients) > 512) ||
1797  (auth_type == REND_STEALTH_AUTH &&
1798  smartlist_len(auth_clients) > 16)) {
1799  control_write_endreply(conn, 512, "Too many auth clients");
1800  goto out;
1801  } else if (non_anonymous != rend_service_non_anonymous_mode_enabled(
1802  get_options())) {
1803  /* If we failed, and the non-anonymous flag is set, Tor must be in
1804  * anonymous hidden service mode.
1805  * The error message changes based on the current Tor config:
1806  * 512 Tor is in anonymous hidden service mode
1807  * 512 Tor is in non-anonymous hidden service mode
1808  * (I've deliberately written them out in full here to aid searchability.)
1809  */
1810  control_printf_endreply(conn, 512,
1811  "Tor is in %sanonymous hidden service " "mode",
1812  non_anonymous ? "" : "non-");
1813  goto out;
1814  }
1815 
1816  /* Parse the "keytype:keyblob" argument. */
1817  int hs_version = 0;
1818  add_onion_secret_key_t pk = { NULL };
1819  const char *key_new_alg = NULL;
1820  char *key_new_blob = NULL;
1821  char *err_msg = NULL;
1822 
1823  const char *onionkey = smartlist_get(args->args, 0);
1824  if (add_onion_helper_keyarg(onionkey, discard_pk,
1825  &key_new_alg, &key_new_blob, &pk, &hs_version,
1826  &err_msg) < 0) {
1827  if (err_msg) {
1828  connection_write_str_to_buf(err_msg, conn);
1829  tor_free(err_msg);
1830  }
1831  goto out;
1832  }
1833  tor_assert(!err_msg);
1834 
1835  /* Hidden service version 3 don't have client authentication support so if
1836  * ClientAuth was given, send back an error. */
1837  if (hs_version == HS_VERSION_THREE && auth_clients) {
1838  control_write_endreply(conn, 513, "ClientAuth not supported");
1839  goto out;
1840  }
1841 
1842  /* Create the HS, using private key pk, client authentication auth_type,
1843  * the list of auth_clients, and port config port_cfg.
1844  * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
1845  * regardless of success/failure.
1846  */
1847  char *service_id = NULL;
1848  int ret = add_onion_helper_add_service(hs_version, &pk, port_cfgs,
1849  max_streams,
1850  max_streams_close_circuit, auth_type,
1851  auth_clients, &service_id);
1852  port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
1853  auth_clients = NULL; /* so is auth_clients */
1854  switch (ret) {
1855  case RSAE_OKAY:
1856  {
1857  if (detach) {
1859  detached_onion_services = smartlist_new();
1861  } else {
1862  if (!conn->ephemeral_onion_services)
1863  conn->ephemeral_onion_services = smartlist_new();
1864  smartlist_add(conn->ephemeral_onion_services, service_id);
1865  }
1866 
1867  tor_assert(service_id);
1868  control_printf_midreply(conn, 250, "ServiceID=%s", service_id);
1869  if (key_new_alg) {
1870  tor_assert(key_new_blob);
1871  control_printf_midreply(conn, 250, "PrivateKey=%s:%s",
1872  key_new_alg, key_new_blob);
1873  }
1874  if (auth_created_clients) {
1875  SMARTLIST_FOREACH(auth_created_clients, rend_authorized_client_t *, ac, {
1876  char *encoded = rend_auth_encode_cookie(ac->descriptor_cookie,
1877  auth_type);
1878  tor_assert(encoded);
1879  connection_printf_to_buf(conn, "250-ClientAuth=%s:%s\r\n",
1880  ac->client_name, encoded);
1881  memwipe(encoded, 0, strlen(encoded));
1882  tor_free(encoded);
1883  });
1884  }
1885 
1886  send_control_done(conn);
1887  break;
1888  }
1889  case RSAE_BADPRIVKEY:
1890  control_write_endreply(conn, 551, "Failed to generate onion address");
1891  break;
1892  case RSAE_ADDREXISTS:
1893  control_write_endreply(conn, 550, "Onion address collision");
1894  break;
1895  case RSAE_BADVIRTPORT:
1896  control_write_endreply(conn, 512, "Invalid VIRTPORT/TARGET");
1897  break;
1898  case RSAE_BADAUTH:
1899  control_write_endreply(conn, 512, "Invalid client authorization");
1900  break;
1901  case RSAE_INTERNAL: /* FALLSTHROUGH */
1902  default:
1903  control_write_endreply(conn, 551, "Failed to add Onion Service");
1904  }
1905  if (key_new_blob) {
1906  memwipe(key_new_blob, 0, strlen(key_new_blob));
1907  tor_free(key_new_blob);
1908  }
1909 
1910  out:
1911  if (port_cfgs) {
1913  rend_service_port_config_free(p));
1914  smartlist_free(port_cfgs);
1915  }
1916 
1917  if (auth_clients) {
1918  SMARTLIST_FOREACH(auth_clients, rend_authorized_client_t *, ac,
1919  rend_authorized_client_free(ac));
1920  smartlist_free(auth_clients);
1921  }
1922  if (auth_created_clients) {
1923  // Do not free entries; they are the same as auth_clients
1924  smartlist_free(auth_created_clients);
1925  }
1926  return 0;
1927 }
1928 
1938 STATIC int
1939 add_onion_helper_keyarg(const char *arg, int discard_pk,
1940  const char **key_new_alg_out, char **key_new_blob_out,
1941  add_onion_secret_key_t *decoded_key, int *hs_version,
1942  char **err_msg_out)
1943 {
1944  smartlist_t *key_args = smartlist_new();
1945  crypto_pk_t *pk = NULL;
1946  const char *key_new_alg = NULL;
1947  char *key_new_blob = NULL;
1948  char *err_msg = NULL;
1949  int ret = -1;
1950 
1951  smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
1952  if (smartlist_len(key_args) != 2) {
1953  err_msg = tor_strdup("512 Invalid key type/blob\r\n");
1954  goto err;
1955  }
1956 
1957  /* The format is "KeyType:KeyBlob". */
1958  static const char *key_type_new = "NEW";
1959  static const char *key_type_best = "BEST";
1960  static const char *key_type_rsa1024 = "RSA1024";
1961  static const char *key_type_ed25519_v3 = "ED25519-V3";
1962 
1963  const char *key_type = smartlist_get(key_args, 0);
1964  const char *key_blob = smartlist_get(key_args, 1);
1965 
1966  if (!strcasecmp(key_type_rsa1024, key_type)) {
1967  /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
1968  pk = crypto_pk_base64_decode_private(key_blob, strlen(key_blob));
1969  if (!pk) {
1970  err_msg = tor_strdup("512 Failed to decode RSA key\r\n");
1971  goto err;
1972  }
1973  if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
1974  crypto_pk_free(pk);
1975  err_msg = tor_strdup("512 Invalid RSA key size\r\n");
1976  goto err;
1977  }
1978  decoded_key->v2 = pk;
1979  *hs_version = HS_VERSION_TWO;
1980  } else if (!strcasecmp(key_type_ed25519_v3, key_type)) {
1981  /* "ED25519-V3:<Base64 Blob>" - Loading a pre-existing ed25519 key. */
1982  ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
1983  if (base64_decode((char *) sk->seckey, sizeof(sk->seckey), key_blob,
1984  strlen(key_blob)) != sizeof(sk->seckey)) {
1985  tor_free(sk);
1986  err_msg = tor_strdup("512 Failed to decode ED25519-V3 key\r\n");
1987  goto err;
1988  }
1989  decoded_key->v3 = sk;
1990  *hs_version = HS_VERSION_THREE;
1991  } else if (!strcasecmp(key_type_new, key_type)) {
1992  /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
1993  if (!strcasecmp(key_type_rsa1024, key_blob) ||
1994  !strcasecmp(key_type_best, key_blob)) {
1995  /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
1996  pk = crypto_pk_new();
1997  if (crypto_pk_generate_key(pk)) {
1998  tor_asprintf(&err_msg, "551 Failed to generate %s key\r\n",
1999  key_type_rsa1024);
2000  goto err;
2001  }
2002  if (!discard_pk) {
2003  if (crypto_pk_base64_encode_private(pk, &key_new_blob)) {
2004  crypto_pk_free(pk);
2005  tor_asprintf(&err_msg, "551 Failed to encode %s key\r\n",
2006  key_type_rsa1024);
2007  goto err;
2008  }
2009  key_new_alg = key_type_rsa1024;
2010  }
2011  decoded_key->v2 = pk;
2012  *hs_version = HS_VERSION_TWO;
2013  } else if (!strcasecmp(key_type_ed25519_v3, key_blob)) {
2014  ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
2015  if (ed25519_secret_key_generate(sk, 1) < 0) {
2016  tor_free(sk);
2017  tor_asprintf(&err_msg, "551 Failed to generate %s key\r\n",
2018  key_type_ed25519_v3);
2019  goto err;
2020  }
2021  if (!discard_pk) {
2022  ssize_t len = base64_encode_size(sizeof(sk->seckey), 0) + 1;
2023  key_new_blob = tor_malloc_zero(len);
2024  if (base64_encode(key_new_blob, len, (const char *) sk->seckey,
2025  sizeof(sk->seckey), 0) != (len - 1)) {
2026  tor_free(sk);
2027  tor_free(key_new_blob);
2028  tor_asprintf(&err_msg, "551 Failed to encode %s key\r\n",
2029  key_type_ed25519_v3);
2030  goto err;
2031  }
2032  key_new_alg = key_type_ed25519_v3;
2033  }
2034  decoded_key->v3 = sk;
2035  *hs_version = HS_VERSION_THREE;
2036  } else {
2037  err_msg = tor_strdup("513 Invalid key type\r\n");
2038  goto err;
2039  }
2040  } else {
2041  err_msg = tor_strdup("513 Invalid key type\r\n");
2042  goto err;
2043  }
2044 
2045  /* Succeeded in loading or generating a private key. */
2046  ret = 0;
2047 
2048  err:
2049  SMARTLIST_FOREACH(key_args, char *, cp, {
2050  memwipe(cp, 0, strlen(cp));
2051  tor_free(cp);
2052  });
2053  smartlist_free(key_args);
2054 
2055  if (err_msg_out) {
2056  *err_msg_out = err_msg;
2057  } else {
2058  tor_free(err_msg);
2059  }
2060  *key_new_alg_out = key_new_alg;
2061  *key_new_blob_out = key_new_blob;
2062 
2063  return ret;
2064 }
2065 
2074 STATIC rend_authorized_client_t *
2075 add_onion_helper_clientauth(const char *arg, int *created, char **err_msg)
2076 {
2077  int ok = 0;
2078 
2079  tor_assert(arg);
2080  tor_assert(created);
2081  tor_assert(err_msg);
2082  *err_msg = NULL;
2083 
2084  smartlist_t *auth_args = smartlist_new();
2085  rend_authorized_client_t *client =
2086  tor_malloc_zero(sizeof(rend_authorized_client_t));
2087  smartlist_split_string(auth_args, arg, ":", 0, 0);
2088  if (smartlist_len(auth_args) < 1 || smartlist_len(auth_args) > 2) {
2089  *err_msg = tor_strdup("512 Invalid ClientAuth syntax\r\n");
2090  goto err;
2091  }
2092  client->client_name = tor_strdup(smartlist_get(auth_args, 0));
2093  if (smartlist_len(auth_args) == 2) {
2094  char *decode_err_msg = NULL;
2095  if (rend_auth_decode_cookie(smartlist_get(auth_args, 1),
2096  client->descriptor_cookie,
2097  NULL, &decode_err_msg) < 0) {
2098  tor_assert(decode_err_msg);
2099  tor_asprintf(err_msg, "512 %s\r\n", decode_err_msg);
2100  tor_free(decode_err_msg);
2101  goto err;
2102  }
2103  *created = 0;
2104  } else {
2105  crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
2106  *created = 1;
2107  }
2108 
2109  if (!rend_valid_client_name(client->client_name)) {
2110  *err_msg = tor_strdup("512 Invalid name in ClientAuth\r\n");
2111  goto err;
2112  }
2113 
2114  ok = 1;
2115  err:
2116  SMARTLIST_FOREACH(auth_args, char *, item, tor_free(item));
2117  smartlist_free(auth_args);
2118  if (!ok) {
2119  rend_authorized_client_free(client);
2120  client = NULL;
2121  }
2122  return client;
2123 }
2124 
2125 static const control_cmd_syntax_t del_onion_syntax = {
2126  .min_args = 1, .max_args = 1,
2127 };
2128 
2131 static int
2133  const control_cmd_args_t *cmd_args)
2134 {
2135  int hs_version = 0;
2136  smartlist_t *args = cmd_args->args;
2137  tor_assert(smartlist_len(args) == 1);
2138 
2139  const char *service_id = smartlist_get(args, 0);
2140  if (rend_valid_v2_service_id(service_id)) {
2141  hs_version = HS_VERSION_TWO;
2142  } else if (hs_address_is_valid(service_id)) {
2143  hs_version = HS_VERSION_THREE;
2144  } else {
2145  control_write_endreply(conn, 512, "Malformed Onion Service id");
2146  goto out;
2147  }
2148 
2149  /* Determine if the onion service belongs to this particular control
2150  * connection, or if it is in the global list of detached services. If it
2151  * is in neither, either the service ID is invalid in some way, or it
2152  * explicitly belongs to a different control connection, and an error
2153  * should be returned.
2154  */
2155  smartlist_t *services[2] = {
2158  };
2159  smartlist_t *onion_services = NULL;
2160  int idx = -1;
2161  for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
2162  idx = smartlist_string_pos(services[i], service_id);
2163  if (idx != -1) {
2164  onion_services = services[i];
2165  break;
2166  }
2167  }
2168  if (onion_services == NULL) {
2169  control_write_endreply(conn, 552, "Unknown Onion Service id");
2170  } else {
2171  int ret = -1;
2172  switch (hs_version) {
2173  case HS_VERSION_TWO:
2174  ret = rend_service_del_ephemeral(service_id);
2175  break;
2176  case HS_VERSION_THREE:
2177  ret = hs_service_del_ephemeral(service_id);
2178  break;
2179  default:
2180  /* The ret value will be -1 thus hitting the warning below. This should
2181  * never happen because of the check at the start of the function. */
2182  break;
2183  }
2184  if (ret < 0) {
2185  /* This should *NEVER* fail, since the service is on either the
2186  * per-control connection list, or the global one.
2187  */
2188  log_warn(LD_BUG, "Failed to remove Onion Service %s.",
2189  escaped(service_id));
2191  }
2192 
2193  /* Remove/scrub the service_id from the appropriate list. */
2194  char *cp = smartlist_get(onion_services, idx);
2195  smartlist_del(onion_services, idx);
2196  memwipe(cp, 0, strlen(cp));
2197  tor_free(cp);
2198 
2199  send_control_done(conn);
2200  }
2201 
2202  out:
2203  return 0;
2204 }
2205 
2206 static const control_cmd_syntax_t obsolete_syntax = {
2207  .max_args = UINT_MAX
2208 };
2209 
2214 static int
2216  const control_cmd_args_t *args)
2217 {
2218  (void)args;
2219  char *command = tor_strdup(conn->current_cmd);
2220  tor_strupper(command);
2221  control_printf_endreply(conn, 511, "%s is obsolete.", command);
2222  tor_free(command);
2223  return 0;
2224 }
2225 
2229 typedef int (*handler_fn_t) (control_connection_t *conn,
2230  const control_cmd_args_t *args);
2231 
2235 typedef struct control_cmd_def_t {
2239  const char *name;
2247  unsigned flags;
2253 
2258 #define CMD_FL_WIPE (1u<<0)
2259 
2263 #define ONE_LINE(name, flags) \
2264  { \
2265  #name, \
2266  handle_control_ ##name, \
2267  flags, \
2268  &name##_syntax, \
2269  }
2270 
2275 #define MULTLINE(name, flags) \
2276  { "+"#name, \
2277  handle_control_ ##name, \
2278  flags, \
2279  &name##_syntax \
2280  }
2281 
2286 #define OBSOLETE(name) \
2287  { #name, \
2288  handle_control_obsolete, \
2289  0, \
2290  &obsolete_syntax, \
2291  }
2292 
2297 {
2298  ONE_LINE(setconf, 0),
2299  ONE_LINE(resetconf, 0),
2300  ONE_LINE(getconf, 0),
2301  MULTLINE(loadconf, 0),
2302  ONE_LINE(setevents, 0),
2303  ONE_LINE(authenticate, CMD_FL_WIPE),
2304  ONE_LINE(saveconf, 0),
2305  ONE_LINE(signal, 0),
2306  ONE_LINE(takeownership, 0),
2307  ONE_LINE(dropownership, 0),
2308  ONE_LINE(mapaddress, 0),
2309  ONE_LINE(getinfo, 0),
2310  ONE_LINE(extendcircuit, 0),
2311  ONE_LINE(setcircuitpurpose, 0),
2312  OBSOLETE(setrouterpurpose),
2313  ONE_LINE(attachstream, 0),
2314  MULTLINE(postdescriptor, 0),
2315  ONE_LINE(redirectstream, 0),
2316  ONE_LINE(closestream, 0),
2317  ONE_LINE(closecircuit, 0),
2318  ONE_LINE(usefeature, 0),
2319  ONE_LINE(resolve, 0),
2320  ONE_LINE(protocolinfo, 0),
2321  ONE_LINE(authchallenge, CMD_FL_WIPE),
2322  ONE_LINE(dropguards, 0),
2323  ONE_LINE(hsfetch, 0),
2324  MULTLINE(hspost, 0),
2325  ONE_LINE(add_onion, CMD_FL_WIPE),
2326  ONE_LINE(del_onion, CMD_FL_WIPE),
2327 };
2328 
2333 
2338 static int
2340  control_connection_t *conn,
2341  uint32_t cmd_data_len,
2342  char *args)
2343 {
2344  int rv = 0;
2345 
2346  control_cmd_args_t *parsed_args;
2347  char *err=NULL;
2348  tor_assert(def->syntax);
2349  parsed_args = control_cmd_parse_args(conn->current_cmd,
2350  def->syntax,
2351  cmd_data_len, args,
2352  &err);
2353  if (!parsed_args) {
2354  control_printf_endreply(conn, 512, "Bad arguments to %s: %s",
2355  conn->current_cmd, err?err:"");
2356  tor_free(err);
2357  } else {
2358  if (BUG(err))
2359  tor_free(err);
2360  if (def->handler(conn, parsed_args))
2361  rv = 0;
2362 
2363  if (def->flags & CMD_FL_WIPE)
2364  control_cmd_args_wipe(parsed_args);
2365 
2366  control_cmd_args_free(parsed_args);
2367  }
2368 
2369  if (def->flags & CMD_FL_WIPE)
2370  memwipe(args, 0, cmd_data_len);
2371 
2372  return rv;
2373 }
2374 
2379 int
2381  uint32_t cmd_data_len,
2382  char *args)
2383 {
2384  tor_assert(conn);
2385  tor_assert(args);
2386  tor_assert(args[cmd_data_len] == '\0');
2387 
2388  for (unsigned i = 0; i < N_CONTROL_COMMANDS; ++i) {
2389  const control_cmd_def_t *def = &CONTROL_COMMANDS[i];
2390  if (!strcasecmp(conn->current_cmd, def->name)) {
2391  return handle_single_control_command(def, conn, cmd_data_len, args);
2392  }
2393  }
2394 
2395  control_printf_endreply(conn, 510, "Unrecognized command \"%s\"",
2396  conn->current_cmd);
2397 
2398  return 0;
2399 }
2400 
2401 void
2402 control_cmd_free_all(void)
2403 {
2404  if (detached_onion_services) { /* Free the detached onion services */
2406  smartlist_free(detached_onion_services);
2407  }
2408 }
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:2258
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:2580
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:1185
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:1641
#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.
void connection_write_str_to_buf(const char *s, control_connection_t *conn)
Definition: control_proto.c:30
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:1635
#define TO_CIRCUIT(x)
Definition: or.h:947
static int handle_control_postdescriptor(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1041
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:718
handler_fn_t handler
Definition: control_cmd.c:2243
#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:1340
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
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, char **err_msg_out)
Definition: control_cmd.c:1939
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:1260
#define ONE_LINE(name, flags)
Definition: control_cmd.c:2263
static int handle_control_obsolete(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:2215
int option_is_recognized(const char *key)
Definition: config.c:2562
static int handle_control_attachstream(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:947
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:5614
int handle_control_command(control_connection_t *conn, uint32_t cmd_data_len, char *args)
Definition: control_cmd.c:2380
socks_request_t * socks_request
Definition for control_cmd_args_t.
#define OBSOLETE(name)
Definition: control_cmd.c:2286
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:649
static int handle_control_closestream(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:1144
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:2275
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:77
int address_is_invalid_destination(const char *address, int client)
Definition: addressmap.c:1078
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:1215
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:2251
Master header file for Tor-specific functionality.
static const size_t N_CONTROL_COMMANDS
Definition: control_cmd.c:2332
#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:2239
uint16_t marked_for_close
static int handle_control_hspost(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1498
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
unsigned int type
Definition: connection_st.h:45
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:2339
#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:1097
static int handle_control_extendcircuit(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:741
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
STATIC rend_authorized_client_t * add_onion_helper_clientauth(const char *arg, int *created, char **err_msg)
Definition: control_cmd.c:2075
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:1362
int circuit_send_next_onion_skin(origin_circuit_t *circ)
Definition: circuitbuild.c:937
int options_save_current(void)
Definition: config.c:7982
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:2595
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:2229
static int handle_control_setcircuitpurpose(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:902
const char * option_get_canonical_name(const char *key)
Definition: config.c:2571
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:2132
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:1658
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:3062
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:2296
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:1331
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)
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:5376
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:1392
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:3678
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:83
void control_write_midreply(control_connection_t *conn, int code, const char *s)
Header file for routerlist.c.
void connection_printf_to_buf(control_connection_t *conn, const char *format,...)
Definition: control_proto.c:39
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:3660
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)