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