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