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