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