22254575341a482da395cbe3028cf4394ac1f474
[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         char *key = alloca(len);
558         char *enckey = alloca(len);
559         char *hexkey = alloca(2 * len + 1);
560
561         /* Create a random key */
562
563         randomize(key, len);
564
565         /* The message we send must be smaller than the modulus of the RSA key.
566            By definition, for a key of k bits, the following formula holds:
567
568            2^(k-1) <= modulus < 2^(k)
569
570            Where ^ means "to the power of", not "xor".
571            This means that to be sure, we must choose our message < 2^(k-1).
572            This can be done by setting the most significant bit to zero.
573          */
574
575         key[0] &= 0x7F;
576
577         if(!cipher_set_key_from_rsa(&ctx->out.cipher, key, len, true)) {
578                 free_legacy_ctx(ctx);
579                 return false;
580         }
581
582         if(debug_level >= DEBUG_SCARY_THINGS) {
583                 bin2hex(key, hexkey, len);
584                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Generated random meta key (unencrypted): %s", hexkey);
585         }
586
587         /* Encrypt the random data
588
589            We do not use one of the PKCS padding schemes here.
590            This is allowed, because we encrypt a totally random string
591            with a length equal to that of the modulus of the RSA key.
592          */
593
594         if(!rsa_public_encrypt(ctx->rsa, key, len, enckey)) {
595                 free_legacy_ctx(ctx);
596                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during encryption of meta key for %s (%s)", c->name, c->hostname);
597                 return false;
598         }
599
600         free_legacy_ctx(c->legacy);
601         c->legacy = ctx;
602
603         /* Convert the encrypted random data to a hexadecimal formatted string */
604
605         bin2hex(enckey, hexkey, len);
606
607         /* Send the meta key */
608
609         bool result = send_request(c, "%d %d %d %d %d %s", METAKEY,
610                                    cipher_get_nid(&c->legacy->out.cipher),
611                                    digest_get_nid(&c->legacy->out.digest), c->outmaclength,
612                                    COMPRESS_NONE, hexkey);
613
614         c->status.encryptout = true;
615         return result;
616 }
617
618 bool metakey_h(connection_t *c, const char *request) {
619         if(!myself->connection->legacy || !c->legacy) {
620                 return false;
621         }
622
623         char hexkey[MAX_STRING_SIZE];
624         int cipher, digest;
625         const size_t len = rsa_size(myself->connection->legacy->rsa);
626         char *enckey = alloca(len);
627         char *key = alloca(len);
628
629         if(sscanf(request, "%*d %d %d %*d %*d " MAX_STRING, &cipher, &digest, hexkey) != 3) {
630                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
631                 return false;
632         }
633
634         /* Convert the challenge from hexadecimal back to binary */
635
636         size_t inlen = hex2bin(hexkey, enckey, len);
637
638         /* Check if the length of the meta key is all right */
639
640         if(inlen != len) {
641                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
642                 return false;
643         }
644
645         /* Decrypt the meta key */
646
647         if(!rsa_private_decrypt(myself->connection->legacy->rsa, enckey, len, key)) {
648                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during decryption of meta key for %s (%s)", c->name, c->hostname);
649                 return false;
650         }
651
652         if(debug_level >= DEBUG_SCARY_THINGS) {
653                 bin2hex(key, hexkey, len);
654                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Received random meta key (unencrypted): %s", hexkey);
655         }
656
657         /* Check and lookup cipher and digest algorithms */
658
659         if(!cipher || !digest) {
660                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): cipher %d, digest %d", c->name, c->hostname, cipher, digest);
661                 return false;
662         }
663
664         if(!init_crypto_by_nid(&c->legacy->in, cipher, digest)) {
665                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of cipher or digest from %s (%s)", c->name, c->hostname);
666                 return false;
667         }
668
669         if(!cipher_set_key_from_rsa(&c->legacy->in.cipher, key, len, false)) {
670                 logger(DEBUG_ALWAYS, LOG_ERR, "Error setting RSA key for %s (%s)", c->name, c->hostname);
671                 return false;
672         }
673
674
675         c->status.decryptin = true;
676
677         c->allow_request = CHALLENGE;
678
679         return send_challenge(c);
680 }
681
682 bool send_challenge(connection_t *c) {
683         const size_t len = rsa_size(c->legacy->rsa);
684         char *buffer = alloca(len * 2 + 1);
685
686         c->hischallenge = xrealloc(c->hischallenge, len);
687
688         /* Copy random data to the buffer */
689
690         randomize(c->hischallenge, len);
691
692         /* Convert to hex */
693
694         bin2hex(c->hischallenge, buffer, len);
695
696         /* Send the challenge */
697
698         return send_request(c, "%d %s", CHALLENGE, buffer);
699 }
700
701 bool challenge_h(connection_t *c, const char *request) {
702         if(!myself->connection->legacy) {
703                 return false;
704         }
705
706         char buffer[MAX_STRING_SIZE];
707         const size_t len = rsa_size(myself->connection->legacy->rsa);
708
709         if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
710                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name, c->hostname);
711                 return false;
712         }
713
714         /* Check if the length of the challenge is all right */
715
716         if(strlen(buffer) != (size_t)len * 2) {
717                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge length");
718                 return false;
719         }
720
721         c->mychallenge = xrealloc(c->mychallenge, len);
722
723         /* Convert the challenge from hexadecimal back to binary */
724
725         hex2bin(buffer, c->mychallenge, len);
726
727         /* The rest is done by send_chal_reply() */
728
729         c->allow_request = CHAL_REPLY;
730
731         if(c->outgoing) {
732                 return send_chal_reply(c);
733         } else {
734                 return true;
735         }
736 }
737
738 bool send_chal_reply(connection_t *c) {
739         const size_t len = rsa_size(myself->connection->legacy->rsa);
740         size_t digestlen = digest_length(&c->legacy->in.digest);
741         char *digest = alloca(digestlen * 2 + 1);
742
743         /* Calculate the hash from the challenge we received */
744
745         if(!digest_create(&c->legacy->in.digest, c->mychallenge, len, digest)) {
746                 return false;
747         }
748
749         free(c->mychallenge);
750         c->mychallenge = NULL;
751
752         /* Convert the hash to a hexadecimal formatted string */
753
754         bin2hex(digest, digest, digestlen);
755
756         /* Send the reply */
757
758         return send_request(c, "%d %s", CHAL_REPLY, digest);
759 }
760
761 bool chal_reply_h(connection_t *c, const char *request) {
762         char hishash[MAX_STRING_SIZE];
763
764         if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
765                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
766                        c->hostname);
767                 return false;
768         }
769
770         /* Convert the hash to binary format */
771
772         size_t inlen = hex2bin(hishash, hishash, sizeof(hishash));
773
774         /* Check if the length of the hash is all right */
775
776         if(inlen != digest_length(&c->legacy->out.digest)) {
777                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply length");
778                 return false;
779         }
780
781
782         /* Verify the hash */
783
784         if(!digest_verify(&c->legacy->out.digest, c->hischallenge, rsa_size(c->legacy->rsa), hishash)) {
785                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply");
786                 return false;
787         }
788
789         /* Identity has now been positively verified.
790            Send an acknowledgement with the rest of the information needed.
791          */
792
793         free(c->hischallenge);
794         c->hischallenge = NULL;
795         c->allow_request = ACK;
796
797         if(!c->outgoing) {
798                 send_chal_reply(c);
799         }
800
801         return send_ack(c);
802 }
803
804 static bool send_upgrade(connection_t *c) {
805         /* Special case when protocol_minor is 1: the other end is Ed25519 capable,
806          * but doesn't know our key yet. So send it now. */
807
808         char *pubkey = ecdsa_get_base64_public_key(myself->connection->ecdsa);
809
810         if(!pubkey) {
811                 return false;
812         }
813
814         bool result = send_request(c, "%d %s", ACK, pubkey);
815         free(pubkey);
816         return result;
817 }
818 #else
819 bool send_metakey(connection_t *c) {
820         (void)c;
821         return false;
822 }
823
824 bool metakey_h(connection_t *c, const char *request) {
825         (void)c;
826         (void)request;
827         return false;
828 }
829
830 bool send_challenge(connection_t *c) {
831         (void)c;
832         return false;
833 }
834
835 bool challenge_h(connection_t *c, const char *request) {
836         (void)c;
837         (void)request;
838         return false;
839 }
840
841 bool send_chal_reply(connection_t *c) {
842         (void)c;
843         return false;
844 }
845
846 bool chal_reply_h(connection_t *c, const char *request) {
847         (void)c;
848         (void)request;
849         return false;
850 }
851
852 static bool send_upgrade(connection_t *c) {
853         (void)c;
854         return false;
855 }
856 #endif
857
858 bool send_ack(connection_t *c) {
859         if(c->protocol_minor == 1) {
860                 return send_upgrade(c);
861         }
862
863         /* ACK message contains rest of the information the other end needs
864            to create node_t and edge_t structures. */
865
866         struct timeval now;
867         bool choice;
868
869         /* Estimate weight */
870
871         gettimeofday(&now, NULL);
872         c->estimated_weight = (int)((now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000);
873
874         /* Check some options */
875
876         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT) {
877                 c->options |= OPTION_INDIRECT;
878         }
879
880         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY) {
881                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
882         }
883
884         if(myself->options & OPTION_PMTU_DISCOVERY && !(c->options & OPTION_TCPONLY)) {
885                 c->options |= OPTION_PMTU_DISCOVERY;
886         }
887
888         choice = myself->options & OPTION_CLAMP_MSS;
889         get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
890
891         if(choice) {
892                 c->options |= OPTION_CLAMP_MSS;
893         }
894
895         if(!get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight)) {
896                 get_config_int(lookup_config(&config_tree, "Weight"), &c->estimated_weight);
897         }
898
899         return send_request(c, "%d %s %d %x", ACK, myport.udp, c->estimated_weight, (c->options & 0xffffff) | (experimental ? (PROT_MINOR << 24) : 0));
900 }
901
902 static void send_everything(connection_t *c) {
903         /* Send all known subnets and edges */
904
905         if(disablebuggypeers) {
906                 static struct {
907                         vpn_packet_t pkt;
908                         char pad[MAXBUFSIZE - MAXSIZE];
909                 } zeropkt;
910
911                 memset(&zeropkt, 0, sizeof(zeropkt));
912                 zeropkt.pkt.len = MAXBUFSIZE;
913                 send_tcppacket(c, &zeropkt.pkt);
914         }
915
916         if(tunnelserver) {
917                 for splay_each(subnet_t, s, &myself->subnet_tree) {
918                         send_add_subnet(c, s);
919                 }
920
921                 return;
922         }
923
924         for splay_each(node_t, n, &node_tree) {
925                 for splay_each(subnet_t, s, &n->subnet_tree) {
926                         send_add_subnet(c, s);
927                 }
928
929                 for splay_each(edge_t, e, &n->edge_tree) {
930                         send_add_edge(c, e);
931                 }
932         }
933 }
934
935 static bool upgrade_h(connection_t *c, const char *request) {
936         char pubkey[MAX_STRING_SIZE];
937
938         if(sscanf(request, "%*d " MAX_STRING, pubkey) != 1) {
939                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name, c->hostname);
940                 return false;
941         }
942
943         if(ecdsa_active(c->ecdsa) || read_ecdsa_public_key(&c->ecdsa, &c->config_tree, c->name)) {
944                 char *knownkey = ecdsa_get_base64_public_key(c->ecdsa);
945                 bool different = strcmp(knownkey, pubkey);
946                 free(knownkey);
947
948                 if(different) {
949                         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);
950                         return false;
951                 }
952
953                 logger(DEBUG_ALWAYS, LOG_INFO, "Already have Ed25519 public key from %s (%s), ignoring.", c->name, c->hostname);
954                 c->allow_request = TERMREQ;
955                 return send_termreq(c);
956         }
957
958         c->ecdsa = ecdsa_set_base64_public_key(pubkey);
959
960         if(!c->ecdsa) {
961                 logger(DEBUG_ALWAYS, LOG_INFO, "Got bad Ed25519 public key from %s (%s), not upgrading.", c->name, c->hostname);
962                 return false;
963         }
964
965         logger(DEBUG_ALWAYS, LOG_INFO, "Got Ed25519 public key from %s (%s), upgrading!", c->name, c->hostname);
966         append_config_file(c->name, "Ed25519PublicKey", pubkey);
967         c->allow_request = TERMREQ;
968
969         if(c->outgoing) {
970                 c->outgoing->timeout = 0;
971         }
972
973         return send_termreq(c);
974 }
975
976 bool ack_h(connection_t *c, const char *request) {
977         if(c->protocol_minor == 1) {
978                 return upgrade_h(c, request);
979         }
980
981         char hisport[MAX_STRING_SIZE];
982         int weight, mtu;
983         uint32_t options;
984         node_t *n;
985         bool choice;
986
987         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
988                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
989                        c->hostname);
990                 return false;
991         }
992
993         /* Check if we already have a node_t for him */
994
995         n = lookup_node(c->name);
996
997         if(!n) {
998                 n = new_node();
999                 n->name = xstrdup(c->name);
1000                 node_add(n);
1001         } else {
1002                 if(n->connection) {
1003                         /* Oh dear, we already have a connection to this node. */
1004                         logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
1005
1006                         if(n->connection->outgoing) {
1007                                 if(c->outgoing) {
1008                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Two outgoing connections to the same node!");
1009                                 } else {
1010                                         c->outgoing = n->connection->outgoing;
1011                                 }
1012
1013                                 n->connection->outgoing = NULL;
1014                         }
1015
1016                         terminate_connection(n->connection, false);
1017                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
1018                         graph();
1019                 }
1020         }
1021
1022         n->connection = c;
1023         c->node = n;
1024
1025         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
1026                 c->options &= ~OPTION_PMTU_DISCOVERY;
1027                 options &= ~OPTION_PMTU_DISCOVERY;
1028         }
1029
1030         c->options |= options;
1031
1032         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
1033                 n->mtu = mtu;
1034         }
1035
1036         if(get_config_int(lookup_config(&config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
1037                 n->mtu = mtu;
1038         }
1039
1040         if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
1041                 if(choice) {
1042                         c->options |= OPTION_CLAMP_MSS;
1043                 } else {
1044                         c->options &= ~OPTION_CLAMP_MSS;
1045                 }
1046         }
1047
1048         /* Activate this connection */
1049
1050         c->allow_request = ALL;
1051
1052         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection with %s (%s) activated", c->name,
1053                c->hostname);
1054
1055         /* Send him everything we know */
1056
1057         send_everything(c);
1058
1059         /* Create an edge_t for this connection */
1060
1061         c->edge = new_edge();
1062         c->edge->from = myself;
1063         c->edge->to = n;
1064         sockaddrcpy(&c->edge->address, &c->address);
1065         sockaddr_setport(&c->edge->address, hisport);
1066         sockaddr_t local_sa;
1067         socklen_t local_salen = sizeof(local_sa);
1068
1069         if(getsockname(c->socket, &local_sa.sa, &local_salen) < 0) {
1070                 logger(DEBUG_ALWAYS, LOG_WARNING, "Could not get local socket address for connection with %s", c->name);
1071         } else {
1072                 sockaddr_setport(&local_sa, myport.udp);
1073                 c->edge->local_address = local_sa;
1074         }
1075
1076         c->edge->weight = (weight + c->estimated_weight) / 2;
1077         c->edge->connection = c;
1078         c->edge->options = c->options;
1079
1080         edge_add(c->edge);
1081
1082         /* Notify everyone of the new edge */
1083
1084         if(tunnelserver) {
1085                 send_add_edge(c, c->edge);
1086         } else {
1087                 send_add_edge(everyone, c->edge);
1088         }
1089
1090         /* Run MST and SSSP algorithms */
1091
1092         graph();
1093
1094         return true;
1095 }