58d80da6b4968f858f4b1ee1468fc73bf22d3a6d
[oweals/tinc.git] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2003 Ivo Timmermans <ivo@o2w.nl>,
4                   2000-2003 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: net_setup.c,v 1.1.2.50 2003/12/20 21:25:17 guus Exp $
21 */
22
23 #include "system.h"
24
25 #include <gnutls/gnutls.h>
26 #include <gnutls/x509.h>
27 #include <gcrypt.h>
28
29 #include "avl_tree.h"
30 #include "conf.h"
31 #include "connection.h"
32 #include "device.h"
33 #include "event.h"
34 #include "graph.h"
35 #include "logger.h"
36 #include "net.h"
37 #include "netutl.h"
38 #include "process.h"
39 #include "protocol.h"
40 #include "route.h"
41 #include "subnet.h"
42 #include "utils.h"
43 #include "xalloc.h"
44
45 char *myport;
46
47 #if 0
48 bool read_rsa_public_key(connection_t *c)
49 {
50         FILE *fp;
51         char *fname;
52         char *key;
53
54         cp();
55
56         if(!c->rsa_key) {
57                 c->rsa_key = RSA_new();
58 //              RSA_blinding_on(c->rsa_key, NULL);
59         }
60
61         /* First, check for simple PublicKey statement */
62
63         if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
64                 BN_hex2bn(&c->rsa_key->n, key);
65                 BN_hex2bn(&c->rsa_key->e, "FFFF");
66                 free(key);
67                 return true;
68         }
69
70         /* Else, check for PublicKeyFile statement and read it */
71
72         if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) {
73                 fp = fopen(fname, "r");
74
75                 if(!fp) {
76                         logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
77                                    fname, strerror(errno));
78                         free(fname);
79                         return false;
80                 }
81
82                 free(fname);
83                 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
84                 fclose(fp);
85
86                 if(c->rsa_key)
87                         return true;            /* Woohoo. */
88
89                 /* If it fails, try PEM_read_RSA_PUBKEY. */
90                 fp = fopen(fname, "r");
91
92                 if(!fp) {
93                         logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"),
94                                    fname, strerror(errno));
95                         free(fname);
96                         return false;
97                 }
98
99                 free(fname);
100                 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
101                 fclose(fp);
102
103                 if(c->rsa_key) {
104 //                              RSA_blinding_on(c->rsa_key, NULL);
105                         return true;
106                 }
107
108                 logger(LOG_ERR, _("Reading RSA public key file `%s' failed: %s"),
109                            fname, strerror(errno));
110                 return false;
111         }
112
113         /* Else, check if a harnessed public key is in the config file */
114
115         asprintf(&fname, "%s/hosts/%s", confbase, c->name);
116         fp = fopen(fname, "r");
117
118         if(fp) {
119                 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
120                 fclose(fp);
121         }
122
123         free(fname);
124
125         if(c->rsa_key)
126                 return true;
127
128         /* Try again with PEM_read_RSA_PUBKEY. */
129
130         asprintf(&fname, "%s/hosts/%s", confbase, c->name);
131         fp = fopen(fname, "r");
132
133         if(fp) {
134                 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
135 //              RSA_blinding_on(c->rsa_key, NULL);
136                 fclose(fp);
137         }
138
139         free(fname);
140
141         if(c->rsa_key)
142                 return true;
143
144         logger(LOG_ERR, _("No public key for %s specified!"), c->name);
145
146         return false;
147 }
148 #endif
149
150 bool setup_credentials(void)
151 {
152         char *trust = NULL, *crl = NULL;
153         char *key = NULL, *cert = NULL;
154         int result;
155
156         cp();
157
158         gnutls_certificate_allocate_credentials(&myself->connection->credentials);
159
160         if(get_config_string(lookup_config(config_tree, "TrustFile"), &trust)) {
161                 result = gnutls_certificate_set_x509_trust_file(myself->connection->credentials, trust, GNUTLS_X509_FMT_PEM);
162                 if(result < 0) {
163                         logger(LOG_ERR, _("Error reading trust file '%s': %s"), trust, gnutls_strerror(result));
164                         free(trust);
165                         return false;
166                 }
167                 free(trust);
168         }
169
170         if(get_config_string(lookup_config(config_tree, "CRLFile"), &crl)) {
171                 result = gnutls_certificate_set_x509_crl_file(myself->connection->credentials, crl, GNUTLS_X509_FMT_PEM);
172                 if(result) {
173                         logger(LOG_ERR, _("Error reading CRL file '%s': %s"), crl, gnutls_strerror(result));
174                         free(crl);
175                         return false;
176                 }
177                 free(crl);
178         }
179
180         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &key))
181                 asprintf(&key, "%s/rsa_key.priv", confbase);
182
183         if(!get_config_string(lookup_config(config_tree, "CertificateFile"), &cert))
184                 asprintf(&cert, "%s/hosts/%s", confbase, myself->name);
185
186         
187         gnutls_certificate_set_x509_trust_file(myself->connection->credentials, cert, GNUTLS_X509_FMT_PEM);
188         logger(LOG_DEBUG, _("JOEHOE"));
189         gnutls_certificate_set_verify_flags(myself->connection->credentials, GNUTLS_VERIFY_DISABLE_CA_SIGN);
190         
191         result = gnutls_certificate_set_x509_key_file(myself->connection->credentials, cert, key, GNUTLS_X509_FMT_PEM);
192
193         if(result) {
194                 logger(LOG_ERR, _("Error reading credentials from %s and %s: %s"), cert, key, gnutls_strerror(result));
195                 free(key);
196                 free(cert);
197                 return false;
198         }
199
200         free(key);
201         free(cert);
202         
203         return true;
204 }
205
206 /*
207   Configure node_t myself and set up the local sockets (listen only)
208 */
209 bool setup_myself(void)
210 {
211         config_t *cfg;
212         subnet_t *subnet;
213         char *name, *hostname, *mode, *afname, *cipher, *digest;
214         char *address = NULL;
215         char *envp[5];
216         struct addrinfo *ai, *aip, hint = {0};
217         bool choice;
218         int i, err, result;
219
220         cp();
221
222         myself = new_node();
223         myself->connection = new_connection();
224         init_configuration(&myself->connection->config_tree);
225
226         asprintf(&myself->hostname, _("MYSELF"));
227         asprintf(&myself->connection->hostname, _("MYSELF"));
228
229         myself->connection->options = 0;
230         myself->connection->protocol_version = PROT_CURRENT;
231
232         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
233                 logger(LOG_ERR, _("Name for tinc daemon required!"));
234                 return false;
235         }
236
237         if(!check_id(name)) {
238                 logger(LOG_ERR, _("Invalid name for myself!"));
239                 free(name);
240                 return false;
241         }
242
243         myself->name = name;
244         myself->connection->name = xstrdup(name);
245
246         if(!setup_credentials())
247                 return false;
248
249         if(!read_connection_config(myself->connection)) {
250                 logger(LOG_ERR, _("Cannot open host configuration file for myself!"));
251                 return false;
252         }
253
254         if(!get_config_string (lookup_config(myself->connection->config_tree, "Port"), &myport))
255                 asprintf(&myport, "655");
256
257         /* Read in all the subnets specified in the host configuration file */
258
259         cfg = lookup_config(myself->connection->config_tree, "Subnet");
260
261         while(cfg) {
262                 if(!get_config_subnet(cfg, &subnet))
263                         return false;
264
265                 subnet_add(myself, subnet);
266
267                 cfg = lookup_config_next(myself->connection->config_tree, cfg);
268         }
269
270         /* Check some options */
271
272         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
273                 myself->options |= OPTION_INDIRECT;
274
275         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
276                 myself->options |= OPTION_TCPONLY;
277
278         if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
279                 myself->options |= OPTION_INDIRECT;
280
281         if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice) && choice)
282                 myself->options |= OPTION_TCPONLY;
283
284         if(get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) && choice)
285                 myself->options |= OPTION_PMTU_DISCOVERY;
286
287         if(myself->options & OPTION_TCPONLY)
288                 myself->options |= OPTION_INDIRECT;
289
290         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
291
292         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
293                 if(!strcasecmp(mode, "router"))
294                         routing_mode = RMODE_ROUTER;
295                 else if(!strcasecmp(mode, "switch"))
296                         routing_mode = RMODE_SWITCH;
297                 else if(!strcasecmp(mode, "hub"))
298                         routing_mode = RMODE_HUB;
299                 else {
300                         logger(LOG_ERR, _("Invalid routing mode!"));
301                         return false;
302                 }
303                 free(mode);
304         } else
305                 routing_mode = RMODE_ROUTER;
306
307         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
308
309 #if !defined(SOL_IP) || !defined(IP_TOS)
310         if(priorityinheritance)
311                 logger(LOG_WARNING, _("PriorityInheritance not supported on this platform"));
312 #endif
313
314         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
315                 macexpire = 600;
316
317         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
318                 if(maxtimeout <= 0) {
319                         logger(LOG_ERR, _("Bogus maximum timeout!"));
320                         return false;
321                 }
322         } else
323                 maxtimeout = 900;
324
325         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
326                 if(!strcasecmp(afname, "IPv4"))
327                         addressfamily = AF_INET;
328                 else if(!strcasecmp(afname, "IPv6"))
329                         addressfamily = AF_INET6;
330                 else if(!strcasecmp(afname, "any"))
331                         addressfamily = AF_UNSPEC;
332                 else {
333                         logger(LOG_ERR, _("Invalid address family!"));
334                         return false;
335                 }
336                 free(afname);
337         }
338
339         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
340
341         /* Generate packet encryption key */
342
343         if(get_config_string (lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) {
344                 if(!strcasecmp(cipher, "none")) {
345                         myself->cipher = GCRY_CIPHER_NONE;
346                 } else {
347                         myself->cipher = gcry_cipher_map_name(cipher);
348
349                         if(!myself->cipher) {
350                                 logger(LOG_ERR, _("Unrecognized cipher type!"));
351                                 return false;
352                         }
353                 }
354         } else
355                 myself->cipher = GCRY_CIPHER_AES;
356
357         if(myself->cipher) {
358                 result = gcry_cipher_open(&myself->cipher_ctx, myself->cipher, GCRY_CIPHER_MODE_CBC, GCRY_CIPHER_SECURE);
359
360                 if(result) {
361                         logger(LOG_ERR, _("Error during initialisation of cipher for %s (%s): %s"),
362                                         myself->name, myself->hostname, gcry_strerror(result));
363                         return false;
364                 }
365
366         }
367
368         if(myself->cipher) {
369                 myself->cipherkeylen = gcry_cipher_get_algo_keylen(myself->cipher);
370                 myself->cipherblklen = gcry_cipher_get_algo_blklen(myself->cipher);
371         } else {
372                 myself->cipherkeylen = 1;
373         }
374
375         logger(LOG_DEBUG, _("Key %s len %d"), gcry_cipher_algo_name(myself->cipher), myself->cipherkeylen);
376         myself->cipherkey = xmalloc(myself->cipherkeylen);
377         gcry_randomize(myself->cipherkey, myself->cipherkeylen, GCRY_STRONG_RANDOM);
378         if(myself->cipher)
379                 gcry_cipher_setkey(myself->cipher_ctx, myself->cipherkey, myself->cipherkeylen);
380
381         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
382                 keylifetime = 3600;
383
384         keyexpires = now + keylifetime;
385         
386         /* Check if we want to use message authentication codes... */
387
388         if(get_config_string (lookup_config(myself->connection->config_tree, "Digest"), &digest)) {
389                 if(!strcasecmp(digest, "none")) {
390                         myself->digest = GCRY_MD_NONE;
391                 } else {
392                         myself->digest = gcry_md_map_name(digest);
393
394                         if(!myself->digest) {
395                                 logger(LOG_ERR, _("Unrecognized digest type!"));
396                                 return false;
397                         }
398                 }
399         } else
400                 myself->digest = GCRY_MD_SHA1;
401
402
403         if(myself->digest) {
404                 result = gcry_md_open(&myself->digest_ctx, myself->digest, GCRY_MD_FLAG_SECURE | GCRY_MD_FLAG_HMAC);
405
406                 if(result) {
407                         logger(LOG_ERR, _("Error during initialisation of digest for %s (%s): %s"),
408                                         myself->name, myself->hostname, gcry_strerror(result));
409                         return false;
410                 }
411
412         }
413
414         if(myself->digest) {
415                 myself->digestlen = gcry_md_get_algo_dlen(myself->digest);
416         } else {
417                 myself->digestlen = 1;
418         }
419
420         myself->digestkey = xmalloc(myself->digestlen);
421         gcry_randomize(myself->digestkey, myself->digestlen, GCRY_STRONG_RANDOM);
422         if(myself->digest)
423                 gcry_md_setkey(myself->digest_ctx, myself->digestkey, myself->digestlen);
424
425         if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->maclength)) {
426                 if(myself->digest) {
427                         if(myself->maclength > myself->digestlen) {
428                                 logger(LOG_ERR, _("MAC length exceeds size of digest!"));
429                                 return false;
430                         } else if(myself->maclength < 0) {
431                                 logger(LOG_ERR, _("Bogus MAC length!"));
432                                 return false;
433                         }
434                 }
435         } else
436                 myself->maclength = 4;
437
438         /* Compression */
439
440         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"),
441                 &myself->compression)) {
442                 if(myself->compression < 0 || myself->compression > 11) {
443                         logger(LOG_ERR, _("Bogus compression level!"));
444                         return false;
445                 }
446         } else
447                 myself->compression = 0;
448
449         /* Done */
450
451         myself->nexthop = myself;
452         myself->via = myself;
453         myself->status.active = true;
454         myself->status.reachable = true;
455         node_add(myself);
456
457         graph();
458
459         /* Open device */
460
461         if(!setup_device())
462                 return false;
463
464         /* Run tinc-up script to further initialize the tap interface */
465         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
466         asprintf(&envp[1], "DEVICE=%s", device ? : "");
467         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
468         asprintf(&envp[3], "NAME=%s", myself->name);
469         envp[4] = NULL;
470
471         execute_script("tinc-up", envp);
472
473         for(i = 0; i < 5; i++)
474                 free(envp[i]);
475
476         /* Open sockets */
477
478         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
479
480         hint.ai_family = addressfamily;
481         hint.ai_socktype = SOCK_STREAM;
482         hint.ai_protocol = IPPROTO_TCP;
483         hint.ai_flags = AI_PASSIVE;
484
485         err = getaddrinfo(address, myport, &hint, &ai);
486
487         if(err || !ai) {
488                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo",
489                            gai_strerror(err));
490                 return false;
491         }
492
493         listen_sockets = 0;
494
495         for(aip = ai; aip; aip = aip->ai_next) {
496                 listen_socket[listen_sockets].tcp =
497                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
498
499                 if(listen_socket[listen_sockets].tcp < 0)
500                         continue;
501
502                 listen_socket[listen_sockets].udp =
503                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
504
505                 if(listen_socket[listen_sockets].udp < 0)
506                         continue;
507
508                 ifdebug(CONNECTIONS) {
509                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
510                         logger(LOG_NOTICE, _("Listening on %s"), hostname);
511                         free(hostname);
512                 }
513
514                 listen_socket[listen_sockets].sa.sa = *aip->ai_addr;
515                 listen_sockets++;
516         }
517
518         freeaddrinfo(ai);
519
520         if(listen_sockets)
521                 logger(LOG_NOTICE, _("Ready"));
522         else {
523                 logger(LOG_ERR, _("Unable to create any listening socket!"));
524                 return false;
525         }
526
527         return true;
528 }
529
530 /*
531   setup all initial network connections
532 */
533 bool setup_network_connections(void)
534 {
535         cp();
536
537         now = time(NULL);
538
539         init_connections();
540         init_subnets();
541         init_nodes();
542         init_edges();
543         init_events();
544         init_requests();
545
546         if(get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout)) {
547                 if(pingtimeout < 1) {
548                         pingtimeout = 86400;
549                 }
550         } else
551                 pingtimeout = 60;
552
553         if(!setup_myself())
554                 return false;
555
556         try_outgoing_connections();
557
558         return true;
559 }
560
561 /*
562   close all open network connections
563 */
564 void close_network_connections(void)
565 {
566         avl_node_t *node, *next;
567         connection_t *c;
568         char *envp[5];
569         int i;
570
571         cp();
572
573         for(node = connection_tree->head; node; node = next) {
574                 next = node->next;
575                 c = node->data;
576
577                 if(c->outgoing)
578                         free(c->outgoing->name), free(c->outgoing), c->outgoing = NULL;
579                 terminate_connection(c, false);
580         }
581
582         if(myself && myself->connection)
583                 terminate_connection(myself->connection, false);
584
585         for(i = 0; i < listen_sockets; i++) {
586                 close(listen_socket[i].tcp);
587                 close(listen_socket[i].udp);
588         }
589
590         exit_requests();
591         exit_events();
592         exit_edges();
593         exit_subnets();
594         exit_nodes();
595         exit_connections();
596
597         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
598         asprintf(&envp[1], "DEVICE=%s", device ? : "");
599         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
600         asprintf(&envp[3], "NAME=%s", myself->name);
601         envp[4] = NULL;
602
603         execute_script("tinc-down", envp);
604
605         for(i = 0; i < 4; i++)
606                 free(envp[i]);
607
608         close_device();
609
610         return;
611 }