4456ea599b90d930224c8b73ce5ea7f429b2f24e
[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.14 2002/09/04 16:26:45 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 %d %d %d %d %s", METAKEY,
199                    c->outcipher?c->outcipher->nid:0, c->outdigest?c->outdigest->type:0,
200                    c->outmaclength, c->outcompression, buffer);
201
202   /* Further outgoing requests are encrypted with the key we just generated */
203
204   if(c->outcipher)
205     {
206       EVP_EncryptInit(c->outctx, c->outcipher,
207                       c->outkey + len - c->outcipher->key_len,
208                       c->outkey + len - c->outcipher->key_len - c->outcipher->iv_len);
209
210       c->status.encryptout = 1;
211     }
212 cp
213   return x;
214 }
215
216 int metakey_h(connection_t *c)
217 {
218   char buffer[MAX_STRING_SIZE];
219   int cipher, digest, maclength, compression;
220   int len;
221 cp
222   if(sscanf(c->buffer, "%*d %d %d %d %d "MAX_STRING, &cipher, &digest, &maclength, &compression, buffer) != 5)
223     {
224        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "METAKEY", c->name, c->hostname);
225        return -1;
226     }
227 cp
228   len = RSA_size(myself->connection->rsa_key);
229
230   /* Check if the length of the meta key is all right */
231
232   if(strlen(buffer) != len*2)
233     {
234       syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong keylength");
235       return -1;
236     }
237
238   /* Allocate buffers for the meta key */
239 cp
240   if(!c->inkey)
241     c->inkey = xmalloc(len);
242
243   if(!c->inctx)
244     c->inctx = xmalloc(sizeof(*c->inctx));
245
246   /* Convert the challenge from hexadecimal back to binary */
247 cp
248   hex2bin(buffer,buffer,len);
249
250   /* Decrypt the meta key */
251 cp  
252   if(RSA_private_decrypt(len, buffer, c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len)    /* See challenge() */
253     {
254       syslog(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), c->name, c->hostname);
255       return -1;
256     }
257
258   if(debug_lvl >= DEBUG_SCARY_THINGS)
259     {
260       bin2hex(c->inkey, buffer, len);
261       buffer[len*2] = '\0';
262       syslog(LOG_DEBUG, _("Received random meta key (unencrypted): %s"), buffer);
263     }
264
265   /* All incoming requests will now be encrypted. */
266 cp
267   /* Check and lookup cipher and digest algorithms */
268
269   if(cipher)
270     {
271       c->incipher = EVP_get_cipherbynid(cipher);
272       if(!c->incipher)
273         {
274           syslog(LOG_ERR, _("%s (%s) uses unknown cipher!"), c->name, c->hostname);
275           return -1;
276         }
277
278       EVP_DecryptInit(c->inctx, c->incipher,
279                       c->inkey + len - c->incipher->key_len,
280                       c->inkey + len - c->incipher->key_len - c->incipher->iv_len);
281
282       c->status.decryptin = 1;
283     }
284   else
285     {
286       c->incipher = NULL;
287     }
288
289   c->inmaclength = maclength;
290
291   if(digest)
292     {
293       c->indigest = EVP_get_digestbynid(digest);
294       if(!c->indigest)
295         {
296           syslog(LOG_ERR, _("Node %s (%s) uses unknown digest!"), c->name, c->hostname);
297           return -1;
298         }
299       
300       if(c->inmaclength > c->indigest->md_size || c->inmaclength < 0)
301         {
302           syslog(LOG_ERR, _("%s (%s) uses bogus MAC length!"), c->name, c->hostname);
303           return -1;
304         }
305     }
306   else
307     {
308       c->indigest = NULL;
309     }
310
311   c->incompression = compression;
312
313   c->allow_request = CHALLENGE;
314 cp
315   return send_challenge(c);
316 }
317
318 int send_challenge(connection_t *c)
319 {
320   char buffer[MAX_STRING_SIZE];
321   int len, x;
322 cp
323   /* CHECKME: what is most reasonable value for len? */
324
325   len = RSA_size(c->rsa_key);
326
327   /* Allocate buffers for the challenge */
328
329   if(!c->hischallenge)
330     c->hischallenge = xmalloc(len);
331 cp
332   /* Copy random data to the buffer */
333
334   RAND_bytes(c->hischallenge, len);
335
336 cp
337   /* Convert to hex */
338
339   bin2hex(c->hischallenge, buffer, len);
340   buffer[len*2] = '\0';
341
342 cp
343   /* Send the challenge */
344
345   x = send_request(c, "%d %s", CHALLENGE, buffer);
346 cp
347   return x;
348 }
349
350 int challenge_h(connection_t *c)
351 {
352   char buffer[MAX_STRING_SIZE];
353   int len;
354 cp
355   if(sscanf(c->buffer, "%*d "MAX_STRING, buffer) != 1)
356     {
357        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "CHALLENGE", c->name, c->hostname);
358        return -1;
359     }
360
361   len = RSA_size(myself->connection->rsa_key);
362
363   /* Check if the length of the challenge is all right */
364
365   if(strlen(buffer) != len*2)
366     {
367       syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, "wrong challenge length");
368       return -1;
369     }
370
371   /* Allocate buffers for the challenge */
372
373   if(!c->mychallenge)
374     c->mychallenge = xmalloc(len);
375
376   /* Convert the challenge from hexadecimal back to binary */
377
378   hex2bin(buffer,c->mychallenge,len);
379
380   c->allow_request = CHAL_REPLY;
381
382   /* Rest is done by send_chal_reply() */
383 cp
384   return send_chal_reply(c);
385 }
386
387 int send_chal_reply(connection_t *c)
388 {
389   char hash[EVP_MAX_MD_SIZE*2+1];
390   EVP_MD_CTX ctx;
391 cp
392   /* Calculate the hash from the challenge we received */
393
394   EVP_DigestInit(&ctx, c->indigest);
395   EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key));
396   EVP_DigestFinal(&ctx, hash, NULL);
397
398   /* Convert the hash to a hexadecimal formatted string */
399
400   bin2hex(hash,hash,c->indigest->md_size);
401   hash[c->indigest->md_size*2] = '\0';
402
403   /* Send the reply */
404
405 cp
406   return send_request(c, "%d %s", CHAL_REPLY, hash);
407 }
408
409 int chal_reply_h(connection_t *c)
410 {
411   char hishash[MAX_STRING_SIZE];
412   char myhash[EVP_MAX_MD_SIZE];
413   EVP_MD_CTX ctx;
414 cp
415   if(sscanf(c->buffer, "%*d "MAX_STRING, hishash) != 1)
416     {
417        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "CHAL_REPLY", c->name, c->hostname);
418        return -1;
419     }
420
421   /* Check if the length of the hash is all right */
422
423   if(strlen(hishash) != c->outdigest->md_size*2)
424     {
425       syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, _("wrong challenge reply length"));
426       return -1;
427     }
428
429   /* Convert the hash to binary format */
430
431   hex2bin(hishash, hishash, c->outdigest->md_size);
432
433   /* Calculate the hash from the challenge we sent */
434
435   EVP_DigestInit(&ctx, c->outdigest);
436   EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key));
437   EVP_DigestFinal(&ctx, myhash, NULL);
438
439   /* Verify the incoming hash with the calculated hash */
440
441   if(memcmp(hishash, myhash, c->outdigest->md_size))
442     {
443       syslog(LOG_ERR, _("Possible intruder %s (%s): %s"), c->name, c->hostname, _("wrong challenge reply"));
444       if(debug_lvl >= DEBUG_SCARY_THINGS)
445         {
446           bin2hex(myhash, hishash, SHA_DIGEST_LENGTH);
447           hishash[SHA_DIGEST_LENGTH*2] = '\0';
448           syslog(LOG_DEBUG, _("Expected challenge reply: %s"), hishash);
449         }
450       return -1;
451     }
452
453   /* Identity has now been positively verified.
454      Send an acknowledgement with the rest of the information needed.
455    */
456
457   c->allow_request = ACK;
458 cp
459   return send_ack(c);
460 }
461
462 int send_ack(connection_t *c)
463 {
464   /* ACK message contains rest of the information the other end needs
465      to create node_t and edge_t structures. */
466
467   int x;
468   struct timeval now;
469 cp
470   /* Estimate weight */
471   
472   gettimeofday(&now, NULL);
473   c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
474   x = send_request(c, "%d %s %d %lx", ACK, myport, c->estimated_weight, c->options);
475 cp
476   return x;
477 }
478
479 void send_everything(connection_t *c)
480 {
481   avl_node_t *node, *node2;
482   node_t *n;
483   subnet_t *s;
484   edge_t *e;
485
486   /* Send all known subnets and edges */
487   
488   for(node = node_tree->head; node; node = node->next)
489     {
490       n = (node_t *)node->data;
491
492       for(node2 = n->subnet_tree->head; node2; node2 = node2->next)
493         {
494           s = (subnet_t *)node2->data;
495           send_add_subnet(c, s);
496         }
497
498       for(node2 = n->edge_tree->head; node2; node2 = node2->next)
499         {
500           e = (edge_t *)node2->data;
501           send_add_edge(c, e);
502         }
503     }
504 }
505
506 int ack_h(connection_t *c)
507 {
508   char hisport[MAX_STRING_SIZE];
509   char *hisaddress, *dummy;
510   int weight;
511   long int options;
512   node_t *n;
513 cp
514   if(sscanf(c->buffer, "%*d "MAX_STRING" %d %lx", hisport, &weight, &options) != 3)
515     {
516        syslog(LOG_ERR, _("Got bad %s from %s (%s)"), "ACK", c->name, c->hostname);
517        return -1;
518     }
519
520   /* Check if we already have a node_t for him */
521
522   n = lookup_node(c->name);
523   
524   if(!n)
525     {
526       n = new_node();
527       n->name = xstrdup(c->name);
528       node_add(n);
529     }
530   else
531     {
532       if(n->connection)
533         {
534           /* Oh dear, we already have a connection to this node. */
535           if(debug_lvl >= DEBUG_CONNECTIONS)
536             syslog(LOG_DEBUG, _("Established a second connection with %s (%s), closing old connection"), n->name, n->hostname);
537           terminate_connection(n->connection, 0);
538         }
539     }
540   
541   n->connection = c;
542   c->node = n;
543   c->options |= options;
544
545   /* Activate this connection */
546
547   c->allow_request = ALL;
548   c->status.active = 1;
549
550   if(debug_lvl >= DEBUG_CONNECTIONS)
551     syslog(LOG_NOTICE, _("Connection with %s (%s) activated"), c->name, c->hostname);
552
553   /* Send him everything we know */
554
555   send_everything(c);
556
557   /* Create an edge_t for this connection */
558
559   c->edge = new_edge();
560 cp  
561   c->edge->from = myself;
562   c->edge->to = n;
563   sockaddr2str(&c->address, &hisaddress, &dummy);
564   c->edge->address = str2sockaddr(hisaddress, hisport);
565   free(hisaddress);
566   free(dummy);
567   c->edge->weight = (weight + c->estimated_weight) / 2;
568   c->edge->connection = c;
569   c->edge->options = c->options;
570 cp
571   edge_add(c->edge);
572
573 cp
574   /* Notify everyone of the new edge */
575
576   send_add_edge(broadcast, c->edge);
577
578   /* Run MST and SSSP algorithms */
579  
580   graph();
581 cp
582   return 0;
583 }