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