protocol_auth.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. /*
  2. protocol_auth.c -- handle the meta-protocol, authentication
  3. Copyright (C) 1999-2005 Ivo Timmermans,
  4. 2000-2016 Guus Sliepen <guus@tinc-vpn.org>
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License along
  14. with this program; if not, write to the Free Software Foundation, Inc.,
  15. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. */
  17. #include "system.h"
  18. #include <openssl/sha.h>
  19. #include <openssl/rand.h>
  20. #include <openssl/err.h>
  21. #include <openssl/evp.h>
  22. #include "avl_tree.h"
  23. #include "conf.h"
  24. #include "connection.h"
  25. #include "edge.h"
  26. #include "graph.h"
  27. #include "logger.h"
  28. #include "meta.h"
  29. #include "net.h"
  30. #include "netutl.h"
  31. #include "node.h"
  32. #include "protocol.h"
  33. #include "proxy.h"
  34. #include "utils.h"
  35. #include "xalloc.h"
  36. bool send_id(connection_t *c) {
  37. if(proxytype && c->outgoing && !c->status.proxy_passed) {
  38. return send_proxyrequest(c);
  39. }
  40. return send_request(c, "%d %s %d", ID, myself->connection->name,
  41. myself->connection->protocol_version);
  42. }
  43. bool id_h(connection_t *c) {
  44. char name[MAX_STRING_SIZE];
  45. if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
  46. logger(LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
  47. c->hostname);
  48. return false;
  49. }
  50. /* Check if identity is a valid name */
  51. if(!check_id(name)) {
  52. logger(LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
  53. c->hostname, "invalid name");
  54. return false;
  55. }
  56. /* If this is an outgoing connection, make sure we are connected to the right host */
  57. if(c->outgoing) {
  58. if(strcmp(c->name, name)) {
  59. logger(LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
  60. c->name);
  61. return false;
  62. }
  63. } else {
  64. if(c->name) {
  65. free(c->name);
  66. }
  67. c->name = xstrdup(name);
  68. }
  69. /* Check if version matches */
  70. if(c->protocol_version != myself->connection->protocol_version) {
  71. logger(LOG_ERR, "Peer %s (%s) uses incompatible version %d",
  72. c->name, c->hostname, c->protocol_version);
  73. return false;
  74. }
  75. if(bypass_security) {
  76. if(!c->config_tree) {
  77. init_configuration(&c->config_tree);
  78. }
  79. c->allow_request = ACK;
  80. return send_ack(c);
  81. }
  82. if(!c->config_tree) {
  83. init_configuration(&c->config_tree);
  84. if(!read_connection_config(c)) {
  85. logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
  86. c->name);
  87. return false;
  88. }
  89. }
  90. if(!read_rsa_public_key(c)) {
  91. return false;
  92. }
  93. c->allow_request = METAKEY;
  94. return send_metakey(c);
  95. }
  96. static uint64_t byte_budget(const EVP_CIPHER *cipher) {
  97. /* Hopefully some failsafe way to calculate the maximum amount of bytes to
  98. send/receive with a given cipher before we might run into birthday paradox
  99. attacks. Because we might use different modes, the block size of the mode
  100. might be 1 byte. In that case, use the IV length. Ensure the whole thing
  101. is limited to what can be represented with a 64 bits integer.
  102. */
  103. int ivlen = EVP_CIPHER_iv_length(cipher);
  104. int blklen = EVP_CIPHER_block_size(cipher);
  105. int len = blklen > 1 ? blklen : ivlen > 1 ? ivlen : 8;
  106. int bits = len * 4 - 1;
  107. return bits < 64 ? UINT64_C(1) << bits : UINT64_MAX;
  108. }
  109. bool send_metakey(connection_t *c) {
  110. bool x;
  111. int len = RSA_size(c->rsa_key);
  112. /* Allocate buffers for the meta key */
  113. char buffer[2 * len + 1];
  114. c->outkey = xrealloc(c->outkey, len);
  115. if(!c->outctx) {
  116. c->outctx = EVP_CIPHER_CTX_new();
  117. if(!c->outctx) {
  118. abort();
  119. }
  120. }
  121. /* Copy random data to the buffer */
  122. if(1 != RAND_bytes((unsigned char *)c->outkey, len)) {
  123. int err = ERR_get_error();
  124. logger(LOG_ERR, "Failed to generate meta key (%s)", ERR_error_string(err, NULL));
  125. return false;
  126. }
  127. /* The message we send must be smaller than the modulus of the RSA key.
  128. By definition, for a key of k bits, the following formula holds:
  129. 2^(k-1) <= modulus < 2^(k)
  130. Where ^ means "to the power of", not "xor".
  131. This means that to be sure, we must choose our message < 2^(k-1).
  132. This can be done by setting the most significant bit to zero.
  133. */
  134. c->outkey[0] &= 0x7F;
  135. ifdebug(SCARY_THINGS) {
  136. bin2hex(c->outkey, buffer, len);
  137. buffer[len * 2] = '\0';
  138. logger(LOG_DEBUG, "Generated random meta key (unencrypted): %s",
  139. buffer);
  140. }
  141. /* Encrypt the random data
  142. We do not use one of the PKCS padding schemes here.
  143. This is allowed, because we encrypt a totally random string
  144. with a length equal to that of the modulus of the RSA key.
  145. */
  146. if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) {
  147. logger(LOG_ERR, "Error during encryption of meta key for %s (%s): %s",
  148. c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
  149. return false;
  150. }
  151. /* Convert the encrypted random data to a hexadecimal formatted string */
  152. bin2hex(buffer, buffer, len);
  153. buffer[len * 2] = '\0';
  154. /* Send the meta key */
  155. x = send_request(c, "%d %d %d %d %d %s", METAKEY,
  156. c->outcipher ? EVP_CIPHER_nid(c->outcipher) : 0,
  157. c->outdigest ? EVP_MD_type(c->outdigest) : 0, c->outmaclength,
  158. c->outcompression, buffer);
  159. /* Further outgoing requests are encrypted with the key we just generated */
  160. if(c->outcipher) {
  161. if(!EVP_EncryptInit(c->outctx, c->outcipher,
  162. (unsigned char *)c->outkey + len - EVP_CIPHER_key_length(c->outcipher),
  163. (unsigned char *)c->outkey + len - EVP_CIPHER_key_length(c->outcipher) -
  164. EVP_CIPHER_iv_length(c->outcipher))) {
  165. logger(LOG_ERR, "Error during initialisation of cipher for %s (%s): %s",
  166. c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
  167. return false;
  168. }
  169. c->outbudget = byte_budget(c->outcipher);
  170. c->status.encryptout = true;
  171. }
  172. return x;
  173. }
  174. bool metakey_h(connection_t *c) {
  175. char buffer[MAX_STRING_SIZE];
  176. int cipher, digest, maclength, compression;
  177. int len;
  178. if(sscanf(c->buffer, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5) {
  179. logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name,
  180. c->hostname);
  181. return false;
  182. }
  183. len = RSA_size(myself->connection->rsa_key);
  184. /* Check if the length of the meta key is all right */
  185. if(strlen(buffer) != (size_t)len * 2) {
  186. logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
  187. return false;
  188. }
  189. /* Allocate buffers for the meta key */
  190. c->inkey = xrealloc(c->inkey, len);
  191. if(!c->inctx) {
  192. c->inctx = EVP_CIPHER_CTX_new();
  193. if(!c->inctx) {
  194. abort();
  195. }
  196. }
  197. /* Convert the challenge from hexadecimal back to binary */
  198. if(!hex2bin(buffer, buffer, len)) {
  199. logger(LOG_ERR, "Got bad %s from %s(%s): %s", "METAKEY", c->name, c->hostname, "invalid key");
  200. return false;
  201. }
  202. /* Decrypt the meta key */
  203. if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */
  204. logger(LOG_ERR, "Error during decryption of meta key for %s (%s): %s",
  205. c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
  206. return false;
  207. }
  208. ifdebug(SCARY_THINGS) {
  209. bin2hex(c->inkey, buffer, len);
  210. buffer[len * 2] = '\0';
  211. logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", buffer);
  212. }
  213. /* All incoming requests will now be encrypted. */
  214. /* Check and lookup cipher and digest algorithms */
  215. if(cipher) {
  216. c->incipher = EVP_get_cipherbynid(cipher);
  217. if(!c->incipher) {
  218. logger(LOG_ERR, "%s (%s) uses unknown cipher!", c->name, c->hostname);
  219. return false;
  220. }
  221. if(!EVP_DecryptInit(c->inctx, c->incipher,
  222. (unsigned char *)c->inkey + len - EVP_CIPHER_key_length(c->incipher),
  223. (unsigned char *)c->inkey + len - EVP_CIPHER_key_length(c->incipher) -
  224. EVP_CIPHER_iv_length(c->incipher))) {
  225. logger(LOG_ERR, "Error during initialisation of cipher from %s (%s): %s",
  226. c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
  227. return false;
  228. }
  229. c->inbudget = byte_budget(c->incipher);
  230. c->status.decryptin = true;
  231. } else {
  232. c->incipher = NULL;
  233. }
  234. c->inmaclength = maclength;
  235. if(digest) {
  236. c->indigest = EVP_get_digestbynid(digest);
  237. if(!c->indigest) {
  238. logger(LOG_ERR, "Node %s (%s) uses unknown digest!", c->name, c->hostname);
  239. return false;
  240. }
  241. if(c->inmaclength > EVP_MD_size(c->indigest) || c->inmaclength < 0) {
  242. logger(LOG_ERR, "%s (%s) uses bogus MAC length!", c->name, c->hostname);
  243. return false;
  244. }
  245. } else {
  246. c->indigest = NULL;
  247. }
  248. c->incompression = compression;
  249. c->allow_request = CHALLENGE;
  250. return send_challenge(c);
  251. }
  252. bool send_challenge(connection_t *c) {
  253. /* CHECKME: what is most reasonable value for len? */
  254. int len = RSA_size(c->rsa_key);
  255. /* Allocate buffers for the challenge */
  256. char buffer[2 * len + 1];
  257. c->hischallenge = xrealloc(c->hischallenge, len);
  258. /* Copy random data to the buffer */
  259. if(1 != RAND_bytes((unsigned char *)c->hischallenge, len)) {
  260. int err = ERR_get_error();
  261. logger(LOG_ERR, "Failed to generate challenge (%s)", ERR_error_string(err, NULL));
  262. return false; // Do not send predictable challenges, let connection attempt fail.
  263. }
  264. /* Convert to hex */
  265. bin2hex(c->hischallenge, buffer, len);
  266. buffer[len * 2] = '\0';
  267. /* Send the challenge */
  268. return send_request(c, "%d %s", CHALLENGE, buffer);
  269. }
  270. bool challenge_h(connection_t *c) {
  271. char buffer[MAX_STRING_SIZE];
  272. int len;
  273. if(sscanf(c->buffer, "%*d " MAX_STRING, buffer) != 1) {
  274. logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name,
  275. c->hostname);
  276. return false;
  277. }
  278. len = RSA_size(myself->connection->rsa_key);
  279. /* Check if the length of the challenge is all right */
  280. if(strlen(buffer) != (size_t)len * 2) {
  281. logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
  282. c->hostname, "wrong challenge length");
  283. return false;
  284. }
  285. /* Allocate buffers for the challenge */
  286. c->mychallenge = xrealloc(c->mychallenge, len);
  287. /* Convert the challenge from hexadecimal back to binary */
  288. if(!hex2bin(buffer, c->mychallenge, len)) {
  289. logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHALLENGE", c->name, c->hostname, "invalid challenge");
  290. return false;
  291. }
  292. c->allow_request = CHAL_REPLY;
  293. /* Rest is done by send_chal_reply() */
  294. return send_chal_reply(c);
  295. }
  296. bool send_chal_reply(connection_t *c) {
  297. char hash[EVP_MAX_MD_SIZE * 2 + 1];
  298. EVP_MD_CTX *ctx;
  299. /* Calculate the hash from the challenge we received */
  300. ctx = EVP_MD_CTX_create();
  301. if(!ctx) {
  302. abort();
  303. }
  304. if(!EVP_DigestInit(ctx, c->indigest)
  305. || !EVP_DigestUpdate(ctx, c->mychallenge, RSA_size(myself->connection->rsa_key))
  306. || !EVP_DigestFinal(ctx, (unsigned char *)hash, NULL)) {
  307. EVP_MD_CTX_destroy(ctx);
  308. logger(LOG_ERR, "Error during calculation of response for %s (%s): %s",
  309. c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
  310. return false;
  311. }
  312. EVP_MD_CTX_destroy(ctx);
  313. /* Convert the hash to a hexadecimal formatted string */
  314. bin2hex(hash, hash, EVP_MD_size(c->indigest));
  315. hash[EVP_MD_size(c->indigest) * 2] = '\0';
  316. /* Send the reply */
  317. return send_request(c, "%d %s", CHAL_REPLY, hash);
  318. }
  319. bool chal_reply_h(connection_t *c) {
  320. char hishash[MAX_STRING_SIZE];
  321. char myhash[EVP_MAX_MD_SIZE];
  322. EVP_MD_CTX *ctx;
  323. if(sscanf(c->buffer, "%*d " MAX_STRING, hishash) != 1) {
  324. logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
  325. c->hostname);
  326. return false;
  327. }
  328. /* Check if the length of the hash is all right */
  329. if(strlen(hishash) != (size_t)EVP_MD_size(c->outdigest) * 2) {
  330. logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
  331. c->hostname, "wrong challenge reply length");
  332. return false;
  333. }
  334. /* Convert the hash to binary format */
  335. if(!hex2bin(hishash, hishash, EVP_MD_size(c->outdigest))) {
  336. logger(LOG_ERR, "Got bad %s from %s(%s): %s", "CHAL_REPLY", c->name, c->hostname, "invalid hash");
  337. return false;
  338. }
  339. /* Calculate the hash from the challenge we sent */
  340. ctx = EVP_MD_CTX_create();
  341. if(!ctx) {
  342. abort();
  343. }
  344. if(!EVP_DigestInit(ctx, c->outdigest)
  345. || !EVP_DigestUpdate(ctx, c->hischallenge, RSA_size(c->rsa_key))
  346. || !EVP_DigestFinal(ctx, (unsigned char *)myhash, NULL)) {
  347. EVP_MD_CTX_destroy(ctx);
  348. logger(LOG_ERR, "Error during calculation of response from %s (%s): %s",
  349. c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
  350. return false;
  351. }
  352. EVP_MD_CTX_destroy(ctx);
  353. /* Verify the incoming hash with the calculated hash */
  354. if(memcmp(hishash, myhash, EVP_MD_size(c->outdigest))) {
  355. logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name,
  356. c->hostname, "wrong challenge reply");
  357. ifdebug(SCARY_THINGS) {
  358. bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
  359. hishash[SHA_DIGEST_LENGTH * 2] = '\0';
  360. logger(LOG_DEBUG, "Expected challenge reply: %s", hishash);
  361. }
  362. return false;
  363. }
  364. /* Identity has now been positively verified.
  365. Send an acknowledgement with the rest of the information needed.
  366. */
  367. c->allow_request = ACK;
  368. return send_ack(c);
  369. }
  370. bool send_ack(connection_t *c) {
  371. /* ACK message contains rest of the information the other end needs
  372. to create node_t and edge_t structures. */
  373. struct timeval now;
  374. bool choice;
  375. /* Estimate weight */
  376. gettimeofday(&now, NULL);
  377. c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
  378. /* Check some options */
  379. if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT) {
  380. c->options |= OPTION_INDIRECT;
  381. }
  382. if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY) {
  383. c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
  384. }
  385. if(myself->options & OPTION_PMTU_DISCOVERY && !(c->options & OPTION_TCPONLY)) {
  386. c->options |= OPTION_PMTU_DISCOVERY;
  387. }
  388. choice = myself->options & OPTION_CLAMP_MSS;
  389. get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
  390. if(choice) {
  391. c->options |= OPTION_CLAMP_MSS;
  392. }
  393. get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
  394. return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
  395. }
  396. static void send_everything(connection_t *c) {
  397. avl_node_t *node, *node2;
  398. node_t *n;
  399. subnet_t *s;
  400. edge_t *e;
  401. /* Send all known subnets and edges */
  402. if(tunnelserver) {
  403. for(node = myself->subnet_tree->head; node; node = node->next) {
  404. s = node->data;
  405. send_add_subnet(c, s);
  406. }
  407. return;
  408. }
  409. for(node = node_tree->head; node; node = node->next) {
  410. n = node->data;
  411. for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
  412. s = node2->data;
  413. send_add_subnet(c, s);
  414. }
  415. for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
  416. e = node2->data;
  417. send_add_edge(c, e);
  418. }
  419. }
  420. }
  421. bool ack_h(connection_t *c) {
  422. char hisport[MAX_STRING_SIZE];
  423. int weight, mtu;
  424. uint32_t options;
  425. node_t *n;
  426. bool choice;
  427. if(sscanf(c->buffer, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
  428. logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
  429. c->hostname);
  430. return false;
  431. }
  432. /* Check if we already have a node_t for him */
  433. n = lookup_node(c->name);
  434. if(!n) {
  435. n = new_node();
  436. n->name = xstrdup(c->name);
  437. node_add(n);
  438. } else {
  439. if(n->connection) {
  440. /* Oh dear, we already have a connection to this node. */
  441. ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection",
  442. n->name, n->hostname);
  443. terminate_connection(n->connection, false);
  444. /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
  445. graph();
  446. }
  447. }
  448. n->connection = c;
  449. c->node = n;
  450. if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
  451. c->options &= ~OPTION_PMTU_DISCOVERY;
  452. options &= ~OPTION_PMTU_DISCOVERY;
  453. }
  454. c->options |= options;
  455. if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
  456. n->mtu = mtu;
  457. }
  458. if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
  459. n->mtu = mtu;
  460. }
  461. if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
  462. if(choice) {
  463. c->options |= OPTION_CLAMP_MSS;
  464. } else {
  465. c->options &= ~OPTION_CLAMP_MSS;
  466. }
  467. }
  468. /* Activate this connection */
  469. c->allow_request = ALL;
  470. c->status.active = true;
  471. ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
  472. c->hostname);
  473. /* Send him everything we know */
  474. send_everything(c);
  475. /* Create an edge_t for this connection */
  476. c->edge = new_edge();
  477. c->edge->from = myself;
  478. c->edge->to = n;
  479. sockaddrcpy(&c->edge->address, &c->address);
  480. sockaddr_setport(&c->edge->address, hisport);
  481. c->edge->weight = (weight + c->estimated_weight) / 2;
  482. c->edge->connection = c;
  483. c->edge->options = c->options;
  484. edge_add(c->edge);
  485. /* Notify everyone of the new edge */
  486. if(tunnelserver) {
  487. send_add_edge(c, c->edge);
  488. } else {
  489. send_add_edge(everyone, c->edge);
  490. }
  491. /* Run MST and SSSP algorithms */
  492. graph();
  493. return true;
  494. }