command.c 45 KB

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