Require ExperimentalProtocol = yes for new features, update documentation.
[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];
147         char sig[siglen];
148
149         // TODO: include nonce? Use relevant parts of SSH or TLS protocol
150
151         if(!ecdh_generate_public(&c->ecdh, key))
152                 return false;
153
154         if(!ecdsa_sign(&myself->connection->ecdsa, key, ECDH_SIZE, sig))
155                 return false;
156
157         char out[MAX_STRING_SIZE];
158
159         bin2hex(key, out, ECDH_SIZE);
160         bin2hex(sig, out + ECDH_SIZE * 2, siglen);
161         out[(ECDH_SIZE + siglen) * 2] = 0;
162         
163         bool result = send_request(c, "%d %s", METAKEY, out);
164 }
165
166 bool send_metakey(connection_t *c) {
167         if(!read_rsa_public_key(c))
168                 return false;
169
170         if(!cipher_open_blowfish_ofb(&c->outcipher))
171                 return false;
172         
173         if(!digest_open_sha1(&c->outdigest, -1))
174                 return false;
175
176         size_t len = rsa_size(&c->rsa);
177         char key[len];
178         char enckey[len];
179         char hexkey[2 * len + 1];
180
181         /* Create a random key */
182
183         randomize(key, len);
184
185         /* The message we send must be smaller than the modulus of the RSA key.
186            By definition, for a key of k bits, the following formula holds:
187
188            2^(k-1) <= modulus < 2^(k)
189
190            Where ^ means "to the power of", not "xor".
191            This means that to be sure, we must choose our message < 2^(k-1).
192            This can be done by setting the most significant bit to zero.
193          */
194
195         key[0] &= 0x7F;
196
197         cipher_set_key_from_rsa(&c->outcipher, key, len, true);
198
199         ifdebug(SCARY_THINGS) {
200                 bin2hex(key, hexkey, len);
201                 hexkey[len * 2] = '\0';
202                 logger(LOG_DEBUG, "Generated random meta key (unencrypted): %s", hexkey);
203         }
204
205         /* Encrypt the random data
206
207            We do not use one of the PKCS padding schemes here.
208            This is allowed, because we encrypt a totally random string
209            with a length equal to that of the modulus of the RSA key.
210          */
211
212         if(!rsa_public_encrypt(&c->rsa, key, len, enckey)) {
213                 logger(LOG_ERR, "Error during encryption of meta key for %s (%s)", c->name, c->hostname);
214                 return false;
215         }
216
217         /* Convert the encrypted random data to a hexadecimal formatted string */
218
219         bin2hex(enckey, hexkey, len);
220         hexkey[len * 2] = '\0';
221
222         /* Send the meta key */
223
224         bool result = send_request(c, "%d %d %d %d %d %s", METAKEY,
225                          cipher_get_nid(&c->outcipher),
226                          digest_get_nid(&c->outdigest), c->outmaclength,
227                          c->outcompression, hexkey);
228         
229         c->status.encryptout = true;
230         return result;
231 }
232
233 static bool metakey_ec_h(connection_t *c, const char *request) {
234         size_t siglen = ecdsa_size(&c->ecdsa);
235         char in[MAX_STRING_SIZE];
236         char key[MAX_STRING_SIZE];
237         char sig[siglen];
238
239         logger(LOG_DEBUG, "Got ECDH metakey from %s", c->name);
240
241         if(sscanf(request, "%*d " MAX_STRING, in) != 1) {
242                 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
243                 return false;
244         }
245
246         if(strlen(in) != (ECDH_SIZE + siglen) * 2) {
247                 logger(LOG_ERR, "Possible intruder %s (%s): %s %d != %d", c->name, c->hostname, "wrong keylength", strlen(in) / 2, (ECDH_SIZE + siglen));
248                 return false;
249         }
250
251         hex2bin(in, key, ECDH_SIZE);
252         hex2bin(in + ECDH_SIZE * 2, sig, siglen);
253
254         if(!ecdsa_verify(&c->ecdsa, key, ECDH_SIZE, sig)) {
255                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "invalid ECDSA signature");
256                 return false;
257         }
258
259         char shared[ECDH_SHARED_SIZE * 2 + 1];
260
261         if(!ecdh_compute_shared(&c->ecdh, key, shared))
262                 return false;
263
264         /* Update our crypto end */
265
266         if(!cipher_open_by_name(&c->incipher, "aes-256-ofb"))
267                 return false;
268         if(!digest_open_by_name(&c->indigest, "sha512", -1))
269                 return false;
270         if(!cipher_open_by_name(&c->outcipher, "aes-256-ofb"))
271                 return false;
272         if(!digest_open_by_name(&c->outdigest, "sha512", -1))
273                 return false;
274
275         size_t mykeylen = cipher_keylength(&c->incipher);
276         size_t hiskeylen = cipher_keylength(&c->outcipher);
277
278         char *mykey;
279         char *hiskey;
280         char *seed;
281         
282         if(strcmp(myself->name, c->name) < 0) {
283                 mykey = key;
284                 hiskey = key + mykeylen * 2;
285                 xasprintf(&seed, "tinc TCP key expansion %s %s", myself->name, c->name);
286         } else {
287                 mykey = key + hiskeylen * 2;
288                 hiskey = key;
289                 xasprintf(&seed, "tinc TCP key expansion %s %s", c->name, myself->name);
290         }
291
292         if(!prf(shared, ECDH_SHARED_SIZE, seed, strlen(seed), key, hiskeylen * 2 + mykeylen * 2))
293                 return false;
294
295         free(seed);
296
297         bin2hex(shared, shared, ECDH_SHARED_SIZE);
298         shared[ECDH_SHARED_SIZE * 2] = 0;
299         logger(LOG_DEBUG, "Shared secret is %s", shared);
300
301         cipher_set_key(&c->incipher, mykey, true);
302         digest_set_key(&c->indigest, mykey + mykeylen, mykeylen);
303
304         cipher_set_key(&c->outcipher, hiskey, false);
305         digest_set_key(&c->outdigest, hiskey + hiskeylen, hiskeylen);
306
307         c->status.decryptin = true;
308         c->status.encryptout = true;
309         c->allow_request = CHALLENGE;
310
311         return send_challenge(c);
312 }
313
314 bool metakey_h(connection_t *c, char *request) {
315         if(c->protocol_minor >= 2)
316                 return metakey_ec_h(c, request);
317
318         char hexkey[MAX_STRING_SIZE];
319         int cipher, digest, maclength, compression;
320         size_t len = rsa_size(&myself->connection->rsa);
321         char enckey[len];
322         char key[len];
323
324         if(sscanf(request, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, hexkey) != 5) {
325                 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
326                 return false;
327         }
328
329         /* Check if the length of the meta key is all right */
330
331         if(strlen(hexkey) != len * 2) {
332                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
333                 return false;
334         }
335
336         /* Convert the challenge from hexadecimal back to binary */
337
338         hex2bin(hexkey, enckey, len);
339
340         /* Decrypt the meta key */
341
342         if(!rsa_private_decrypt(&myself->connection->rsa, enckey, len, key)) {
343                 logger(LOG_ERR, "Error during decryption of meta key for %s (%s)", c->name, c->hostname);
344                 return false;
345         }
346
347         ifdebug(SCARY_THINGS) {
348                 bin2hex(key, hexkey, len);
349                 hexkey[len * 2] = '\0';
350                 logger(LOG_DEBUG, "Received random meta key (unencrypted): %s", hexkey);
351         }
352
353         /* Check and lookup cipher and digest algorithms */
354
355         if(!cipher_open_by_nid(&c->incipher, cipher) || !cipher_set_key_from_rsa(&c->incipher, key, len, false)) {
356                 logger(LOG_ERR, "Error during initialisation of cipher from %s (%s)", c->name, c->hostname);
357                 return false;
358         }
359
360         if(!digest_open_by_nid(&c->indigest, digest, -1)) {
361                 logger(LOG_ERR, "Error during initialisation of digest from %s (%s)", c->name, c->hostname);
362                 return false;
363         }
364
365         c->status.decryptin = true;
366
367         c->allow_request = CHALLENGE;
368
369         return send_challenge(c);
370 }
371
372 bool send_challenge(connection_t *c) {
373         size_t len = c->protocol_minor >= 2 ? ECDH_SIZE : rsa_size(&c->rsa);
374         char buffer[len * 2 + 1];
375
376         if(!c->hischallenge)
377                 c->hischallenge = xrealloc(c->hischallenge, len);
378
379         /* Copy random data to the buffer */
380
381         randomize(c->hischallenge, len);
382
383         /* Convert to hex */
384
385         bin2hex(c->hischallenge, buffer, len);
386         buffer[len * 2] = '\0';
387
388         /* Send the challenge */
389
390         return send_request(c, "%d %s", CHALLENGE, buffer);
391 }
392
393 bool challenge_h(connection_t *c, char *request) {
394         char buffer[MAX_STRING_SIZE];
395         size_t len = c->protocol_minor >= 2 ? ECDH_SIZE : rsa_size(&myself->connection->rsa);
396         size_t digestlen = digest_length(&c->indigest);
397         char digest[digestlen];
398
399         if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
400                 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name, c->hostname);
401                 return false;
402         }
403
404         /* Check if the length of the challenge is all right */
405
406         if(strlen(buffer) != len * 2) {
407                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge length");
408                 return false;
409         }
410
411         /* Convert the challenge from hexadecimal back to binary */
412
413         hex2bin(buffer, buffer, len);
414
415         c->allow_request = CHAL_REPLY;
416
417         /* Calculate the hash from the challenge we received */
418
419         digest_create(&c->indigest, buffer, len, digest);
420
421         /* Convert the hash to a hexadecimal formatted string */
422
423         bin2hex(digest, buffer, digestlen);
424         buffer[digestlen * 2] = '\0';
425
426         /* Send the reply */
427
428         return send_request(c, "%d %s", CHAL_REPLY, buffer);
429 }
430
431 bool chal_reply_h(connection_t *c, char *request) {
432         char hishash[MAX_STRING_SIZE];
433
434         if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
435                 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
436                            c->hostname);
437                 return false;
438         }
439
440         /* Check if the length of the hash is all right */
441
442         if(strlen(hishash) != digest_length(&c->outdigest) * 2) {
443                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply length");
444                 return false;
445         }
446
447         /* Convert the hash to binary format */
448
449         hex2bin(hishash, hishash, digest_length(&c->outdigest));
450
451         /* Verify the hash */
452
453         if(!digest_verify(&c->outdigest, c->hischallenge, c->protocol_minor >= 2 ? ECDH_SIZE : rsa_size(&c->rsa), hishash)) {
454                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply");
455                 return false;
456         }
457
458         /* Identity has now been positively verified.
459            Send an acknowledgement with the rest of the information needed.
460          */
461
462         free(c->hischallenge);
463         c->hischallenge = NULL;
464         c->allow_request = ACK;
465
466         return send_ack(c);
467 }
468
469 static bool send_upgrade(connection_t *c) {
470         /* Special case when protocol_minor is 1: the other end is ECDSA capable,
471          * but doesn't know our key yet. So send it now. */
472
473         char *pubkey = ecdsa_get_base64_public_key(&myself->connection->ecdsa);
474
475         if(!pubkey)
476                 return false;
477
478         bool result = send_request(c, "%d %s", ACK, pubkey);
479         free(pubkey);
480         return result;
481 }
482
483 bool send_ack(connection_t *c) {
484         if(c->protocol_minor == 1)
485                 return send_upgrade(c);
486
487         /* ACK message contains rest of the information the other end needs
488            to create node_t and edge_t structures. */
489
490         struct timeval now;
491         bool choice;
492
493         /* Estimate weight */
494
495         gettimeofday(&now, NULL);
496         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
497
498         /* Check some options */
499
500         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
501                 c->options |= OPTION_INDIRECT;
502
503         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
504                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
505
506         if(myself->options & OPTION_PMTU_DISCOVERY)
507                 c->options |= OPTION_PMTU_DISCOVERY;
508
509         choice = myself->options & OPTION_CLAMP_MSS;
510         get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
511         if(choice)
512                 c->options |= OPTION_CLAMP_MSS;
513
514         get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
515
516         return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
517 }
518
519 static void send_everything(connection_t *c) {
520         splay_node_t *node, *node2;
521         node_t *n;
522         subnet_t *s;
523         edge_t *e;
524
525         /* Send all known subnets and edges */
526
527         if(tunnelserver) {
528                 for(node = myself->subnet_tree->head; node; node = node->next) {
529                         s = node->data;
530                         send_add_subnet(c, s);
531                 }
532
533                 return;
534         }
535
536         for(node = node_tree->head; node; node = node->next) {
537                 n = node->data;
538
539                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
540                         s = node2->data;
541                         send_add_subnet(c, s);
542                 }
543
544                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
545                         e = node2->data;
546                         send_add_edge(c, e);
547                 }
548         }
549 }
550
551 static bool upgrade_h(connection_t *c, char *request) {
552         char pubkey[MAX_STRING_SIZE];
553
554         if(sscanf(request, "%*d " MAX_STRING, pubkey) != 1) {
555                 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name, c->hostname);
556                 return false;
557         }
558
559         if(ecdsa_active(&c->ecdsa) || read_ecdsa_public_key(c)) {
560                 logger(LOG_INFO, "Already have ECDSA public key from %s (%s), not upgrading.", c->name, c->hostname);
561                 return false;
562         }
563
564         logger(LOG_INFO, "Got ECDSA public key from %s (%s), upgrading!", c->name, c->hostname);
565         append_connection_config(c, "ECDSAPublicKey", pubkey);
566         c->allow_request = TERMREQ;
567         return send_termreq(c);
568 }
569
570 bool ack_h(connection_t *c, char *request) {
571         if(c->protocol_minor == 1)
572                 return upgrade_h(c, request);
573
574         char hisport[MAX_STRING_SIZE];
575         char *hisaddress;
576         int weight, mtu;
577         uint32_t options;
578         node_t *n;
579         bool choice;
580
581         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
582                 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
583                            c->hostname);
584                 return false;
585         }
586
587         /* Check if we already have a node_t for him */
588
589         n = lookup_node(c->name);
590
591         if(!n) {
592                 n = new_node();
593                 n->name = xstrdup(c->name);
594                 node_add(n);
595         } else {
596                 if(n->connection) {
597                         /* Oh dear, we already have a connection to this node. */
598                         ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
599
600                         if(n->connection->outgoing) {
601                                 if(c->outgoing)
602                                         logger(LOG_WARNING, "Two outgoing connections to the same node!");
603                                 else
604                                         c->outgoing = n->connection->outgoing;
605
606                                 n->connection->outgoing = NULL;
607                         }
608
609                         terminate_connection(n->connection, false);
610                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
611                         graph();
612                 }
613         }
614
615         n->connection = c;
616         c->node = n;
617         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
618                 c->options &= ~OPTION_PMTU_DISCOVERY;
619                 options &= ~OPTION_PMTU_DISCOVERY;
620         }
621         c->options |= options;
622
623         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
624                 n->mtu = mtu;
625
626         if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
627                 n->mtu = mtu;
628
629         if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
630                 if(choice)
631                         c->options |= OPTION_CLAMP_MSS;
632                 else
633                         c->options &= ~OPTION_CLAMP_MSS;
634         }
635
636         if(c->protocol_minor > 0)
637                 c->node->status.ecdh = true;
638
639         /* Activate this connection */
640
641         c->allow_request = ALL;
642         c->status.active = true;
643
644         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
645                            c->hostname);
646
647         /* Send him everything we know */
648
649         send_everything(c);
650
651         /* Create an edge_t for this connection */
652
653         c->edge = new_edge();
654         c->edge->from = myself;
655         c->edge->to = n;
656         sockaddr2str(&c->address, &hisaddress, NULL);
657         c->edge->address = str2sockaddr(hisaddress, hisport);
658         free(hisaddress);
659         c->edge->weight = (weight + c->estimated_weight) / 2;
660         c->edge->connection = c;
661         c->edge->options = c->options;
662
663         edge_add(c->edge);
664
665         /* Notify everyone of the new edge */
666
667         if(tunnelserver)
668                 send_add_edge(c, c->edge);
669         else
670                 send_add_edge(broadcast, c->edge);
671
672         /* Run MST and SSSP algorithms */
673
674         graph();
675
676         return true;
677 }