onion.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. /* Copyright 2001,2002 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. extern or_options_t options; /* command-line and config-file options */
  6. static int onion_process(circuit_t *circ);
  7. static int onion_deliver_to_conn(aci_t aci, unsigned char *onion, uint32_t onionlen, connection_t *conn);
  8. static int count_acceptable_routers(routerinfo_t **rarray, int rarray_len);
  9. static int find_tracked_onion(unsigned char *onion, uint32_t onionlen);
  10. int decide_aci_type(uint32_t local_addr, uint16_t local_port,
  11. uint32_t remote_addr, uint16_t remote_port) {
  12. if(local_addr > remote_addr)
  13. return ACI_TYPE_HIGHER;
  14. if(local_addr < remote_addr)
  15. return ACI_TYPE_LOWER;
  16. if(local_port > remote_port)
  17. return ACI_TYPE_HIGHER;
  18. /* else */
  19. return ACI_TYPE_LOWER;
  20. }
  21. /* global (within this file) variables used by the next few functions */
  22. static struct onion_queue_t *ol_list=NULL;
  23. static struct onion_queue_t *ol_tail=NULL;
  24. static int ol_length=0;
  25. int onion_pending_add(circuit_t *circ) {
  26. struct onion_queue_t *tmp;
  27. tmp = malloc(sizeof(struct onion_queue_t));
  28. memset(tmp, 0, sizeof(struct onion_queue_t));
  29. tmp->circ = circ;
  30. if(!ol_tail) {
  31. assert(!ol_list);
  32. assert(!ol_length);
  33. ol_list = tmp;
  34. ol_tail = tmp;
  35. ol_length++;
  36. return 0;
  37. }
  38. assert(ol_list);
  39. assert(!ol_tail->next);
  40. if(ol_length >= options.MaxOnionsPending) {
  41. log(LOG_INFO,"onion_pending_add(): Already have %d onions queued. Closing.", ol_length);
  42. free(tmp);
  43. return -1;
  44. }
  45. ol_length++;
  46. ol_tail->next = tmp;
  47. ol_tail = tmp;
  48. return 0;
  49. }
  50. int onion_pending_check(void) {
  51. if(ol_list)
  52. return 1;
  53. else
  54. return 0;
  55. }
  56. void onion_pending_process_one(void) {
  57. struct data_queue_t *tmpd;
  58. circuit_t *circ;
  59. if(!ol_list)
  60. return; /* no onions pending, we're done */
  61. assert(ol_list->circ && ol_list->circ->p_conn);
  62. assert(ol_length > 0);
  63. circ = ol_list->circ;
  64. if(onion_process(circ) < 0) {
  65. log(LOG_DEBUG,"onion_pending_process_one(): Failed. Closing.");
  66. onion_pending_remove(circ);
  67. circuit_close(circ);
  68. } else {
  69. log(LOG_DEBUG,"onion_pending_process_one(): Succeeded. Delivering queued data cells.");
  70. for(tmpd = ol_list->data_cells; tmpd; tmpd=tmpd->next) {
  71. command_process_data_cell(tmpd->cell, circ->p_conn);
  72. }
  73. onion_pending_remove(circ);
  74. }
  75. return;
  76. }
  77. /* go through ol_list, find the onion_queue_t element which points to
  78. * circ, remove and free that element. leave circ itself alone.
  79. */
  80. void onion_pending_remove(circuit_t *circ) {
  81. struct onion_queue_t *tmpo, *victim;
  82. struct data_queue_t *tmpd;
  83. if(!ol_list)
  84. return; /* nothing here. */
  85. /* first check to see if it's the first entry */
  86. tmpo = ol_list;
  87. if(tmpo->circ == circ) {
  88. /* it's the first one. remove it from the list. */
  89. ol_list = tmpo->next;
  90. if(!ol_list)
  91. ol_tail = NULL;
  92. ol_length--;
  93. victim = tmpo;
  94. } else { /* we need to hunt through the rest of the list */
  95. for( ;tmpo->next && tmpo->next->circ != circ; tmpo=tmpo->next) ;
  96. if(!tmpo->next) {
  97. log(LOG_WARNING,"onion_pending_remove(): circ (p_aci %d), not in list!",circ->p_aci);
  98. return;
  99. }
  100. /* now we know tmpo->next->circ == circ */
  101. victim = tmpo->next;
  102. tmpo->next = victim->next;
  103. if(ol_tail == victim)
  104. ol_tail = tmpo;
  105. ol_length--;
  106. }
  107. /* now victim points to the element that needs to be removed */
  108. /* first dump the attached data cells too, if any */
  109. while(victim->data_cells) {
  110. tmpd = victim->data_cells;
  111. victim->data_cells = tmpd->next;
  112. free(tmpd->cell);
  113. free(tmpd);
  114. }
  115. free(victim);
  116. }
  117. struct data_queue_t *data_queue_add(struct data_queue_t *list, cell_t *cell) {
  118. struct data_queue_t *tmpd, *newd;
  119. newd = malloc(sizeof(struct data_queue_t));
  120. memset(newd, 0, sizeof(struct data_queue_t));
  121. newd->cell = malloc(sizeof(cell_t));
  122. memcpy(newd->cell, cell, sizeof(cell_t));
  123. if(!list) {
  124. return newd;
  125. }
  126. for(tmpd = list; tmpd->next; tmpd=tmpd->next) ;
  127. /* now tmpd->next is null */
  128. tmpd->next = newd;
  129. return list;
  130. }
  131. /* a data cell has arrived for a circuit which is still pending. Find
  132. * the right entry in ol_list, and add it to the end of the 'data_cells'
  133. * list.
  134. */
  135. void onion_pending_data_add(circuit_t *circ, cell_t *cell) {
  136. struct onion_queue_t *tmpo;
  137. for(tmpo=ol_list; tmpo; tmpo=tmpo->next) {
  138. if(tmpo->circ == circ) {
  139. tmpo->data_cells = data_queue_add(tmpo->data_cells, cell);
  140. return;
  141. }
  142. }
  143. }
  144. /* helper function for onion_process */
  145. static int onion_deliver_to_conn(aci_t aci, unsigned char *onion, uint32_t onionlen, connection_t *conn) {
  146. char *buf;
  147. int buflen, dataleft;
  148. cell_t cell;
  149. assert(aci && onion && onionlen);
  150. buflen = onionlen+4;
  151. buf = malloc(buflen);
  152. if(!buf)
  153. return -1;
  154. log(LOG_DEBUG,"onion_deliver_to_conn(): Setting onion length to %u.",onionlen);
  155. *(uint32_t*)buf = htonl(onionlen);
  156. memcpy((buf+4),onion,onionlen);
  157. dataleft = buflen;
  158. while(dataleft > 0) {
  159. memset(&cell,0,sizeof(cell_t));
  160. cell.command = CELL_CREATE;
  161. cell.aci = aci;
  162. if(dataleft >= CELL_PAYLOAD_SIZE)
  163. cell.length = CELL_PAYLOAD_SIZE;
  164. else
  165. cell.length = dataleft;
  166. memcpy(cell.payload, buf+buflen-dataleft, cell.length);
  167. dataleft -= cell.length;
  168. log(LOG_DEBUG,"onion_deliver_to_conn(): Delivering create cell, payload %d bytes.",cell.length);
  169. if(connection_write_cell_to_buf(&cell, conn) < 0) {
  170. log(LOG_DEBUG,"onion_deliver_to_conn(): Could not buffer new create cells. Closing.");
  171. free(buf);
  172. return -1;
  173. }
  174. }
  175. free(buf);
  176. return 0;
  177. }
  178. static int onion_process(circuit_t *circ) {
  179. connection_t *n_conn;
  180. int retval;
  181. aci_t aci_type;
  182. struct sockaddr_in me; /* my router identity */
  183. if(learn_my_address(&me) < 0)
  184. return -1;
  185. /* decrypt it in-place */
  186. if(decrypt_onion(circ->onion,circ->onionlen,getprivatekey()) < 0) {
  187. log(LOG_DEBUG,"command_process_create_cell(): decrypt_onion() failed, closing circuit.");
  188. return -1;
  189. }
  190. log(LOG_DEBUG,"command_process_create_cell(): Onion decrypted.");
  191. /* check freshness */
  192. if (ntohl(*(uint32_t *)(circ->onion+8)) < (uint32_t)time(NULL)) /* expired onion */
  193. {
  194. log(LOG_NOTICE,"I have just received an expired onion. This could be a replay attack.");
  195. return -1;
  196. }
  197. aci_type = decide_aci_type(ntohl(me.sin_addr.s_addr), ntohs(me.sin_port),
  198. ntohl(*(uint32_t *)(circ->onion+4)),ntohs(*(uint16_t *)(circ->onion+2)));
  199. if(circuit_init(circ, aci_type) < 0) {
  200. log(LOG_ERR,"process_onion(): init_circuit() failed.");
  201. return -1;
  202. }
  203. /* check for replay. at the same time, add it to the pile of tracked onions. */
  204. if(find_tracked_onion(circ->onion, circ->onionlen)) {
  205. log(LOG_NOTICE,"process_onion(): I have just received a replayed onion. This could be a replay attack.");
  206. return -1;
  207. }
  208. /* now we must send create cells to the next router */
  209. if(circ->n_addr && circ->n_port) {
  210. n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
  211. if(!n_conn || n_conn->type != CONN_TYPE_OR) {
  212. /* i've disabled making connections through OPs, but it's definitely
  213. * possible here. I'm not sure if it would be a bug or a feature. -RD
  214. */
  215. /* note also that this will close circuits where the onion has the same
  216. * router twice in a row in the path. i think that's ok. -RD
  217. */
  218. log(LOG_DEBUG,"command_process_create_cell(): Next router not connected. Closing.");
  219. return -1;
  220. }
  221. circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
  222. circ->n_port = n_conn->port;
  223. circ->n_conn = n_conn;
  224. log(LOG_DEBUG,"command_process_create_cell(): n_conn is %s:%u",n_conn->address,n_conn->port);
  225. /* send the CREATE cells on to the next hop */
  226. pad_onion(circ->onion, circ->onionlen, ONION_LAYER_SIZE);
  227. log(LOG_DEBUG,"command_process_create_cell(): Padded the onion with random data.");
  228. retval = onion_deliver_to_conn(circ->n_aci, circ->onion, circ->onionlen, n_conn);
  229. free(circ->onion);
  230. circ->onion = NULL;
  231. if (retval == -1) {
  232. log(LOG_DEBUG,"command_process_create_cell(): Could not deliver the onion to next conn. Closing.");
  233. return -1;
  234. }
  235. } else { /* this is destined for an exit */
  236. log(LOG_DEBUG,"command_process_create_cell(): create cell reached exit. Circuit established.");
  237. #if 0
  238. log(LOG_DEBUG,"command_process_create_cell(): Creating new exit connection.");
  239. n_conn = connection_new(CONN_TYPE_EXIT);
  240. if(!n_conn) {
  241. log(LOG_DEBUG,"command_process_create_cell(): connection_new failed. Closing.");
  242. return -1;
  243. }
  244. n_conn->state = EXIT_CONN_STATE_CONNECTING_WAIT;
  245. n_conn->receiver_bucket = -1; /* edge connections don't do receiver buckets */
  246. n_conn->bandwidth = -1;
  247. n_conn->s = -1; /* not yet valid */
  248. if(connection_add(n_conn) < 0) { /* no space, forget it */
  249. log(LOG_DEBUG,"command_process_create_cell(): connection_add failed. Closing.");
  250. connection_free(n_conn);
  251. return -1;
  252. }
  253. circ->n_conn = n_conn;
  254. #endif
  255. }
  256. return 0;
  257. }
  258. /* uses a weighted coin with weight cw to choose a route length */
  259. int chooselen(double cw)
  260. {
  261. int len = 2;
  262. int retval = 0;
  263. unsigned char coin;
  264. if ((cw < 0) || (cw >= 1)) /* invalid parameter */
  265. return -1;
  266. while(1)
  267. {
  268. retval = crypto_pseudo_rand(1, &coin);
  269. if (retval)
  270. return -1;
  271. if (coin > cw*255) /* don't extend */
  272. break;
  273. else
  274. len++;
  275. }
  276. return len;
  277. }
  278. /* returns an array of pointers to routent that define a new route through the OR network
  279. * int cw is the coin weight to use when choosing the route
  280. * order of routers is from last to first
  281. */
  282. unsigned int *new_route(double cw, routerinfo_t **rarray, int rarray_len, int *routelen)
  283. {
  284. int i, j;
  285. int num_acceptable_routers;
  286. unsigned int *route = NULL;
  287. unsigned int oldchoice, choice;
  288. assert((cw >= 0) && (cw < 1) && (rarray) && (routelen) ); /* valid parameters */
  289. *routelen = chooselen(cw);
  290. if (*routelen == -1) {
  291. log(LOG_ERR,"Choosing route length failed.");
  292. return NULL;
  293. }
  294. log(LOG_DEBUG,"new_route(): Chosen route length %d.",*routelen);
  295. num_acceptable_routers = count_acceptable_routers(rarray, rarray_len);
  296. if(num_acceptable_routers < *routelen) {
  297. log(LOG_DEBUG,"new_route(): Cutting routelen from %d to %d.",*routelen, num_acceptable_routers);
  298. *routelen = num_acceptable_routers;
  299. }
  300. if(*routelen < 1) {
  301. log(LOG_ERR,"new_route(): Didn't find any acceptable routers. Failing.");
  302. return NULL;
  303. }
  304. /* allocate memory for the new route */
  305. route = (unsigned int *)malloc(*routelen * sizeof(unsigned int));
  306. if (!route) {
  307. log(LOG_ERR,"Memory allocation failed.");
  308. return NULL;
  309. }
  310. oldchoice = rarray_len;
  311. for(i=0;i<*routelen;i++) {
  312. log(LOG_DEBUG,"new_route(): Choosing hop %u.",i);
  313. if(crypto_pseudo_rand(sizeof(unsigned int),(unsigned char *)&choice)) {
  314. free((void *)route);
  315. return NULL;
  316. }
  317. choice = choice % (rarray_len);
  318. log(LOG_DEBUG,"new_route(): Contemplating router %u.",choice);
  319. if(choice == oldchoice ||
  320. (oldchoice < rarray_len && !crypto_pk_cmp_keys(rarray[choice]->pkey, rarray[oldchoice]->pkey)) ||
  321. (options.ORPort && !connection_twin_get_by_addr_port(rarray[choice]->addr, rarray[choice]->or_port))) {
  322. /* Same router as last choice, or router twin,
  323. * or no routers with that key are connected to us.
  324. * Try again. */
  325. log(LOG_DEBUG,"new_route(): Picked a router %d that won't work as next hop.",choice);
  326. i--;
  327. continue;
  328. }
  329. log(LOG_DEBUG,"new_route(): Chosen router %u for hop %u.",choice,i);
  330. oldchoice = choice;
  331. route[i] = choice;
  332. }
  333. return route;
  334. }
  335. static int count_acceptable_routers(routerinfo_t **rarray, int rarray_len) {
  336. int i, j;
  337. int num=0;
  338. for(i=0;i<rarray_len;i++) {
  339. log(LOG_DEBUG,"Contemplating whether router %d is a new option...",i);
  340. if(options.ORPort &&
  341. !connection_exact_get_by_addr_port(rarray[i]->addr, rarray[i]->or_port)) {
  342. log(LOG_DEBUG,"Nope, %d is not connected.",i);
  343. goto next_i_loop;
  344. }
  345. for(j=0;j<i;j++) {
  346. if(!crypto_pk_cmp_keys(rarray[i]->pkey, rarray[j]->pkey)) {
  347. /* these guys are twins. so we've already counted him. */
  348. log(LOG_DEBUG,"Nope, %d is a twin of %d.",i,j);
  349. goto next_i_loop;
  350. }
  351. }
  352. num++;
  353. log(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  354. next_i_loop:
  355. ; /* our compiler may need an explicit statement after the label */
  356. }
  357. return num;
  358. }
  359. crypto_cipher_env_t *
  360. create_onion_cipher(int cipher_type, char *key, char *iv, int encrypt_mode)
  361. {
  362. switch (cipher_type) {
  363. case ONION_CIPHER_DES:
  364. cipher_type = CRYPTO_CIPHER_DES;
  365. break;
  366. case ONION_CIPHER_3DES:
  367. cipher_type = CRYPTO_CIPHER_3DES;
  368. break;
  369. case ONION_CIPHER_RC4 :
  370. cipher_type = CRYPTO_CIPHER_RC4;
  371. break;
  372. case ONION_CIPHER_IDENTITY :
  373. cipher_type = CRYPTO_CIPHER_IDENTITY;
  374. break;
  375. default:
  376. log(LOG_ERR, "Unknown cipher type %d", cipher_type);
  377. return NULL;
  378. }
  379. return crypto_create_init_cipher(cipher_type, key, iv, encrypt_mode);
  380. }
  381. /* creates a new onion from route, stores it and its length into buf and len respectively */
  382. unsigned char *create_onion(routerinfo_t **rarray, int rarray_len, unsigned int *route, int routelen, int *len, crypt_path_t **cpath)
  383. {
  384. int i,j;
  385. char *layer;
  386. crypt_path_t *hop = NULL;
  387. unsigned char *buf;
  388. routerinfo_t *router;
  389. unsigned char iv[16];
  390. struct in_addr netaddr;
  391. assert(rarray && route && len && routelen);
  392. /* calculate the size of the onion */
  393. *len = routelen * ONION_LAYER_SIZE + ONION_PADDING_SIZE;
  394. /* 28 bytes per layer + 100 bytes padding for the innermost layer */
  395. log(LOG_DEBUG,"create_onion() : Size of the onion is %u.",*len);
  396. /* allocate memory for the onion */
  397. buf = malloc(*len);
  398. if(!buf) {
  399. log(LOG_ERR,"Error allocating memory.");
  400. return NULL;
  401. }
  402. log(LOG_DEBUG,"create_onion() : Allocated memory for the onion.");
  403. for(i=0; i<routelen; i++) {
  404. netaddr.s_addr = htonl((rarray[route[i]])->addr);
  405. log(LOG_DEBUG,"create_onion(): %u : %s:%u, %u/%u",routelen-i,
  406. inet_ntoa(netaddr),
  407. (rarray[route[i]])->or_port,
  408. (rarray[route[i]])->pkey,
  409. crypto_pk_keysize((rarray[route[i]])->pkey));
  410. }
  411. layer = buf + *len - ONION_LAYER_SIZE - ONION_PADDING_SIZE; /* pointer to innermost layer */
  412. /* create the onion layer by layer, starting with the innermost */
  413. for (i=0;i<routelen;i++) {
  414. router = rarray[route[i]];
  415. // log(LOG_DEBUG,"create_onion() : %u",router);
  416. // log(LOG_DEBUG,"create_onion() : This router is %s:%u",inet_ntoa(*((struct in_addr *)&router->addr)),router->or_port);
  417. // log(LOG_DEBUG,"create_onion() : Key pointer = %u.",router->pkey);
  418. // log(LOG_DEBUG,"create_onion() : Key size = %u.",crypto_pk_keysize(router->pkey));
  419. *layer = OR_VERSION;
  420. /* Back F + Forw F both use DES OFB*/
  421. *(layer+1) = (ONION_DEFAULT_CIPHER << 4) /* for backf */ +
  422. ONION_DEFAULT_CIPHER; /* for forwf */
  423. /* Dest Port */
  424. if (i) /* not last hop */
  425. *(uint16_t *)(layer+2) = htons(rarray[route[i-1]]->or_port);
  426. else
  427. *(uint16_t *)(layer+2) = htons(0);
  428. /* Dest Addr */
  429. if (i) /* not last hop */
  430. *(uint32_t *)(layer+4) = htonl(rarray[route[i-1]]->addr);
  431. else
  432. *(uint32_t *)(layer+4) = htonl(0);
  433. /* Expiration Time */
  434. *(uint32_t *)(layer+8) = htonl((uint32_t)(time(NULL) + 86400)); /* NOW + 1 day */
  435. /* Key Seed Material */
  436. if(crypto_rand(16, layer+12)) { /* error */
  437. log(LOG_ERR,"Error generating random data.");
  438. goto error;
  439. }
  440. // log(LOG_DEBUG,"create_onion() : Onion layer %u built : %u, %u, %u, %s, %u.",i+1,layer->zero,layer->backf,layer->forwf,inet_ntoa(*((struct in_addr *)&layer->addr)),layer->port);
  441. /* build up the crypt_path */
  442. if(cpath) {
  443. cpath[i] = (crypt_path_t *)malloc(sizeof(crypt_path_t));
  444. if(!cpath[i]) {
  445. log(LOG_ERR,"Error allocating memory.");
  446. goto error;
  447. }
  448. log(LOG_DEBUG,"create_onion() : Building hop %u of crypt path.",i+1);
  449. hop = cpath[i];
  450. /* set crypto functions */
  451. hop->backf = *(layer+1) >> 4;
  452. hop->forwf = *(layer+1) & 0x0f;
  453. /* calculate keys */
  454. crypto_SHA_digest(layer+12,16,hop->digest3);
  455. log(LOG_DEBUG,"create_onion() : First SHA pass performed.");
  456. crypto_SHA_digest(hop->digest3,20,hop->digest2);
  457. log(LOG_DEBUG,"create_onion() : Second SHA pass performed.");
  458. crypto_SHA_digest(hop->digest2,20,hop->digest3);
  459. log(LOG_DEBUG,"create_onion() : Third SHA pass performed.");
  460. log(LOG_DEBUG,"create_onion() : Keys generated.");
  461. /* set IV to zero */
  462. memset((void *)iv,0,16);
  463. /* initialize cipher engines */
  464. if (! (hop->f_crypto = create_onion_cipher(hop->forwf, hop->digest3, iv, 1))) {
  465. /* cipher initialization failed */
  466. log(LOG_ERR,"Could not create a crypto environment.");
  467. goto error;
  468. }
  469. if (! (hop->b_crypto = create_onion_cipher(hop->backf, hop->digest2, iv, 0))) {
  470. /* cipher initialization failed */
  471. log(LOG_ERR,"Could not create a crypto environment.");
  472. goto error;
  473. }
  474. log(LOG_DEBUG,"create_onion() : Built corresponding crypt path hop.");
  475. }
  476. /* padding if this is the innermost layer */
  477. if (!i) {
  478. if (crypto_pseudo_rand(ONION_PADDING_SIZE, layer + ONION_LAYER_SIZE)) { /* error */
  479. log(LOG_ERR,"Error generating pseudo-random data.");
  480. goto error;
  481. }
  482. log(LOG_DEBUG,"create_onion() : This is the innermost layer. Adding 100 bytes of padding.");
  483. }
  484. /* encrypt */
  485. if(encrypt_onion(layer,ONION_PADDING_SIZE+(i+1)*ONION_LAYER_SIZE,router->pkey) < 0) {
  486. log(LOG_ERR,"Error encrypting onion layer.");
  487. goto error;
  488. }
  489. log(LOG_DEBUG,"create_onion() : Encrypted layer.");
  490. /* calculate pointer to next layer */
  491. layer = buf + (routelen-i-2)*ONION_LAYER_SIZE;
  492. }
  493. return buf;
  494. error:
  495. if (buf)
  496. free(buf);
  497. if (cpath) {
  498. for (j=0;j<i;j++) {
  499. if(cpath[i]->f_crypto)
  500. crypto_free_cipher_env(cpath[i]->f_crypto);
  501. if(cpath[i]->b_crypto)
  502. crypto_free_cipher_env(cpath[i]->b_crypto);
  503. free((void *)cpath[i]);
  504. }
  505. }
  506. return NULL;
  507. }
  508. /* encrypts 128 bytes of the onion with the specified public key, the rest with
  509. * DES OFB with the key as defined in the outter layer */
  510. int encrypt_onion(unsigned char *onion, uint32_t onionlen, crypto_pk_env_t *pkey) {
  511. unsigned char *tmpbuf = NULL; /* temporary buffer for crypto operations */
  512. unsigned char digest[20]; /* stores SHA1 output - 160 bits */
  513. unsigned char iv[8];
  514. crypto_cipher_env_t *crypt_env = NULL; /* crypto environment */
  515. assert(onion && pkey);
  516. assert(onionlen >= 128);
  517. memset(iv,0,8);
  518. // log(LOG_DEBUG,"Onion layer : %u, %u, %u, %s, %u.",onion->zero,onion->backf,onion->forwf,inet_ntoa(*((struct in_addr *)&onion->addr)),onion->port);
  519. /* allocate space for tmpbuf */
  520. tmpbuf = (unsigned char *)malloc(onionlen);
  521. if(!tmpbuf) {
  522. log(LOG_ERR,"Could not allocate memory.");
  523. return -1;
  524. }
  525. log(LOG_DEBUG,"encrypt_onion() : allocated %u bytes of memory for the encrypted onion (at %u).",onionlen,tmpbuf);
  526. /* get key1 = SHA1(KeySeed) */
  527. if (crypto_SHA_digest(onion+12,16,digest)) {
  528. log(LOG_ERR,"Error computing SHA1 digest.");
  529. goto error;
  530. }
  531. log(LOG_DEBUG,"encrypt_onion() : Computed DES key.");
  532. log(LOG_DEBUG,"encrypt_onion() : Trying to RSA encrypt.");
  533. /* encrypt 128 bytes with RSA *pkey */
  534. if (crypto_pk_public_encrypt(pkey, onion, 128, tmpbuf, RSA_NO_PADDING) == -1) {
  535. log(LOG_ERR,"Error RSA-encrypting data :%s",crypto_perror());
  536. goto error;
  537. }
  538. log(LOG_DEBUG,"encrypt_onion() : RSA encrypted first 128 bytes of the onion.");
  539. /* now encrypt the rest with 3DES OFB */
  540. crypt_env = crypto_create_init_cipher(CRYPTO_CIPHER_3DES, digest, iv, 1);
  541. if (!crypt_env) {
  542. log(LOG_ERR,"Error creating the crypto environment.");
  543. goto error;
  544. }
  545. if (crypto_cipher_encrypt(crypt_env,onion+128, onionlen-128, (unsigned char *)tmpbuf+128)) { /* error */
  546. log(LOG_ERR,"Error performing DES encryption:%s",crypto_perror());
  547. goto error;
  548. }
  549. log(LOG_DEBUG,"encrypt_onion() : 3DES OFB encrypted the rest of the onion.");
  550. /* now copy tmpbuf to onion */
  551. memcpy(onion,tmpbuf,onionlen);
  552. log(LOG_DEBUG,"encrypt_onion() : Copied cipher to original onion buffer.");
  553. free(tmpbuf);
  554. crypto_free_cipher_env(crypt_env);
  555. return 0;
  556. error:
  557. if (tmpbuf)
  558. free(tmpbuf);
  559. if (crypt_env)
  560. crypto_free_cipher_env(crypt_env);
  561. return -1;
  562. }
  563. /* decrypts the first 128 bytes using RSA and prkey, decrypts the rest with DES OFB with key1 */
  564. int decrypt_onion(unsigned char *onion, uint32_t onionlen, crypto_pk_env_t *prkey) {
  565. void *tmpbuf = NULL; /* temporary buffer for crypto operations */
  566. unsigned char digest[20]; /* stores SHA1 output - 160 bits */
  567. unsigned char iv[8];
  568. crypto_cipher_env_t *crypt_env =NULL; /* crypto environment */
  569. assert(onion && prkey);
  570. memset(iv,0,8);
  571. /* allocate space for tmpbuf */
  572. tmpbuf = malloc(onionlen);
  573. if (!tmpbuf) {
  574. log(LOG_ERR,"Could not allocate memory.");
  575. return -1;
  576. }
  577. log(LOG_DEBUG,"decrypt_onion() : Allocated memory for the temporary buffer.");
  578. /* decrypt 128 bytes with RSA *prkey */
  579. if (crypto_pk_private_decrypt(prkey, onion, 128, tmpbuf, RSA_NO_PADDING) == -1)
  580. {
  581. log(LOG_ERR,"Error RSA-decrypting data :%s",crypto_perror());
  582. goto error;
  583. }
  584. log(LOG_DEBUG,"decrypt_onion() : RSA decryption complete.");
  585. /* get key1 = SHA1(KeySeed) */
  586. if (crypto_SHA_digest(tmpbuf+12,16,digest)) {
  587. log(LOG_ERR,"Error computing SHA1 digest.");
  588. goto error;
  589. }
  590. log(LOG_DEBUG,"decrypt_onion() : Computed DES key.");
  591. /* now decrypt the rest with 3DES OFB */
  592. crypt_env = crypto_create_init_cipher(CRYPTO_CIPHER_3DES, digest, iv, 0);
  593. if (!crypt_env) {
  594. log(LOG_ERR,"Error creating crypto environment");
  595. goto error;
  596. }
  597. if (crypto_cipher_decrypt(crypt_env,onion+128, onionlen-128,tmpbuf+128)) {
  598. log(LOG_ERR,"Error performing DES decryption:%s",crypto_perror());
  599. goto error;
  600. }
  601. log(LOG_DEBUG,"decrypt_onion() : DES decryption complete.");
  602. /* now copy tmpbuf to onion */
  603. memcpy(onion,tmpbuf,onionlen);
  604. free(tmpbuf);
  605. crypto_free_cipher_env(crypt_env);
  606. return 0;
  607. error:
  608. if (tmpbuf)
  609. free(tmpbuf);
  610. if (crypt_env)
  611. crypto_free_cipher_env(crypt_env);
  612. return -1;
  613. }
  614. /* delete first n bytes of the onion and pads the end with n bytes of random data */
  615. void pad_onion(unsigned char *onion, uint32_t onionlen, int n)
  616. {
  617. assert(onion);
  618. memmove(onion,onion+n,onionlen-n);
  619. crypto_pseudo_rand(n, onion+onionlen-n);
  620. }
  621. /* red black tree using Niels' tree.h. I used
  622. http://www.openbsd.org/cgi-bin/cvsweb/src/regress/sys/sys/tree/rb/
  623. as my guide */
  624. #include "tree.h"
  625. struct tracked_onion {
  626. RB_ENTRY(tracked_onion) node;
  627. uint32_t expire;
  628. char digest[20]; /* SHA digest of the onion */
  629. struct tracked_onion *next;
  630. };
  631. RB_HEAD(tracked_tree, tracked_onion) tracked_root;
  632. int compare_tracked_onions(struct tracked_onion *a, struct tracked_onion *b) {
  633. return memcmp(a->digest, b->digest, 20);
  634. }
  635. RB_PROTOTYPE(tracked_tree, tracked_onion, node, compare_tracked_onions)
  636. RB_GENERATE(tracked_tree, tracked_onion, node, compare_tracked_onions)
  637. void init_tracked_tree(void) {
  638. RB_INIT(&tracked_root);
  639. }
  640. /* see if this onion has been seen before. if so, return 1, else
  641. * return 0 and add the sha1 of this onion to the tree.
  642. */
  643. static int find_tracked_onion(unsigned char *onion, uint32_t onionlen) {
  644. static struct tracked_onion *head_tracked_onions = NULL; /* linked list of tracked onions */
  645. static struct tracked_onion *tail_tracked_onions = NULL;
  646. uint32_t now = time(NULL);
  647. struct tracked_onion *to;
  648. /* first take this opportunity to see if there are any expired
  649. * onions in the tree. we know this is fast because the linked list
  650. * 'tracked_onions' is ordered by when they were seen.
  651. */
  652. while(head_tracked_onions && (head_tracked_onions->expire < now)) {
  653. to = head_tracked_onions;
  654. log(LOG_DEBUG,"find_tracked_onion(): Forgetting old onion (expires %d)", to->expire);
  655. head_tracked_onions = to->next;
  656. if(!head_tracked_onions) /* if there are no more, */
  657. tail_tracked_onions = NULL; /* then make sure the list's tail knows that too */
  658. RB_REMOVE(tracked_tree, &tracked_root, to);
  659. free(to);
  660. }
  661. to = malloc(sizeof(struct tracked_onion));
  662. /* compute the SHA digest of the onion */
  663. crypto_SHA_digest(onion, onionlen, to->digest);
  664. /* try adding it to the tree. if it's already there it will return it. */
  665. if(RB_INSERT(tracked_tree, &tracked_root, to)) {
  666. /* yes, it's already there: this is a replay. */
  667. free(to);
  668. return 1;
  669. }
  670. /* this is a new onion. add it to the list. */
  671. to->expire = ntohl(*(uint32_t *)(onion+8)); /* set the expiration date */
  672. to->next = NULL;
  673. if (!head_tracked_onions) {
  674. head_tracked_onions = to;
  675. } else {
  676. tail_tracked_onions->next = to;
  677. }
  678. tail_tracked_onions = to;
  679. log(LOG_DEBUG,"find_tracked_onion(): Remembered new onion (expires %d)", to->expire);
  680. return 0;
  681. }
  682. /*
  683. Local Variables:
  684. mode:c
  685. indent-tabs-mode:nil
  686. c-basic-offset:2
  687. End:
  688. */