Refactor crypto RNG; add getrandom() 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
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                 fclose(f);
300                 return false;
301         }
302
303         size_t buflen = strlen(buf);
304
305         // Strip whitespace at the end
306         while(buflen && strchr(" \t\r\n", buf[buflen - 1])) {
307                 buf[--buflen] = 0;
308         }
309
310         // Split the first line into variable and value
311         len = strcspn(buf, " \t=");
312         char *name = buf + len;
313         name += strspn(name, " \t");
314
315         if(*name == '=') {
316                 name++;
317                 name += strspn(name, " \t");
318         }
319
320         buf[len] = 0;
321
322         // Check that it is a valid Name
323         if(!*buf || !*name || strcasecmp(buf, "Name") || !check_id(name) || !strcmp(name, myself->name)) {
324                 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid invitation file %s\n", cookie);
325                 fclose(f);
326                 return false;
327         }
328
329         free(c->name);
330         c->name = xstrdup(name);
331
332         // Send the node the contents of the invitation file
333         rewind(f);
334         size_t result;
335
336         while((result = fread(buf, 1, sizeof(buf), f))) {
337                 sptps_send_record(&c->sptps, 0, buf, result);
338         }
339
340         if(!feof(f)) {
341                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not read invitation file %s\n", cookie);
342                 fclose(f);
343                 return false;
344         }
345
346         sptps_send_record(&c->sptps, 1, buf, 0);
347         fclose(f);
348         unlink(usedname);
349
350         c->status.invitation_used = true;
351
352         logger(DEBUG_CONNECTIONS, LOG_INFO, "Invitation %s successfully sent to %s (%s)", cookie, c->name, c->hostname);
353         return true;
354 }
355
356 bool id_h(connection_t *c, const char *request) {
357         char name[MAX_STRING_SIZE];
358
359         if(sscanf(request, "%*d " MAX_STRING " %2d.%3d", name, &c->protocol_major, &c->protocol_minor) < 2) {
360                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
361                        c->hostname);
362                 return false;
363         }
364
365         /* Check if this is a control connection */
366
367         if(name[0] == '^' && !strcmp(name + 1, controlcookie)) {
368                 c->status.control = true;
369                 c->allow_request = CONTROL;
370                 c->last_ping_time = now.tv_sec + 3600;
371
372                 free(c->name);
373                 c->name = xstrdup("<control>");
374
375                 if(!c->outgoing) {
376                         send_id(c);
377                 }
378
379                 return send_request(c, "%d %d %d", ACK, TINC_CTL_VERSION_CURRENT, getpid());
380         }
381
382         if(name[0] == '?') {
383                 if(!invitation_key) {
384                         logger(DEBUG_ALWAYS, LOG_ERR, "Got invitation from %s but we don't have an invitation key", c->hostname);
385                         return false;
386                 }
387
388                 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
389
390                 if(!c->ecdsa) {
391                         logger(DEBUG_ALWAYS, LOG_ERR, "Got bad invitation from %s", c->hostname);
392                         return false;
393                 }
394
395                 c->status.invitation = true;
396                 char *mykey = ecdsa_get_base64_public_key(invitation_key);
397
398                 if(!mykey) {
399                         return false;
400                 }
401
402                 if(!c->outgoing) {
403                         send_id(c);
404                 }
405
406                 if(!send_request(c, "%d %s", ACK, mykey)) {
407                         return false;
408                 }
409
410                 free(mykey);
411
412                 c->protocol_minor = 2;
413
414                 return sptps_start(&c->sptps, c, false, false, invitation_key, c->ecdsa, "tinc invitation", 15, send_meta_sptps, receive_invitation_sptps);
415         }
416
417         /* Check if identity is a valid name */
418
419         if(!check_id(name) || !strcmp(name, myself->name)) {
420                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
421                        c->hostname, "invalid name");
422                 return false;
423         }
424
425         /* If this is an outgoing connection, make sure we are connected to the right host */
426
427         if(c->outgoing) {
428                 if(strcmp(c->name, name)) {
429                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
430                                c->name);
431                         return false;
432                 }
433         } else {
434                 free(c->name);
435                 c->name = xstrdup(name);
436         }
437
438         /* Check if version matches */
439
440         if(c->protocol_major != myself->connection->protocol_major) {
441                 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) uses incompatible version %d.%d",
442                        c->name, c->hostname, c->protocol_major, c->protocol_minor);
443                 return false;
444         }
445
446         if(bypass_security) {
447                 if(!c->config_tree) {
448                         c->config_tree = create_configuration();
449                 }
450
451                 c->allow_request = ACK;
452
453                 if(!c->outgoing) {
454                         send_id(c);
455                 }
456
457                 return send_ack(c);
458         }
459
460         if(!experimental) {
461                 c->protocol_minor = 0;
462         }
463
464         if(!c->config_tree) {
465                 c->config_tree = create_configuration();
466
467                 if(!read_host_config(c->config_tree, c->name, false)) {
468                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname, c->name);
469                         return false;
470                 }
471
472                 if(experimental) {
473                         read_ecdsa_public_key(&c->ecdsa, &c->config_tree, c->name);
474                 }
475
476                 /* Ignore failures if no key known yet */
477         }
478
479         if(c->protocol_minor && !ecdsa_active(c->ecdsa)) {
480                 c->protocol_minor = 1;
481         }
482
483         /* Forbid version rollback for nodes whose Ed25519 key we know */
484
485         if(ecdsa_active(c->ecdsa) && c->protocol_minor < 1) {
486                 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) tries to roll back protocol version to %d.%d",
487                        c->name, c->hostname, c->protocol_major, c->protocol_minor);
488                 return false;
489         }
490
491         c->allow_request = METAKEY;
492
493         if(!c->outgoing) {
494                 send_id(c);
495         }
496
497         if(c->protocol_minor >= 2) {
498                 c->allow_request = ACK;
499
500                 const size_t labellen = 25 + strlen(myself->name) + strlen(c->name);
501                 char *label = alloca(labellen);
502
503                 if(c->outgoing) {
504                         snprintf(label, labellen, "tinc TCP key expansion %s %s", myself->name, c->name);
505                 } else {
506                         snprintf(label, labellen, "tinc TCP key expansion %s %s", c->name, myself->name);
507                 }
508
509                 return sptps_start(&c->sptps, c, c->outgoing, false, myself->connection->ecdsa, c->ecdsa, label, labellen, send_meta_sptps, receive_meta_sptps);
510         } else {
511                 return send_metakey(c);
512         }
513 }
514
515 #ifndef DISABLE_LEGACY
516 bool send_metakey(connection_t *c) {
517         if(!myself->connection->rsa) {
518                 logger(DEBUG_CONNECTIONS, LOG_ERR, "Peer %s (%s) uses legacy protocol which we don't support", c->name, c->hostname);
519                 return false;
520         }
521
522         if(!read_rsa_public_key(&c->rsa, c->config_tree, c->name)) {
523                 return false;
524         }
525
526         /* We need to use a stream mode for the meta protocol. Use AES for this,
527            but try to match the key size with the one from the cipher selected
528            by Cipher.
529         */
530
531         size_t keylen = cipher_keylength(myself->incipher);
532         const char *cipher_name;
533
534         if(keylen <= 16) {
535                 cipher_name = "aes-128-cfb";
536         } else if(keylen <= 24) {
537                 cipher_name = "aes-192-cfb";
538         } else {
539                 cipher_name = "aes-256-cfb";
540         }
541
542         if(!cipher_open_by_name(&c->outcipher, cipher_name)) {
543                 return false;
544         }
545
546         c->outbudget = cipher_budget(&c->outcipher);
547
548         if(!digest_open_by_name(&c->outdigest, "sha256", DIGEST_ALGO_SIZE)) {
549                 cipher_close(&c->outcipher);
550                 return false;
551         }
552
553         const size_t len = rsa_size(c->rsa);
554         char *key = alloca(len);
555         char *enckey = alloca(len);
556         char *hexkey = alloca(2 * len + 1);
557
558         /* Create a random key */
559
560         randomize(key, len);
561
562         /* The message we send must be smaller than the modulus of the RSA key.
563            By definition, for a key of k bits, the following formula holds:
564
565            2^(k-1) <= modulus < 2^(k)
566
567            Where ^ means "to the power of", not "xor".
568            This means that to be sure, we must choose our message < 2^(k-1).
569            This can be done by setting the most significant bit to zero.
570          */
571
572         key[0] &= 0x7F;
573
574         if(!cipher_set_key_from_rsa(&c->outcipher, key, len, true)) {
575                 return false;
576         }
577
578         if(debug_level >= DEBUG_SCARY_THINGS) {
579                 bin2hex(key, hexkey, len);
580                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Generated random meta key (unencrypted): %s", hexkey);
581         }
582
583         /* Encrypt the random data
584
585            We do not use one of the PKCS padding schemes here.
586            This is allowed, because we encrypt a totally random string
587            with a length equal to that of the modulus of the RSA key.
588          */
589
590         if(!rsa_public_encrypt(c->rsa, key, len, enckey)) {
591                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during encryption of meta key for %s (%s)", c->name, c->hostname);
592                 return false;
593         }
594
595         /* Convert the encrypted random data to a hexadecimal formatted string */
596
597         bin2hex(enckey, hexkey, len);
598
599         /* Send the meta key */
600
601         bool result = send_request(c, "%d %d %d %d %d %s", METAKEY,
602                                    cipher_get_nid(&c->outcipher),
603                                    digest_get_nid(&c->outdigest), c->outmaclength,
604                                    c->outcompression, hexkey);
605
606         c->status.encryptout = true;
607         return result;
608 }
609
610 bool metakey_h(connection_t *c, const char *request) {
611         if(!myself->connection->rsa) {
612                 return false;
613         }
614
615         char hexkey[MAX_STRING_SIZE];
616         int cipher, digest, maclength, compression;
617         const size_t len = rsa_size(myself->connection->rsa);
618         char *enckey = alloca(len);
619         char *key = alloca(len);
620
621         if(sscanf(request, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, hexkey) != 5) {
622                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
623                 return false;
624         }
625
626         /* Convert the challenge from hexadecimal back to binary */
627
628         size_t inlen = hex2bin(hexkey, enckey, len);
629
630         /* Check if the length of the meta key is all right */
631
632         if(inlen != len) {
633                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
634                 return false;
635         }
636
637         /* Decrypt the meta key */
638
639         if(!rsa_private_decrypt(myself->connection->rsa, enckey, len, key)) {
640                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during decryption of meta key for %s (%s)", c->name, c->hostname);
641                 return false;
642         }
643
644         if(debug_level >= DEBUG_SCARY_THINGS) {
645                 bin2hex(key, hexkey, len);
646                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Received random meta key (unencrypted): %s", hexkey);
647         }
648
649         /* Check and lookup cipher and digest algorithms */
650
651         if(cipher) {
652                 if(!cipher_open_by_nid(&c->incipher, cipher) || !cipher_set_key_from_rsa(&c->incipher, key, len, false)) {
653                         logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of cipher from %s (%s)", c->name, c->hostname);
654                         return false;
655                 }
656         } else {
657                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "null cipher");
658                 return false;
659         }
660
661         c->inbudget = cipher_budget(&c->incipher);
662
663         if(digest) {
664                 if(!digest_open_by_nid(&c->indigest, digest, DIGEST_ALGO_SIZE)) {
665                         logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of digest from %s (%s)", c->name, c->hostname);
666                         return false;
667                 }
668         } else {
669                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "null digest");
670                 return false;
671         }
672
673         c->status.decryptin = true;
674
675         c->allow_request = CHALLENGE;
676
677         return send_challenge(c);
678 }
679
680 bool send_challenge(connection_t *c) {
681         const size_t len = rsa_size(c->rsa);
682         char *buffer = alloca(len * 2 + 1);
683
684         c->hischallenge = xrealloc(c->hischallenge, len);
685
686         /* Copy random data to the buffer */
687
688         randomize(c->hischallenge, len);
689
690         /* Convert to hex */
691
692         bin2hex(c->hischallenge, buffer, len);
693
694         /* Send the challenge */
695
696         return send_request(c, "%d %s", CHALLENGE, buffer);
697 }
698
699 bool challenge_h(connection_t *c, const char *request) {
700         if(!myself->connection->rsa) {
701                 return false;
702         }
703
704         char buffer[MAX_STRING_SIZE];
705         const size_t len = rsa_size(myself->connection->rsa);
706
707         if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
708                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name, c->hostname);
709                 return false;
710         }
711
712         /* Check if the length of the challenge is all right */
713
714         if(strlen(buffer) != (size_t)len * 2) {
715                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge length");
716                 return false;
717         }
718
719         c->mychallenge = xrealloc(c->mychallenge, len);
720
721         /* Convert the challenge from hexadecimal back to binary */
722
723         hex2bin(buffer, c->mychallenge, len);
724
725         /* The rest is done by send_chal_reply() */
726
727         c->allow_request = CHAL_REPLY;
728
729         if(c->outgoing) {
730                 return send_chal_reply(c);
731         } else {
732                 return true;
733         }
734 }
735
736 bool send_chal_reply(connection_t *c) {
737         const size_t len = rsa_size(myself->connection->rsa);
738         size_t digestlen = digest_length(&c->indigest);
739         char *digest = alloca(digestlen * 2 + 1);
740
741         /* Calculate the hash from the challenge we received */
742
743         if(!digest_create(&c->indigest, c->mychallenge, len, digest)) {
744                 return false;
745         }
746
747         free(c->mychallenge);
748         c->mychallenge = NULL;
749
750         /* Convert the hash to a hexadecimal formatted string */
751
752         bin2hex(digest, digest, digestlen);
753
754         /* Send the reply */
755
756         return send_request(c, "%d %s", CHAL_REPLY, digest);
757 }
758
759 bool chal_reply_h(connection_t *c, const char *request) {
760         char hishash[MAX_STRING_SIZE];
761
762         if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
763                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
764                        c->hostname);
765                 return false;
766         }
767
768         /* Convert the hash to binary format */
769
770         size_t inlen = hex2bin(hishash, hishash, sizeof(hishash));
771
772         /* Check if the length of the hash is all right */
773
774         if(inlen != digest_length(&c->outdigest)) {
775                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply length");
776                 return false;
777         }
778
779
780         /* Verify the hash */
781
782         if(!digest_verify(&c->outdigest, c->hischallenge, rsa_size(c->rsa), hishash)) {
783                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply");
784                 return false;
785         }
786
787         /* Identity has now been positively verified.
788            Send an acknowledgement with the rest of the information needed.
789          */
790
791         free(c->hischallenge);
792         c->hischallenge = NULL;
793         c->allow_request = ACK;
794
795         if(!c->outgoing) {
796                 send_chal_reply(c);
797         }
798
799         return send_ack(c);
800 }
801
802 static bool send_upgrade(connection_t *c) {
803         /* Special case when protocol_minor is 1: the other end is Ed25519 capable,
804          * but doesn't know our key yet. So send it now. */
805
806         char *pubkey = ecdsa_get_base64_public_key(myself->connection->ecdsa);
807
808         if(!pubkey) {
809                 return false;
810         }
811
812         bool result = send_request(c, "%d %s", ACK, pubkey);
813         free(pubkey);
814         return result;
815 }
816 #else
817 bool send_metakey(connection_t *c) {
818         (void)c;
819         return false;
820 }
821
822 bool metakey_h(connection_t *c, const char *request) {
823         (void)c;
824         (void)request;
825         return false;
826 }
827
828 bool send_challenge(connection_t *c) {
829         (void)c;
830         return false;
831 }
832
833 bool challenge_h(connection_t *c, const char *request) {
834         (void)c;
835         (void)request;
836         return false;
837 }
838
839 bool send_chal_reply(connection_t *c) {
840         (void)c;
841         return false;
842 }
843
844 bool chal_reply_h(connection_t *c, const char *request) {
845         (void)c;
846         (void)request;
847         return false;
848 }
849
850 static bool send_upgrade(connection_t *c) {
851         (void)c;
852         return false;
853 }
854 #endif
855
856 bool send_ack(connection_t *c) {
857         if(c->protocol_minor == 1) {
858                 return send_upgrade(c);
859         }
860
861         /* ACK message contains rest of the information the other end needs
862            to create node_t and edge_t structures. */
863
864         struct timeval now;
865         bool choice;
866
867         /* Estimate weight */
868
869         gettimeofday(&now, NULL);
870         c->estimated_weight = (int)((now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000);
871
872         /* Check some options */
873
874         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT) {
875                 c->options |= OPTION_INDIRECT;
876         }
877
878         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY) {
879                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
880         }
881
882         if(myself->options & OPTION_PMTU_DISCOVERY && !(c->options & OPTION_TCPONLY)) {
883                 c->options |= OPTION_PMTU_DISCOVERY;
884         }
885
886         choice = myself->options & OPTION_CLAMP_MSS;
887         get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
888
889         if(choice) {
890                 c->options |= OPTION_CLAMP_MSS;
891         }
892
893         if(!get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight)) {
894                 get_config_int(lookup_config(&config_tree, "Weight"), &c->estimated_weight);
895         }
896
897         return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, (c->options & 0xffffff) | (experimental ? (PROT_MINOR << 24) : 0));
898 }
899
900 static void send_everything(connection_t *c) {
901         /* Send all known subnets and edges */
902
903         if(disablebuggypeers) {
904                 static struct {
905                         vpn_packet_t pkt;
906                         char pad[MAXBUFSIZE - MAXSIZE];
907                 } zeropkt;
908
909                 memset(&zeropkt, 0, sizeof(zeropkt));
910                 zeropkt.pkt.len = MAXBUFSIZE;
911                 send_tcppacket(c, &zeropkt.pkt);
912         }
913
914         if(tunnelserver) {
915                 for splay_each(subnet_t, s, &myself->subnet_tree) {
916                         send_add_subnet(c, s);
917                 }
918
919                 return;
920         }
921
922         for splay_each(node_t, n, &node_tree) {
923                 for splay_each(subnet_t, s, &n->subnet_tree) {
924                         send_add_subnet(c, s);
925                 }
926
927                 for splay_each(edge_t, e, &n->edge_tree) {
928                         send_add_edge(c, e);
929                 }
930         }
931 }
932
933 static bool upgrade_h(connection_t *c, const char *request) {
934         char pubkey[MAX_STRING_SIZE];
935
936         if(sscanf(request, "%*d " MAX_STRING, pubkey) != 1) {
937                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name, c->hostname);
938                 return false;
939         }
940
941         if(ecdsa_active(c->ecdsa) || read_ecdsa_public_key(&c->ecdsa, &c->config_tree, c->name)) {
942                 char *knownkey = ecdsa_get_base64_public_key(c->ecdsa);
943                 bool different = strcmp(knownkey, pubkey);
944                 free(knownkey);
945
946                 if(different) {
947                         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);
948                         return false;
949                 }
950
951                 logger(DEBUG_ALWAYS, LOG_INFO, "Already have Ed25519 public key from %s (%s), ignoring.", c->name, c->hostname);
952                 c->allow_request = TERMREQ;
953                 return send_termreq(c);
954         }
955
956         c->ecdsa = ecdsa_set_base64_public_key(pubkey);
957
958         if(!c->ecdsa) {
959                 logger(DEBUG_ALWAYS, LOG_INFO, "Got bad Ed25519 public key from %s (%s), not upgrading.", c->name, c->hostname);
960                 return false;
961         }
962
963         logger(DEBUG_ALWAYS, LOG_INFO, "Got Ed25519 public key from %s (%s), upgrading!", c->name, c->hostname);
964         append_config_file(c->name, "Ed25519PublicKey", pubkey);
965         c->allow_request = TERMREQ;
966
967         if(c->outgoing) {
968                 c->outgoing->timeout = 0;
969         }
970
971         return send_termreq(c);
972 }
973
974 bool ack_h(connection_t *c, const char *request) {
975         if(c->protocol_minor == 1) {
976                 return upgrade_h(c, request);
977         }
978
979         char hisport[MAX_STRING_SIZE];
980         int weight, mtu;
981         uint32_t options;
982         node_t *n;
983         bool choice;
984
985         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
986                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
987                        c->hostname);
988                 return false;
989         }
990
991         /* Check if we already have a node_t for him */
992
993         n = lookup_node(c->name);
994
995         if(!n) {
996                 n = new_node();
997                 n->name = xstrdup(c->name);
998                 node_add(n);
999         } else {
1000                 if(n->connection) {
1001                         /* Oh dear, we already have a connection to this node. */
1002                         logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
1003
1004                         if(n->connection->outgoing) {
1005                                 if(c->outgoing) {
1006                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Two outgoing connections to the same node!");
1007                                 } else {
1008                                         c->outgoing = n->connection->outgoing;
1009                                 }
1010
1011                                 n->connection->outgoing = NULL;
1012                         }
1013
1014                         terminate_connection(n->connection, false);
1015                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
1016                         graph();
1017                 }
1018         }
1019
1020         n->connection = c;
1021         c->node = n;
1022
1023         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
1024                 c->options &= ~OPTION_PMTU_DISCOVERY;
1025                 options &= ~OPTION_PMTU_DISCOVERY;
1026         }
1027
1028         c->options |= options;
1029
1030         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
1031                 n->mtu = mtu;
1032         }
1033
1034         if(get_config_int(lookup_config(&config_tree, "PMTU"), &mtu) && mtu < n->mtu) {
1035                 n->mtu = mtu;
1036         }
1037
1038         if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
1039                 if(choice) {
1040                         c->options |= OPTION_CLAMP_MSS;
1041                 } else {
1042                         c->options &= ~OPTION_CLAMP_MSS;
1043                 }
1044         }
1045
1046         /* Activate this connection */
1047
1048         c->allow_request = ALL;
1049
1050         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection with %s (%s) activated", c->name,
1051                c->hostname);
1052
1053         /* Send him everything we know */
1054
1055         send_everything(c);
1056
1057         /* Create an edge_t for this connection */
1058
1059         c->edge = new_edge();
1060         c->edge->from = myself;
1061         c->edge->to = n;
1062         sockaddrcpy(&c->edge->address, &c->address);
1063         sockaddr_setport(&c->edge->address, hisport);
1064         sockaddr_t local_sa;
1065         socklen_t local_salen = sizeof(local_sa);
1066
1067         if(getsockname(c->socket, &local_sa.sa, &local_salen) < 0) {
1068                 logger(DEBUG_ALWAYS, LOG_WARNING, "Could not get local socket address for connection with %s", c->name);
1069         } else {
1070                 sockaddr_setport(&local_sa, myport);
1071                 c->edge->local_address = local_sa;
1072         }
1073
1074         c->edge->weight = (weight + c->estimated_weight) / 2;
1075         c->edge->connection = c;
1076         c->edge->options = c->options;
1077
1078         edge_add(c->edge);
1079
1080         /* Notify everyone of the new edge */
1081
1082         if(tunnelserver) {
1083                 send_add_edge(c, c->edge);
1084         } else {
1085                 send_add_edge(everyone, c->edge);
1086         }
1087
1088         /* Run MST and SSSP algorithms */
1089
1090         graph();
1091
1092         return true;
1093 }