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