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