Remove unused '#include's.
[tinc] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2017 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 "ecdsa.h"
31 #include "edge.h"
32 #include "graph.h"
33 #include "logger.h"
34 #include "meta.h"
35 #include "names.h"
36 #include "net.h"
37 #include "netutl.h"
38 #include "node.h"
39 #include "protocol.h"
40 #include "rsa.h"
41 #include "script.h"
42 #include "sptps.h"
43 #include "utils.h"
44 #include "xalloc.h"
45
46 #include "ed25519/sha512.h"
47 #include "keys.h"
48
49 int invitation_lifetime;
50 ecdsa_t *invitation_key = NULL;
51
52 static bool send_proxyrequest(connection_t *c) {
53         switch(proxytype) {
54         case PROXY_HTTP: {
55                 char *host;
56                 char *port;
57
58                 sockaddr2str(&c->address, &host, &port);
59                 send_request(c, "CONNECT %s:%s HTTP/1.1\r\n\r", host, port);
60                 free(host);
61                 free(port);
62                 return true;
63         }
64
65         case PROXY_SOCKS4: {
66                 if(c->address.sa.sa_family != AF_INET) {
67                         logger(DEBUG_ALWAYS, LOG_ERR, "Cannot connect to an IPv6 host through a SOCKS 4 proxy!");
68                         return false;
69                 }
70
71                 char s4req[9 + (proxyuser ? strlen(proxyuser) : 0)];
72                 s4req[0] = 4;
73                 s4req[1] = 1;
74                 memcpy(s4req + 2, &c->address.in.sin_port, 2);
75                 memcpy(s4req + 4, &c->address.in.sin_addr, 4);
76
77                 if(proxyuser) {
78                         memcpy(s4req + 8, proxyuser, strlen(proxyuser));
79                 }
80
81                 s4req[sizeof(s4req) - 1] = 0;
82                 c->tcplen = 8;
83                 return send_meta(c, s4req, sizeof(s4req));
84         }
85
86         case PROXY_SOCKS5: {
87                 int len = 3 + 6 + (c->address.sa.sa_family == AF_INET ? 4 : 16);
88                 c->tcplen = 2;
89
90                 if(proxypass) {
91                         len += 3 + strlen(proxyuser) + strlen(proxypass);
92                 }
93
94                 char s5req[len];
95                 int i = 0;
96                 s5req[i++] = 5;
97                 s5req[i++] = 1;
98
99                 if(proxypass) {
100                         s5req[i++] = 2;
101                         s5req[i++] = 1;
102                         s5req[i++] = strlen(proxyuser);
103                         memcpy(s5req + i, proxyuser, strlen(proxyuser));
104                         i += strlen(proxyuser);
105                         s5req[i++] = strlen(proxypass);
106                         memcpy(s5req + i, proxypass, strlen(proxypass));
107                         i += strlen(proxypass);
108                         c->tcplen += 2;
109                 } else {
110                         s5req[i++] = 0;
111                 }
112
113                 s5req[i++] = 5;
114                 s5req[i++] = 1;
115                 s5req[i++] = 0;
116
117                 if(c->address.sa.sa_family == AF_INET) {
118                         s5req[i++] = 1;
119                         memcpy(s5req + i, &c->address.in.sin_addr, 4);
120                         i += 4;
121                         memcpy(s5req + i, &c->address.in.sin_port, 2);
122                         i += 2;
123                         c->tcplen += 10;
124                 } else if(c->address.sa.sa_family == AF_INET6) {
125                         s5req[i++] = 3;
126                         memcpy(s5req + i, &c->address.in6.sin6_addr, 16);
127                         i += 16;
128                         memcpy(s5req + i, &c->address.in6.sin6_port, 2);
129                         i += 2;
130                         c->tcplen += 22;
131                 } else {
132                         logger(DEBUG_ALWAYS, LOG_ERR, "Address family %x not supported for SOCKS 5 proxies!", c->address.sa.sa_family);
133                         return false;
134                 }
135
136                 if(i > len) {
137                         abort();
138                 }
139
140                 return send_meta(c, s5req, sizeof(s5req));
141         }
142
143         case PROXY_SOCKS4A:
144                 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type not implemented yet");
145                 return false;
146
147         case PROXY_EXEC:
148                 return true;
149
150         default:
151                 logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type");
152                 return false;
153         }
154 }
155
156 bool send_id(connection_t *c) {
157         gettimeofday(&c->start, NULL);
158
159         int minor = 0;
160
161         if(experimental) {
162                 if(c->outgoing && !read_ecdsa_public_key(&c->ecdsa, &c->config_tree, c->name)) {
163                         minor = 1;
164                 } else {
165                         minor = myself->connection->protocol_minor;
166                 }
167         }
168
169         if(proxytype && c->outgoing)
170                 if(!send_proxyrequest(c)) {
171                         return false;
172                 }
173
174         return send_request(c, "%d %s %d.%d", ID, myself->connection->name, myself->connection->protocol_major, minor);
175 }
176
177 static bool finalize_invitation(connection_t *c, const char *data, uint16_t len) {
178         (void)len;
179
180         if(strchr(data, '\n')) {
181                 logger(DEBUG_ALWAYS, LOG_ERR, "Received invalid key from invited node %s (%s)!\n", c->name, c->hostname);
182                 return false;
183         }
184
185         // Create a new host config file
186         char filename[PATH_MAX];
187         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
188
189         if(!access(filename, F_OK)) {
190                 logger(DEBUG_ALWAYS, LOG_ERR, "Host config file for %s (%s) already exists!\n", c->name, c->hostname);
191                 return false;
192         }
193
194         FILE *f = fopen(filename, "w");
195
196         if(!f) {
197                 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to create %s: %s\n", filename, strerror(errno));
198                 return false;
199         }
200
201         fprintf(f, "Ed25519PublicKey = %s\n", data);
202         fclose(f);
203
204         logger(DEBUG_CONNECTIONS, LOG_INFO, "Key successfully received from %s (%s)", c->name, c->hostname);
205
206         // Call invitation-accepted script
207         environment_t env;
208         char *address, *port;
209
210         environment_init(&env);
211         environment_add(&env, "NODE=%s", c->name);
212         sockaddr2str(&c->address, &address, &port);
213         environment_add(&env, "REMOTEADDRESS=%s", address);
214         environment_add(&env, "NAME=%s", myself->name);
215
216         free(address);
217         free(port);
218
219         execute_script("invitation-accepted", &env);
220
221         environment_exit(&env);
222
223         sptps_send_record(&c->sptps, 2, data, 0);
224         return true;
225 }
226
227 static bool receive_invitation_sptps(void *handle, uint8_t type, const void *data, uint16_t len) {
228         connection_t *c = handle;
229
230         if(type == 128) {
231                 return true;
232         }
233
234         if(type == 1 && c->status.invitation_used) {
235                 return finalize_invitation(c, data, len);
236         }
237
238         if(type != 0 || len != 18 || c->status.invitation_used) {
239                 return false;
240         }
241
242         // Recover the filename from the cookie and the key
243         char *fingerprint = ecdsa_get_base64_public_key(invitation_key);
244         char hashbuf[18 + strlen(fingerprint)];
245         char cookie[64];
246         memcpy(hashbuf, data, 18);
247         memcpy(hashbuf + 18, fingerprint, sizeof(hashbuf) - 18);
248         sha512(hashbuf, sizeof(hashbuf), cookie);
249         b64encode_urlsafe(cookie, cookie, 18);
250         free(fingerprint);
251
252         char filename[PATH_MAX], usedname[PATH_MAX];
253         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", confbase, cookie);
254         snprintf(usedname, sizeof(usedname), "%s" SLASH "invitations" SLASH "%s.used", confbase, cookie);
255
256         // Atomically rename the invitation file
257         if(rename(filename, usedname)) {
258                 if(errno == ENOENT) {
259                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s tried to use non-existing invitation %s\n", c->hostname, cookie);
260                 } else {
261                         logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to rename invitation %s\n", cookie);
262                 }
263
264                 return false;
265         }
266
267         // Check the timestamp of the invitation
268         struct stat st;
269
270         if(stat(usedname, &st)) {
271                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not stat %s", usedname);
272                 return false;
273         }
274
275         if(st.st_mtime + invitation_lifetime < now.tv_sec) {
276                 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s tried to use expired invitation %s", c->hostname, cookie);
277                 return false;
278         }
279
280         // Open the renamed file
281         FILE *f = fopen(usedname, "r");
282
283         if(!f) {
284                 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to open invitation %s\n", cookie);
285                 return false;
286         }
287
288         // Read the new node's Name from the file
289         char buf[1024] = "";
290         fgets(buf, sizeof(buf), f);
291         size_t buflen = strlen(buf);
292
293         // Strip whitespace at the end
294         while(buflen && strchr(" \t\r\n", buf[buflen - 1])) {
295                 buf[--buflen] = 0;
296         }
297
298         // Split the first line into variable and value
299         len = strcspn(buf, " \t=");
300         char *name = buf + len;
301         name += strspn(name, " \t");
302
303         if(*name == '=') {
304                 name++;
305                 name += strspn(name, " \t");
306         }
307
308         buf[len] = 0;
309
310         // Check that it is a valid Name
311         if(!*buf || !*name || strcasecmp(buf, "Name") || !check_id(name) || !strcmp(name, myself->name)) {
312                 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid invitation file %s\n", cookie);
313                 fclose(f);
314                 return false;
315         }
316
317         free(c->name);
318         c->name = xstrdup(name);
319
320         // Send the node the contents of the invitation file
321         rewind(f);
322         size_t result;
323
324         while((result = fread(buf, 1, sizeof(buf), f))) {
325                 sptps_send_record(&c->sptps, 0, buf, result);
326         }
327
328         sptps_send_record(&c->sptps, 1, buf, 0);
329         fclose(f);
330         unlink(usedname);
331
332         c->status.invitation_used = true;
333
334         logger(DEBUG_CONNECTIONS, LOG_INFO, "Invitation %s successfully sent to %s (%s)", cookie, c->name, c->hostname);
335         return true;
336 }
337
338 bool id_h(connection_t *c, const char *request) {
339         char name[MAX_STRING_SIZE];
340
341         if(sscanf(request, "%*d " MAX_STRING " %2d.%3d", name, &c->protocol_major, &c->protocol_minor) < 2) {
342                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
343                        c->hostname);
344                 return false;
345         }
346
347         /* Check if this is a control connection */
348
349         if(name[0] == '^' && !strcmp(name + 1, controlcookie)) {
350                 c->status.control = true;
351                 c->allow_request = CONTROL;
352                 c->last_ping_time = now.tv_sec + 3600;
353
354                 free(c->name);
355                 c->name = xstrdup("<control>");
356
357                 if(!c->outgoing) {
358                         send_id(c);
359                 }
360
361                 return send_request(c, "%d %d %d", ACK, TINC_CTL_VERSION_CURRENT, getpid());
362         }
363
364         if(name[0] == '?') {
365                 if(!invitation_key) {
366                         logger(DEBUG_ALWAYS, LOG_ERR, "Got invitation from %s but we don't have an invitation key", c->hostname);
367                         return false;
368                 }
369
370                 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
371
372                 if(!c->ecdsa) {
373                         logger(DEBUG_ALWAYS, LOG_ERR, "Got bad invitation from %s", c->hostname);
374                         return false;
375                 }
376
377                 c->status.invitation = true;
378                 char *mykey = ecdsa_get_base64_public_key(invitation_key);
379
380                 if(!mykey) {
381                         return false;
382                 }
383
384                 if(!c->outgoing) {
385                         send_id(c);
386                 }
387
388                 if(!send_request(c, "%d %s", ACK, mykey)) {
389                         return false;
390                 }
391
392                 free(mykey);
393
394                 c->protocol_minor = 2;
395
396                 return sptps_start(&c->sptps, c, false, false, invitation_key, c->ecdsa, "tinc invitation", 15, send_meta_sptps, receive_invitation_sptps);
397         }
398
399         /* Check if identity is a valid name */
400
401         if(!check_id(name) || !strcmp(name, myself->name)) {
402                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
403                        c->hostname, "invalid name");
404                 return false;
405         }
406
407         /* If this is an outgoing connection, make sure we are connected to the right host */
408
409         if(c->outgoing) {
410                 if(strcmp(c->name, name)) {
411                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
412                                c->name);
413                         return false;
414                 }
415         } else {
416                 free(c->name);
417                 c->name = xstrdup(name);
418         }
419
420         /* Check if version matches */
421
422         if(c->protocol_major != myself->connection->protocol_major) {
423                 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) uses incompatible version %d.%d",
424                        c->name, c->hostname, c->protocol_major, c->protocol_minor);
425                 return false;
426         }
427
428         if(bypass_security) {
429                 if(!c->config_tree) {
430                         init_configuration(&c->config_tree);
431                 }
432
433                 c->allow_request = ACK;
434
435                 if(!c->outgoing) {
436                         send_id(c);
437                 }
438
439                 return send_ack(c);
440         }
441
442         if(!experimental) {
443                 c->protocol_minor = 0;
444         }
445
446         if(!c->config_tree) {
447                 init_configuration(&c->config_tree);
448
449                 if(!read_host_config(c->config_tree, c->name, false)) {
450                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname, c->name);
451                         return false;
452                 }
453
454                 if(experimental) {
455                         read_ecdsa_public_key(&c->ecdsa, &c->config_tree, c->name);
456                 }
457
458                 /* Ignore failures if no key known yet */
459         }
460
461         if(c->protocol_minor && !ecdsa_active(c->ecdsa)) {
462                 c->protocol_minor = 1;
463         }
464
465         /* Forbid version rollback for nodes whose Ed25519 key we know */
466
467         if(ecdsa_active(c->ecdsa) && c->protocol_minor < 1) {
468                 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) tries to roll back protocol version to %d.%d",
469                        c->name, c->hostname, c->protocol_major, c->protocol_minor);
470                 return false;
471         }
472
473         c->allow_request = METAKEY;
474
475         if(!c->outgoing) {
476                 send_id(c);
477         }
478
479         if(c->protocol_minor >= 2) {
480                 c->allow_request = ACK;
481                 char label[25 + strlen(myself->name) + strlen(c->name)];
482
483                 if(c->outgoing) {
484                         snprintf(label, sizeof(label), "tinc TCP key expansion %s %s", myself->name, c->name);
485                 } else {
486                         snprintf(label, sizeof(label), "tinc TCP key expansion %s %s", c->name, myself->name);
487                 }
488
489                 return sptps_start(&c->sptps, c, c->outgoing, false, myself->connection->ecdsa, c->ecdsa, label, sizeof(label), send_meta_sptps, receive_meta_sptps);
490         } else {
491                 return send_metakey(c);
492         }
493 }
494
495 #ifndef DISABLE_LEGACY
496 bool send_metakey(connection_t *c) {
497         if(!myself->connection->rsa) {
498                 logger(DEBUG_CONNECTIONS, LOG_ERR, "Peer %s (%s) uses legacy protocol which we don't support", c->name, c->hostname);
499                 return false;
500         }
501
502         if(!read_rsa_public_key(&c->rsa, c->config_tree, c->name)) {
503                 return false;
504         }
505
506         /* We need to use a stream mode for the meta protocol. Use AES for this,
507            but try to match the key size with the one from the cipher selected
508            by Cipher.
509         */
510
511         int keylen = cipher_keylength(myself->incipher);
512
513         if(keylen <= 16) {
514                 c->outcipher = cipher_open_by_name("aes-128-cfb");
515         } else if(keylen <= 24) {
516                 c->outcipher = cipher_open_by_name("aes-192-cfb");
517         } else {
518                 c->outcipher = cipher_open_by_name("aes-256-cfb");
519         }
520
521         if(!c) {
522                 return false;
523         }
524
525         c->outbudget = cipher_budget(c->outcipher);
526
527         if(!(c->outdigest = digest_open_by_name("sha256", -1))) {
528                 return false;
529         }
530
531         const size_t len = rsa_size(c->rsa);
532         char key[len];
533         char enckey[len];
534         char hexkey[2 * len + 1];
535
536         /* Create a random key */
537
538         randomize(key, len);
539
540         /* The message we send must be smaller than the modulus of the RSA key.
541            By definition, for a key of k bits, the following formula holds:
542
543            2^(k-1) <= modulus < 2^(k)
544
545            Where ^ means "to the power of", not "xor".
546            This means that to be sure, we must choose our message < 2^(k-1).
547            This can be done by setting the most significant bit to zero.
548          */
549
550         key[0] &= 0x7F;
551
552         if(!cipher_set_key_from_rsa(c->outcipher, key, len, true)) {
553                 return false;
554         }
555
556         if(debug_level >= DEBUG_SCARY_THINGS) {
557                 bin2hex(key, hexkey, len);
558                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Generated random meta key (unencrypted): %s", hexkey);
559         }
560
561         /* Encrypt the random data
562
563            We do not use one of the PKCS padding schemes here.
564            This is allowed, because we encrypt a totally random string
565            with a length equal to that of the modulus of the RSA key.
566          */
567
568         if(!rsa_public_encrypt(c->rsa, key, len, enckey)) {
569                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during encryption of meta key for %s (%s)", c->name, c->hostname);
570                 return false;
571         }
572
573         /* Convert the encrypted random data to a hexadecimal formatted string */
574
575         bin2hex(enckey, hexkey, len);
576
577         /* Send the meta key */
578
579         bool result = send_request(c, "%d %d %d %d %d %s", METAKEY,
580                                    cipher_get_nid(c->outcipher),
581                                    digest_get_nid(c->outdigest), c->outmaclength,
582                                    c->outcompression, hexkey);
583
584         c->status.encryptout = true;
585         return result;
586 }
587
588 bool metakey_h(connection_t *c, const char *request) {
589         if(!myself->connection->rsa) {
590                 return false;
591         }
592
593         char hexkey[MAX_STRING_SIZE];
594         int cipher, digest, maclength, compression;
595         const size_t len = rsa_size(myself->connection->rsa);
596         char enckey[len];
597         char key[len];
598
599         if(sscanf(request, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, hexkey) != 5) {
600                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
601                 return false;
602         }
603
604         /* Convert the challenge from hexadecimal back to binary */
605
606         size_t inlen = hex2bin(hexkey, enckey, sizeof(enckey));
607
608         /* Check if the length of the meta key is all right */
609
610         if(inlen != len) {
611                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
612                 return false;
613         }
614
615         /* Decrypt the meta key */
616
617         if(!rsa_private_decrypt(myself->connection->rsa, enckey, len, key)) {
618                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during decryption of meta key for %s (%s)", c->name, c->hostname);
619                 return false;
620         }
621
622         if(debug_level >= DEBUG_SCARY_THINGS) {
623                 bin2hex(key, hexkey, len);
624                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Received random meta key (unencrypted): %s", hexkey);
625         }
626
627         /* Check and lookup cipher and digest algorithms */
628
629         if(cipher) {
630                 if(!(c->incipher = cipher_open_by_nid(cipher)) || !cipher_set_key_from_rsa(c->incipher, key, len, false)) {
631                         logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of cipher from %s (%s)", c->name, c->hostname);
632                         return false;
633                 }
634         } else {
635                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "null cipher");
636                 return false;
637         }
638
639         c->inbudget = cipher_budget(c->incipher);
640
641         if(digest) {
642                 if(!(c->indigest = digest_open_by_nid(digest, -1))) {
643                         logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of digest from %s (%s)", c->name, c->hostname);
644                         return false;
645                 }
646         } else {
647                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "null digest");
648                 return false;
649         }
650
651         c->status.decryptin = true;
652
653         c->allow_request = CHALLENGE;
654
655         return send_challenge(c);
656 }
657
658 bool send_challenge(connection_t *c) {
659         const size_t len = rsa_size(c->rsa);
660         char buffer[len * 2 + 1];
661
662         c->hischallenge = xrealloc(c->hischallenge, len);
663
664         /* Copy random data to the buffer */
665
666         randomize(c->hischallenge, len);
667
668         /* Convert to hex */
669
670         bin2hex(c->hischallenge, buffer, len);
671
672         /* Send the challenge */
673
674         return send_request(c, "%d %s", CHALLENGE, buffer);
675 }
676
677 bool challenge_h(connection_t *c, const char *request) {
678         if(!myself->connection->rsa) {
679                 return false;
680         }
681
682         char buffer[MAX_STRING_SIZE];
683         const size_t len = rsa_size(myself->connection->rsa);
684
685         if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
686                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name, c->hostname);
687                 return false;
688         }
689
690         /* Check if the length of the challenge is all right */
691
692         if(strlen(buffer) != (size_t)len * 2) {
693                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge length");
694                 return false;
695         }
696
697         c->mychallenge = xrealloc(c->mychallenge, len);
698
699         /* Convert the challenge from hexadecimal back to binary */
700
701         hex2bin(buffer, c->mychallenge, len);
702
703         /* The rest is done by send_chal_reply() */
704
705         c->allow_request = CHAL_REPLY;
706
707         if(c->outgoing) {
708                 return send_chal_reply(c);
709         } else {
710                 return true;
711         }
712 }
713
714 bool send_chal_reply(connection_t *c) {
715         const size_t len = rsa_size(myself->connection->rsa);
716         size_t digestlen = digest_length(c->indigest);
717         char digest[digestlen * 2 + 1];
718
719         /* Calculate the hash from the challenge we received */
720
721         if(!digest_create(c->indigest, c->mychallenge, len, digest)) {
722                 return false;
723         }
724
725         free(c->mychallenge);
726         c->mychallenge = NULL;
727
728         /* Convert the hash to a hexadecimal formatted string */
729
730         bin2hex(digest, digest, digestlen);
731
732         /* Send the reply */
733
734         return send_request(c, "%d %s", CHAL_REPLY, digest);
735 }
736
737 bool chal_reply_h(connection_t *c, const char *request) {
738         char hishash[MAX_STRING_SIZE];
739
740         if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
741                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
742                        c->hostname);
743                 return false;
744         }
745
746         /* Convert the hash to binary format */
747
748         size_t inlen = hex2bin(hishash, hishash, sizeof(hishash));
749
750         /* Check if the length of the hash is all right */
751
752         if(inlen != digest_length(c->outdigest)) {
753                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply length");
754                 return false;
755         }
756
757
758         /* Verify the hash */
759
760         if(!digest_verify(c->outdigest, c->hischallenge, rsa_size(c->rsa), hishash)) {
761                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply");
762                 return false;
763         }
764
765         /* Identity has now been positively verified.
766            Send an acknowledgement with the rest of the information needed.
767          */
768
769         free(c->hischallenge);
770         c->hischallenge = NULL;
771         c->allow_request = ACK;
772
773         if(!c->outgoing) {
774                 send_chal_reply(c);
775         }
776
777         return send_ack(c);
778 }
779
780 static bool send_upgrade(connection_t *c) {
781         /* Special case when protocol_minor is 1: the other end is Ed25519 capable,
782          * but doesn't know our key yet. So send it now. */
783
784         char *pubkey = ecdsa_get_base64_public_key(myself->connection->ecdsa);
785
786         if(!pubkey) {
787                 return false;
788         }
789
790         bool result = send_request(c, "%d %s", ACK, pubkey);
791         free(pubkey);
792         return result;
793 }
794 #else
795 bool send_metakey(connection_t *c) {
796         (void)c;
797         return false;
798 }
799
800 bool metakey_h(connection_t *c, const char *request) {
801         (void)c;
802         (void)request;
803         return false;
804 }
805
806 bool send_challenge(connection_t *c) {
807         (void)c;
808         return false;
809 }
810
811 bool challenge_h(connection_t *c, const char *request) {
812         (void)c;
813         (void)request;
814         return false;
815 }
816
817 bool send_chal_reply(connection_t *c) {
818         (void)c;
819         return false;
820 }
821
822 bool chal_reply_h(connection_t *c, const char *request) {
823         (void)c;
824         (void)request;
825         return false;
826 }
827
828 static bool send_upgrade(connection_t *c) {
829         (void)c;
830         return false;
831 }
832 #endif
833
834 bool send_ack(connection_t *c) {
835         if(c->protocol_minor == 1) {
836                 return send_upgrade(c);
837         }
838
839         /* ACK message contains rest of the information the other end needs
840            to create node_t and edge_t structures. */
841
842         struct timeval now;
843         bool choice;
844
845         /* Estimate weight */
846
847         gettimeofday(&now, NULL);
848         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
849
850         /* Check some options */
851
852         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT) {
853                 c->options |= OPTION_INDIRECT;
854         }
855
856         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY) {
857                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
858         }
859
860         if(myself->options & OPTION_PMTU_DISCOVERY && !(c->options & OPTION_TCPONLY)) {
861                 c->options |= OPTION_PMTU_DISCOVERY;
862         }
863
864         choice = myself->options & OPTION_CLAMP_MSS;
865         get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
866
867         if(choice) {
868                 c->options |= OPTION_CLAMP_MSS;
869         }
870
871         if(!get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight)) {
872                 get_config_int(lookup_config(config_tree, "Weight"), &c->estimated_weight);
873         }
874
875         return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, (c->options & 0xffffff) | (experimental ? (PROT_MINOR << 24) : 0));
876 }
877
878 static void send_everything(connection_t *c) {
879         /* Send all known subnets and edges */
880
881         if(disablebuggypeers) {
882                 static struct {
883                         vpn_packet_t pkt;
884                         char pad[MAXBUFSIZE - MAXSIZE];
885                 } zeropkt;
886
887                 memset(&zeropkt, 0, sizeof(zeropkt));
888                 zeropkt.pkt.len = MAXBUFSIZE;
889                 send_tcppacket(c, &zeropkt.pkt);
890         }
891
892         if(tunnelserver) {
893                 for splay_each(subnet_t, s, myself->subnet_tree) {
894                         send_add_subnet(c, s);
895                 }
896
897                 return;
898         }
899
900         for splay_each(node_t, n, node_tree) {
901                 for splay_each(subnet_t, s, n->subnet_tree) {
902                         send_add_subnet(c, s);
903                 }
904
905                 for splay_each(edge_t, e, n->edge_tree) {
906                         send_add_edge(c, e);
907                 }
908         }
909 }
910
911 static bool upgrade_h(connection_t *c, const char *request) {
912         char pubkey[MAX_STRING_SIZE];
913
914         if(sscanf(request, "%*d " MAX_STRING, pubkey) != 1) {
915                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name, c->hostname);
916                 return false;
917         }
918
919         if(ecdsa_active(c->ecdsa) || read_ecdsa_public_key(&c->ecdsa, &c->config_tree, c->name)) {
920                 char *knownkey = ecdsa_get_base64_public_key(c->ecdsa);
921                 bool different = strcmp(knownkey, pubkey);
922                 free(knownkey);
923
924                 if(different) {
925                         logger(DEBUG_ALWAYS, LOG_ERR, "Already have an Ed25519 public key from %s (%s) which is different from the one presented now!", c->name, c->hostname);
926                         return false;
927                 }
928
929                 logger(DEBUG_ALWAYS, LOG_INFO, "Already have Ed25519 public key from %s (%s), ignoring.", c->name, c->hostname);
930                 c->allow_request = TERMREQ;
931                 return send_termreq(c);
932         }
933
934         c->ecdsa = ecdsa_set_base64_public_key(pubkey);
935
936         if(!c->ecdsa) {
937                 logger(DEBUG_ALWAYS, LOG_INFO, "Got bad Ed25519 public key from %s (%s), not upgrading.", c->name, c->hostname);
938                 return false;
939         }
940
941         logger(DEBUG_ALWAYS, LOG_INFO, "Got Ed25519 public key from %s (%s), upgrading!", c->name, c->hostname);
942         append_config_file(c->name, "Ed25519PublicKey", pubkey);
943         c->allow_request = TERMREQ;
944
945         if(c->outgoing) {
946                 c->outgoing->timeout = 0;
947         }
948
949         return send_termreq(c);
950 }
951
952 bool ack_h(connection_t *c, const char *request) {
953         if(c->protocol_minor == 1) {
954                 return upgrade_h(c, request);
955         }
956
957         char hisport[MAX_STRING_SIZE];
958         int weight, mtu;
959         uint32_t options;
960         node_t *n;
961         bool choice;
962
963         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
964                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
965                        c->hostname);
966                 return false;
967         }
968
969         /* Check if we already have a node_t for him */
970
971         n = lookup_node(c->name);
972
973         if(!n) {
974                 n = new_node();
975                 n->name = xstrdup(c->name);
976                 node_add(n);
977         } else {
978                 if(n->connection) {
979                         /* Oh dear, we already have a connection to this node. */
980                         logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
981
982                         if(n->connection->outgoing) {
983                                 if(c->outgoing) {
984                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Two outgoing connections to the same node!");
985                                 } else {
986                                         c->outgoing = n->connection->outgoing;
987                                 }
988
989                                 n->connection->outgoing = NULL;
990                         }
991
992                         terminate_connection(n->connection, false);
993                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
994                         graph();
995                 }
996         }
997
998         n->connection = c;
999         c->node = n;
1000
1001         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
1002                 c->options &= ~OPTION_PMTU_DISCOVERY;
1003                 options &= ~OPTION_PMTU_DISCOVERY;
1004         }
1005
1006         c->options |= options;
1007
1008         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
1009                 n->mtu = mtu;
1010         }
1011
1012         if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
1013                 n->mtu = mtu;
1014         }
1015
1016         if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
1017                 if(choice) {
1018                         c->options |= OPTION_CLAMP_MSS;
1019                 } else {
1020                         c->options &= ~OPTION_CLAMP_MSS;
1021                 }
1022         }
1023
1024         /* Activate this connection */
1025
1026         c->allow_request = ALL;
1027
1028         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection with %s (%s) activated", c->name,
1029                c->hostname);
1030
1031         /* Send him everything we know */
1032
1033         send_everything(c);
1034
1035         /* Create an edge_t for this connection */
1036
1037         c->edge = new_edge();
1038         c->edge->from = myself;
1039         c->edge->to = n;
1040         sockaddrcpy(&c->edge->address, &c->address);
1041         sockaddr_setport(&c->edge->address, hisport);
1042         sockaddr_t local_sa;
1043         socklen_t local_salen = sizeof(local_sa);
1044
1045         if(getsockname(c->socket, &local_sa.sa, &local_salen) < 0) {
1046                 logger(DEBUG_ALWAYS, LOG_WARNING, "Could not get local socket address for connection with %s", c->name);
1047         } else {
1048                 sockaddr_setport(&local_sa, myport);
1049                 c->edge->local_address = local_sa;
1050         }
1051
1052         c->edge->weight = (weight + c->estimated_weight) / 2;
1053         c->edge->connection = c;
1054         c->edge->options = c->options;
1055
1056         edge_add(c->edge);
1057
1058         /* Notify everyone of the new edge */
1059
1060         if(tunnelserver) {
1061                 send_add_edge(c, c->edge);
1062         } else {
1063                 send_add_edge(everyone, c->edge);
1064         }
1065
1066         /* Run MST and SSSP algorithms */
1067
1068         graph();
1069
1070         return true;
1071 }