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