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