onion.c 25 KB

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