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