connection_or.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char connection_or_c_id[] = "$Id$";
  7. /**
  8. * \file connection_or.c
  9. * \brief Functions to handle OR connections, TLS handshaking, and
  10. * cells on the network.
  11. **/
  12. #include "or.h"
  13. /** How much clock skew do we tolerate when checking certificates for
  14. * known routers? (sec) */
  15. #define TIGHT_CERT_ALLOW_SKEW (90*60)
  16. static int connection_tls_finish_handshake(connection_t *conn);
  17. static int connection_or_process_cells_from_inbuf(connection_t *conn);
  18. /**************************************************************/
  19. /** Pack the cell_t host-order structure <b>src</b> into network-order
  20. * in the buffer <b>dest</b>. See tor-spec.txt for details about the
  21. * wire format.
  22. */
  23. static void cell_pack(char *dest, const cell_t *src) {
  24. *(uint16_t*)dest = htons(src->circ_id);
  25. *(uint8_t*)(dest+2) = src->command;
  26. memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
  27. }
  28. /** Unpack the network-order buffer <b>src</b> into a host-order
  29. * cell_t structure <b>dest</b>.
  30. */
  31. static void cell_unpack(cell_t *dest, const char *src) {
  32. dest->circ_id = ntohs(*(uint16_t*)(src));
  33. dest->command = *(uint8_t*)(src+2);
  34. memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
  35. }
  36. int connection_or_reached_eof(connection_t *conn) {
  37. log_fn(LOG_INFO,"OR connection reached EOF. Closing.");
  38. connection_mark_for_close(conn);
  39. return 0;
  40. }
  41. /** Handle any new bytes that have come in on connection <b>conn</b>.
  42. * If conn is in 'open' state, hand it to
  43. * connection_or_process_cells_from_inbuf()
  44. * (else do nothing).
  45. */
  46. int connection_or_process_inbuf(connection_t *conn) {
  47. tor_assert(conn);
  48. tor_assert(conn->type == CONN_TYPE_OR);
  49. if (conn->state != OR_CONN_STATE_OPEN)
  50. return 0; /* don't do anything */
  51. return connection_or_process_cells_from_inbuf(conn);
  52. }
  53. /** Connection <b>conn</b> has finished writing and has no bytes left on
  54. * its outbuf.
  55. *
  56. * Otherwise it's in state "open": stop writing and return.
  57. *
  58. * If <b>conn</b> is broken, mark it for close and return -1, else
  59. * return 0.
  60. */
  61. int connection_or_finished_flushing(connection_t *conn) {
  62. tor_assert(conn);
  63. tor_assert(conn->type == CONN_TYPE_OR);
  64. assert_connection_ok(conn,0);
  65. if (conn->state != OR_CONN_STATE_OPEN) {
  66. log_fn(LOG_WARN,"BUG: called in unexpected state %d",conn->state);
  67. return -1;
  68. }
  69. connection_stop_writing(conn);
  70. return 0;
  71. }
  72. /** Connected handler for OR connections: begin the TLS handshake.
  73. */
  74. int connection_or_finished_connecting(connection_t *conn)
  75. {
  76. tor_assert(conn);
  77. tor_assert(conn->type == CONN_TYPE_OR);
  78. tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
  79. log_fn(LOG_INFO,"OR connect() to router at %s:%u finished.",
  80. conn->address,conn->port);
  81. if (connection_tls_start_handshake(conn, 0) < 0) {
  82. /* TLS handshaking error of some kind. */
  83. connection_mark_for_close(conn);
  84. return -1;
  85. }
  86. return 0;
  87. }
  88. /** Initialize <b>conn</b> to include all the relevant data from <b>router</b>.
  89. * This function is called either from connection_or_connect(), if
  90. * we initiated the connect, or from connection_tls_finish_handshake()
  91. * if the other side initiated it.
  92. */
  93. static void
  94. connection_or_init_conn_from_router(connection_t *conn, routerinfo_t *router) {
  95. conn->addr = router->addr;
  96. conn->port = router->or_port;
  97. conn->receiver_bucket = conn->bandwidth = router->bandwidthburst;
  98. conn->identity_pkey = crypto_pk_dup_key(router->identity_pkey);
  99. crypto_pk_get_digest(conn->identity_pkey, conn->identity_digest);
  100. conn->nickname = tor_strdup(router->nickname);
  101. tor_free(conn->address);
  102. conn->address = tor_strdup(router->address);
  103. }
  104. static void
  105. connection_or_init_conn_from_address(connection_t *conn,
  106. uint32_t addr, uint16_t port,
  107. const char *id_digest)
  108. {
  109. struct in_addr in;
  110. const char *n;
  111. or_options_t *options = get_options();
  112. routerinfo_t *r = router_get_by_digest(id_digest);
  113. if (r) {
  114. connection_or_init_conn_from_router(conn,r);
  115. return;
  116. }
  117. conn->addr = addr;
  118. conn->port = port;
  119. /* This next part isn't really right, but it's good enough for now. */
  120. conn->receiver_bucket = conn->bandwidth = (int)options->BandwidthBurst;
  121. memcpy(conn->identity_digest, id_digest, DIGEST_LEN);
  122. /* If we're an authoritative directory server, we may know a
  123. * nickname for this router. */
  124. n = dirserv_get_nickname_by_digest(id_digest);
  125. if (n) {
  126. conn->nickname = tor_strdup(n);
  127. } else {
  128. conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
  129. conn->nickname[0] = '$';
  130. base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
  131. conn->identity_digest, DIGEST_LEN);
  132. }
  133. tor_free(conn->address);
  134. in.s_addr = htonl(addr);
  135. conn->address = tor_strdup(inet_ntoa(in));
  136. }
  137. void
  138. connection_or_update_nickname(connection_t *conn)
  139. {
  140. routerinfo_t *r;
  141. const char *n;
  142. tor_assert(conn);
  143. tor_assert(conn->type == CONN_TYPE_OR);
  144. n = dirserv_get_nickname_by_digest(conn->identity_digest);
  145. if (n) {
  146. if (!conn->nickname || strcmp(conn->nickname, n)) {
  147. tor_free(conn->nickname);
  148. conn->nickname = tor_strdup(n);
  149. }
  150. return;
  151. }
  152. r = router_get_by_digest(conn->identity_digest);
  153. if (r && r->is_verified) {
  154. if (!conn->nickname || strcmp(conn->nickname, r->nickname)) {
  155. tor_free(conn->nickname);
  156. conn->nickname = tor_strdup(r->nickname);
  157. }
  158. return;
  159. }
  160. if (conn->nickname[0] != '$') {
  161. tor_free(conn->nickname);
  162. conn->nickname = tor_malloc(HEX_DIGEST_LEN+1);
  163. base16_encode(conn->nickname, HEX_DIGEST_LEN+1,
  164. conn->identity_digest, DIGEST_LEN);
  165. }
  166. }
  167. /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
  168. * handshake with an OR with identity digest <b>id_digest</b>.
  169. *
  170. * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
  171. * return that connection. If the connect() is in progress, set the
  172. * new conn's state to 'connecting' and return it. If connect() succeeds,
  173. * call * connection_tls_start_handshake() on it.
  174. *
  175. * This function is called from router_retry_connections(), for
  176. * ORs connecting to ORs, and circuit_establish_circuit(), for
  177. * OPs connecting to ORs.
  178. *
  179. * Return the launched conn, or NULL if it failed.
  180. */
  181. connection_t *connection_or_connect(uint32_t addr, uint16_t port,
  182. const char *id_digest) {
  183. connection_t *conn;
  184. routerinfo_t *me;
  185. tor_assert(id_digest);
  186. if (server_mode(get_options()) && (me=router_get_my_routerinfo()) &&
  187. !memcmp(me->identity_digest, id_digest,DIGEST_LEN)) {
  188. log_fn(LOG_WARN,"Request to connect to myself! Failing.");
  189. return NULL;
  190. }
  191. /* this function should never be called if we're already connected to
  192. * id_digest, but check first to be sure */
  193. /*XXX this is getting called, at least by dirservers. */
  194. conn = connection_get_by_identity_digest(id_digest, CONN_TYPE_OR);
  195. if (conn) {
  196. tor_assert(conn->nickname);
  197. log_fn(LOG_WARN,"Asked me to connect to router '%s', but there's already a connection.", conn->nickname);
  198. return conn;
  199. }
  200. conn = connection_new(CONN_TYPE_OR);
  201. /* set up conn so it's got all the data we need to remember */
  202. connection_or_init_conn_from_address(conn, addr, port, id_digest);
  203. conn->state = OR_CONN_STATE_CONNECTING;
  204. control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED);
  205. switch (connection_connect(conn, conn->address, addr, port)) {
  206. case -1:
  207. router_mark_as_down(conn->identity_digest);
  208. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
  209. connection_free(conn);
  210. return NULL;
  211. case 0:
  212. connection_watch_events(conn, POLLIN | POLLOUT | POLLERR);
  213. /* writable indicates finish, readable indicates broken link,
  214. error indicates broken link on windows */
  215. return conn;
  216. /* case 1: fall through */
  217. }
  218. if (connection_tls_start_handshake(conn, 0) >= 0)
  219. return conn;
  220. /* failure */
  221. connection_mark_for_close(conn);
  222. return NULL;
  223. }
  224. /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
  225. * we initiated the connection, else it's 1.
  226. *
  227. * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and pass
  228. * <b>conn</b> to connection_tls_continue_handshake().
  229. *
  230. * Return -1 if <b>conn</b> is broken, else return 0.
  231. */
  232. int connection_tls_start_handshake(connection_t *conn, int receiving) {
  233. conn->state = OR_CONN_STATE_HANDSHAKING;
  234. conn->tls = tor_tls_new(conn->s, receiving, 0);
  235. if (!conn->tls) {
  236. log_fn(LOG_WARN,"tor_tls_new failed. Closing.");
  237. return -1;
  238. }
  239. connection_start_reading(conn);
  240. log_fn(LOG_DEBUG,"starting the handshake");
  241. if (connection_tls_continue_handshake(conn) < 0) {
  242. return -1;
  243. }
  244. return 0;
  245. }
  246. /** Move forward with the tls handshake. If it finishes, hand
  247. * <b>conn</b> to connection_tls_finish_handshake().
  248. *
  249. * Return -1 if <b>conn</b> is broken, else return 0.
  250. */
  251. int connection_tls_continue_handshake(connection_t *conn) {
  252. switch (tor_tls_handshake(conn->tls)) {
  253. case TOR_TLS_ERROR:
  254. case TOR_TLS_CLOSE:
  255. log_fn(LOG_INFO,"tls error. breaking.");
  256. return -1;
  257. case TOR_TLS_DONE:
  258. return connection_tls_finish_handshake(conn);
  259. case TOR_TLS_WANTWRITE:
  260. connection_start_writing(conn);
  261. log_fn(LOG_DEBUG,"wanted write");
  262. return 0;
  263. case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
  264. log_fn(LOG_DEBUG,"wanted read");
  265. return 0;
  266. }
  267. return 0;
  268. }
  269. static char ZERO_DIGEST[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
  270. int connection_or_nonopen_was_started_here(connection_t *conn)
  271. {
  272. tor_assert(sizeof(ZERO_DIGEST) == DIGEST_LEN);
  273. tor_assert(conn->type == CONN_TYPE_OR);
  274. if (!memcmp(ZERO_DIGEST, conn->identity_digest, DIGEST_LEN))
  275. return 0;
  276. else
  277. return 1;
  278. }
  279. /** The tls handshake is finished.
  280. *
  281. * Make sure we are happy with the person we just handshaked with:
  282. * If it's an OP (that is, it has no certificate), make sure I'm an OR.
  283. * If it's an OR (it has a certificate), make sure it has a recognized
  284. * nickname, and its cert is signed by the identity key of that nickname.
  285. * If I initiated the connection, make sure it's the right guy; and if
  286. * he initiated the connection, make sure he's not already connected.
  287. *
  288. * If he initiated the conn, also initialize conn from the information
  289. * in router.
  290. *
  291. * If either of us is an OP, set bandwidth to the default OP bandwidth.
  292. *
  293. * If all is successful and he's an OR, then call circuit_n_conn_done()
  294. * to handle events that have been pending on the tls handshake
  295. * completion, and set the directory to be dirty (only matters if I'm
  296. * an authdirserver).
  297. */
  298. static int
  299. connection_tls_finish_handshake(connection_t *conn) {
  300. routerinfo_t *router;
  301. char nickname[MAX_NICKNAME_LEN+1];
  302. connection_t *c;
  303. crypto_pk_env_t *identity_rcvd=NULL;
  304. char digest_rcvd[DIGEST_LEN];
  305. or_options_t *options = get_options();
  306. conn->state = OR_CONN_STATE_OPEN;
  307. connection_watch_events(conn, POLLIN);
  308. log_fn(LOG_DEBUG,"tls handshake done. verifying.");
  309. if (! tor_tls_peer_has_cert(conn->tls)) { /* It's an old OP. */
  310. if (server_mode(options)) { /* I'm an OR; good. */
  311. conn->receiver_bucket = conn->bandwidth = DEFAULT_BANDWIDTH_OP;
  312. return 0;
  313. } else { /* Neither side sent a certificate: ouch. */
  314. log_fn(LOG_WARN,"Neither peer sent a cert! Closing.");
  315. return -1;
  316. }
  317. }
  318. /* Okay; the other side is an OR or a post-0.0.8 OP (with a cert). */
  319. if (tor_tls_get_peer_cert_nickname(conn->tls, nickname, MAX_NICKNAME_LEN)) {
  320. log_fn(LOG_WARN,"Other side (%s:%d) has a cert without a valid nickname. Closing.",
  321. conn->address, conn->port);
  322. return -1;
  323. }
  324. log_fn(LOG_DEBUG, "Other side (%s:%d) claims to be router '%s'",
  325. conn->address, conn->port, nickname);
  326. if (tor_tls_verify(conn->tls, &identity_rcvd) < 0) {
  327. log_fn(LOG_WARN,"Other side, which claims to be router '%s' (%s:%d), has a cert but it's invalid. Closing.",
  328. nickname, conn->address, conn->port);
  329. return -1;
  330. }
  331. #if 0
  332. if (tor_tls_check_lifetime(conn->tls, LOOSE_CERT_ALLOW_SKEW)<0) {
  333. log_fn(LOG_WARN,"Other side '%s' (%s:%d) has a very highly skewed clock, or an expired certificate. Closing.",
  334. nickname, conn->address, conn->port);
  335. return -1;
  336. }
  337. #endif
  338. log_fn(LOG_DEBUG,"The router's cert is valid.");
  339. crypto_pk_get_digest(identity_rcvd, digest_rcvd);
  340. if (crypto_pk_cmp_keys(get_identity_key(), identity_rcvd)<0) {
  341. conn->circ_id_type = CIRC_ID_TYPE_LOWER;
  342. } else {
  343. conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
  344. }
  345. crypto_free_pk_env(identity_rcvd);
  346. router = router_get_by_nickname(nickname);
  347. if (router && /* we know this nickname */
  348. router->is_verified && /* make sure it's the right guy */
  349. memcmp(digest_rcvd, router->identity_digest, DIGEST_LEN) != 0) {
  350. log_fn(LOG_WARN, "Identity key not as expected for router claiming to be '%s' (%s:%d) ", nickname, conn->address, conn->port);
  351. return -1;
  352. }
  353. if (router_get_by_digest(digest_rcvd)) {
  354. /* This is a known router; don't cut it slack with its clock skew. */
  355. if (tor_tls_check_lifetime(conn->tls, TIGHT_CERT_ALLOW_SKEW)<0) {
  356. log_fn(LOG_WARN,"Router '%s' (%s:%d) has a skewed clock, or an expired certificate; or else our clock is skewed. Closing.",
  357. nickname, conn->address, conn->port);
  358. return -1;
  359. }
  360. }
  361. if (connection_or_nonopen_was_started_here(conn)) {
  362. /* I initiated this connection. */
  363. if (strcasecmp(conn->nickname, nickname)) {
  364. log_fn(options->DirPort ? LOG_WARN : LOG_INFO,
  365. "Other side (%s:%d) is '%s', but we tried to connect to '%s'",
  366. conn->address, conn->port, nickname, conn->nickname);
  367. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
  368. return -1;
  369. }
  370. } else {
  371. if ((c=connection_get_by_identity_digest(digest_rcvd, CONN_TYPE_OR))) {
  372. log_fn(LOG_INFO,"Router '%s' is already connected on fd %d. Dropping fd %d.", nickname, c->s, conn->s);
  373. return -1;
  374. }
  375. connection_or_init_conn_from_address(conn,conn->addr,conn->port,digest_rcvd);
  376. }
  377. if (!server_mode(options)) { /* If I'm an OP... */
  378. conn->receiver_bucket = conn->bandwidth = DEFAULT_BANDWIDTH_OP;
  379. }
  380. directory_set_dirty();
  381. circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
  382. /* Note the success */
  383. rep_hist_note_connect_succeeded(conn->identity_digest, time(NULL));
  384. control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED);
  385. return 0;
  386. }
  387. /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s
  388. * outbuf.
  389. *
  390. * (Commented out) If it's an OR conn, and an entire TLS record is
  391. * ready, then try to flush the record now.
  392. */
  393. void connection_or_write_cell_to_buf(const cell_t *cell, connection_t *conn) {
  394. char networkcell[CELL_NETWORK_SIZE];
  395. char *n = networkcell;
  396. tor_assert(cell);
  397. tor_assert(conn);
  398. tor_assert(connection_speaks_cells(conn));
  399. cell_pack(n, cell);
  400. connection_write_to_buf(n, CELL_NETWORK_SIZE, conn);
  401. #if 0 /* commented out -- can we get away with not doing this,
  402. * because we're already round-robining in handle_read?
  403. */
  404. #define MIN_TLS_FLUSHLEN 15872
  405. /* openssl tls record size is 16383, this is close. The goal here is to
  406. * push data out as soon as we know there's enough for a tls record, so
  407. * during periods of high load we won't read the entire megabyte from
  408. * input before pushing any data out. */
  409. if (conn->outbuf_flushlen-CELL_NETWORK_SIZE < MIN_TLS_FLUSHLEN &&
  410. conn->outbuf_flushlen >= MIN_TLS_FLUSHLEN) {
  411. int extra = conn->outbuf_flushlen - MIN_TLS_FLUSHLEN;
  412. conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
  413. if (connection_handle_write(conn) < 0) {
  414. log_fn(LOG_WARN,"flushing failed.");
  415. return;
  416. }
  417. if (extra) {
  418. conn->outbuf_flushlen += extra;
  419. connection_start_writing(conn);
  420. }
  421. }
  422. #endif
  423. }
  424. /** Process cells from <b>conn</b>'s inbuf.
  425. *
  426. * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
  427. * and hand it to command_process_cell().
  428. *
  429. * Always return 0.
  430. */
  431. static int connection_or_process_cells_from_inbuf(connection_t *conn) {
  432. char buf[CELL_NETWORK_SIZE];
  433. cell_t cell;
  434. loop:
  435. log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object).",
  436. conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls));
  437. if (buf_datalen(conn->inbuf) < CELL_NETWORK_SIZE) /* entire response available? */
  438. return 0; /* not yet */
  439. connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, conn);
  440. /* retrieve cell info from buf (create the host-order struct from the
  441. * network-order string) */
  442. cell_unpack(&cell, buf);
  443. command_process_cell(&cell, conn);
  444. goto loop; /* process the remainder of the buffer */
  445. }