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