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