]> git.meshlink.io Git - meshlink/blob - src/protocol_auth.c
Don't forget to send a newline when forwarding requests.
[meshlink] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2012 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 "splay_tree.h"
24 #include "conf.h"
25 #include "connection.h"
26 #include "control.h"
27 #include "control_common.h"
28 #include "cipher.h"
29 #include "crypto.h"
30 #include "digest.h"
31 #include "edge.h"
32 #include "graph.h"
33 #include "logger.h"
34 #include "meta.h"
35 #include "net.h"
36 #include "netutl.h"
37 #include "node.h"
38 #include "prf.h"
39 #include "protocol.h"
40 #include "rsa.h"
41 #include "sptps.h"
42 #include "utils.h"
43 #include "xalloc.h"
44
45 bool send_id(connection_t *c) {
46         gettimeofday(&c->start, NULL);
47
48         int minor = 0;
49
50         if(experimental) {
51                 if(c->config_tree && !read_ecdsa_public_key(c))
52                         minor = 1;
53                 else
54                         minor = myself->connection->protocol_minor;
55         }
56
57         return send_request(c, "%d %s %d.%d", ID, myself->connection->name, myself->connection->protocol_major, minor);
58 }
59
60 bool id_h(connection_t *c, const char *request) {
61         char name[MAX_STRING_SIZE];
62
63         if(sscanf(request, "%*d " MAX_STRING " %d.%d", name, &c->protocol_major, &c->protocol_minor) < 2) {
64                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
65                            c->hostname);
66                 return false;
67         }
68
69         /* Check if this is a control connection */
70
71         if(name[0] == '^' && !strcmp(name + 1, controlcookie)) {
72                 c->status.control = true;
73                 c->allow_request = CONTROL;
74                 c->last_ping_time = time(NULL) + 3600;
75
76                 free(c->name);
77                 c->name = xstrdup("<control>");
78
79                 return send_request(c, "%d %d %d", ACK, TINC_CTL_VERSION_CURRENT, getpid());
80         }
81
82         /* Check if identity is a valid name */
83
84         if(!check_id(name)) {
85                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
86                            c->hostname, "invalid name");
87                 return false;
88         }
89
90         /* If this is an outgoing connection, make sure we are connected to the right host */
91
92         if(c->outgoing) {
93                 if(strcmp(c->name, name)) {
94                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
95                                    c->name);
96                         return false;
97                 }
98         } else {
99                 if(c->name)
100                         free(c->name);
101                 c->name = xstrdup(name);
102         }
103
104         /* Check if version matches */
105
106         if(c->protocol_major != myself->connection->protocol_major) {
107                 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) uses incompatible version %d.%d",
108                            c->name, c->hostname, c->protocol_major, c->protocol_minor);
109                 return false;
110         }
111
112         if(bypass_security) {
113                 if(!c->config_tree)
114                         init_configuration(&c->config_tree);
115                 c->allow_request = ACK;
116                 return send_ack(c);
117         }
118
119         if(!experimental)
120                 c->protocol_minor = 0;
121
122         if(!c->config_tree) {
123                 init_configuration(&c->config_tree);
124
125                 if(!read_connection_config(c)) {
126                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
127                                    c->name);
128                         return false;
129                 }
130
131                 if(experimental && c->protocol_minor >= 2) {
132                         if(!read_ecdsa_public_key(c))
133                                 return false;
134                 }
135         } else {
136                 if(c->protocol_minor && !ecdsa_active(&c->ecdsa))
137                         c->protocol_minor = 1;
138         }
139
140         c->allow_request = METAKEY;
141
142         if(c->protocol_minor >= 2) {
143                 c->allow_request = ACK;
144                 char label[25 + strlen(myself->name) + strlen(c->name)];
145
146                 if(c->outgoing)
147                         snprintf(label, sizeof label, "tinc TCP key expansion %s %s", myself->name, c->name);
148                 else
149                         snprintf(label, sizeof label, "tinc TCP key expansion %s %s", c->name, myself->name);
150
151                 return sptps_start(&c->sptps, c, c->outgoing, false, myself->connection->ecdsa, c->ecdsa, label, sizeof label, send_meta_sptps, receive_meta_sptps);
152         } else {
153                 return send_metakey(c);
154         }
155 }
156
157 bool send_metakey(connection_t *c) {
158         if(!read_rsa_public_key(c))
159                 return false;
160
161         if(!cipher_open_blowfish_ofb(&c->outcipher))
162                 return false;
163         
164         if(!digest_open_sha1(&c->outdigest, -1))
165                 return false;
166
167         size_t len = rsa_size(&c->rsa);
168         char key[len];
169         char enckey[len];
170         char hexkey[2 * len + 1];
171
172         /* Create a random key */
173
174         randomize(key, len);
175
176         /* The message we send must be smaller than the modulus of the RSA key.
177            By definition, for a key of k bits, the following formula holds:
178
179            2^(k-1) <= modulus < 2^(k)
180
181            Where ^ means "to the power of", not "xor".
182            This means that to be sure, we must choose our message < 2^(k-1).
183            This can be done by setting the most significant bit to zero.
184          */
185
186         key[0] &= 0x7F;
187
188         cipher_set_key_from_rsa(&c->outcipher, key, len, true);
189
190         if(debug_level >= DEBUG_SCARY_THINGS) {
191                 bin2hex(key, hexkey, len);
192                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Generated random meta key (unencrypted): %s", hexkey);
193         }
194
195         /* Encrypt the random data
196
197            We do not use one of the PKCS padding schemes here.
198            This is allowed, because we encrypt a totally random string
199            with a length equal to that of the modulus of the RSA key.
200          */
201
202         if(!rsa_public_encrypt(&c->rsa, key, len, enckey)) {
203                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during encryption of meta key for %s (%s)", c->name, c->hostname);
204                 return false;
205         }
206
207         /* Convert the encrypted random data to a hexadecimal formatted string */
208
209         bin2hex(enckey, hexkey, len);
210
211         /* Send the meta key */
212
213         bool result = send_request(c, "%d %d %d %d %d %s", METAKEY,
214                          cipher_get_nid(&c->outcipher),
215                          digest_get_nid(&c->outdigest), c->outmaclength,
216                          c->outcompression, hexkey);
217         
218         c->status.encryptout = true;
219         return result;
220 }
221
222 bool metakey_h(connection_t *c, const char *request) {
223         char hexkey[MAX_STRING_SIZE];
224         int cipher, digest, maclength, compression;
225         size_t len = rsa_size(&myself->connection->rsa);
226         char enckey[len];
227         char key[len];
228
229         if(sscanf(request, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, hexkey) != 5) {
230                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
231                 return false;
232         }
233
234         /* Convert the challenge from hexadecimal back to binary */
235
236         int inlen = hex2bin(hexkey, enckey, sizeof enckey);
237
238         /* Check if the length of the meta key is all right */
239
240         if(inlen != len) {
241                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
242                 return false;
243         }
244
245         /* Decrypt the meta key */
246
247         if(!rsa_private_decrypt(&myself->connection->rsa, enckey, len, key)) {
248                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during decryption of meta key for %s (%s)", c->name, c->hostname);
249                 return false;
250         }
251
252         if(debug_level >= DEBUG_SCARY_THINGS) {
253                 bin2hex(key, hexkey, len);
254                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Received random meta key (unencrypted): %s", hexkey);
255         }
256
257         /* Check and lookup cipher and digest algorithms */
258
259         if(!cipher_open_by_nid(&c->incipher, cipher) || !cipher_set_key_from_rsa(&c->incipher, key, len, false)) {
260                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of cipher from %s (%s)", c->name, c->hostname);
261                 return false;
262         }
263
264         if(!digest_open_by_nid(&c->indigest, digest, -1)) {
265                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of digest from %s (%s)", c->name, c->hostname);
266                 return false;
267         }
268
269         c->status.decryptin = true;
270
271         c->allow_request = CHALLENGE;
272
273         return send_challenge(c);
274 }
275
276 bool send_challenge(connection_t *c) {
277         size_t len = rsa_size(&c->rsa);
278         char buffer[len * 2 + 1];
279
280         if(!c->hischallenge)
281                 c->hischallenge = xrealloc(c->hischallenge, len);
282
283         /* Copy random data to the buffer */
284
285         randomize(c->hischallenge, len);
286
287         /* Convert to hex */
288
289         bin2hex(c->hischallenge, buffer, len);
290
291         /* Send the challenge */
292
293         return send_request(c, "%d %s", CHALLENGE, buffer);
294 }
295
296 bool challenge_h(connection_t *c, const char *request) {
297         char buffer[MAX_STRING_SIZE];
298         size_t len = rsa_size(&myself->connection->rsa);
299         size_t digestlen = digest_length(&c->indigest);
300         char digest[digestlen];
301
302         if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
303                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name, c->hostname);
304                 return false;
305         }
306
307         /* Convert the challenge from hexadecimal back to binary */
308
309         int inlen = hex2bin(buffer, buffer, sizeof buffer);
310
311         /* Check if the length of the challenge is all right */
312
313         if(inlen != len) {
314                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge length");
315                 return false;
316         }
317
318         c->allow_request = CHAL_REPLY;
319
320         /* Calculate the hash from the challenge we received */
321
322         digest_create(&c->indigest, buffer, len, digest);
323
324         /* Convert the hash to a hexadecimal formatted string */
325
326         bin2hex(digest, buffer, digestlen);
327
328         /* Send the reply */
329
330         return send_request(c, "%d %s", CHAL_REPLY, buffer);
331 }
332
333 bool chal_reply_h(connection_t *c, const char *request) {
334         char hishash[MAX_STRING_SIZE];
335
336         if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
337                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
338                            c->hostname);
339                 return false;
340         }
341
342         /* Convert the hash to binary format */
343
344         int inlen = hex2bin(hishash, hishash, sizeof hishash);
345
346         /* Check if the length of the hash is all right */
347
348         if(inlen != digest_length(&c->outdigest)) {
349                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply length");
350                 return false;
351         }
352
353
354         /* Verify the hash */
355
356         if(!digest_verify(&c->outdigest, c->hischallenge, rsa_size(&c->rsa), hishash)) {
357                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply");
358                 return false;
359         }
360
361         /* Identity has now been positively verified.
362            Send an acknowledgement with the rest of the information needed.
363          */
364
365         free(c->hischallenge);
366         c->hischallenge = NULL;
367         c->allow_request = ACK;
368
369         return send_ack(c);
370 }
371
372 static bool send_upgrade(connection_t *c) {
373         /* Special case when protocol_minor is 1: the other end is ECDSA capable,
374          * but doesn't know our key yet. So send it now. */
375
376         char *pubkey = ecdsa_get_base64_public_key(&myself->connection->ecdsa);
377
378         if(!pubkey)
379                 return false;
380
381         bool result = send_request(c, "%d %s", ACK, pubkey);
382         free(pubkey);
383         return result;
384 }
385
386 bool send_ack(connection_t *c) {
387         if(c->protocol_minor == 1)
388                 return send_upgrade(c);
389
390         /* ACK message contains rest of the information the other end needs
391            to create node_t and edge_t structures. */
392
393         struct timeval now;
394         bool choice;
395
396         /* Estimate weight */
397
398         gettimeofday(&now, NULL);
399         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
400
401         /* Check some options */
402
403         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
404                 c->options |= OPTION_INDIRECT;
405
406         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
407                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
408
409         if(myself->options & OPTION_PMTU_DISCOVERY)
410                 c->options |= OPTION_PMTU_DISCOVERY;
411
412         choice = myself->options & OPTION_CLAMP_MSS;
413         get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
414         if(choice)
415                 c->options |= OPTION_CLAMP_MSS;
416
417         get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight);
418
419         return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, c->options);
420 }
421
422 static void send_everything(connection_t *c) {
423         splay_node_t *node, *node2;
424         node_t *n;
425         subnet_t *s;
426         edge_t *e;
427
428         /* Send all known subnets and edges */
429
430         if(tunnelserver) {
431                 for(node = myself->subnet_tree->head; node; node = node->next) {
432                         s = node->data;
433                         send_add_subnet(c, s);
434                 }
435
436                 return;
437         }
438
439         for(node = node_tree->head; node; node = node->next) {
440                 n = node->data;
441
442                 for(node2 = n->subnet_tree->head; node2; node2 = node2->next) {
443                         s = node2->data;
444                         send_add_subnet(c, s);
445                 }
446
447                 for(node2 = n->edge_tree->head; node2; node2 = node2->next) {
448                         e = node2->data;
449                         send_add_edge(c, e);
450                 }
451         }
452 }
453
454 static bool upgrade_h(connection_t *c, const char *request) {
455         char pubkey[MAX_STRING_SIZE];
456
457         if(sscanf(request, "%*d " MAX_STRING, pubkey) != 1) {
458                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name, c->hostname);
459                 return false;
460         }
461
462         if(ecdsa_active(&c->ecdsa) || read_ecdsa_public_key(c)) {
463                 logger(DEBUG_ALWAYS, LOG_INFO, "Already have ECDSA public key from %s (%s), not upgrading.", c->name, c->hostname);
464                 return false;
465         }
466
467         logger(DEBUG_ALWAYS, LOG_INFO, "Got ECDSA public key from %s (%s), upgrading!", c->name, c->hostname);
468         append_config_file(c->name, "ECDSAPublicKey", pubkey);
469         c->allow_request = TERMREQ;
470         return send_termreq(c);
471 }
472
473 bool ack_h(connection_t *c, const char *request) {
474         if(c->protocol_minor == 1)
475                 return upgrade_h(c, request);
476
477         char hisport[MAX_STRING_SIZE];
478         char *hisaddress;
479         int weight, mtu;
480         uint32_t options;
481         node_t *n;
482         bool choice;
483
484         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
485                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
486                            c->hostname);
487                 return false;
488         }
489
490         /* Check if we already have a node_t for him */
491
492         n = lookup_node(c->name);
493
494         if(!n) {
495                 n = new_node();
496                 n->name = xstrdup(c->name);
497                 node_add(n);
498         } else {
499                 if(n->connection) {
500                         /* Oh dear, we already have a connection to this node. */
501                         logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
502
503                         if(n->connection->outgoing) {
504                                 if(c->outgoing)
505                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Two outgoing connections to the same node!");
506                                 else
507                                         c->outgoing = n->connection->outgoing;
508
509                                 n->connection->outgoing = NULL;
510                         }
511
512                         terminate_connection(n->connection, false);
513                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
514                         graph();
515                 }
516         }
517
518         n->connection = c;
519         c->node = n;
520         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
521                 c->options &= ~OPTION_PMTU_DISCOVERY;
522                 options &= ~OPTION_PMTU_DISCOVERY;
523         }
524         c->options |= options;
525
526         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
527                 n->mtu = mtu;
528
529         if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
530                 n->mtu = mtu;
531
532         if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
533                 if(choice)
534                         c->options |= OPTION_CLAMP_MSS;
535                 else
536                         c->options &= ~OPTION_CLAMP_MSS;
537         }
538
539         if(c->protocol_minor > 0)
540                 c->node->status.ecdh = true;
541
542         /* Activate this connection */
543
544         c->allow_request = ALL;
545         c->status.active = true;
546
547         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection with %s (%s) activated", c->name,
548                            c->hostname);
549
550         /* Send him everything we know */
551
552         send_everything(c);
553
554         /* Create an edge_t for this connection */
555
556         c->edge = new_edge();
557         c->edge->from = myself;
558         c->edge->to = n;
559         sockaddr2str(&c->address, &hisaddress, NULL);
560         c->edge->address = str2sockaddr(hisaddress, hisport);
561         free(hisaddress);
562         c->edge->weight = (weight + c->estimated_weight) / 2;
563         c->edge->connection = c;
564         c->edge->options = c->options;
565
566         edge_add(c->edge);
567
568         /* Notify everyone of the new edge */
569
570         if(tunnelserver)
571                 send_add_edge(c, c->edge);
572         else
573                 send_add_edge(everyone, c->edge);
574
575         /* Run MST and SSSP algorithms */
576
577         graph();
578
579         return true;
580 }