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