command.c 48 KB

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