command.c 47 KB

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