command.c 45 KB

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