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