]> git.meshlink.io Git - meshlink/blob - src/protocol_auth.c
Merge branch 'master' of git://tinc-vpn.org/tinc into 1.1
[meshlink] / 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(!experimental)
114                 c->protocol_minor = 0;
115
116         if(!c->config_tree) {
117                 init_configuration(&c->config_tree);
118
119                 if(!read_connection_config(c)) {
120                         logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
121                                    c->name);
122                         return false;
123                 }
124
125                 if(experimental && c->protocol_minor >= 2)
126                         if(!read_ecdsa_public_key(c))
127                                 return false;
128         } else {
129                 if(c->protocol_minor && !ecdsa_active(&c->ecdsa))
130                         c->protocol_minor = 1;
131         }
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
230         logger(LOG_DEBUG, "Got ECDH metakey from %s", c->name);
231
232         if(sscanf(request, "%*d " MAX_STRING, key) != 1) {
233                 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
234                 return false;
235         }
236
237         int inlen = b64decode(key, key, sizeof key);
238
239         if(inlen != (ECDH_SIZE + siglen)) {
240                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
241                 return false;
242         }
243
244         if(!ecdsa_verify(&c->ecdsa, key, ECDH_SIZE, key + ECDH_SIZE)) {
245                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "invalid ECDSA signature");
246                 return false;
247         }
248
249         char shared[ECDH_SHARED_SIZE];
250
251         if(!ecdh_compute_shared(&c->ecdh, key, shared))
252                 return false;
253
254         /* Update our crypto end */
255
256         if(!cipher_open_by_name(&c->incipher, "aes-256-ofb"))
257                 return false;
258         if(!digest_open_by_name(&c->indigest, "sha512", -1))
259                 return false;
260         if(!cipher_open_by_name(&c->outcipher, "aes-256-ofb"))
261                 return false;
262         if(!digest_open_by_name(&c->outdigest, "sha512", -1))
263                 return false;
264
265         size_t mykeylen = cipher_keylength(&c->incipher);
266         size_t hiskeylen = cipher_keylength(&c->outcipher);
267
268         char *mykey;
269         char *hiskey;
270         char *seed;
271         
272         if(strcmp(myself->name, c->name) < 0) {
273                 mykey = key;
274                 hiskey = key + mykeylen * 2;
275                 xasprintf(&seed, "tinc TCP key expansion %s %s", myself->name, c->name);
276         } else {
277                 mykey = key + hiskeylen * 2;
278                 hiskey = key;
279                 xasprintf(&seed, "tinc TCP key expansion %s %s", c->name, myself->name);
280         }
281
282         if(!prf(shared, ECDH_SHARED_SIZE, seed, strlen(seed), key, hiskeylen * 2 + mykeylen * 2))
283                 return false;
284
285         free(seed);
286
287         cipher_set_key(&c->incipher, mykey, false);
288         digest_set_key(&c->indigest, mykey + mykeylen, mykeylen);
289
290         cipher_set_key(&c->outcipher, hiskey, true);
291         digest_set_key(&c->outdigest, hiskey + hiskeylen, hiskeylen);
292
293         c->status.decryptin = true;
294         c->status.encryptout = true;
295         c->allow_request = CHALLENGE;
296
297         return send_challenge(c);
298 }
299
300 bool metakey_h(connection_t *c, char *request) {
301         if(c->protocol_minor >= 2)
302                 return metakey_ec_h(c, request);
303
304         char hexkey[MAX_STRING_SIZE];
305         int cipher, digest, maclength, compression;
306         size_t len = rsa_size(&myself->connection->rsa);
307         char enckey[len];
308         char key[len];
309
310         if(sscanf(request, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, hexkey) != 5) {
311                 logger(LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
312                 return false;
313         }
314
315         /* Convert the challenge from hexadecimal back to binary */
316
317         int inlen = hex2bin(hexkey, enckey, sizeof enckey);
318
319         /* Check if the length of the meta key is all right */
320
321         if(inlen != len) {
322                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
323                 return false;
324         }
325
326         /* Decrypt the meta key */
327
328         if(!rsa_private_decrypt(&myself->connection->rsa, enckey, len, key)) {
329                 logger(LOG_ERR, "Error during decryption of meta key for %s (%s)", c->name, c->hostname);
330                 return false;
331         }
332
333         ifdebug(SCARY_THINGS) {
334                 bin2hex(key, hexkey, len);
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
372         /* Send the challenge */
373
374         return send_request(c, "%d %s", CHALLENGE, buffer);
375 }
376
377 bool challenge_h(connection_t *c, char *request) {
378         char buffer[MAX_STRING_SIZE];
379         size_t len = c->protocol_minor >= 2 ? ECDH_SIZE : rsa_size(&myself->connection->rsa);
380         size_t digestlen = digest_length(&c->indigest);
381         char digest[digestlen];
382
383         if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
384                 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name, c->hostname);
385                 return false;
386         }
387
388         /* Convert the challenge from hexadecimal back to binary */
389
390         int inlen = hex2bin(buffer, buffer, sizeof buffer);
391
392         /* Check if the length of the challenge is all right */
393
394         if(inlen != len) {
395                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge length");
396                 return false;
397         }
398
399         c->allow_request = CHAL_REPLY;
400
401         /* Calculate the hash from the challenge we received */
402
403         digest_create(&c->indigest, buffer, len, digest);
404
405         /* Convert the hash to a hexadecimal formatted string */
406
407         bin2hex(digest, buffer, digestlen);
408
409         /* Send the reply */
410
411         return send_request(c, "%d %s", CHAL_REPLY, buffer);
412 }
413
414 bool chal_reply_h(connection_t *c, char *request) {
415         char hishash[MAX_STRING_SIZE];
416
417         if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
418                 logger(LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
419                            c->hostname);
420                 return false;
421         }
422
423         /* Convert the hash to binary format */
424
425         int inlen = hex2bin(hishash, hishash, sizeof hishash);
426
427         /* Check if the length of the hash is all right */
428
429         if(inlen != digest_length(&c->outdigest)) {
430                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply length");
431                 return false;
432         }
433
434
435         /* Verify the hash */
436
437         if(!digest_verify(&c->outdigest, c->hischallenge, c->protocol_minor >= 2 ? ECDH_SIZE : rsa_size(&c->rsa), hishash)) {
438                 logger(LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply");
439                 return false;
440         }
441
442         /* Identity has now been positively verified.
443            Send an acknowledgement with the rest of the information needed.
444          */
445
446         free(c->hischallenge);
447         c->hischallenge = NULL;
448         c->allow_request = ACK;
449
450         return send_ack(c);
451 }
452
453 static bool send_upgrade(connection_t *c) {
454         /* Special case when protocol_minor is 1: the other end is ECDSA capable,
455          * but doesn't know our key yet. So send it now. */
456
457         char *pubkey = ecdsa_get_base64_public_key(&myself->connection->ecdsa);
458
459         if(!pubkey)
460                 return false;
461
462         bool result = send_request(c, "%d %s", ACK, pubkey);
463         free(pubkey);
464         return result;
465 }
466
467 bool send_ack(connection_t *c) {
468         if(c->protocol_minor == 1)
469                 return send_upgrade(c);
470
471         /* ACK message contains rest of the information the other end needs
472            to create node_t and edge_t structures. */
473
474         struct timeval now;
475         bool choice;
476
477         /* Estimate weight */
478
479         gettimeofday(&now, NULL);
480         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
481
482         /* Check some options */
483
484         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
485                 c->options |= OPTION_INDIRECT;
486
487         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
488                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
489
490         if(myself->options & OPTION_PMTU_DISCOVERY)
491                 c->options |= OPTION_PMTU_DISCOVERY;
492
493         choice = myself->options & OPTION_CLAMP_MSS;
494         get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
495         if(choice)
496                 c->options |= OPTION_CLAMP_MSS;
497
498         get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
499
500         return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
501 }
502
503 static void send_everything(connection_t *c) {
504         splay_node_t *node, *node2;
505         node_t *n;
506         subnet_t *s;
507         edge_t *e;
508
509         /* Send all known subnets and edges */
510
511         if(tunnelserver) {
512                 for(node = myself->subnet_tree->head; node; node = node->next) {
513                         s = node->data;
514                         send_add_subnet(c, s);
515                 }
516
517                 return;
518         }
519
520         for(node = node_tree->head; node; node = node->next) {
521                 n = node->data;
522
523                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
524                         s = node2->data;
525                         send_add_subnet(c, s);
526                 }
527
528                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
529                         e = node2->data;
530                         send_add_edge(c, e);
531                 }
532         }
533 }
534
535 static bool upgrade_h(connection_t *c, char *request) {
536         char pubkey[MAX_STRING_SIZE];
537
538         if(sscanf(request, "%*d " MAX_STRING, pubkey) != 1) {
539                 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name, c->hostname);
540                 return false;
541         }
542
543         if(ecdsa_active(&c->ecdsa) || read_ecdsa_public_key(c)) {
544                 logger(LOG_INFO, "Already have ECDSA public key from %s (%s), not upgrading.", c->name, c->hostname);
545                 return false;
546         }
547
548         logger(LOG_INFO, "Got ECDSA public key from %s (%s), upgrading!", c->name, c->hostname);
549         append_config_file(c->name, "ECDSAPublicKey", pubkey);
550         c->allow_request = TERMREQ;
551         return send_termreq(c);
552 }
553
554 bool ack_h(connection_t *c, char *request) {
555         if(c->protocol_minor == 1)
556                 return upgrade_h(c, request);
557
558         char hisport[MAX_STRING_SIZE];
559         char *hisaddress;
560         int weight, mtu;
561         uint32_t options;
562         node_t *n;
563         bool choice;
564
565         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
566                 logger(LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
567                            c->hostname);
568                 return false;
569         }
570
571         /* Check if we already have a node_t for him */
572
573         n = lookup_node(c->name);
574
575         if(!n) {
576                 n = new_node();
577                 n->name = xstrdup(c->name);
578                 node_add(n);
579         } else {
580                 if(n->connection) {
581                         /* Oh dear, we already have a connection to this node. */
582                         ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
583
584                         if(n->connection->outgoing) {
585                                 if(c->outgoing)
586                                         logger(LOG_WARNING, "Two outgoing connections to the same node!");
587                                 else
588                                         c->outgoing = n->connection->outgoing;
589
590                                 n->connection->outgoing = NULL;
591                         }
592
593                         terminate_connection(n->connection, false);
594                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
595                         graph();
596                 }
597         }
598
599         n->connection = c;
600         c->node = n;
601         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
602                 c->options &= ~OPTION_PMTU_DISCOVERY;
603                 options &= ~OPTION_PMTU_DISCOVERY;
604         }
605         c->options |= options;
606
607         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
608                 n->mtu = mtu;
609
610         if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
611                 n->mtu = mtu;
612
613         if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
614                 if(choice)
615                         c->options |= OPTION_CLAMP_MSS;
616                 else
617                         c->options &= ~OPTION_CLAMP_MSS;
618         }
619
620         if(c->protocol_minor > 0)
621                 c->node->status.ecdh = true;
622
623         /* Activate this connection */
624
625         c->allow_request = ALL;
626         c->status.active = true;
627
628         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection with %s (%s) activated", c->name,
629                            c->hostname);
630
631         /* Send him everything we know */
632
633         send_everything(c);
634
635         /* Create an edge_t for this connection */
636
637         c->edge = new_edge();
638         c->edge->from = myself;
639         c->edge->to = n;
640         sockaddr2str(&c->address, &hisaddress, NULL);
641         c->edge->address = str2sockaddr(hisaddress, hisport);
642         free(hisaddress);
643         c->edge->weight = (weight + c->estimated_weight) / 2;
644         c->edge->connection = c;
645         c->edge->options = c->options;
646
647         edge_add(c->edge);
648
649         /* Notify everyone of the new edge */
650
651         if(tunnelserver)
652                 send_add_edge(c, c->edge);
653         else
654                 send_add_edge(everyone, c->edge);
655
656         /* Run MST and SSSP algorithms */
657
658         graph();
659
660         return true;
661 }