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