onion.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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. onion_layer_t layer;
  184. if(learn_my_address(&me) < 0)
  185. return -1;
  186. /* decrypt it in-place */
  187. if(decrypt_onion(circ->onion,circ->onionlen,getprivatekey(),&layer) < 0) {
  188. log(LOG_DEBUG,"command_process_create_cell(): decrypt_onion() failed, closing circuit.");
  189. return -1;
  190. }
  191. log(LOG_DEBUG,"command_process_create_cell(): Onion decrypted.");
  192. /* check freshness */
  193. if (layer.expire < (uint32_t)time(NULL)) /* expired onion */ /*XXXX*/
  194. {
  195. log(LOG_NOTICE,"I have just received an expired onion. This could be a replay attack.");
  196. return -1;
  197. }
  198. aci_type = decide_aci_type(ntohl(me.sin_addr.s_addr), ntohs(me.sin_port),
  199. layer.addr, layer.port);
  200. if(circuit_init(circ, aci_type, &layer) < 0) {
  201. log(LOG_ERR,"process_onion(): init_circuit() failed.");
  202. return -1;
  203. }
  204. /* check for replay. at the same time, add it to the pile of tracked onions. */
  205. if(find_tracked_onion(circ->onion, circ->onionlen)) {
  206. log(LOG_NOTICE,"process_onion(): I have just received a replayed onion. This could be a replay attack.");
  207. return -1;
  208. }
  209. /* now we must send create cells to the next router */
  210. if(circ->n_addr && circ->n_port) {
  211. n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
  212. if(!n_conn || n_conn->type != CONN_TYPE_OR) {
  213. /* i've disabled making connections through OPs, but it's definitely
  214. * possible here. I'm not sure if it would be a bug or a feature. -RD
  215. */
  216. /* note also that this will close circuits where the onion has the same
  217. * router twice in a row in the path. i think that's ok. -RD
  218. */
  219. log(LOG_DEBUG,"command_process_create_cell(): Next router not connected. Closing.");
  220. return -1;
  221. }
  222. circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
  223. circ->n_port = n_conn->port;
  224. circ->n_conn = n_conn;
  225. log(LOG_DEBUG,"command_process_create_cell(): n_conn is %s:%u",n_conn->address,n_conn->port);
  226. /* send the CREATE cells on to the next hop */
  227. pad_onion(circ->onion, circ->onionlen, ONION_LAYER_SIZE);
  228. log(LOG_DEBUG,"command_process_create_cell(): Padded the onion with random data.");
  229. retval = onion_deliver_to_conn(circ->n_aci, circ->onion, circ->onionlen, n_conn);
  230. free(circ->onion);
  231. circ->onion = NULL;
  232. if (retval == -1) {
  233. log(LOG_DEBUG,"command_process_create_cell(): Could not deliver the onion to next conn. Closing.");
  234. return -1;
  235. }
  236. } else { /* this is destined for an exit */
  237. log(LOG_DEBUG,"command_process_create_cell(): create cell reached exit. Circuit established.");
  238. #if 0
  239. log(LOG_DEBUG,"command_process_create_cell(): Creating new exit connection.");
  240. n_conn = connection_new(CONN_TYPE_EXIT);
  241. if(!n_conn) {
  242. log(LOG_DEBUG,"command_process_create_cell(): connection_new failed. Closing.");
  243. return -1;
  244. }
  245. n_conn->state = EXIT_CONN_STATE_CONNECTING_WAIT;
  246. n_conn->receiver_bucket = -1; /* edge connections don't do receiver buckets */
  247. n_conn->bandwidth = -1;
  248. n_conn->s = -1; /* not yet valid */
  249. if(connection_add(n_conn) < 0) { /* no space, forget it */
  250. log(LOG_DEBUG,"command_process_create_cell(): connection_add failed. Closing.");
  251. connection_free(n_conn);
  252. return -1;
  253. }
  254. circ->n_conn = n_conn;
  255. #endif
  256. }
  257. return 0;
  258. }
  259. /* uses a weighted coin with weight cw to choose a route length */
  260. int chooselen(double cw)
  261. {
  262. int len = 2;
  263. int retval = 0;
  264. unsigned char coin;
  265. if ((cw < 0) || (cw >= 1)) /* invalid parameter */
  266. return -1;
  267. while(1)
  268. {
  269. retval = crypto_pseudo_rand(1, &coin);
  270. if (retval)
  271. return -1;
  272. if (coin > cw*255) /* don't extend */
  273. break;
  274. else
  275. len++;
  276. }
  277. return len;
  278. }
  279. /* returns an array of pointers to routent that define a new route through the OR network
  280. * int cw is the coin weight to use when choosing the route
  281. * order of routers is from last to first
  282. */
  283. unsigned int *new_route(double cw, routerinfo_t **rarray, int rarray_len, int *routelen)
  284. {
  285. int i;
  286. int num_acceptable_routers;
  287. unsigned int *route;
  288. unsigned int oldchoice, choice;
  289. assert((cw >= 0) && (cw < 1) && (rarray) && (routelen) ); /* valid parameters */
  290. *routelen = chooselen(cw);
  291. if (*routelen == -1) {
  292. log(LOG_ERR,"Choosing route length failed.");
  293. return NULL;
  294. }
  295. log(LOG_DEBUG,"new_route(): Chosen route length %d.",*routelen);
  296. num_acceptable_routers = count_acceptable_routers(rarray, rarray_len);
  297. if(num_acceptable_routers < 2) {
  298. log(LOG_INFO,"new_route(): Not enough acceptable routers. Failing.");
  299. return NULL;
  300. }
  301. if(num_acceptable_routers < *routelen) {
  302. log(LOG_DEBUG,"new_route(): Cutting routelen from %d to %d.",*routelen, num_acceptable_routers);
  303. *routelen = num_acceptable_routers;
  304. }
  305. if(*routelen < 1) {
  306. log(LOG_ERR,"new_route(): Didn't find any acceptable routers. Failing.");
  307. return NULL;
  308. }
  309. /* allocate memory for the new route */
  310. route = (unsigned int *)malloc(*routelen * sizeof(unsigned int));
  311. if (!route) {
  312. log(LOG_ERR,"Memory allocation failed.");
  313. return NULL;
  314. }
  315. oldchoice = rarray_len;
  316. for(i=0;i<*routelen;i++) {
  317. log(LOG_DEBUG,"new_route(): Choosing hop %u.",i);
  318. if(crypto_pseudo_rand(sizeof(unsigned int),(unsigned char *)&choice)) {
  319. free((void *)route);
  320. return NULL;
  321. }
  322. choice = choice % (rarray_len);
  323. log(LOG_DEBUG,"new_route(): Contemplating router %u.",choice);
  324. if(choice == oldchoice ||
  325. (oldchoice < rarray_len && !crypto_pk_cmp_keys(rarray[choice]->pkey, rarray[oldchoice]->pkey)) ||
  326. (options.ORPort && !connection_twin_get_by_addr_port(rarray[choice]->addr, rarray[choice]->or_port))) {
  327. /* Same router as last choice, or router twin,
  328. * or no routers with that key are connected to us.
  329. * Try again. */
  330. log(LOG_DEBUG,"new_route(): Picked a router %d that won't work as next hop.",choice);
  331. i--;
  332. continue;
  333. }
  334. log(LOG_DEBUG,"new_route(): Chosen router %u for hop %u.",choice,i);
  335. oldchoice = choice;
  336. route[i] = choice;
  337. }
  338. return route;
  339. }
  340. static int count_acceptable_routers(routerinfo_t **rarray, int rarray_len) {
  341. int i, j;
  342. int num=0;
  343. connection_t *conn;
  344. for(i=0;i<rarray_len;i++) {
  345. log(LOG_DEBUG,"Contemplating whether router %d is a new option...",i);
  346. if(options.ORPort) {
  347. conn = connection_exact_get_by_addr_port(rarray[i]->addr, rarray[i]->or_port);
  348. if(!conn || conn->type != CONN_TYPE_OR || conn->state != OR_CONN_STATE_OPEN) {
  349. log(LOG_DEBUG,"Nope, %d is not connected.",i);
  350. goto next_i_loop;
  351. }
  352. }
  353. for(j=0;j<i;j++) {
  354. if(!crypto_pk_cmp_keys(rarray[i]->pkey, rarray[j]->pkey)) {
  355. /* these guys are twins. so we've already counted him. */
  356. log(LOG_DEBUG,"Nope, %d is a twin of %d.",i,j);
  357. goto next_i_loop;
  358. }
  359. }
  360. num++;
  361. log(LOG_DEBUG,"I like %d. num_acceptable_routers now %d.",i, num);
  362. next_i_loop:
  363. ; /* our compiler may need an explicit statement after the label */
  364. }
  365. return num;
  366. }
  367. /* creates a new onion from route, stores it and its length into buf and len respectively */
  368. unsigned char *create_onion(routerinfo_t **rarray, int rarray_len, unsigned int *route, int routelen, int *len, crypt_path_t **cpath)
  369. {
  370. int i,j;
  371. char *layerp;
  372. crypt_path_t *hop = NULL;
  373. unsigned char *buf;
  374. routerinfo_t *router;
  375. unsigned char iv[16];
  376. struct in_addr netaddr;
  377. onion_layer_t layer;
  378. assert(rarray && route && len && routelen);
  379. /* calculate the size of the onion */
  380. *len = routelen * ONION_LAYER_SIZE + ONION_PADDING_SIZE;
  381. /* 28 bytes per layer + 100 bytes padding for the innermost layer */
  382. log(LOG_DEBUG,"create_onion() : Size of the onion is %u.",*len);
  383. /* allocate memory for the onion */
  384. buf = malloc(*len);
  385. if(!buf) {
  386. log(LOG_ERR,"Error allocating memory.");
  387. return NULL;
  388. }
  389. log(LOG_DEBUG,"create_onion() : Allocated memory for the onion.");
  390. for(i=0; i<routelen; i++) {
  391. netaddr.s_addr = htonl((rarray[route[i]])->addr);
  392. log(LOG_DEBUG,"create_onion(): %u : %s:%u, %u/%u",routelen-i,
  393. inet_ntoa(netaddr),
  394. (rarray[route[i]])->or_port,
  395. (rarray[route[i]])->pkey,
  396. crypto_pk_keysize((rarray[route[i]])->pkey));
  397. }
  398. layerp = buf + *len - ONION_LAYER_SIZE - ONION_PADDING_SIZE; /* pointer to innermost layer */
  399. /* create the onion layer by layer, starting with the innermost */
  400. for (i=0;i<routelen;i++) {
  401. router = rarray[route[i]];
  402. // log(LOG_DEBUG,"create_onion() : %u",router);
  403. // log(LOG_DEBUG,"create_onion() : This router is %s:%u",inet_ntoa(*((struct in_addr *)&router->addr)),router->or_port);
  404. // log(LOG_DEBUG,"create_onion() : Key pointer = %u.",router->pkey);
  405. // log(LOG_DEBUG,"create_onion() : Key size = %u.",crypto_pk_keysize(router->pkey));
  406. layer.version = OR_VERSION;
  407. if (i) /* not last hop */
  408. layer.port = rarray[route[i-1]]->or_port;
  409. else
  410. layer.port = 0;
  411. /* Dest Addr */
  412. if (i) /* not last hop */
  413. layer.addr = rarray[route[i-1]]->addr;
  414. else
  415. layer.addr = 0;
  416. /* Expiration Time */
  417. layer.expire = (uint32_t)(time(NULL) + 86400); /* NOW + 1 day */
  418. /* Key Seed Material */
  419. if(crypto_rand(ONION_KEYSEED_LEN, layer.keyseed)) { /* error */
  420. log(LOG_ERR,"Error generating random data.");
  421. goto error;
  422. }
  423. onion_pack(layerp, &layer);
  424. // 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);
  425. /* build up the crypt_path */
  426. if(cpath) {
  427. cpath[i] = (crypt_path_t *)malloc(sizeof(crypt_path_t));
  428. if(!cpath[i]) {
  429. log(LOG_ERR,"Error allocating memory.");
  430. goto error;
  431. }
  432. log(LOG_DEBUG,"create_onion() : Building hop %u of crypt path.",i+1);
  433. hop = cpath[i];
  434. /* calculate keys */
  435. crypto_SHA_digest(layer.keyseed,16,hop->digest3);
  436. log(LOG_DEBUG,"create_onion() : First SHA pass performed.");
  437. crypto_SHA_digest(hop->digest3,20,hop->digest2);
  438. log(LOG_DEBUG,"create_onion() : Second SHA pass performed.");
  439. crypto_SHA_digest(hop->digest2,20,hop->digest3);
  440. log(LOG_DEBUG,"create_onion() : Third SHA pass performed.");
  441. log(LOG_DEBUG,"create_onion() : Keys generated.");
  442. /* set IV to zero */
  443. memset((void *)iv,0,16);
  444. /* initialize cipher engines */
  445. if (! (hop->f_crypto =
  446. crypto_create_init_cipher(DEFAULT_CIPHER, hop->digest3, iv, 1))) {
  447. /* cipher initialization failed */
  448. log(LOG_ERR,"Could not create a crypto environment.");
  449. goto error;
  450. }
  451. if (! (hop->b_crypto =
  452. crypto_create_init_cipher(DEFAULT_CIPHER, hop->digest2, iv, 0))) {
  453. /* cipher initialization failed */
  454. log(LOG_ERR,"Could not create a crypto environment.");
  455. goto error;
  456. }
  457. log(LOG_DEBUG,"create_onion() : Built corresponding crypt path hop.");
  458. }
  459. /* padding if this is the innermost layer */
  460. if (!i) {
  461. if (crypto_pseudo_rand(ONION_PADDING_SIZE, layerp + ONION_LAYER_SIZE)) { /* error */
  462. log(LOG_ERR,"Error generating pseudo-random data.");
  463. goto error;
  464. }
  465. log(LOG_DEBUG,"create_onion() : This is the innermost layer. Adding 100 bytes of padding.");
  466. }
  467. /* encrypt */
  468. if(encrypt_onion(layerp,ONION_PADDING_SIZE+(i+1)*ONION_LAYER_SIZE,router->pkey,layer.keyseed) < 0) {
  469. log(LOG_ERR,"Error encrypting onion layer.");
  470. goto error;
  471. }
  472. log(LOG_DEBUG,"create_onion() : Encrypted layer.");
  473. /* calculate pointer to next layer */
  474. layerp = buf + (routelen-i-2)*ONION_LAYER_SIZE;
  475. }
  476. return buf;
  477. error:
  478. if (buf)
  479. free(buf);
  480. if (cpath) {
  481. for (j=0;j<i;j++) {
  482. if(cpath[i]->f_crypto)
  483. crypto_free_cipher_env(cpath[i]->f_crypto);
  484. if(cpath[i]->b_crypto)
  485. crypto_free_cipher_env(cpath[i]->b_crypto);
  486. free((void *)cpath[i]);
  487. }
  488. }
  489. return NULL;
  490. }
  491. /* encrypts 128 bytes of the onion with the specified public key, the rest with
  492. * DES OFB with the key as defined in the outter layer */
  493. int encrypt_onion(unsigned char *onion, uint32_t onionlen, crypto_pk_env_t *pkey, char* keyseed) {
  494. unsigned char *tmpbuf = NULL; /* temporary buffer for crypto operations */
  495. unsigned char digest[20]; /* stores SHA1 output - 160 bits */
  496. unsigned char iv[8];
  497. crypto_cipher_env_t *crypt_env = NULL; /* crypto environment */
  498. assert(onion && pkey);
  499. assert(onionlen >= 128);
  500. memset(iv,0,8);
  501. // 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);
  502. /* allocate space for tmpbuf */
  503. tmpbuf = (unsigned char *)malloc(onionlen);
  504. if(!tmpbuf) {
  505. log(LOG_ERR,"Could not allocate memory.");
  506. return -1;
  507. }
  508. log(LOG_DEBUG,"encrypt_onion() : allocated %u bytes of memory for the encrypted onion (at %u).",onionlen,tmpbuf);
  509. /* get key1 = SHA1(KeySeed) */
  510. if (crypto_SHA_digest(keyseed,16,digest)) {
  511. log(LOG_ERR,"Error computing SHA1 digest.");
  512. goto error;
  513. }
  514. log(LOG_DEBUG,"encrypt_onion() : Computed DES key.");
  515. log(LOG_DEBUG,"encrypt_onion() : Trying to RSA encrypt.");
  516. /* encrypt 128 bytes with RSA *pkey */
  517. if (crypto_pk_public_encrypt(pkey, onion, 128, tmpbuf, RSA_NO_PADDING) == -1) {
  518. log(LOG_ERR,"Error RSA-encrypting data :%s",crypto_perror());
  519. goto error;
  520. }
  521. log(LOG_DEBUG,"encrypt_onion() : RSA encrypted first 128 bytes of the onion.");
  522. /* now encrypt the rest with 3DES OFB */
  523. crypt_env = crypto_create_init_cipher(CRYPTO_CIPHER_3DES, digest, iv, 1);
  524. if (!crypt_env) {
  525. log(LOG_ERR,"Error creating the crypto environment.");
  526. goto error;
  527. }
  528. if (crypto_cipher_encrypt(crypt_env,onion+128, onionlen-128, (unsigned char *)tmpbuf+128)) { /* error */
  529. log(LOG_ERR,"Error performing DES encryption:%s",crypto_perror());
  530. goto error;
  531. }
  532. log(LOG_DEBUG,"encrypt_onion() : 3DES OFB encrypted the rest of the onion.");
  533. /* now copy tmpbuf to onion */
  534. memcpy(onion,tmpbuf,onionlen);
  535. log(LOG_DEBUG,"encrypt_onion() : Copied cipher to original onion buffer.");
  536. free(tmpbuf);
  537. crypto_free_cipher_env(crypt_env);
  538. return 0;
  539. error:
  540. if (tmpbuf)
  541. free(tmpbuf);
  542. if (crypt_env)
  543. crypto_free_cipher_env(crypt_env);
  544. return -1;
  545. }
  546. /* decrypts the first 128 bytes using RSA and prkey, decrypts the rest with DES OFB with key1 */
  547. int decrypt_onion(unsigned char *onion, uint32_t onionlen, crypto_pk_env_t *prkey, onion_layer_t *layer) {
  548. void *tmpbuf = NULL; /* temporary buffer for crypto operations */
  549. unsigned char digest[20]; /* stores SHA1 output - 160 bits */
  550. unsigned char iv[8];
  551. crypto_cipher_env_t *crypt_env =NULL; /* crypto environment */
  552. assert(onion && prkey);
  553. memset(iv,0,8);
  554. /* allocate space for tmpbuf */
  555. tmpbuf = malloc(onionlen);
  556. if (!tmpbuf) {
  557. log(LOG_ERR,"Could not allocate memory.");
  558. return -1;
  559. }
  560. log(LOG_DEBUG,"decrypt_onion() : Allocated memory for the temporary buffer.");
  561. /* decrypt 128 bytes with RSA *prkey */
  562. if (crypto_pk_private_decrypt(prkey, onion, 128, tmpbuf, RSA_NO_PADDING) == -1)
  563. {
  564. log(LOG_ERR,"Error RSA-decrypting data :%s",crypto_perror());
  565. goto error;
  566. }
  567. log(LOG_DEBUG,"decrypt_onion() : RSA decryption complete.");
  568. onion_unpack(layer, tmpbuf);
  569. /* get key1 = SHA1(KeySeed) */
  570. if (crypto_SHA_digest(layer->keyseed,16,digest)) {
  571. log(LOG_ERR,"Error computing SHA1 digest.");
  572. goto error;
  573. }
  574. log(LOG_DEBUG,"decrypt_onion() : Computed DES key.");
  575. /* now decrypt the rest with 3DES OFB */
  576. crypt_env = crypto_create_init_cipher(CRYPTO_CIPHER_3DES, digest, iv, 0);
  577. if (!crypt_env) {
  578. log(LOG_ERR,"Error creating crypto environment");
  579. goto error;
  580. }
  581. if (crypto_cipher_decrypt(crypt_env,onion+128, onionlen-128,tmpbuf+128)) {
  582. log(LOG_ERR,"Error performing DES decryption:%s",crypto_perror());
  583. goto error;
  584. }
  585. log(LOG_DEBUG,"decrypt_onion() : DES decryption complete.");
  586. /* now copy tmpbuf to onion */
  587. memcpy(onion,tmpbuf,onionlen);
  588. free(tmpbuf);
  589. crypto_free_cipher_env(crypt_env);
  590. return 0;
  591. error:
  592. if (tmpbuf)
  593. free(tmpbuf);
  594. if (crypt_env)
  595. crypto_free_cipher_env(crypt_env);
  596. return -1;
  597. }
  598. /* delete first n bytes of the onion and pads the end with n bytes of random data */
  599. void pad_onion(unsigned char *onion, uint32_t onionlen, int n)
  600. {
  601. assert(onion);
  602. memmove(onion,onion+n,onionlen-n);
  603. crypto_pseudo_rand(n, onion+onionlen-n);
  604. }
  605. /* red black tree using Niels' tree.h. I used
  606. http://www.openbsd.org/cgi-bin/cvsweb/src/regress/sys/sys/tree/rb/
  607. as my guide */
  608. #include "tree.h"
  609. struct tracked_onion {
  610. RB_ENTRY(tracked_onion) node;
  611. uint32_t expire;
  612. char digest[20]; /* SHA digest of the onion */
  613. struct tracked_onion *next;
  614. };
  615. RB_HEAD(tracked_tree, tracked_onion) tracked_root;
  616. int compare_tracked_onions(struct tracked_onion *a, struct tracked_onion *b) {
  617. return memcmp(a->digest, b->digest, 20);
  618. }
  619. RB_PROTOTYPE(tracked_tree, tracked_onion, node, compare_tracked_onions)
  620. RB_GENERATE(tracked_tree, tracked_onion, node, compare_tracked_onions)
  621. void init_tracked_tree(void) {
  622. RB_INIT(&tracked_root);
  623. }
  624. /* see if this onion has been seen before. if so, return 1, else
  625. * return 0 and add the sha1 of this onion to the tree.
  626. */
  627. static int find_tracked_onion(unsigned char *onion, uint32_t onionlen) {
  628. static struct tracked_onion *head_tracked_onions = NULL; /* linked list of tracked onions */
  629. static struct tracked_onion *tail_tracked_onions = NULL;
  630. uint32_t now = time(NULL);
  631. struct tracked_onion *to;
  632. /* first take this opportunity to see if there are any expired
  633. * onions in the tree. we know this is fast because the linked list
  634. * 'tracked_onions' is ordered by when they were seen.
  635. */
  636. while(head_tracked_onions && (head_tracked_onions->expire < now)) {
  637. to = head_tracked_onions;
  638. log(LOG_DEBUG,"find_tracked_onion(): Forgetting old onion (expires %d)", to->expire);
  639. head_tracked_onions = to->next;
  640. if(!head_tracked_onions) /* if there are no more, */
  641. tail_tracked_onions = NULL; /* then make sure the list's tail knows that too */
  642. RB_REMOVE(tracked_tree, &tracked_root, to);
  643. free(to);
  644. }
  645. to = malloc(sizeof(struct tracked_onion));
  646. /* compute the SHA digest of the onion */
  647. crypto_SHA_digest(onion, onionlen, to->digest);
  648. /* try adding it to the tree. if it's already there it will return it. */
  649. if(RB_INSERT(tracked_tree, &tracked_root, to)) {
  650. /* yes, it's already there: this is a replay. */
  651. free(to);
  652. return 1;
  653. }
  654. /* this is a new onion. add it to the list. */
  655. to->expire = ntohl(*(uint32_t *)(onion+7)); /* set the expiration date */
  656. to->next = NULL;
  657. if (!head_tracked_onions) {
  658. head_tracked_onions = to;
  659. } else {
  660. tail_tracked_onions->next = to;
  661. }
  662. tail_tracked_onions = to;
  663. log(LOG_DEBUG,"find_tracked_onion(): Remembered new onion (expires %d)", to->expire);
  664. return 0;
  665. }
  666. void
  667. onion_pack(char *dest, onion_layer_t *src)
  668. {
  669. assert((src->version & 0x80) == 0);
  670. *(uint8_t*)(dest) = src->version;
  671. *(uint16_t*)(dest+1) = htons(src->port);
  672. *(uint32_t*)(dest+3) = htonl(src->addr);
  673. *(uint32_t*)(dest+7) = htonl(src->expire);
  674. memcpy(dest+11, src->keyseed, ONION_KEYSEED_LEN);
  675. log(LOG_DEBUG,"onion_pack(): version %d, port %d, addr %s, expire %u", src->version, src->port,
  676. inet_ntoa(*((struct in_addr *)(dest+3))), src->expire);
  677. }
  678. void
  679. onion_unpack(onion_layer_t *dest, char *src)
  680. {
  681. dest->version = *(uint8_t*)src;
  682. dest->port = ntohs(*(uint16_t*)(src+1));
  683. dest->addr = ntohl(*(uint32_t*)(src+3));
  684. dest->expire = ntohl(*(uint32_t*)(src+7));
  685. memcpy(dest->keyseed, src+11, ONION_KEYSEED_LEN);
  686. log(LOG_DEBUG,"onion_unpack(): version %d, port %d, addr %s, expire %u", dest->version, dest->port,
  687. inet_ntoa(*((struct in_addr *)(src+3))), dest->expire);
  688. }
  689. /*
  690. Local Variables:
  691. mode:c
  692. indent-tabs-mode:nil
  693. c-basic-offset:2
  694. End:
  695. */