Forgot to merge new files from pre5.
[tinc] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
3     Copyright (C) 1999-2002 Ivo Timmermans <itimmermans@bigfoot.com>,
4                   2000-2002 Guus Sliepen <guus@sliepen.warande.net>
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
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: protocol_auth.c,v 1.1.4.1 2002/02/11 10:05:58 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <syslog.h>
28 #include <stdio.h>
29 #include <stdarg.h>
30 #include <errno.h>
31
32 #include <utils.h>
33 #include <xalloc.h>
34 #include <avl_tree.h>
35
36 #include <openssl/sha.h>
37 #include <openssl/rand.h>
38 #include <openssl/evp.h>
39
40 #ifndef HAVE_RAND_PSEUDO_BYTES
41 #define RAND_pseudo_bytes RAND_bytes
42 #endif
43
44 #include "conf.h"
45 #include "net.h"
46 #include "netutl.h"
47 #include "protocol.h"
48 #include "meta.h"
49 #include "connection.h"
50 #include "node.h"
51 #include "edge.h"
52 #include "graph.h"
53
54 #include "system.h"
55
56 int send_id(connection_t *c)
57 {
58 cp
59   return send_request(c, "%d %s %d", ID, myself->connection->name, myself->connection->protocol_version);
60 }
61
62 int id_h(connection_t *c)
63 {
64   char name[MAX_STRING_SIZE];
65   int bla;
66 cp
67   if(sscanf(c->buffer, "%*d "MAX_STRING" %d", name, &c->protocol_version) != 2)
68     {
69        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "ID", c->name, c->hostname);
70        return -1;
71     }
72
73   /* Check if identity is a valid name */
74
75   if(check_id(name))
76     {
77       syslog(LOG_ERR, _("Got bad %s from %s (%s): %s"), "ID", c->name, c->hostname, "invalid name");
78       return -1;
79     }
80
81   /* If we set c->name in advance, make sure we are connected to the right host */
82   
83   if(c->name)
84     {
85       if(strcmp(c->name, name))
86         {
87           syslog(LOG_ERR, _("Peer %s is %s instead of %s"), c->hostname, name, c->name);
88           return -1;
89         }
90     }
91   else
92     c->name = xstrdup(name);
93
94   /* Check if version matches */
95
96   if(c->protocol_version != myself->connection->protocol_version)
97     {
98       syslog(LOG_ERR, _("Peer %s (%s) uses incompatible version %d"),
99              c->name, c->hostname, c->protocol_version);
100       return -1;
101     }
102   
103   if(bypass_security)
104     {
105       if(!c->config_tree)
106         init_configuration(&c->config_tree);
107       c->allow_request = ACK;
108       return send_ack(c);
109     }
110
111   if(!c->config_tree)
112     {
113       init_configuration(&c->config_tree);
114
115       if((bla = read_connection_config(c)))
116         {
117           syslog(LOG_ERR, _("Peer %s had unknown identity (%s)"), c->hostname, c->name);
118           return -1;
119         }
120     }
121
122   if(read_rsa_public_key(c))
123     {
124       return -1;
125     }
126
127   /* Check some options */
128   
129   if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &bla) && bla) || myself->options & OPTION_INDIRECT)
130         c->options |= OPTION_INDIRECT;
131
132   if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &bla) && bla) || myself->options & OPTION_TCPONLY)
133         c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
134
135   c->allow_request = METAKEY;
136 cp
137   return send_metakey(c);
138 }
139
140 int send_metakey(connection_t *c)
141 {
142   char buffer[MAX_STRING_SIZE];
143   int len, x;
144 cp
145   len = RSA_size(c->rsa_key);
146
147   /* Allocate buffers for the meta key */
148
149   if(!c->outkey)
150     c->outkey = xmalloc(len);
151     
152   if(!c->outctx)
153     c->outctx = xmalloc(sizeof(*c->outctx));
154 cp
155   /* Copy random data to the buffer */
156
157   RAND_bytes(c->outkey, len);
158
159   /* The message we send must be smaller than the modulus of the RSA key.
160      By definition, for a key of k bits, the following formula holds:
161      
162        2^(k-1) <= modulus < 2^(k)
163      
164      Where ^ means "to the power of", not "xor".
165      This means that to be sure, we must choose our message < 2^(k-1).
166      This can be done by setting the most significant bit to zero.
167   */
168   
169   c->outkey[0] &= 0x7F;
170   
171   if(debug_lvl >= DEBUG_SCARY_THINGS)
172     {
173       bin2hex(c->outkey, buffer, len);
174       buffer[len*2] = '\0';
175       syslog(LOG_DEBUG, _("Generated random meta key (unencrypted): %s"), buffer);
176     }
177
178   /* Encrypt the random data
179   
180      We do not use one of the PKCS padding schemes here.
181      This is allowed, because we encrypt a totally random string
182      with a length equal to that of the modulus of the RSA key.
183   */
184
185   if(RSA_public_encrypt(len, c->outkey, buffer, c->rsa_key, RSA_NO_PADDING) != len)
186     {
187       syslog(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), c->name, c->hostname);
188       return -1;
189     }
190 cp
191   /* Convert the encrypted random data to a hexadecimal formatted string */
192
193   bin2hex(buffer, buffer, len);
194   buffer[len*2] = '\0';
195
196   /* Send the meta key */
197
198   x = send_request(c, "%d %s", METAKEY, buffer);
199
200   /* Further outgoing requests are encrypted with the key we just generated */
201
202   EVP_EncryptInit(c->outctx, EVP_bf_cfb(),
203                   c->outkey + len - EVP_bf_cfb()->key_len,
204                   c->outkey + len - EVP_bf_cfb()->key_len - EVP_bf_cfb()->iv_len);
205
206   c->status.encryptout = 1;
207 cp
208   return x;
209 }
210
211 int metakey_h(connection_t *c)
212 {
213   char buffer[MAX_STRING_SIZE];
214   int len;
215 cp
216   if(sscanf(c->buffer, "%*d "MAX_STRING, buffer) != 1)
217     {
218        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name, c->hostname);
219        return -1;
220     }
221 cp
222   len = RSA_size(myself->connection->rsa_key);
223
224   /* Check if the length of the meta key is all right */
225
226   if(strlen(buffer) != len*2)
227     {
228       syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
229       return -1;
230     }
231
232   /* Allocate buffers for the meta key */
233 cp
234   if(!c->inkey)
235     c->inkey = xmalloc(len);
236
237   if(!c->inctx)
238     c->inctx = xmalloc(sizeof(*c->inctx));
239
240   /* Convert the challenge from hexadecimal back to binary */
241 cp
242   hex2bin(buffer,buffer,len);
243
244   /* Decrypt the meta key */
245 cp  
246   if(RSA_private_decrypt(len, buffer, c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len)    /* See challenge() */
247     {
248       syslog(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), c->name, c->hostname);
249       return -1;
250     }
251
252   if(debug_lvl >= DEBUG_SCARY_THINGS)
253     {
254       bin2hex(c->inkey, buffer, len);
255       buffer[len*2] = '\0';
256       syslog(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
257     }
258
259   /* All incoming requests will now be encrypted. */
260 cp
261   EVP_DecryptInit(c->inctx, EVP_bf_cfb(),
262                   c->inkey + len - EVP_bf_cfb()->key_len,
263                   c->inkey + len - EVP_bf_cfb()->key_len - EVP_bf_cfb()->iv_len);
264   
265   c->status.decryptin = 1;
266
267   c->allow_request = CHALLENGE;
268 cp
269   return send_challenge(c);
270 }
271
272 int send_challenge(connection_t *c)
273 {
274   char buffer[MAX_STRING_SIZE];
275   int len, x;
276 cp
277   /* CHECKME: what is most reasonable value for len? */
278
279   len = RSA_size(c->rsa_key);
280
281   /* Allocate buffers for the challenge */
282
283   if(!c->hischallenge)
284     c->hischallenge = xmalloc(len);
285 cp
286   /* Copy random data to the buffer */
287
288   RAND_bytes(c->hischallenge, len);
289
290 cp
291   /* Convert to hex */
292
293   bin2hex(c->hischallenge, buffer, len);
294   buffer[len*2] = '\0';
295
296 cp
297   /* Send the challenge */
298
299   x = send_request(c, "%d %s", CHALLENGE, buffer);
300 cp
301   return x;
302 }
303
304 int challenge_h(connection_t *c)
305 {
306   char buffer[MAX_STRING_SIZE];
307   int len;
308 cp
309   if(sscanf(c->buffer, "%*d "MAX_STRING, buffer) != 1)
310     {
311        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name, c->hostname);
312        return -1;
313     }
314
315   len = RSA_size(myself->connection->rsa_key);
316
317   /* Check if the length of the challenge is all right */
318
319   if(strlen(buffer) != len*2)
320     {
321       syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong challenge length");
322       return -1;
323     }
324
325   /* Allocate buffers for the challenge */
326
327   if(!c->mychallenge)
328     c->mychallenge = xmalloc(len);
329
330   /* Convert the challenge from hexadecimal back to binary */
331
332   hex2bin(buffer,c->mychallenge,len);
333
334   c->allow_request = CHAL_REPLY;
335
336   /* Rest is done by send_chal_reply() */
337 cp
338   return send_chal_reply(c);
339 }
340
341 int send_chal_reply(connection_t *c)
342 {
343   char hash[SHA_DIGEST_LENGTH*2+1];
344 cp
345   /* Calculate the hash from the challenge we received */
346
347   SHA1(c->mychallenge, RSA_size(myself->connection->rsa_key), hash);
348
349   /* Convert the hash to a hexadecimal formatted string */
350
351   bin2hex(hash,hash,SHA_DIGEST_LENGTH);
352   hash[SHA_DIGEST_LENGTH*2] = '\0';
353
354   /* Send the reply */
355
356 cp
357   return send_request(c, "%d %s", CHAL_REPLY, hash);
358 }
359
360 int chal_reply_h(connection_t *c)
361 {
362   char hishash[MAX_STRING_SIZE];
363   char myhash[SHA_DIGEST_LENGTH];
364 cp
365   if(sscanf(c->buffer, "%*d "MAX_STRING, hishash) != 1)
366     {
367        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "CHAL_REPLY", c->name, c->hostname);
368        return -1;
369     }
370
371   /* Check if the length of the hash is all right */
372
373   if(strlen(hishash) != SHA_DIGEST_LENGTH*2)
374     {
375       syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, _("wrong challenge reply length"));
376       return -1;
377     }
378
379   /* Convert the hash to binary format */
380
381   hex2bin(hishash, hishash, SHA_DIGEST_LENGTH);
382
383   /* Calculate the hash from the challenge we sent */
384
385   SHA1(c->hischallenge, RSA_size(c->rsa_key), myhash);
386
387   /* Verify the incoming hash with the calculated hash */
388
389   if(memcmp(hishash, myhash, SHA_DIGEST_LENGTH))
390     {
391       syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, _("wrong challenge reply"));
392       if(debug_lvl >= DEBUG_SCARY_THINGS)
393         {
394           bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
395           hishash[SHA_DIGEST_LENGTH*2] = '\0';
396           syslog(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
397         }
398       return -1;
399     }
400
401   /* Identity has now been positively verified.
402      Send an acknowledgement with the rest of the information needed.
403    */
404
405   c->allow_request = ACK;
406 cp
407   return send_ack(c);
408 }
409
410 int send_ack(connection_t *c)
411 {
412   /* ACK message contains rest of the information the other end needs
413      to create node_t and edge_t structures. */
414
415   int x;
416   char *addrstr;
417   struct timeval now;
418 cp
419   /* Estimate weight */
420   
421   gettimeofday(&now, NULL);
422   c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
423   addrstr = address2str(c->address);
424   x = send_request(c, "%d %hd %s %d %d", ACK, myself->port, addrstr, c->estimated_weight, c->options);
425   free(addrstr);
426 cp
427   return x;
428 }
429
430 void send_everything(connection_t *c)
431 {
432   avl_node_t *node, *node2;
433   node_t *n;
434   subnet_t *s;
435   edge_t *e;
436
437   /* Send all known subnets */
438   
439   for(node = node_tree->head; node; node = node->next)
440     {
441       n = (node_t *)node->data;
442
443       for(node2 = n->subnet_tree->head; node2; node2 = node2->next)
444         {
445           s = (subnet_t *)node2->data;
446           send_add_subnet(c, s);
447         }
448     }
449
450   /* Send all known edges */
451
452   for(node = edge_tree->head; node; node = node->next)
453     {
454       e = (edge_t *)node->data;
455
456       if(e == c->edge)
457         continue;
458
459       send_add_edge(c, e);
460     }
461 }
462
463 int ack_h(connection_t *c)
464 {
465   port_t hisport;
466   char addrstr[MAX_STRING_SIZE];
467   int weight;
468   int options;
469   node_t *n;
470   connection_t *other;
471   avl_node_t *node;
472 cp
473   if(sscanf(c->buffer, "%*d %hd "MAX_STRING" %d %d", &hisport, addrstr, &weight, &options) != 4)
474     {
475        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name, c->hostname);
476        return -1;
477     }
478
479   /* Check if we already have a node_t for him */
480
481   n = lookup_node(c->name);
482   
483   if(!n)
484     {
485       n = new_node();
486       n->name = xstrdup(c->name);
487       n->address = c->address;
488       n->hostname = xstrdup(c->hostname);
489       n->port = hisport;
490
491       /* FIXME: Also check if no other tinc daemon uses the same IP and port for UDP traffic */
492
493       node_add(n);
494     }
495   else
496     {
497       if(n->connection)
498         {
499           /* Oh dear, we already have a connection to this node. */
500           if(debug_lvl >= DEBUG_CONNECTIONS)
501             syslog(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"), n->name, n->hostname);
502           terminate_connection(n->connection, 0);
503         }
504           
505       /* FIXME: check if information in existing node matches that of the other end of this connection */
506     }
507   
508   n->connection = c;
509   c->node = n;
510   c->options |= options;
511
512   /* Create an edge_t for this connection */
513
514   c->edge = new_edge();
515   
516   c->edge->from.node = myself;
517   c->edge->from.address = str2address(addrstr);
518   c->edge->from.port = myself->port;
519   c->edge->to.node = n;
520   c->edge->to.address = c->address;
521   c->edge->to.port = hisport;
522   c->edge->weight = (weight + c->estimated_weight) / 2;
523   c->edge->connection = c;
524   c->edge->options = c->options;
525
526   edge_add(c->edge);
527
528   /* Activate this connection */
529
530   c->allow_request = ALL;
531   c->status.active = 1;
532
533   if(debug_lvl >= DEBUG_CONNECTIONS)
534     syslog(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name, c->hostname);
535
536 cp
537   /* Send him everything we know */
538
539   send_everything(c);
540
541   /* Notify others of this connection */
542
543   for(node = connection_tree->head; node; node = node->next)
544     {
545       other = (connection_t *)node->data;
546
547       if(other->status.active && other != c)
548         send_add_edge(other, c->edge);
549     }
550
551   /* Run MST and SSSP algorithms */
552  
553   graph();
554
555   /* Succesful connection, reset timeout if this is an outgoing connection. */
556   
557   if(c->outgoing)
558     c->outgoing->timeout = 0;
559 cp
560   return 0;
561 }