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