Fix compiler warnings.
[tinc] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2010 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 along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include "splay_tree.h"
24 #include "conf.h"
25 #include "connection.h"
26 #include "control.h"
27 #include "control_common.h"
28 #include "cipher.h"
29 #include "crypto.h"
30 #include "digest.h"
31 #include "edge.h"
32 #include "graph.h"
33 #include "logger.h"
34 #include "net.h"
35 #include "netutl.h"
36 #include "node.h"
37 #include "prf.h"
38 #include "protocol.h"
39 #include "rsa.h"
40 #include "utils.h"
41 #include "xalloc.h"
42
43 bool send_id(connection_t *c) {
44         gettimeofday(&c->start, NULL);
45
46         int minor = 0;
47
48         if(experimental) {
49                 if(c->config_tree && !read_ecdsa_public_key(c))
50                         minor = 1;
51                 else
52                         minor = myself->connection->protocol_minor;
53         }
54
55         return send_request(c, "%d %s %d.%d", ID, myself->connection->name, myself->connection->protocol_major, minor);
56 }
57
58 bool id_h(connection_t *c, char *request) {
59         char name[MAX_STRING_SIZE];
60
61         if(sscanf(request, "%*d " MAX_STRING " %d.%d", name, &c->protocol_major, &c->protocol_minor) < 2) {
62                 logger(LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
63                            c->hostname);
64                 return false;
65         }
66
67         /* Check if this is a control connection */
68
69         if(name[0] == '^' && !strcmp(name + 1, controlcookie)) {
70                 c->status.control = true;
71                 c->allow_request = CONTROL;
72                 c->last_ping_time = time(NULL) + 3600;
73                 return send_request(c, "%d %d %d", ACK, TINC_CTL_VERSION_CURRENT, getpid());
74         }
75
76         /* Check if identity is a valid name */
77
78         if(!check_id(name)) {
79                 logger(LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
80                            c->hostname, "invalid name");
81                 return false;
82         }
83
84         /* If this is an outgoing connection, make sure we are connected to the right host */
85
86         if(c->outgoing) {
87                 if(strcmp(c->name, name)) {
88                         logger(LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
89                                    c->name);
90                         return false;
91                 }
92         } else {
93                 if(c->name)
94                         free(c->name);
95                 c->name = xstrdup(name);
96         }
97
98         /* Check if version matches */
99
100         if(c->protocol_major != myself->connection->protocol_major) {
101                 logger(LOG_ERR, "Peer %s (%s) uses incompatible version %d.%d",
102                            c->name, c->hostname, c->protocol_major, c->protocol_minor);
103                 return false;
104         }
105
106         if(bypass_security) {
107                 if(!c->config_tree)
108                         init_configuration(&c->config_tree);
109                 c->allow_request = ACK;
110                 return send_ack(c);
111         }
112
113         if(!c->config_tree) {
114                 init_configuration(&c->config_tree);
115
116                 if(!read_connection_config(c)) {
117                         logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
118                                    c->name);
119                         return false;
120                 }
121
122                 if(experimental && c->protocol_minor >= 2)
123                         if(!read_ecdsa_public_key(c))
124                                 return false;
125         } else {
126                 if(!ecdsa_active(&c->ecdsa))
127                         c->protocol_minor = 1;
128         }
129
130         if(!experimental)
131                 c->protocol_minor = 0;
132
133         c->allow_request = METAKEY;
134
135         if(c->protocol_minor >= 2)
136                 return send_metakey_ec(c);
137         else
138                 return send_metakey(c);
139 }
140
141 bool send_metakey_ec(connection_t *c) {
142         logger(LOG_DEBUG, "Sending ECDH metakey to %s", c->name);
143
144         size_t siglen = ecdsa_size(&myself->connection->ecdsa);
145
146         char key[(ECDH_SIZE + siglen) * 2 + 1];
147
148         // TODO: include nonce? Use relevant parts of SSH or TLS protocol
149
150         if(!ecdh_generate_public(&c->ecdh, key))
151                 return false;
152
153         if(!ecdsa_sign(&myself->connection->ecdsa, key, ECDH_SIZE, key + ECDH_SIZE))
154                 return false;
155
156         b64encode(key, key, ECDH_SIZE + siglen);
157         
158         return send_request(c, "%d %s", METAKEY, key);
159 }
160
161 bool send_metakey(connection_t *c) {
162         if(!read_rsa_public_key(c))
163                 return false;
164
165         if(!cipher_open_blowfish_ofb(&c->outcipher))
166                 return false;
167         
168         if(!digest_open_sha1(&c->outdigest, -1))
169                 return false;
170
171         size_t len = rsa_size(&c->rsa);
172         char key[len];
173         char enckey[len];
174         char hexkey[2 * len + 1];
175
176         /* Create a random key */
177
178         randomize(key, len);
179
180         /* The message we send must be smaller than the modulus of the RSA key.
181            By definition, for a key of k bits, the following formula holds:
182
183            2^(k-1) <= modulus < 2^(k)
184
185            Where ^ means "to the power of", not "xor".
186            This means that to be sure, we must choose our message < 2^(k-1).
187            This can be done by setting the most significant bit to zero.
188          */
189
190         key[0] &= 0x7F;
191
192         cipher_set_key_from_rsa(&c->outcipher, key, len, true);
193
194         ifdebug(SCARY_THINGS) {
195                 bin2hex(key, hexkey, len);
196                 logger(LOG_DEBUG, "Generated random meta key (unencrypted): %s", hexkey);
197         }
198
199         /* Encrypt the random data
200
201            We do not use one of the PKCS padding schemes here.
202            This is allowed, because we encrypt a totally random string
203            with a length equal to that of the modulus of the RSA key.
204          */
205
206         if(!rsa_public_encrypt(&c->rsa, key, len, enckey)) {
207                 logger(LOG_ERR, "Error during encryption of meta key for %s (%s)", c->name, c->hostname);
208                 return false;
209         }
210
211         /* Convert the encrypted random data to a hexadecimal formatted string */
212
213         bin2hex(enckey, hexkey, len);
214
215         /* Send the meta key */
216
217         bool result = send_request(c, "%d %d %d %d %d %s", METAKEY,
218                          cipher_get_nid(&c->outcipher),
219                          digest_get_nid(&c->outdigest), c->outmaclength,
220                          c->outcompression, hexkey);
221         
222         c->status.encryptout = true;
223         return result;
224 }
225
226 static bool metakey_ec_h(connection_t *c, const char *request) {
227         size_t siglen = ecdsa_size(&c->ecdsa);
228         char key[MAX_STRING_SIZE];
229         char sig[siglen];
230
231         logger(LOG_DEBUG, "Got ECDH metakey from %s", c->name);
232
233         if(sscanf(request, "%*d " MAX_STRING, key) != 1) {
234                 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
235                 return false;
236         }
237
238         int inlen = b64decode(key, key, sizeof key);
239
240         if(inlen != (ECDH_SIZE + siglen)) {
241                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
242                 return false;
243         }
244
245         if(!ecdsa_verify(&c->ecdsa, key, ECDH_SIZE, key + ECDH_SIZE)) {
246                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "invalid ECDSA signature");
247                 return false;
248         }
249
250         char shared[ECDH_SHARED_SIZE];
251
252         if(!ecdh_compute_shared(&c->ecdh, key, shared))
253                 return false;
254
255         /* Update our crypto end */
256
257         if(!cipher_open_by_name(&c->incipher, "aes-256-ofb"))
258                 return false;
259         if(!digest_open_by_name(&c->indigest, "sha512", -1))
260                 return false;
261         if(!cipher_open_by_name(&c->outcipher, "aes-256-ofb"))
262                 return false;
263         if(!digest_open_by_name(&c->outdigest, "sha512", -1))
264                 return false;
265
266         size_t mykeylen = cipher_keylength(&c->incipher);
267         size_t hiskeylen = cipher_keylength(&c->outcipher);
268
269         char *mykey;
270         char *hiskey;
271         char *seed;
272         
273         if(strcmp(myself->name, c->name) < 0) {
274                 mykey = key;
275                 hiskey = key + mykeylen * 2;
276                 xasprintf(&seed, "tinc TCP key expansion %s %s", myself->name, c->name);
277         } else {
278                 mykey = key + hiskeylen * 2;
279                 hiskey = key;
280                 xasprintf(&seed, "tinc TCP key expansion %s %s", c->name, myself->name);
281         }
282
283         if(!prf(shared, ECDH_SHARED_SIZE, seed, strlen(seed), key, hiskeylen * 2 + mykeylen * 2))
284                 return false;
285
286         free(seed);
287
288         cipher_set_key(&c->incipher, mykey, true);
289         digest_set_key(&c->indigest, mykey + mykeylen, mykeylen);
290
291         cipher_set_key(&c->outcipher, hiskey, false);
292         digest_set_key(&c->outdigest, hiskey + hiskeylen, hiskeylen);
293
294         c->status.decryptin = true;
295         c->status.encryptout = true;
296         c->allow_request = CHALLENGE;
297
298         return send_challenge(c);
299 }
300
301 bool metakey_h(connection_t *c, char *request) {
302         if(c->protocol_minor >= 2)
303                 return metakey_ec_h(c, request);
304
305         char hexkey[MAX_STRING_SIZE];
306         int cipher, digest, maclength, compression;
307         size_t len = rsa_size(&myself->connection->rsa);
308         char enckey[len];
309         char key[len];
310
311         if(sscanf(request, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, hexkey) != 5) {
312                 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
313                 return false;
314         }
315
316         /* Convert the challenge from hexadecimal back to binary */
317
318         int inlen = hex2bin(hexkey, enckey, sizeof enckey);
319
320         /* Check if the length of the meta key is all right */
321
322         if(inlen != len) {
323                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
324                 return false;
325         }
326
327         /* Decrypt the meta key */
328
329         if(!rsa_private_decrypt(&myself->connection->rsa, enckey, len, key)) {
330                 logger(LOG_ERR, "Error during decryption of meta key for %s (%s)", c->name, c->hostname);
331                 return false;
332         }
333
334         ifdebug(SCARY_THINGS) {
335                 bin2hex(key, hexkey, len);
336                 logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", hexkey);
337         }
338
339         /* Check and lookup cipher and digest algorithms */
340
341         if(!cipher_open_by_nid(&c->incipher, cipher) || !cipher_set_key_from_rsa(&c->incipher, key, len, false)) {
342                 logger(LOG_ERR, "Error during initialisation of cipher from %s (%s)", c->name, c->hostname);
343                 return false;
344         }
345
346         if(!digest_open_by_nid(&c->indigest, digest, -1)) {
347                 logger(LOG_ERR, "Error during initialisation of digest from %s (%s)", c->name, c->hostname);
348                 return false;
349         }
350
351         c->status.decryptin = true;
352
353         c->allow_request = CHALLENGE;
354
355         return send_challenge(c);
356 }
357
358 bool send_challenge(connection_t *c) {
359         size_t len = c->protocol_minor >= 2 ? ECDH_SIZE : rsa_size(&c->rsa);
360         char buffer[len * 2 + 1];
361
362         if(!c->hischallenge)
363                 c->hischallenge = xrealloc(c->hischallenge, len);
364
365         /* Copy random data to the buffer */
366
367         randomize(c->hischallenge, len);
368
369         /* Convert to hex */
370
371         bin2hex(c->hischallenge, buffer, len);
372
373         /* Send the challenge */
374
375         return send_request(c, "%d %s", CHALLENGE, buffer);
376 }
377
378 bool challenge_h(connection_t *c, char *request) {
379         char buffer[MAX_STRING_SIZE];
380         size_t len = c->protocol_minor >= 2 ? ECDH_SIZE : rsa_size(&myself->connection->rsa);
381         size_t digestlen = digest_length(&c->indigest);
382         char digest[digestlen];
383
384         if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
385                 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name, c->hostname);
386                 return false;
387         }
388
389         /* Convert the challenge from hexadecimal back to binary */
390
391         int inlen = hex2bin(buffer, buffer, sizeof buffer);
392
393         /* Check if the length of the challenge is all right */
394
395         if(inlen != len) {
396                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge length");
397                 return false;
398         }
399
400         c->allow_request = CHAL_REPLY;
401
402         /* Calculate the hash from the challenge we received */
403
404         digest_create(&c->indigest, buffer, len, digest);
405
406         /* Convert the hash to a hexadecimal formatted string */
407
408         bin2hex(digest, buffer, digestlen);
409
410         /* Send the reply */
411
412         return send_request(c, "%d %s", CHAL_REPLY, buffer);
413 }
414
415 bool chal_reply_h(connection_t *c, char *request) {
416         char hishash[MAX_STRING_SIZE];
417
418         if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
419                 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
420                            c->hostname);
421                 return false;
422         }
423
424         /* Convert the hash to binary format */
425
426         int inlen = hex2bin(hishash, hishash, sizeof hishash);
427
428         /* Check if the length of the hash is all right */
429
430         if(inlen != digest_length(&c->outdigest)) {
431                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply length");
432                 return false;
433         }
434
435
436         /* Verify the hash */
437
438         if(!digest_verify(&c->outdigest, c->hischallenge, c->protocol_minor >= 2 ? ECDH_SIZE : rsa_size(&c->rsa), hishash)) {
439                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply");
440                 return false;
441         }
442
443         /* Identity has now been positively verified.
444            Send an acknowledgement with the rest of the information needed.
445          */
446
447         free(c->hischallenge);
448         c->hischallenge = NULL;
449         c->allow_request = ACK;
450
451         return send_ack(c);
452 }
453
454 static bool send_upgrade(connection_t *c) {
455         /* Special case when protocol_minor is 1: the other end is ECDSA capable,
456          * but doesn't know our key yet. So send it now. */
457
458         char *pubkey = ecdsa_get_base64_public_key(&myself->connection->ecdsa);
459
460         if(!pubkey)
461                 return false;
462
463         bool result = send_request(c, "%d %s", ACK, pubkey);
464         free(pubkey);
465         return result;
466 }
467
468 bool send_ack(connection_t *c) {
469         if(c->protocol_minor == 1)
470                 return send_upgrade(c);
471
472         /* ACK message contains rest of the information the other end needs
473            to create node_t and edge_t structures. */
474
475         struct timeval now;
476         bool choice;
477
478         /* Estimate weight */
479
480         gettimeofday(&now, NULL);
481         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
482
483         /* Check some options */
484
485         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
486                 c->options |= OPTION_INDIRECT;
487
488         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
489                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
490
491         if(myself->options & OPTION_PMTU_DISCOVERY)
492                 c->options |= OPTION_PMTU_DISCOVERY;
493
494         choice = myself->options & OPTION_CLAMP_MSS;
495         get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
496         if(choice)
497                 c->options |= OPTION_CLAMP_MSS;
498
499         get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
500
501         return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
502 }
503
504 static void send_everything(connection_t *c) {
505         splay_node_t *node, *node2;
506         node_t *n;
507         subnet_t *s;
508         edge_t *e;
509
510         /* Send all known subnets and edges */
511
512         if(tunnelserver) {
513                 for(node = myself->subnet_tree->head; node; node = node->next) {
514                         s = node->data;
515                         send_add_subnet(c, s);
516                 }
517
518                 return;
519         }
520
521         for(node = node_tree->head; node; node = node->next) {
522                 n = node->data;
523
524                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
525                         s = node2->data;
526                         send_add_subnet(c, s);
527                 }
528
529                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
530                         e = node2->data;
531                         send_add_edge(c, e);
532                 }
533         }
534 }
535
536 static bool upgrade_h(connection_t *c, char *request) {
537         char pubkey[MAX_STRING_SIZE];
538
539         if(sscanf(request, "%*d " MAX_STRING, pubkey) != 1) {
540                 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name, c->hostname);
541                 return false;
542         }
543
544         if(ecdsa_active(&c->ecdsa) || read_ecdsa_public_key(c)) {
545                 logger(LOG_INFO, "Already have ECDSA public key from %s (%s), not upgrading.", c->name, c->hostname);
546                 return false;
547         }
548
549         logger(LOG_INFO, "Got ECDSA public key from %s (%s), upgrading!", c->name, c->hostname);
550         append_connection_config(c, "ECDSAPublicKey", pubkey);
551         c->allow_request = TERMREQ;
552         return send_termreq(c);
553 }
554
555 bool ack_h(connection_t *c, char *request) {
556         if(c->protocol_minor == 1)
557                 return upgrade_h(c, request);
558
559         char hisport[MAX_STRING_SIZE];
560         char *hisaddress;
561         int weight, mtu;
562         uint32_t options;
563         node_t *n;
564         bool choice;
565
566         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
567                 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
568                            c->hostname);
569                 return false;
570         }
571
572         /* Check if we already have a node_t for him */
573
574         n = lookup_node(c->name);
575
576         if(!n) {
577                 n = new_node();
578                 n->name = xstrdup(c->name);
579                 node_add(n);
580         } else {
581                 if(n->connection) {
582                         /* Oh dear, we already have a connection to this node. */
583                         ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
584
585                         if(n->connection->outgoing) {
586                                 if(c->outgoing)
587                                         logger(LOG_WARNING, "Two outgoing connections to the same node!");
588                                 else
589                                         c->outgoing = n->connection->outgoing;
590
591                                 n->connection->outgoing = NULL;
592                         }
593
594                         terminate_connection(n->connection, false);
595                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
596                         graph();
597                 }
598         }
599
600         n->connection = c;
601         c->node = n;
602         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
603                 c->options &= ~OPTION_PMTU_DISCOVERY;
604                 options &= ~OPTION_PMTU_DISCOVERY;
605         }
606         c->options |= options;
607
608         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
609                 n->mtu = mtu;
610
611         if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
612                 n->mtu = mtu;
613
614         if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
615                 if(choice)
616                         c->options |= OPTION_CLAMP_MSS;
617                 else
618                         c->options &= ~OPTION_CLAMP_MSS;
619         }
620
621         if(c->protocol_minor > 0)
622                 c->node->status.ecdh = true;
623
624         /* Activate this connection */
625
626         c->allow_request = ALL;
627         c->status.active = true;
628
629         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
630                            c->hostname);
631
632         /* Send him everything we know */
633
634         send_everything(c);
635
636         /* Create an edge_t for this connection */
637
638         c->edge = new_edge();
639         c->edge->from = myself;
640         c->edge->to = n;
641         sockaddr2str(&c->address, &hisaddress, NULL);
642         c->edge->address = str2sockaddr(hisaddress, hisport);
643         free(hisaddress);
644         c->edge->weight = (weight + c->estimated_weight) / 2;
645         c->edge->connection = c;
646         c->edge->options = c->options;
647
648         edge_add(c->edge);
649
650         /* Notify everyone of the new edge */
651
652         if(tunnelserver)
653                 send_add_edge(c, c->edge);
654         else
655                 send_add_edge(broadcast, c->edge);
656
657         /* Run MST and SSSP algorithms */
658
659         graph();
660
661         return true;
662 }