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