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