command.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file command.c
  8. * \brief Functions for processing incoming cells.
  9. **/
  10. /* In-points to command.c:
  11. *
  12. * - command_process_cell(), called from
  13. * connection_or_process_cells_from_inbuf() in connection_or.c
  14. */
  15. #include "or.h"
  16. #include "circuitbuild.h"
  17. #include "circuitlist.h"
  18. #include "command.h"
  19. #include "connection.h"
  20. #include "connection_or.h"
  21. #include "config.h"
  22. #include "control.h"
  23. #include "cpuworker.h"
  24. #include "hibernate.h"
  25. #include "nodelist.h"
  26. #include "onion.h"
  27. #include "relay.h"
  28. #include "router.h"
  29. #include "routerlist.h"
  30. /** How many CELL_PADDING cells have we received, ever? */
  31. uint64_t stats_n_padding_cells_processed = 0;
  32. /** How many CELL_CREATE cells have we received, ever? */
  33. uint64_t stats_n_create_cells_processed = 0;
  34. /** How many CELL_CREATED cells have we received, ever? */
  35. uint64_t stats_n_created_cells_processed = 0;
  36. /** How many CELL_RELAY cells have we received, ever? */
  37. uint64_t stats_n_relay_cells_processed = 0;
  38. /** How many CELL_DESTROY cells have we received, ever? */
  39. uint64_t stats_n_destroy_cells_processed = 0;
  40. /** How many CELL_VERSIONS cells have we received, ever? */
  41. uint64_t stats_n_versions_cells_processed = 0;
  42. /** How many CELL_NETINFO cells have we received, ever? */
  43. uint64_t stats_n_netinfo_cells_processed = 0;
  44. /** How many CELL_VPADDING cells have we received, ever? */
  45. uint64_t stats_n_vpadding_cells_processed = 0;
  46. /** How many CELL_CERTS cells have we received, ever? */
  47. uint64_t stats_n_certs_cells_processed = 0;
  48. /** How many CELL_AUTH_CHALLENGE cells have we received, ever? */
  49. uint64_t stats_n_auth_challenge_cells_processed = 0;
  50. /** How many CELL_AUTHENTICATE cells have we received, ever? */
  51. uint64_t stats_n_authenticate_cells_processed = 0;
  52. /** How many CELL_AUTHORIZE cells have we received, ever? */
  53. uint64_t stats_n_authorize_cells_processed = 0;
  54. /* These are the main functions for processing cells */
  55. static void command_process_create_cell(cell_t *cell, or_connection_t *conn);
  56. static void command_process_created_cell(cell_t *cell, or_connection_t *conn);
  57. static void command_process_relay_cell(cell_t *cell, or_connection_t *conn);
  58. static void command_process_destroy_cell(cell_t *cell, or_connection_t *conn);
  59. static void command_process_versions_cell(var_cell_t *cell,
  60. or_connection_t *conn);
  61. static void command_process_netinfo_cell(cell_t *cell, or_connection_t *conn);
  62. static void command_process_certs_cell(var_cell_t *cell,
  63. or_connection_t *conn);
  64. static void command_process_auth_challenge_cell(var_cell_t *cell,
  65. or_connection_t *conn);
  66. static void command_process_authenticate_cell(var_cell_t *cell,
  67. or_connection_t *conn);
  68. static int enter_v3_handshake_with_cell(var_cell_t *cell,
  69. or_connection_t *conn);
  70. #ifdef KEEP_TIMING_STATS
  71. /** This is a wrapper function around the actual function that processes the
  72. * <b>cell</b> that just arrived on <b>conn</b>. Increment <b>*time</b>
  73. * by the number of microseconds used by the call to <b>*func(cell, conn)</b>.
  74. */
  75. static void
  76. command_time_process_cell(cell_t *cell, or_connection_t *conn, int *time,
  77. void (*func)(cell_t *, or_connection_t *))
  78. {
  79. struct timeval start, end;
  80. long time_passed;
  81. tor_gettimeofday(&start);
  82. (*func)(cell, conn);
  83. tor_gettimeofday(&end);
  84. time_passed = tv_udiff(&start, &end) ;
  85. if (time_passed > 10000) { /* more than 10ms */
  86. log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
  87. }
  88. if (time_passed < 0) {
  89. log_info(LD_GENERAL,"That call took us back in time!");
  90. time_passed = 0;
  91. }
  92. *time += time_passed;
  93. }
  94. #endif
  95. /** Process a <b>cell</b> that was just received on <b>conn</b>. Keep internal
  96. * statistics about how many of each cell we've processed so far
  97. * this second, and the total number of microseconds it took to
  98. * process each type of cell.
  99. */
  100. void
  101. command_process_cell(cell_t *cell, or_connection_t *conn)
  102. {
  103. int handshaking = (conn->_base.state != OR_CONN_STATE_OPEN);
  104. #ifdef KEEP_TIMING_STATS
  105. /* how many of each cell have we seen so far this second? needs better
  106. * name. */
  107. static int num_create=0, num_created=0, num_relay=0, num_destroy=0;
  108. /* how long has it taken to process each type of cell? */
  109. static int create_time=0, created_time=0, relay_time=0, destroy_time=0;
  110. static time_t current_second = 0; /* from previous calls to time */
  111. time_t now = time(NULL);
  112. if (now > current_second) { /* the second has rolled over */
  113. /* print stats */
  114. log_info(LD_OR,
  115. "At end of second: %d creates (%d ms), %d createds (%d ms), "
  116. "%d relays (%d ms), %d destroys (%d ms)",
  117. num_create, create_time/1000,
  118. num_created, created_time/1000,
  119. num_relay, relay_time/1000,
  120. num_destroy, destroy_time/1000);
  121. /* zero out stats */
  122. num_create = num_created = num_relay = num_destroy = 0;
  123. create_time = created_time = relay_time = destroy_time = 0;
  124. /* remember which second it is, for next time */
  125. current_second = now;
  126. }
  127. #endif
  128. #ifdef KEEP_TIMING_STATS
  129. #define PROCESS_CELL(tp, cl, cn) STMT_BEGIN { \
  130. ++num ## tp; \
  131. command_time_process_cell(cl, cn, & tp ## time , \
  132. command_process_ ## tp ## _cell); \
  133. } STMT_END
  134. #else
  135. #define PROCESS_CELL(tp, cl, cn) command_process_ ## tp ## _cell(cl, cn)
  136. #endif
  137. if (conn->_base.marked_for_close)
  138. return;
  139. /* Reject all but VERSIONS and NETINFO when handshaking. */
  140. /* (VERSIONS should actually be impossible; it's variable-length.) */
  141. if (handshaking && cell->command != CELL_VERSIONS &&
  142. cell->command != CELL_NETINFO) {
  143. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  144. "Received unexpected cell command %d in state %s; ignoring it.",
  145. (int)cell->command,
  146. conn_state_to_string(CONN_TYPE_OR,conn->_base.state));
  147. return;
  148. }
  149. if (conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
  150. or_handshake_state_record_cell(conn->handshake_state, cell, 1);
  151. switch (cell->command) {
  152. case CELL_PADDING:
  153. ++stats_n_padding_cells_processed;
  154. /* do nothing */
  155. break;
  156. case CELL_CREATE:
  157. case CELL_CREATE_FAST:
  158. ++stats_n_create_cells_processed;
  159. PROCESS_CELL(create, cell, conn);
  160. break;
  161. case CELL_CREATED:
  162. case CELL_CREATED_FAST:
  163. ++stats_n_created_cells_processed;
  164. PROCESS_CELL(created, cell, conn);
  165. break;
  166. case CELL_RELAY:
  167. case CELL_RELAY_EARLY:
  168. ++stats_n_relay_cells_processed;
  169. PROCESS_CELL(relay, cell, conn);
  170. break;
  171. case CELL_DESTROY:
  172. ++stats_n_destroy_cells_processed;
  173. PROCESS_CELL(destroy, cell, conn);
  174. break;
  175. case CELL_VERSIONS:
  176. tor_fragile_assert();
  177. break;
  178. case CELL_NETINFO:
  179. ++stats_n_netinfo_cells_processed;
  180. PROCESS_CELL(netinfo, cell, conn);
  181. break;
  182. default:
  183. log_fn(LOG_INFO, LD_PROTOCOL,
  184. "Cell of unknown type (%d) received. Dropping.", cell->command);
  185. break;
  186. }
  187. }
  188. /** Return true if <b>command</b> is a cell command that's allowed to start a
  189. * V3 handshake. */
  190. static int
  191. command_allowed_before_handshake(uint8_t command)
  192. {
  193. switch (command) {
  194. case CELL_VERSIONS:
  195. case CELL_VPADDING:
  196. case CELL_AUTHORIZE:
  197. return 1;
  198. default:
  199. return 0;
  200. }
  201. }
  202. /** Process a <b>cell</b> that was just received on <b>conn</b>. Keep internal
  203. * statistics about how many of each cell we've processed so far
  204. * this second, and the total number of microseconds it took to
  205. * process each type of cell.
  206. */
  207. void
  208. command_process_var_cell(var_cell_t *cell, or_connection_t *conn)
  209. {
  210. #ifdef KEEP_TIMING_STATS
  211. /* how many of each cell have we seen so far this second? needs better
  212. * name. */
  213. static int num_versions=0, num_certs=0;
  214. time_t now = time(NULL);
  215. if (now > current_second) { /* the second has rolled over */
  216. /* print stats */
  217. log_info(LD_OR,
  218. "At end of second: %d versions (%d ms), %d certs (%d ms)",
  219. num_versions, versions_time/1000,
  220. num_certs, certs_time/1000);
  221. num_versions = num_certs = 0;
  222. versions_time = certs_time = 0;
  223. /* remember which second it is, for next time */
  224. current_second = now;
  225. }
  226. #endif
  227. if (conn->_base.marked_for_close)
  228. return;
  229. switch (conn->_base.state)
  230. {
  231. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  232. if (cell->command != CELL_VERSIONS)
  233. return;
  234. break;
  235. case OR_CONN_STATE_TLS_HANDSHAKING:
  236. /* If we're using bufferevents, it's entirely possible for us to
  237. * notice "hey, data arrived!" before we notice "hey, the handshake
  238. * finished!" And we need to be accepting both at once to handle both
  239. * the v2 and v3 handshakes. */
  240. /* fall through */
  241. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  242. if (! command_allowed_before_handshake(cell->command)) {
  243. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  244. "Received a cell with command %d in state %s; "
  245. "ignoring it.",
  246. (int)cell->command,
  247. conn_state_to_string(CONN_TYPE_OR,conn->_base.state));
  248. return;
  249. } else {
  250. if (enter_v3_handshake_with_cell(cell, conn)<0)
  251. return;
  252. }
  253. break;
  254. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  255. if (cell->command != CELL_AUTHENTICATE)
  256. or_handshake_state_record_var_cell(conn->handshake_state, cell, 1);
  257. break; /* Everything is allowed */
  258. case OR_CONN_STATE_OPEN:
  259. if (conn->link_proto < 3) {
  260. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  261. "Received a variable-length cell with command %d in state %s "
  262. "with link protocol %d; ignoring it.",
  263. (int)cell->command,
  264. conn_state_to_string(CONN_TYPE_OR,conn->_base.state),
  265. (int)conn->link_proto);
  266. return;
  267. }
  268. break;
  269. default:
  270. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  271. "Received var-length cell with command %d in unexpected state "
  272. "%s [%d]; ignoring it.",
  273. (int)cell->command,
  274. conn_state_to_string(CONN_TYPE_OR,conn->_base.state),
  275. (int)conn->_base.state);
  276. return;
  277. }
  278. switch (cell->command) {
  279. case CELL_VERSIONS:
  280. ++stats_n_versions_cells_processed;
  281. PROCESS_CELL(versions, cell, conn);
  282. break;
  283. case CELL_VPADDING:
  284. ++stats_n_vpadding_cells_processed;
  285. /* Do nothing */
  286. break;
  287. case CELL_CERTS:
  288. ++stats_n_certs_cells_processed;
  289. PROCESS_CELL(certs, cell, conn);
  290. break;
  291. case CELL_AUTH_CHALLENGE:
  292. ++stats_n_auth_challenge_cells_processed;
  293. PROCESS_CELL(auth_challenge, cell, conn);
  294. break;
  295. case CELL_AUTHENTICATE:
  296. ++stats_n_authenticate_cells_processed;
  297. PROCESS_CELL(authenticate, cell, conn);
  298. break;
  299. case CELL_AUTHORIZE:
  300. ++stats_n_authorize_cells_processed;
  301. /* Ignored so far. */
  302. break;
  303. default:
  304. log_fn(LOG_INFO, LD_PROTOCOL,
  305. "Variable-length cell of unknown type (%d) received.",
  306. cell->command);
  307. break;
  308. }
  309. }
  310. /** Process a 'create' <b>cell</b> that just arrived from <b>conn</b>. Make a
  311. * new circuit with the p_circ_id specified in cell. Put the circuit in state
  312. * onionskin_pending, and pass the onionskin to the cpuworker. Circ will get
  313. * picked up again when the cpuworker finishes decrypting it.
  314. */
  315. static void
  316. command_process_create_cell(cell_t *cell, or_connection_t *conn)
  317. {
  318. or_circuit_t *circ;
  319. const or_options_t *options = get_options();
  320. int id_is_high;
  321. if (we_are_hibernating()) {
  322. log_info(LD_OR,
  323. "Received create cell but we're shutting down. Sending back "
  324. "destroy.");
  325. connection_or_send_destroy(cell->circ_id, conn,
  326. END_CIRC_REASON_HIBERNATING);
  327. return;
  328. }
  329. if (!server_mode(options) ||
  330. (!public_server_mode(options) && conn->is_outgoing)) {
  331. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  332. "Received create cell (type %d) from %s:%d, but we're connected "
  333. "to it as a client. "
  334. "Sending back a destroy.",
  335. (int)cell->command, conn->_base.address, conn->_base.port);
  336. connection_or_send_destroy(cell->circ_id, conn,
  337. END_CIRC_REASON_TORPROTOCOL);
  338. return;
  339. }
  340. /* If the high bit of the circuit ID is not as expected, close the
  341. * circ. */
  342. id_is_high = cell->circ_id & (1<<15);
  343. if ((id_is_high && conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ||
  344. (!id_is_high && conn->circ_id_type == CIRC_ID_TYPE_LOWER)) {
  345. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  346. "Received create cell with unexpected circ_id %d. Closing.",
  347. cell->circ_id);
  348. connection_or_send_destroy(cell->circ_id, conn,
  349. END_CIRC_REASON_TORPROTOCOL);
  350. return;
  351. }
  352. if (circuit_id_in_use_on_orconn(cell->circ_id, conn)) {
  353. const node_t *node = node_get_by_id(conn->identity_digest);
  354. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  355. "Received CREATE cell (circID %d) for known circ. "
  356. "Dropping (age %d).",
  357. cell->circ_id, (int)(time(NULL) - conn->_base.timestamp_created));
  358. if (node) {
  359. char *p = esc_for_log(node_get_platform(node));
  360. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  361. "Details: router %s, platform %s.",
  362. node_describe(node), p);
  363. tor_free(p);
  364. }
  365. return;
  366. }
  367. circ = or_circuit_new(cell->circ_id, conn);
  368. circ->_base.purpose = CIRCUIT_PURPOSE_OR;
  369. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_ONIONSKIN_PENDING);
  370. if (cell->command == CELL_CREATE) {
  371. char *onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
  372. memcpy(onionskin, cell->payload, ONIONSKIN_CHALLENGE_LEN);
  373. /* hand it off to the cpuworkers, and then return. */
  374. if (assign_onionskin_to_cpuworker(NULL, circ, onionskin) < 0) {
  375. #define WARN_HANDOFF_FAILURE_INTERVAL (6*60*60)
  376. static ratelim_t handoff_warning =
  377. RATELIM_INIT(WARN_HANDOFF_FAILURE_INTERVAL);
  378. char *m;
  379. if ((m = rate_limit_log(&handoff_warning, approx_time()))) {
  380. log_warn(LD_GENERAL,"Failed to hand off onionskin. Closing.%s",m);
  381. tor_free(m);
  382. }
  383. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  384. return;
  385. }
  386. log_debug(LD_OR,"success: handed off onionskin.");
  387. } else {
  388. /* This is a CREATE_FAST cell; we can handle it immediately without using
  389. * a CPU worker. */
  390. char keys[CPATH_KEY_MATERIAL_LEN];
  391. char reply[DIGEST_LEN*2];
  392. tor_assert(cell->command == CELL_CREATE_FAST);
  393. /* Make sure we never try to use the OR connection on which we
  394. * received this cell to satisfy an EXTEND request, */
  395. conn->is_connection_with_client = 1;
  396. if (fast_server_handshake(cell->payload, (uint8_t*)reply,
  397. (uint8_t*)keys, sizeof(keys))<0) {
  398. log_warn(LD_OR,"Failed to generate key material. Closing.");
  399. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  400. return;
  401. }
  402. if (onionskin_answer(circ, CELL_CREATED_FAST, reply, keys)<0) {
  403. log_warn(LD_OR,"Failed to reply to CREATE_FAST cell. Closing.");
  404. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  405. return;
  406. }
  407. }
  408. }
  409. /** Process a 'created' <b>cell</b> that just arrived from <b>conn</b>.
  410. * Find the circuit
  411. * that it's intended for. If we're not the origin of the circuit, package
  412. * the 'created' cell in an 'extended' relay cell and pass it back. If we
  413. * are the origin of the circuit, send it to circuit_finish_handshake() to
  414. * finish processing keys, and then call circuit_send_next_onion_skin() to
  415. * extend to the next hop in the circuit if necessary.
  416. */
  417. static void
  418. command_process_created_cell(cell_t *cell, or_connection_t *conn)
  419. {
  420. circuit_t *circ;
  421. circ = circuit_get_by_circid_orconn(cell->circ_id, conn);
  422. if (!circ) {
  423. log_info(LD_OR,
  424. "(circID %d) unknown circ (probably got a destroy earlier). "
  425. "Dropping.", cell->circ_id);
  426. return;
  427. }
  428. if (circ->n_circ_id != cell->circ_id) {
  429. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
  430. "got created cell from Tor client? Closing.");
  431. circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  432. return;
  433. }
  434. if (CIRCUIT_IS_ORIGIN(circ)) { /* we're the OP. Handshake this. */
  435. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  436. int err_reason = 0;
  437. log_debug(LD_OR,"at OP. Finishing handshake.");
  438. if ((err_reason = circuit_finish_handshake(origin_circ, cell->command,
  439. cell->payload)) < 0) {
  440. log_warn(LD_OR,"circuit_finish_handshake failed.");
  441. circuit_mark_for_close(circ, -err_reason);
  442. return;
  443. }
  444. log_debug(LD_OR,"Moving to next skin.");
  445. if ((err_reason = circuit_send_next_onion_skin(origin_circ)) < 0) {
  446. log_info(LD_OR,"circuit_send_next_onion_skin failed.");
  447. /* XXX push this circuit_close lower */
  448. circuit_mark_for_close(circ, -err_reason);
  449. return;
  450. }
  451. } else { /* pack it into an extended relay cell, and send it. */
  452. log_debug(LD_OR,
  453. "Converting created cell to extended relay cell, sending.");
  454. relay_send_command_from_edge(0, circ, RELAY_COMMAND_EXTENDED,
  455. (char*)cell->payload, ONIONSKIN_REPLY_LEN,
  456. NULL);
  457. }
  458. }
  459. /** Process a 'relay' or 'relay_early' <b>cell</b> that just arrived from
  460. * <b>conn</b>. Make sure it came in with a recognized circ_id. Pass it on to
  461. * circuit_receive_relay_cell() for actual processing.
  462. */
  463. static void
  464. command_process_relay_cell(cell_t *cell, or_connection_t *conn)
  465. {
  466. circuit_t *circ;
  467. int reason, direction;
  468. circ = circuit_get_by_circid_orconn(cell->circ_id, conn);
  469. if (!circ) {
  470. log_debug(LD_OR,
  471. "unknown circuit %d on connection from %s:%d. Dropping.",
  472. cell->circ_id, conn->_base.address, conn->_base.port);
  473. return;
  474. }
  475. if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
  476. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,"circuit in create_wait. Closing.");
  477. circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  478. return;
  479. }
  480. if (CIRCUIT_IS_ORIGIN(circ)) {
  481. /* if we're a relay and treating connections with recent local
  482. * traffic better, then this is one of them. */
  483. conn->client_used = time(NULL);
  484. }
  485. if (!CIRCUIT_IS_ORIGIN(circ) &&
  486. cell->circ_id == TO_OR_CIRCUIT(circ)->p_circ_id)
  487. direction = CELL_DIRECTION_OUT;
  488. else
  489. direction = CELL_DIRECTION_IN;
  490. /* If we have a relay_early cell, make sure that it's outbound, and we've
  491. * gotten no more than MAX_RELAY_EARLY_CELLS_PER_CIRCUIT of them. */
  492. if (cell->command == CELL_RELAY_EARLY) {
  493. if (direction == CELL_DIRECTION_IN) {
  494. /* Allow an unlimited number of inbound relay_early cells,
  495. * for hidden service compatibility. There isn't any way to make
  496. * a long circuit through inbound relay_early cells anyway. See
  497. * bug 1038. -RD */
  498. } else {
  499. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  500. if (or_circ->remaining_relay_early_cells == 0) {
  501. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  502. "Received too many RELAY_EARLY cells on circ %d from %s:%d."
  503. " Closing circuit.",
  504. cell->circ_id, safe_str(conn->_base.address),
  505. conn->_base.port);
  506. circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  507. return;
  508. }
  509. --or_circ->remaining_relay_early_cells;
  510. }
  511. }
  512. if ((reason = circuit_receive_relay_cell(cell, circ, direction)) < 0) {
  513. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,"circuit_receive_relay_cell "
  514. "(%s) failed. Closing.",
  515. direction==CELL_DIRECTION_OUT?"forward":"backward");
  516. circuit_mark_for_close(circ, -reason);
  517. }
  518. }
  519. /** Process a 'destroy' <b>cell</b> that just arrived from
  520. * <b>conn</b>. Find the circ that it refers to (if any).
  521. *
  522. * If the circ is in state
  523. * onionskin_pending, then call onion_pending_remove() to remove it
  524. * from the pending onion list (note that if it's already being
  525. * processed by the cpuworker, it won't be in the list anymore; but
  526. * when the cpuworker returns it, the circuit will be gone, and the
  527. * cpuworker response will be dropped).
  528. *
  529. * Then mark the circuit for close (which marks all edges for close,
  530. * and passes the destroy cell onward if necessary).
  531. */
  532. static void
  533. command_process_destroy_cell(cell_t *cell, or_connection_t *conn)
  534. {
  535. circuit_t *circ;
  536. int reason;
  537. circ = circuit_get_by_circid_orconn(cell->circ_id, conn);
  538. if (!circ) {
  539. log_info(LD_OR,"unknown circuit %d on connection from %s:%d. Dropping.",
  540. cell->circ_id, conn->_base.address, conn->_base.port);
  541. return;
  542. }
  543. log_debug(LD_OR,"Received for circID %d.",cell->circ_id);
  544. reason = (uint8_t)cell->payload[0];
  545. if (!CIRCUIT_IS_ORIGIN(circ) &&
  546. cell->circ_id == TO_OR_CIRCUIT(circ)->p_circ_id) {
  547. /* the destroy came from behind */
  548. circuit_set_p_circid_orconn(TO_OR_CIRCUIT(circ), 0, NULL);
  549. circuit_mark_for_close(circ, reason|END_CIRC_REASON_FLAG_REMOTE);
  550. } else { /* the destroy came from ahead */
  551. circuit_set_n_circid_orconn(circ, 0, NULL);
  552. if (CIRCUIT_IS_ORIGIN(circ)) {
  553. circuit_mark_for_close(circ, reason|END_CIRC_REASON_FLAG_REMOTE);
  554. } else {
  555. char payload[1];
  556. log_debug(LD_OR, "Delivering 'truncated' back.");
  557. payload[0] = (char)reason;
  558. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  559. payload, sizeof(payload), NULL);
  560. }
  561. }
  562. }
  563. /** Called when we as a server receive an appropriate cell while waiting
  564. * either for a cell or a TLS handshake. Set the connection's state to
  565. * "handshaking_v3', initializes the or_handshake_state field as needed,
  566. * and add the cell to the hash of incoming cells.)
  567. *
  568. * Return 0 on success; return -1 and mark the connection on failure.
  569. */
  570. static int
  571. enter_v3_handshake_with_cell(var_cell_t *cell, or_connection_t *conn)
  572. {
  573. const int started_here = connection_or_nonopen_was_started_here(conn);
  574. tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING ||
  575. conn->_base.state == OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
  576. if (started_here) {
  577. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  578. "Received a cell while TLS-handshaking, not in "
  579. "OR_HANDSHAKING_V3, on a connection we originated.");
  580. }
  581. conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
  582. if (connection_init_or_handshake_state(conn, started_here) < 0) {
  583. connection_mark_for_close(TO_CONN(conn));
  584. return -1;
  585. }
  586. or_handshake_state_record_var_cell(conn->handshake_state, cell, 1);
  587. return 0;
  588. }
  589. /** Process a 'versions' cell. The current link protocol version must be 0
  590. * to indicate that no version has yet been negotiated. We compare the
  591. * versions in the cell to the list of versions we support, pick the
  592. * highest version we have in common, and continue the negotiation from
  593. * there.
  594. */
  595. static void
  596. command_process_versions_cell(var_cell_t *cell, or_connection_t *conn)
  597. {
  598. int highest_supported_version = 0;
  599. const uint8_t *cp, *end;
  600. const int started_here = connection_or_nonopen_was_started_here(conn);
  601. if (conn->link_proto != 0 ||
  602. (conn->handshake_state && conn->handshake_state->received_versions)) {
  603. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  604. "Received a VERSIONS cell on a connection with its version "
  605. "already set to %d; dropping", (int) conn->link_proto);
  606. return;
  607. }
  608. switch (conn->_base.state)
  609. {
  610. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  611. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  612. break;
  613. case OR_CONN_STATE_TLS_HANDSHAKING:
  614. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  615. default:
  616. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  617. "VERSIONS cell while in unexpected state");
  618. return;
  619. }
  620. tor_assert(conn->handshake_state);
  621. end = cell->payload + cell->payload_len;
  622. for (cp = cell->payload; cp+1 < end; ++cp) {
  623. uint16_t v = ntohs(get_uint16(cp));
  624. if (is_or_protocol_version_known(v) && v > highest_supported_version)
  625. highest_supported_version = v;
  626. }
  627. if (!highest_supported_version) {
  628. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  629. "Couldn't find a version in common between my version list and the "
  630. "list in the VERSIONS cell; closing connection.");
  631. connection_mark_for_close(TO_CONN(conn));
  632. return;
  633. } else if (highest_supported_version == 1) {
  634. /* Negotiating version 1 makes no sense, since version 1 has no VERSIONS
  635. * cells. */
  636. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  637. "Used version negotiation protocol to negotiate a v1 connection. "
  638. "That's crazily non-compliant. Closing connection.");
  639. connection_mark_for_close(TO_CONN(conn));
  640. return;
  641. } else if (highest_supported_version < 3 &&
  642. conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
  643. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  644. "Negotiated link protocol 2 or lower after doing a v3 TLS "
  645. "handshake. Closing connection.");
  646. connection_mark_for_close(TO_CONN(conn));
  647. return;
  648. }
  649. conn->link_proto = highest_supported_version;
  650. conn->handshake_state->received_versions = 1;
  651. if (conn->link_proto == 2) {
  652. log_info(LD_OR, "Negotiated version %d with %s:%d; sending NETINFO.",
  653. highest_supported_version,
  654. safe_str_client(conn->_base.address),
  655. conn->_base.port);
  656. if (connection_or_send_netinfo(conn) < 0) {
  657. connection_mark_for_close(TO_CONN(conn));
  658. return;
  659. }
  660. } else {
  661. const int send_versions = !started_here;
  662. /* If we want to authenticate, send a CERTS cell */
  663. const int send_certs = !started_here || public_server_mode(get_options());
  664. /* If we're a relay that got a connection, ask for authentication. */
  665. const int send_chall = !started_here && public_server_mode(get_options());
  666. /* If our certs cell will authenticate us, we can send a netinfo cell
  667. * right now. */
  668. const int send_netinfo = !started_here;
  669. const int send_any =
  670. send_versions || send_certs || send_chall || send_netinfo;
  671. tor_assert(conn->link_proto >= 3);
  672. log_info(LD_OR, "Negotiated version %d with %s:%d; %s%s%s%s%s",
  673. highest_supported_version,
  674. safe_str_client(conn->_base.address),
  675. conn->_base.port,
  676. send_any ? "Sending cells:" : "Waiting for CERTS cell",
  677. send_versions ? " VERSIONS" : "",
  678. send_certs ? " CERTS" : "",
  679. send_chall ? " AUTH_CHALLENGE" : "",
  680. send_netinfo ? " NETINFO" : "");
  681. #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
  682. if (1) {
  683. connection_mark_for_close(TO_CONN(conn));
  684. return;
  685. }
  686. #endif
  687. if (send_versions) {
  688. if (connection_or_send_versions(conn, 1) < 0) {
  689. log_warn(LD_OR, "Couldn't send versions cell");
  690. connection_mark_for_close(TO_CONN(conn));
  691. return;
  692. }
  693. }
  694. if (send_certs) {
  695. if (connection_or_send_certs_cell(conn) < 0) {
  696. log_warn(LD_OR, "Couldn't send certs cell");
  697. connection_mark_for_close(TO_CONN(conn));
  698. return;
  699. }
  700. }
  701. if (send_chall) {
  702. if (connection_or_send_auth_challenge_cell(conn) < 0) {
  703. log_warn(LD_OR, "Couldn't send auth_challenge cell");
  704. connection_mark_for_close(TO_CONN(conn));
  705. return;
  706. }
  707. }
  708. if (send_netinfo) {
  709. if (connection_or_send_netinfo(conn) < 0) {
  710. log_warn(LD_OR, "Couldn't send netinfo cell");
  711. connection_mark_for_close(TO_CONN(conn));
  712. return;
  713. }
  714. }
  715. }
  716. }
  717. /** Process a 'netinfo' cell: read and act on its contents, and set the
  718. * connection state to "open". */
  719. static void
  720. command_process_netinfo_cell(cell_t *cell, or_connection_t *conn)
  721. {
  722. time_t timestamp;
  723. uint8_t my_addr_type;
  724. uint8_t my_addr_len;
  725. const uint8_t *my_addr_ptr;
  726. const uint8_t *cp, *end;
  727. uint8_t n_other_addrs;
  728. time_t now = time(NULL);
  729. long apparent_skew = 0;
  730. uint32_t my_apparent_addr = 0;
  731. if (conn->link_proto < 2) {
  732. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  733. "Received a NETINFO cell on %s connection; dropping.",
  734. conn->link_proto == 0 ? "non-versioned" : "a v1");
  735. return;
  736. }
  737. if (conn->_base.state != OR_CONN_STATE_OR_HANDSHAKING_V2 &&
  738. conn->_base.state != OR_CONN_STATE_OR_HANDSHAKING_V3) {
  739. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  740. "Received a NETINFO cell on non-handshaking connection; dropping.");
  741. return;
  742. }
  743. tor_assert(conn->handshake_state &&
  744. conn->handshake_state->received_versions);
  745. if (conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
  746. tor_assert(conn->link_proto >= 3);
  747. if (conn->handshake_state->started_here) {
  748. if (!conn->handshake_state->authenticated) {
  749. log_fn(LOG_PROTOCOL_WARN, LD_OR, "Got a NETINFO cell from server, "
  750. "but no authentication. Closing the connection.");
  751. connection_mark_for_close(TO_CONN(conn));
  752. return;
  753. }
  754. } else {
  755. /* we're the server. If the client never authenticated, we have
  756. some housekeeping to do.*/
  757. if (!conn->handshake_state->authenticated) {
  758. tor_assert(tor_digest_is_zero(
  759. (const char*)conn->handshake_state->authenticated_peer_id));
  760. connection_or_set_circid_type(conn, NULL);
  761. connection_or_init_conn_from_address(conn,
  762. &conn->_base.addr,
  763. conn->_base.port,
  764. (const char*)conn->handshake_state->authenticated_peer_id,
  765. 0);
  766. }
  767. }
  768. }
  769. /* Decode the cell. */
  770. timestamp = ntohl(get_uint32(cell->payload));
  771. if (labs(now - conn->handshake_state->sent_versions_at) < 180) {
  772. apparent_skew = now - timestamp;
  773. }
  774. my_addr_type = (uint8_t) cell->payload[4];
  775. my_addr_len = (uint8_t) cell->payload[5];
  776. my_addr_ptr = (uint8_t*) cell->payload + 6;
  777. end = cell->payload + CELL_PAYLOAD_SIZE;
  778. cp = cell->payload + 6 + my_addr_len;
  779. if (cp >= end) {
  780. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  781. "Addresses too long in netinfo cell; closing connection.");
  782. connection_mark_for_close(TO_CONN(conn));
  783. return;
  784. } else if (my_addr_type == RESOLVED_TYPE_IPV4 && my_addr_len == 4) {
  785. my_apparent_addr = ntohl(get_uint32(my_addr_ptr));
  786. }
  787. n_other_addrs = (uint8_t) *cp++;
  788. while (n_other_addrs && cp < end-2) {
  789. /* Consider all the other addresses; if any matches, this connection is
  790. * "canonical." */
  791. tor_addr_t addr;
  792. const uint8_t *next =
  793. decode_address_from_payload(&addr, cp, (int)(end-cp));
  794. if (next == NULL) {
  795. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  796. "Bad address in netinfo cell; closing connection.");
  797. connection_mark_for_close(TO_CONN(conn));
  798. return;
  799. }
  800. if (tor_addr_eq(&addr, &conn->real_addr)) {
  801. conn->is_canonical = 1;
  802. break;
  803. }
  804. cp = next;
  805. --n_other_addrs;
  806. }
  807. /* Act on apparent skew. */
  808. /** Warn when we get a netinfo skew with at least this value. */
  809. #define NETINFO_NOTICE_SKEW 3600
  810. if (labs(apparent_skew) > NETINFO_NOTICE_SKEW &&
  811. router_get_by_id_digest(conn->identity_digest)) {
  812. char dbuf[64];
  813. int severity;
  814. /*XXXX be smarter about when everybody says we are skewed. */
  815. if (router_digest_is_trusted_dir(conn->identity_digest))
  816. severity = LOG_WARN;
  817. else
  818. severity = LOG_INFO;
  819. format_time_interval(dbuf, sizeof(dbuf), apparent_skew);
  820. log_fn(severity, LD_GENERAL, "Received NETINFO cell with skewed time from "
  821. "server at %s:%d. It seems that our clock is %s by %s, or "
  822. "that theirs is %s. Tor requires an accurate clock to work: "
  823. "please check your time and date settings.",
  824. conn->_base.address, (int)conn->_base.port,
  825. apparent_skew>0 ? "ahead" : "behind", dbuf,
  826. apparent_skew>0 ? "behind" : "ahead");
  827. if (severity == LOG_WARN) /* only tell the controller if an authority */
  828. control_event_general_status(LOG_WARN,
  829. "CLOCK_SKEW SKEW=%ld SOURCE=OR:%s:%d",
  830. apparent_skew,
  831. conn->_base.address, conn->_base.port);
  832. }
  833. /* XXX maybe act on my_apparent_addr, if the source is sufficiently
  834. * trustworthy. */
  835. (void)my_apparent_addr;
  836. if (connection_or_set_state_open(conn)<0) {
  837. log_fn(LOG_PROTOCOL_WARN, LD_OR, "Got good NETINFO cell from %s:%d; but "
  838. "was unable to make the OR connection become open.",
  839. safe_str_client(conn->_base.address),
  840. conn->_base.port);
  841. connection_mark_for_close(TO_CONN(conn));
  842. } else {
  843. log_info(LD_OR, "Got good NETINFO cell from %s:%d; OR connection is now "
  844. "open, using protocol version %d. Its ID digest is %s",
  845. safe_str_client(conn->_base.address),
  846. conn->_base.port, (int)conn->link_proto,
  847. hex_str(conn->identity_digest, DIGEST_LEN));
  848. }
  849. assert_connection_ok(TO_CONN(conn),time(NULL));
  850. }
  851. /** Process a CERTS cell from an OR connection.
  852. *
  853. * If the other side should not have sent us a CERTS cell, or the cell is
  854. * malformed, or it is supposed to authenticate the TLS key but it doesn't,
  855. * then mark the connection.
  856. *
  857. * If the cell has a good cert chain and we're doing a v3 handshake, then
  858. * store the certificates in or_handshake_state. If this is the client side
  859. * of the connection, we then authenticate the server or mark the connection.
  860. * If it's the server side, wait for an AUTHENTICATE cell.
  861. */
  862. static void
  863. command_process_certs_cell(var_cell_t *cell, or_connection_t *conn)
  864. {
  865. #define ERR(s) \
  866. do { \
  867. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
  868. "Received a bad CERTS cell from %s:%d: %s", \
  869. safe_str(conn->_base.address), conn->_base.port, (s)); \
  870. connection_mark_for_close(TO_CONN(conn)); \
  871. goto err; \
  872. } while (0)
  873. tor_cert_t *link_cert = NULL;
  874. tor_cert_t *id_cert = NULL;
  875. tor_cert_t *auth_cert = NULL;
  876. uint8_t *ptr;
  877. int n_certs, i;
  878. int send_netinfo = 0;
  879. if (conn->_base.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
  880. ERR("We're not doing a v3 handshake!");
  881. if (conn->link_proto < 3)
  882. ERR("We're not using link protocol >= 3");
  883. if (conn->handshake_state->received_certs_cell)
  884. ERR("We already got one");
  885. if (conn->handshake_state->authenticated) {
  886. /* Should be unreachable, but let's make sure. */
  887. ERR("We're already authenticated!");
  888. }
  889. if (cell->payload_len < 1)
  890. ERR("It had no body");
  891. if (cell->circ_id)
  892. ERR("It had a nonzero circuit ID");
  893. n_certs = cell->payload[0];
  894. ptr = cell->payload + 1;
  895. for (i = 0; i < n_certs; ++i) {
  896. uint8_t cert_type;
  897. uint16_t cert_len;
  898. if (ptr + 3 > cell->payload + cell->payload_len) {
  899. goto truncated;
  900. }
  901. cert_type = *ptr;
  902. cert_len = ntohs(get_uint16(ptr+1));
  903. if (ptr + 3 + cert_len > cell->payload + cell->payload_len) {
  904. goto truncated;
  905. }
  906. if (cert_type == OR_CERT_TYPE_TLS_LINK ||
  907. cert_type == OR_CERT_TYPE_ID_1024 ||
  908. cert_type == OR_CERT_TYPE_AUTH_1024) {
  909. tor_cert_t *cert = tor_cert_decode(ptr + 3, cert_len);
  910. if (!cert) {
  911. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  912. "Received undecodable certificate in CERTS cell from %s:%d",
  913. safe_str(conn->_base.address), conn->_base.port);
  914. } else {
  915. if (cert_type == OR_CERT_TYPE_TLS_LINK) {
  916. if (link_cert) {
  917. tor_cert_free(cert);
  918. ERR("Too many TLS_LINK certificates");
  919. }
  920. link_cert = cert;
  921. } else if (cert_type == OR_CERT_TYPE_ID_1024) {
  922. if (id_cert) {
  923. tor_cert_free(cert);
  924. ERR("Too many ID_1024 certificates");
  925. }
  926. id_cert = cert;
  927. } else if (cert_type == OR_CERT_TYPE_AUTH_1024) {
  928. if (auth_cert) {
  929. tor_cert_free(cert);
  930. ERR("Too many AUTH_1024 certificates");
  931. }
  932. auth_cert = cert;
  933. } else {
  934. tor_cert_free(cert);
  935. }
  936. }
  937. }
  938. ptr += 3 + cert_len;
  939. continue;
  940. truncated:
  941. ERR("It ends in the middle of a certificate");
  942. }
  943. if (conn->handshake_state->started_here) {
  944. int severity;
  945. if (! (id_cert && link_cert))
  946. ERR("The certs we wanted were missing");
  947. /* Okay. We should be able to check the certificates now. */
  948. if (! tor_tls_cert_matches_key(conn->tls, link_cert)) {
  949. ERR("The link certificate didn't match the TLS public key");
  950. }
  951. /* Note that this warns more loudly about time and validity if we were
  952. * _trying_ to connect to an authority, not necessarily if we _did_ connect
  953. * to one. */
  954. if (router_digest_is_trusted_dir(conn->identity_digest))
  955. severity = LOG_WARN;
  956. else
  957. severity = LOG_PROTOCOL_WARN;
  958. if (! tor_tls_cert_is_valid(severity, link_cert, id_cert, 0))
  959. ERR("The link certificate was not valid");
  960. if (! tor_tls_cert_is_valid(severity, id_cert, id_cert, 1))
  961. ERR("The ID certificate was not valid");
  962. conn->handshake_state->authenticated = 1;
  963. {
  964. const digests_t *id_digests = tor_cert_get_id_digests(id_cert);
  965. crypto_pk_t *identity_rcvd;
  966. if (!id_digests)
  967. ERR("Couldn't compute digests for key in ID cert");
  968. identity_rcvd = tor_tls_cert_get_key(id_cert);
  969. if (!identity_rcvd)
  970. ERR("Internal error: Couldn't get RSA key from ID cert.");
  971. memcpy(conn->handshake_state->authenticated_peer_id,
  972. id_digests->d[DIGEST_SHA1], DIGEST_LEN);
  973. connection_or_set_circid_type(conn, identity_rcvd);
  974. crypto_pk_free(identity_rcvd);
  975. }
  976. if (connection_or_client_learned_peer_id(conn,
  977. conn->handshake_state->authenticated_peer_id) < 0)
  978. ERR("Problem setting or checking peer id");
  979. log_info(LD_OR, "Got some good certificates from %s:%d: Authenticated it.",
  980. safe_str(conn->_base.address), conn->_base.port);
  981. conn->handshake_state->id_cert = id_cert;
  982. id_cert = NULL;
  983. if (!public_server_mode(get_options())) {
  984. /* If we initiated the connection and we are not a public server, we
  985. * aren't planning to authenticate at all. At this point we know who we
  986. * are talking to, so we can just send a netinfo now. */
  987. send_netinfo = 1;
  988. }
  989. } else {
  990. if (! (id_cert && auth_cert))
  991. ERR("The certs we wanted were missing");
  992. /* Remember these certificates so we can check an AUTHENTICATE cell */
  993. if (! tor_tls_cert_is_valid(LOG_PROTOCOL_WARN, auth_cert, id_cert, 1))
  994. ERR("The authentication certificate was not valid");
  995. if (! tor_tls_cert_is_valid(LOG_PROTOCOL_WARN, id_cert, id_cert, 1))
  996. ERR("The ID certificate was not valid");
  997. log_info(LD_OR, "Got some good certificates from %s:%d: "
  998. "Waiting for AUTHENTICATE.",
  999. safe_str(conn->_base.address), conn->_base.port);
  1000. /* XXXX check more stuff? */
  1001. conn->handshake_state->id_cert = id_cert;
  1002. conn->handshake_state->auth_cert = auth_cert;
  1003. id_cert = auth_cert = NULL;
  1004. }
  1005. conn->handshake_state->received_certs_cell = 1;
  1006. if (send_netinfo) {
  1007. if (connection_or_send_netinfo(conn) < 0) {
  1008. log_warn(LD_OR, "Couldn't send netinfo cell");
  1009. connection_mark_for_close(TO_CONN(conn));
  1010. goto err;
  1011. }
  1012. }
  1013. err:
  1014. tor_cert_free(id_cert);
  1015. tor_cert_free(link_cert);
  1016. tor_cert_free(auth_cert);
  1017. #undef ERR
  1018. }
  1019. /** Process an AUTH_CHALLENGE cell from an OR connection.
  1020. *
  1021. * If we weren't supposed to get one (for example, because we're not the
  1022. * originator of the connection), or it's ill-formed, or we aren't doing a v3
  1023. * handshake, mark the connection. If the cell is well-formed but we don't
  1024. * want to authenticate, just drop it. If the cell is well-formed *and* we
  1025. * want to authenticate, send an AUTHENTICATE cell and then a NETINFO cell. */
  1026. static void
  1027. command_process_auth_challenge_cell(var_cell_t *cell, or_connection_t *conn)
  1028. {
  1029. int n_types, i, use_type = -1;
  1030. uint8_t *cp;
  1031. #define ERR(s) \
  1032. do { \
  1033. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
  1034. "Received a bad AUTH_CHALLENGE cell from %s:%d: %s", \
  1035. safe_str(conn->_base.address), conn->_base.port, (s)); \
  1036. connection_mark_for_close(TO_CONN(conn)); \
  1037. return; \
  1038. } while (0)
  1039. if (conn->_base.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
  1040. ERR("We're not currently doing a v3 handshake");
  1041. if (conn->link_proto < 3)
  1042. ERR("We're not using link protocol >= 3");
  1043. if (! conn->handshake_state->started_here)
  1044. ERR("We didn't originate this connection");
  1045. if (conn->handshake_state->received_auth_challenge)
  1046. ERR("We already received one");
  1047. if (! conn->handshake_state->received_certs_cell)
  1048. ERR("We haven't gotten a CERTS cell yet");
  1049. if (cell->payload_len < OR_AUTH_CHALLENGE_LEN + 2)
  1050. ERR("It was too short");
  1051. if (cell->circ_id)
  1052. ERR("It had a nonzero circuit ID");
  1053. n_types = ntohs(get_uint16(cell->payload + OR_AUTH_CHALLENGE_LEN));
  1054. if (cell->payload_len < OR_AUTH_CHALLENGE_LEN + 2 + 2*n_types)
  1055. ERR("It looks truncated");
  1056. /* Now see if there is an authentication type we can use */
  1057. cp=cell->payload+OR_AUTH_CHALLENGE_LEN+2;
  1058. for (i=0; i < n_types; ++i, cp += 2) {
  1059. uint16_t authtype = ntohs(get_uint16(cp));
  1060. if (authtype == AUTHTYPE_RSA_SHA256_TLSSECRET)
  1061. use_type = authtype;
  1062. }
  1063. conn->handshake_state->received_auth_challenge = 1;
  1064. if (! public_server_mode(get_options())) {
  1065. /* If we're not a public server then we don't want to authenticate on a
  1066. connection we originated, and we already sent a NETINFO cell when we
  1067. got the CERTS cell. We have nothing more to do. */
  1068. return;
  1069. }
  1070. if (use_type >= 0) {
  1071. log_info(LD_OR, "Got an AUTH_CHALLENGE cell from %s:%d: Sending "
  1072. "authentication",
  1073. safe_str(conn->_base.address), conn->_base.port);
  1074. if (connection_or_send_authenticate_cell(conn, use_type) < 0) {
  1075. log_warn(LD_OR, "Couldn't send authenticate cell");
  1076. connection_mark_for_close(TO_CONN(conn));
  1077. return;
  1078. }
  1079. } else {
  1080. log_info(LD_OR, "Got an AUTH_CHALLENGE cell from %s:%d, but we don't "
  1081. "know any of its authentication types. Not authenticating.",
  1082. safe_str(conn->_base.address), conn->_base.port);
  1083. }
  1084. if (connection_or_send_netinfo(conn) < 0) {
  1085. log_warn(LD_OR, "Couldn't send netinfo cell");
  1086. connection_mark_for_close(TO_CONN(conn));
  1087. return;
  1088. }
  1089. #undef ERR
  1090. }
  1091. /** Process an AUTHENTICATE cell from an OR connection.
  1092. *
  1093. * If it's ill-formed or we weren't supposed to get one or we're not doing a
  1094. * v3 handshake, then mark the connection. If it does not authenticate the
  1095. * other side of the connection successfully (because it isn't signed right,
  1096. * we didn't get a CERTS cell, etc) mark the connection. Otherwise, accept
  1097. * the identity of the router on the other side of the connection.
  1098. */
  1099. static void
  1100. command_process_authenticate_cell(var_cell_t *cell, or_connection_t *conn)
  1101. {
  1102. uint8_t expected[V3_AUTH_FIXED_PART_LEN];
  1103. const uint8_t *auth;
  1104. int authlen;
  1105. #define ERR(s) \
  1106. do { \
  1107. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
  1108. "Received a bad AUTHENTICATE cell from %s:%d: %s", \
  1109. safe_str(conn->_base.address), conn->_base.port, (s)); \
  1110. connection_mark_for_close(TO_CONN(conn)); \
  1111. return; \
  1112. } while (0)
  1113. if (conn->_base.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
  1114. ERR("We're not doing a v3 handshake");
  1115. if (conn->link_proto < 3)
  1116. ERR("We're not using link protocol >= 3");
  1117. if (conn->handshake_state->started_here)
  1118. ERR("We originated this connection");
  1119. if (conn->handshake_state->received_authenticate)
  1120. ERR("We already got one!");
  1121. if (conn->handshake_state->authenticated) {
  1122. /* Should be impossible given other checks */
  1123. ERR("The peer is already authenticated");
  1124. }
  1125. if (! conn->handshake_state->received_certs_cell)
  1126. ERR("We never got a certs cell");
  1127. if (conn->handshake_state->auth_cert == NULL)
  1128. ERR("We never got an authentication certificate");
  1129. if (conn->handshake_state->id_cert == NULL)
  1130. ERR("We never got an identity certificate");
  1131. if (cell->payload_len < 4)
  1132. ERR("Cell was way too short");
  1133. auth = cell->payload;
  1134. {
  1135. uint16_t type = ntohs(get_uint16(auth));
  1136. uint16_t len = ntohs(get_uint16(auth+2));
  1137. if (4 + len > cell->payload_len)
  1138. ERR("Authenticator was truncated");
  1139. if (type != AUTHTYPE_RSA_SHA256_TLSSECRET)
  1140. ERR("Authenticator type was not recognized");
  1141. auth += 4;
  1142. authlen = len;
  1143. }
  1144. if (authlen < V3_AUTH_BODY_LEN + 1)
  1145. ERR("Authenticator was too short");
  1146. if (connection_or_compute_authenticate_cell_body(
  1147. conn, expected, sizeof(expected), NULL, 1) < 0)
  1148. ERR("Couldn't compute expected AUTHENTICATE cell body");
  1149. if (tor_memneq(expected, auth, sizeof(expected)))
  1150. ERR("Some field in the AUTHENTICATE cell body was not as expected");
  1151. {
  1152. crypto_pk_t *pk = tor_tls_cert_get_key(
  1153. conn->handshake_state->auth_cert);
  1154. char d[DIGEST256_LEN];
  1155. char *signed_data;
  1156. size_t keysize;
  1157. int signed_len;
  1158. if (!pk)
  1159. ERR("Internal error: couldn't get RSA key from AUTH cert.");
  1160. crypto_digest256(d, (char*)auth, V3_AUTH_BODY_LEN, DIGEST_SHA256);
  1161. keysize = crypto_pk_keysize(pk);
  1162. signed_data = tor_malloc(keysize);
  1163. signed_len = crypto_pk_public_checksig(pk, signed_data, keysize,
  1164. (char*)auth + V3_AUTH_BODY_LEN,
  1165. authlen - V3_AUTH_BODY_LEN);
  1166. crypto_pk_free(pk);
  1167. if (signed_len < 0) {
  1168. tor_free(signed_data);
  1169. ERR("Signature wasn't valid");
  1170. }
  1171. if (signed_len < DIGEST256_LEN) {
  1172. tor_free(signed_data);
  1173. ERR("Not enough data was signed");
  1174. }
  1175. /* Note that we deliberately allow *more* than DIGEST256_LEN bytes here,
  1176. * in case they're later used to hold a SHA3 digest or something. */
  1177. if (tor_memneq(signed_data, d, DIGEST256_LEN)) {
  1178. tor_free(signed_data);
  1179. ERR("Signature did not match data to be signed.");
  1180. }
  1181. tor_free(signed_data);
  1182. }
  1183. /* Okay, we are authenticated. */
  1184. conn->handshake_state->received_authenticate = 1;
  1185. conn->handshake_state->authenticated = 1;
  1186. conn->handshake_state->digest_received_data = 0;
  1187. {
  1188. crypto_pk_t *identity_rcvd =
  1189. tor_tls_cert_get_key(conn->handshake_state->id_cert);
  1190. const digests_t *id_digests =
  1191. tor_cert_get_id_digests(conn->handshake_state->id_cert);
  1192. /* This must exist; we checked key type when reading the cert. */
  1193. tor_assert(id_digests);
  1194. memcpy(conn->handshake_state->authenticated_peer_id,
  1195. id_digests->d[DIGEST_SHA1], DIGEST_LEN);
  1196. connection_or_set_circid_type(conn, identity_rcvd);
  1197. crypto_pk_free(identity_rcvd);
  1198. connection_or_init_conn_from_address(conn,
  1199. &conn->_base.addr,
  1200. conn->_base.port,
  1201. (const char*)conn->handshake_state->authenticated_peer_id,
  1202. 0);
  1203. log_info(LD_OR, "Got an AUTHENTICATE cell from %s:%d: Looks good.",
  1204. safe_str(conn->_base.address), conn->_base.port);
  1205. }
  1206. #undef ERR
  1207. }