299e3729e0cb131555d99238e8b4c2745325c69b
[tinc] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2012 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6                   2010      Brandon Black <blblack@gmail.com>
7
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17
18     You should have received a copy of the GNU General Public License along
19     with this program; if not, write to the Free Software Foundation, Inc.,
20     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #include "system.h"
24
25 #include <openssl/pem.h>
26 #include <openssl/rsa.h>
27 #include <openssl/rand.h>
28 #include <openssl/err.h>
29 #include <openssl/evp.h>
30
31 #include "avl_tree.h"
32 #include "conf.h"
33 #include "connection.h"
34 #include "device.h"
35 #include "event.h"
36 #include "graph.h"
37 #include "logger.h"
38 #include "net.h"
39 #include "netutl.h"
40 #include "process.h"
41 #include "protocol.h"
42 #include "route.h"
43 #include "subnet.h"
44 #include "utils.h"
45 #include "xalloc.h"
46
47 char *myport;
48 devops_t devops;
49
50 bool read_rsa_public_key(connection_t *c) {
51         FILE *fp;
52         char *fname;
53         char *key;
54
55         if(!c->rsa_key) {
56                 c->rsa_key = RSA_new();
57 //              RSA_blinding_on(c->rsa_key, NULL);
58         }
59
60         /* First, check for simple PublicKey statement */
61
62         if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
63                 BN_hex2bn(&c->rsa_key->n, key);
64                 BN_hex2bn(&c->rsa_key->e, "FFFF");
65                 free(key);
66                 return true;
67         }
68
69         /* Else, check for PublicKeyFile statement and read it */
70
71         if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) {
72                 fp = fopen(fname, "r");
73
74                 if(!fp) {
75                         logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
76                                    fname, strerror(errno));
77                         free(fname);
78                         return false;
79                 }
80
81                 free(fname);
82                 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
83                 fclose(fp);
84
85                 if(c->rsa_key)
86                         return true;            /* Woohoo. */
87
88                 /* If it fails, try PEM_read_RSA_PUBKEY. */
89                 fp = fopen(fname, "r");
90
91                 if(!fp) {
92                         logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
93                                    fname, strerror(errno));
94                         free(fname);
95                         return false;
96                 }
97
98                 free(fname);
99                 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
100                 fclose(fp);
101
102                 if(c->rsa_key) {
103 //                              RSA_blinding_on(c->rsa_key, NULL);
104                         return true;
105                 }
106
107                 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s",
108                            fname, strerror(errno));
109                 return false;
110         }
111
112         /* Else, check if a harnessed public key is in the config file */
113
114         xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
115         fp = fopen(fname, "r");
116
117         if(!fp) {
118                 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", fname, strerror(errno));
119                 free(fname);
120                 return false;
121         }
122
123         c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
124         fclose(fp);
125         free(fname);
126
127         if(c->rsa_key)
128                 return true;
129
130         /* Try again with PEM_read_RSA_PUBKEY. */
131
132         xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
133         fp = fopen(fname, "r");
134
135         if(!fp) {
136                 logger(LOG_ERR, "Error reading RSA public key file `%s': %s", fname, strerror(errno));
137                 free(fname);
138                 return false;
139         }
140
141         c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
142 //      RSA_blinding_on(c->rsa_key, NULL);
143         fclose(fp);
144         free(fname);
145
146         if(c->rsa_key)
147                 return true;
148
149         logger(LOG_ERR, "No public key for %s specified!", c->name);
150
151         return false;
152 }
153
154 static bool read_rsa_private_key(void) {
155         FILE *fp;
156         char *fname, *key, *pubkey;
157         struct stat s;
158
159         if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
160                 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
161                         logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
162                         return false;
163                 }
164                 myself->connection->rsa_key = RSA_new();
165 //              RSA_blinding_on(myself->connection->rsa_key, NULL);
166                 BN_hex2bn(&myself->connection->rsa_key->d, key);
167                 BN_hex2bn(&myself->connection->rsa_key->n, pubkey);
168                 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
169                 free(key);
170                 free(pubkey);
171                 return true;
172         }
173
174         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
175                 xasprintf(&fname, "%s/rsa_key.priv", confbase);
176
177         fp = fopen(fname, "r");
178
179         if(!fp) {
180                 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
181                            fname, strerror(errno));
182                 free(fname);
183                 return false;
184         }
185
186 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
187         if(fstat(fileno(fp), &s)) {
188                 logger(LOG_ERR, "Could not stat RSA private key file `%s': %s'",
189                                 fname, strerror(errno));
190                 free(fname);
191                 return false;
192         }
193
194         if(s.st_mode & ~0100700)
195                 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
196 #endif
197
198         myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
199         fclose(fp);
200
201         if(!myself->connection->rsa_key) {
202                 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
203                            fname, strerror(errno));
204                 free(fname);
205                 return false;
206         }
207
208         free(fname);
209         return true;
210 }
211
212 /*
213   Read Subnets from all host config files
214 */
215 void load_all_subnets(void) {
216         DIR *dir;
217         struct dirent *ent;
218         char *dname;
219         char *fname;
220         avl_tree_t *config_tree;
221         config_t *cfg;
222         subnet_t *s, *s2;
223         node_t *n;
224         bool result;
225
226         xasprintf(&dname, "%s/hosts", confbase);
227         dir = opendir(dname);
228         if(!dir) {
229                 logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
230                 free(dname);
231                 return;
232         }
233
234         while((ent = readdir(dir))) {
235                 if(!check_id(ent->d_name))
236                         continue;
237
238                 n = lookup_node(ent->d_name);
239                 #ifdef _DIRENT_HAVE_D_TYPE
240                 //if(ent->d_type != DT_REG)
241                 //      continue;
242                 #endif
243
244                 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
245                 init_configuration(&config_tree);
246                 result = read_config_file(config_tree, fname);
247                 free(fname);
248                 if(!result)
249                         continue;
250
251                 if(!n) {
252                         n = new_node();
253                         n->name = xstrdup(ent->d_name);
254                         node_add(n);
255                 }
256
257                 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
258                         if(!get_config_subnet(cfg, &s))
259                                 continue;
260
261                         if((s2 = lookup_subnet(n, s))) {
262                                 s2->expires = -1;
263                         } else {
264                                 subnet_add(n, s);
265                         }
266                 }
267
268                 exit_configuration(&config_tree);
269         }
270
271         closedir(dir);
272 }
273
274 /*
275   Configure node_t myself and set up the local sockets (listen only)
276 */
277 static bool setup_myself(void) {
278         config_t *cfg;
279         subnet_t *subnet;
280         char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
281         char *fname = NULL;
282         char *address = NULL;
283         char *envp[5];
284         struct addrinfo *ai, *aip, hint = {0};
285         bool choice;
286         int i, err;
287         int replaywin_int;
288
289         myself = new_node();
290         myself->connection = new_connection();
291
292         myself->hostname = xstrdup("MYSELF");
293         myself->connection->hostname = xstrdup("MYSELF");
294
295         myself->connection->options = 0;
296         myself->connection->protocol_version = PROT_CURRENT;
297
298         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
299                 logger(LOG_ERR, "Name for tinc daemon required!");
300                 return false;
301         }
302
303         if(!check_id(name)) {
304                 logger(LOG_ERR, "Invalid name for myself!");
305                 free(name);
306                 return false;
307         }
308
309         myself->name = name;
310         myself->connection->name = xstrdup(name);
311         xasprintf(&fname, "%s/hosts/%s", confbase, name);
312         read_config_options(config_tree, name);
313         read_config_file(config_tree, fname);
314         free(fname);
315
316         if(!read_rsa_private_key())
317                 return false;
318
319         if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
320                 myport = xstrdup("655");
321
322         if(!atoi(myport)) {
323                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
324                 sockaddr_t sa;
325                 if(!ai || !ai->ai_addr)
326                         return false;
327                 free(myport);
328                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
329                 sockaddr2str(&sa, NULL, &myport);
330         }
331
332         /* Read in all the subnets specified in the host configuration file */
333
334         cfg = lookup_config(config_tree, "Subnet");
335
336         while(cfg) {
337                 if(!get_config_subnet(cfg, &subnet))
338                         return false;
339
340                 subnet_add(myself, subnet);
341
342                 cfg = lookup_config_next(config_tree, cfg);
343         }
344
345         /* Check some options */
346
347         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
348                 myself->options |= OPTION_INDIRECT;
349
350         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
351                 myself->options |= OPTION_TCPONLY;
352
353         if(myself->options & OPTION_TCPONLY)
354                 myself->options |= OPTION_INDIRECT;
355
356         get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
357         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
358         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
359         strictsubnets |= tunnelserver;
360
361         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
362                 if(!strcasecmp(mode, "router"))
363                         routing_mode = RMODE_ROUTER;
364                 else if(!strcasecmp(mode, "switch"))
365                         routing_mode = RMODE_SWITCH;
366                 else if(!strcasecmp(mode, "hub"))
367                         routing_mode = RMODE_HUB;
368                 else {
369                         logger(LOG_ERR, "Invalid routing mode!");
370                         return false;
371                 }
372                 free(mode);
373         }
374
375         if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
376                 if(!strcasecmp(mode, "off"))
377                         forwarding_mode = FMODE_OFF;
378                 else if(!strcasecmp(mode, "internal"))
379                         forwarding_mode = FMODE_INTERNAL;
380                 else if(!strcasecmp(mode, "kernel"))
381                         forwarding_mode = FMODE_KERNEL;
382                 else {
383                         logger(LOG_ERR, "Invalid forwarding mode!");
384                         return false;
385                 }
386                 free(mode);
387         }
388
389         choice = true;
390         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
391         if(choice)
392                 myself->options |= OPTION_PMTU_DISCOVERY;
393
394         choice = true;
395         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
396         if(choice)
397                 myself->options |= OPTION_CLAMP_MSS;
398
399         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
400         get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
401         get_config_bool(lookup_config(config_tree, "Broadcast"), &broadcast);
402
403 #if !defined(SOL_IP) || !defined(IP_TOS)
404         if(priorityinheritance)
405                 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
406 #endif
407
408         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
409                 macexpire = 600;
410
411         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
412                 if(maxtimeout <= 0) {
413                         logger(LOG_ERR, "Bogus maximum timeout!");
414                         return false;
415                 }
416         } else
417                 maxtimeout = 900;
418
419         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
420                 if(udp_rcvbuf <= 0) {
421                         logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
422                         return false;
423                 }
424         }
425
426         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
427                 if(udp_sndbuf <= 0) {
428                         logger(LOG_ERR, "UDPSndBuf cannot be negative!");
429                         return false;
430                 }
431         }
432
433         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
434                 if(replaywin_int < 0) {
435                         logger(LOG_ERR, "ReplayWindow cannot be negative!");
436                         return false;
437                 }
438                 replaywin = (unsigned)replaywin_int;
439         }
440
441         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
442                 if(!strcasecmp(afname, "IPv4"))
443                         addressfamily = AF_INET;
444                 else if(!strcasecmp(afname, "IPv6"))
445                         addressfamily = AF_INET6;
446                 else if(!strcasecmp(afname, "any"))
447                         addressfamily = AF_UNSPEC;
448                 else {
449                         logger(LOG_ERR, "Invalid address family!");
450                         return false;
451                 }
452                 free(afname);
453         }
454
455         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
456
457         /* Generate packet encryption key */
458
459         if(get_config_string
460            (lookup_config(config_tree, "Cipher"), &cipher)) {
461                 if(!strcasecmp(cipher, "none")) {
462                         myself->incipher = NULL;
463                 } else {
464                         myself->incipher = EVP_get_cipherbyname(cipher);
465
466                         if(!myself->incipher) {
467                                 logger(LOG_ERR, "Unrecognized cipher type!");
468                                 return false;
469                         }
470                 }
471         } else
472                 myself->incipher = EVP_bf_cbc();
473
474         if(myself->incipher)
475                 myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
476         else
477                 myself->inkeylength = 1;
478
479         myself->connection->outcipher = EVP_bf_ofb();
480
481         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
482                 keylifetime = 3600;
483
484         keyexpires = now + keylifetime;
485         
486         /* Check if we want to use message authentication codes... */
487
488         if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
489                 if(!strcasecmp(digest, "none")) {
490                         myself->indigest = NULL;
491                 } else {
492                         myself->indigest = EVP_get_digestbyname(digest);
493
494                         if(!myself->indigest) {
495                                 logger(LOG_ERR, "Unrecognized digest type!");
496                                 return false;
497                         }
498                 }
499         } else
500                 myself->indigest = EVP_sha1();
501
502         myself->connection->outdigest = EVP_sha1();
503
504         if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
505                 if(myself->indigest) {
506                         if(myself->inmaclength > myself->indigest->md_size) {
507                                 logger(LOG_ERR, "MAC length exceeds size of digest!");
508                                 return false;
509                         } else if(myself->inmaclength < 0) {
510                                 logger(LOG_ERR, "Bogus MAC length!");
511                                 return false;
512                         }
513                 }
514         } else
515                 myself->inmaclength = 4;
516
517         myself->connection->outmaclength = 0;
518
519         /* Compression */
520
521         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
522                 if(myself->incompression < 0 || myself->incompression > 11) {
523                         logger(LOG_ERR, "Bogus compression level!");
524                         return false;
525                 }
526         } else
527                 myself->incompression = 0;
528
529         myself->connection->outcompression = 0;
530
531         /* Done */
532
533         myself->nexthop = myself;
534         myself->via = myself;
535         myself->status.reachable = true;
536         node_add(myself);
537
538         graph();
539
540         if(strictsubnets)
541                 load_all_subnets();
542
543         /* Open device */
544
545         devops = os_devops;
546
547         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
548                 if(!strcasecmp(type, "dummy"))
549                         devops = dummy_devops;
550                 else if(!strcasecmp(type, "raw_socket"))
551                         devops = raw_socket_devops;
552 #ifdef ENABLE_UML
553                 else if(!strcasecmp(type, "uml"))
554                         devops = uml_devops;
555 #endif
556 #ifdef ENABLE_VDE
557                 else if(!strcasecmp(type, "vde"))
558                         devops = vde_devops;
559 #endif
560         }
561
562         if(!devops.setup())
563                 return false;
564
565         /* Run tinc-up script to further initialize the tap interface */
566         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
567         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
568         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
569         xasprintf(&envp[3], "NAME=%s", myself->name);
570         envp[4] = NULL;
571
572         execute_script("tinc-up", envp);
573
574         for(i = 0; i < 5; i++)
575                 free(envp[i]);
576
577         /* Run subnet-up scripts for our own subnets */
578
579         subnet_update(myself, NULL, true);
580
581         /* Open sockets */
582
583         listen_sockets = 0;
584         cfg = lookup_config(config_tree, "BindToAddress");
585
586         do {
587                 get_config_string(cfg, &address);
588                 if(cfg)
589                         cfg = lookup_config_next(config_tree, cfg);
590
591                 hint.ai_family = addressfamily;
592                 hint.ai_socktype = SOCK_STREAM;
593                 hint.ai_protocol = IPPROTO_TCP;
594                 hint.ai_flags = AI_PASSIVE;
595
596                 err = getaddrinfo(address, myport, &hint, &ai);
597                 free(address);
598
599                 if(err || !ai) {
600                         logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
601                                    gai_strerror(err));
602                         return false;
603                 }
604
605                 for(aip = ai; aip; aip = aip->ai_next) {
606                         if(listen_sockets >= MAXSOCKETS) {
607                                 logger(LOG_ERR, "Too many listening sockets");
608                                 return false;
609                         }
610
611                         listen_socket[listen_sockets].tcp =
612                                 setup_listen_socket((sockaddr_t *) aip->ai_addr);
613
614                         if(listen_socket[listen_sockets].tcp < 0)
615                                 continue;
616
617                         listen_socket[listen_sockets].udp =
618                                 setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
619
620                         if(listen_socket[listen_sockets].udp < 0)
621                                 continue;
622
623                         ifdebug(CONNECTIONS) {
624                                 hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
625                                 logger(LOG_NOTICE, "Listening on %s", hostname);
626                                 free(hostname);
627                         }
628
629                         memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
630                         listen_sockets++;
631                 }
632
633                 freeaddrinfo(ai);
634         } while(cfg);
635
636         if(listen_sockets)
637                 logger(LOG_NOTICE, "Ready");
638         else {
639                 logger(LOG_ERR, "Unable to create any listening socket!");
640                 return false;
641         }
642
643         return true;
644 }
645
646 /*
647   initialize network
648 */
649 bool setup_network(void) {
650         now = time(NULL);
651
652         init_events();
653         init_connections();
654         init_subnets();
655         init_nodes();
656         init_edges();
657         init_requests();
658
659         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
660                 if(pinginterval < 1) {
661                         pinginterval = 86400;
662                 }
663         } else
664                 pinginterval = 60;
665
666         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
667                 pingtimeout = 5;
668         if(pingtimeout < 1 || pingtimeout > pinginterval)
669                 pingtimeout = pinginterval;
670
671         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
672                 maxoutbufsize = 10 * MTU;
673
674         if(!setup_myself())
675                 return false;
676
677         return true;
678 }
679
680 /*
681   close all open network connections
682 */
683 void close_network_connections(void) {
684         avl_node_t *node, *next;
685         connection_t *c;
686         char *envp[5];
687         int i;
688
689         for(node = connection_tree->head; node; node = next) {
690                 next = node->next;
691                 c = node->data;
692                 c->outgoing = NULL;
693                 terminate_connection(c, false);
694         }
695
696         for(list_node_t *node = outgoing_list->head; node; node = node->next) {
697                 outgoing_t *outgoing = node->data;
698
699                 if(outgoing->event)
700                         event_del(outgoing->event);
701         }
702
703         list_delete_list(outgoing_list);
704
705         if(myself && myself->connection) {
706                 subnet_update(myself, NULL, false);
707                 terminate_connection(myself->connection, false);
708                 free_connection(myself->connection);
709         }
710
711         for(i = 0; i < listen_sockets; i++) {
712                 close(listen_socket[i].tcp);
713                 close(listen_socket[i].udp);
714         }
715
716         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
717         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
718         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
719         xasprintf(&envp[3], "NAME=%s", myself->name);
720         envp[4] = NULL;
721
722         exit_requests();
723         exit_edges();
724         exit_subnets();
725         exit_nodes();
726         exit_connections();
727         exit_events();
728
729         execute_script("tinc-down", envp);
730
731         if(myport) free(myport);
732
733         for(i = 0; i < 4; i++)
734                 free(envp[i]);
735
736         devops.close();
737
738         return;
739 }