Free resources in rsa_t.
[oweals/tinc.git] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2010 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 "splay_tree.h"
26 #include "cipher.h"
27 #include "conf.h"
28 #include "connection.h"
29 #include "control.h"
30 #include "device.h"
31 #include "digest.h"
32 #include "graph.h"
33 #include "logger.h"
34 #include "net.h"
35 #include "netutl.h"
36 #include "process.h"
37 #include "protocol.h"
38 #include "route.h"
39 #include "rsa.h"
40 #include "subnet.h"
41 #include "utils.h"
42 #include "xalloc.h"
43
44 char *myport;
45 static struct event device_ev;
46
47 bool read_rsa_public_key(connection_t *c) {
48         FILE *fp;
49         char *fname;
50         char *n;
51         bool result;
52
53         /* First, check for simple PublicKey statement */
54
55         if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &n)) {
56                 result = rsa_set_hex_public_key(&c->rsa, n, "FFFF");
57                 free(n);
58                 return result;
59         }
60
61         /* Else, check for PublicKeyFile statement and read it */
62
63         if(!get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
64                 xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
65
66         fp = fopen(fname, "r");
67
68         if(!fp) {
69                 logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
70                            fname, strerror(errno));
71                 free(fname);
72                 return false;
73         }
74
75         result = rsa_read_pem_public_key(&c->rsa, fp);
76         fclose(fp);
77
78         if(!result) 
79                 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s", fname, strerror(errno));
80         free(fname);
81         return result;
82 }
83
84 bool read_rsa_private_key() {
85         FILE *fp;
86         char *fname;
87         char *n, *d;
88         bool result;
89
90         /* First, check for simple PrivateKey statement */
91
92         if(get_config_string(lookup_config(config_tree, "PrivateKey"), &d)) {
93                 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &n)) {
94                         logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
95                         free(d);
96                         return false;
97                 }
98                 result = rsa_set_hex_private_key(&myself->connection->rsa, n, "FFFF", d);
99                 free(n);
100                 free(d);
101                 return true;
102         }
103
104         /* Else, check for PrivateKeyFile statement and read it */
105
106         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
107                 xasprintf(&fname, "%s/rsa_key.priv", confbase);
108
109         fp = fopen(fname, "r");
110
111         if(!fp) {
112                 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
113                            fname, strerror(errno));
114                 free(fname);
115                 return false;
116         }
117
118 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
119         struct stat s;
120
121         if(fstat(fileno(fp), &s)) {
122                 logger(LOG_ERR, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
123                 free(fname);
124                 return false;
125         }
126
127         if(s.st_mode & ~0100700)
128                 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
129 #endif
130
131         result = rsa_read_pem_private_key(&myself->connection->rsa, fp);
132         fclose(fp);
133
134         if(!result) 
135                 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s", fname, strerror(errno));
136         free(fname);
137         return result;
138 }
139
140 static struct event keyexpire_event;
141
142 static void keyexpire_handler(void *data) {
143         regenerate_key();
144 }
145
146 void regenerate_key() {
147         ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");
148         event_del(&keyexpire_event);
149         send_key_changed(broadcast, myself);
150         keyexpire_event.time = time(NULL) + keylifetime;
151         keyexpire_event.handler = keyexpire_handler;
152         event_add(&keyexpire_event);
153 }
154
155 /*
156   Read Subnets from all host config files
157 */
158 void load_all_subnets(void) {
159         DIR *dir;
160         struct dirent *ent;
161         char *dname;
162         char *fname;
163         splay_tree_t *config_tree;
164         config_t *cfg;
165         subnet_t *s, *s2;
166         node_t *n;
167         bool result;
168
169         xasprintf(&dname, "%s/hosts", confbase);
170         dir = opendir(dname);
171         if(!dir) {
172                 logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
173                 free(dname);
174                 return;
175         }
176
177         while((ent = readdir(dir))) {
178                 if(!check_id(ent->d_name))
179                         continue;
180
181                 n = lookup_node(ent->d_name);
182                 #ifdef _DIRENT_HAVE_D_TYPE
183                 //if(ent->d_type != DT_REG)
184                 //      continue;
185                 #endif
186
187                 xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
188                 init_configuration(&config_tree);
189                 result = read_config_file(config_tree, fname);
190                 free(fname);
191                 if(!result)
192                         continue;
193
194                 if(!n) {
195                         n = new_node();
196                         n->name = xstrdup(ent->d_name);
197                         node_add(n);
198                 }
199
200                 for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
201                         if(!get_config_subnet(cfg, &s))
202                                 continue;
203
204                         if((s2 = lookup_subnet(n, s))) {
205                                 s2->expires = -1;
206                         } else {
207                                 subnet_add(n, s);
208                         }
209                 }
210
211                 exit_configuration(&config_tree);
212         }
213
214         closedir(dir);
215 }
216
217 /*
218   Configure node_t myself and set up the local sockets (listen only)
219 */
220 bool setup_myself(void) {
221         config_t *cfg;
222         subnet_t *subnet;
223         char *name, *hostname, *mode, *afname, *cipher, *digest;
224         char *fname = NULL;
225         char *address = NULL;
226         char *envp[5];
227         struct addrinfo *ai, *aip, hint = {0};
228         bool choice;
229         int i, err;
230         int replaywin_int;
231
232         myself = new_node();
233         myself->connection = new_connection();
234
235         myself->hostname = xstrdup("MYSELF");
236         myself->connection->hostname = xstrdup("MYSELF");
237
238         myself->connection->options = 0;
239         myself->connection->protocol_version = PROT_CURRENT;
240
241         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
242                 logger(LOG_ERR, "Name for tinc daemon required!");
243                 return false;
244         }
245
246         if(!check_id(name)) {
247                 logger(LOG_ERR, "Invalid name for myself!");
248                 free(name);
249                 return false;
250         }
251
252         myself->name = name;
253         myself->connection->name = xstrdup(name);
254         xasprintf(&fname, "%s/hosts/%s", confbase, name);
255         read_config_options(config_tree, name);
256         read_config_file(config_tree, fname);
257         free(fname);
258
259         if(!read_rsa_private_key())
260                 return false;
261
262         if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
263                 myport = xstrdup("655");
264
265         if(!atoi(myport)) {
266                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
267                 sockaddr_t sa;
268                 if(!ai || !ai->ai_addr)
269                         return false;
270                 free(myport);
271                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
272                 sockaddr2str(&sa, NULL, &myport);
273         }
274
275         /* Read in all the subnets specified in the host configuration file */
276
277         cfg = lookup_config(config_tree, "Subnet");
278
279         while(cfg) {
280                 if(!get_config_subnet(cfg, &subnet))
281                         return false;
282
283                 subnet_add(myself, subnet);
284
285                 cfg = lookup_config_next(config_tree, cfg);
286         }
287
288         /* Check some options */
289
290         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
291                 myself->options |= OPTION_INDIRECT;
292
293         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
294                 myself->options |= OPTION_TCPONLY;
295
296         if(myself->options & OPTION_TCPONLY)
297                 myself->options |= OPTION_INDIRECT;
298
299         get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
300         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
301         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
302         strictsubnets |= tunnelserver;
303
304         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
305                 if(!strcasecmp(mode, "router"))
306                         routing_mode = RMODE_ROUTER;
307                 else if(!strcasecmp(mode, "switch"))
308                         routing_mode = RMODE_SWITCH;
309                 else if(!strcasecmp(mode, "hub"))
310                         routing_mode = RMODE_HUB;
311                 else {
312                         logger(LOG_ERR, "Invalid routing mode!");
313                         return false;
314                 }
315                 free(mode);
316         }
317
318         if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
319                 if(!strcasecmp(mode, "off"))
320                         forwarding_mode = FMODE_OFF;
321                 else if(!strcasecmp(mode, "internal"))
322                         forwarding_mode = FMODE_INTERNAL;
323                 else if(!strcasecmp(mode, "kernel"))
324                         forwarding_mode = FMODE_KERNEL;
325                 else {
326                         logger(LOG_ERR, "Invalid forwarding mode!");
327                         return false;
328                 }
329                 free(mode);
330         }
331
332         choice = true;
333         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
334         if(choice)
335                 myself->options |= OPTION_PMTU_DISCOVERY;
336
337         choice = true;
338         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
339         if(choice)
340                 myself->options |= OPTION_CLAMP_MSS;
341
342         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
343
344 #if !defined(SOL_IP) || !defined(IP_TOS)
345         if(priorityinheritance)
346                 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
347 #endif
348
349         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
350                 macexpire = 600;
351
352         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
353                 if(maxtimeout <= 0) {
354                         logger(LOG_ERR, "Bogus maximum timeout!");
355                         return false;
356                 }
357         } else
358                 maxtimeout = 900;
359
360         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
361                 if(udp_rcvbuf <= 0) {
362                         logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
363                         return false;
364                 }
365         }
366
367         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
368                 if(udp_sndbuf <= 0) {
369                         logger(LOG_ERR, "UDPSndBuf cannot be negative!");
370                         return false;
371                 }
372         }
373
374         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
375                 if(replaywin_int < 0) {
376                         logger(LOG_ERR, "ReplayWindow cannot be negative!");
377                         return false;
378                 }
379                 replaywin = (unsigned)replaywin_int;
380         }
381
382         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
383                 if(!strcasecmp(afname, "IPv4"))
384                         addressfamily = AF_INET;
385                 else if(!strcasecmp(afname, "IPv6"))
386                         addressfamily = AF_INET6;
387                 else if(!strcasecmp(afname, "any"))
388                         addressfamily = AF_UNSPEC;
389                 else {
390                         logger(LOG_ERR, "Invalid address family!");
391                         return false;
392                 }
393                 free(afname);
394         }
395
396         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
397
398         /* Generate packet encryption key */
399
400         if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher))
401                 cipher = xstrdup("blowfish");
402
403         if(!cipher_open_by_name(&myself->incipher, cipher)) {
404                 logger(LOG_ERR, "Unrecognized cipher type!");
405                 return false;
406         }
407
408         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
409                 keylifetime = 3600;
410
411         regenerate_key();
412
413         /* Check if we want to use message authentication codes... */
414
415         if(!get_config_string(lookup_config(config_tree, "Digest"), &digest))
416                 digest = xstrdup("sha1");
417
418         int maclength = 4;
419         get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
420
421         if(maclength < 0) {
422                 logger(LOG_ERR, "Bogus MAC length!");
423                 return false;
424         }
425
426         if(!digest_open_by_name(&myself->indigest, digest, maclength)) {
427                 logger(LOG_ERR, "Unrecognized digest type!");
428                 return false;
429         }
430
431         /* Compression */
432
433         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
434                 if(myself->incompression < 0 || myself->incompression > 11) {
435                         logger(LOG_ERR, "Bogus compression level!");
436                         return false;
437                 }
438         } else
439                 myself->incompression = 0;
440
441         myself->connection->outcompression = 0;
442
443         /* Done */
444
445         myself->nexthop = myself;
446         myself->via = myself;
447         myself->status.reachable = true;
448         node_add(myself);
449
450         graph();
451
452         if(strictsubnets)
453                 load_all_subnets();
454
455         /* Open device */
456
457         if(!setup_device())
458                 return false;
459
460         /* Run tinc-up script to further initialize the tap interface */
461         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
462         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
463         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
464         xasprintf(&envp[3], "NAME=%s", myself->name);
465         envp[4] = NULL;
466
467         execute_script("tinc-up", envp);
468
469         for(i = 0; i < 4; i++)
470                 free(envp[i]);
471
472         /* Run subnet-up scripts for our own subnets */
473
474         subnet_update(myself, NULL, true);
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                         close(listen_socket[listen_sockets].tcp);
507                         continue;
508                 }
509
510                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
511
512                 if(!thread_create(&listen_socket[listen_sockets].tcp_thread, handle_new_meta_connection, &listen_socket[listen_sockets])) {
513                         logger(LOG_ERR, "thread_create failed: %s", strerror(errno));
514                         abort();
515                 }
516
517                 if(!thread_create(&listen_socket[listen_sockets].udp_thread, handle_incoming_vpn_data, &listen_socket[listen_sockets])) {
518                         logger(LOG_ERR, "thread_create failed: %s", strerror(errno));
519                         abort();
520                 }
521
522                 ifdebug(CONNECTIONS) {
523                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
524                         logger(LOG_NOTICE, "Listening on %s", hostname);
525                         free(hostname);
526                 }
527
528                 listen_sockets++;
529
530                 if(listen_sockets >= MAXSOCKETS) {
531                         logger(LOG_WARNING, "Maximum of %d listening sockets reached", MAXSOCKETS);
532                         break;
533                 }
534         }
535
536         freeaddrinfo(ai);
537
538         if(listen_sockets)
539                 logger(LOG_NOTICE, "Ready");
540         else {
541                 logger(LOG_ERR, "Unable to create any listening socket!");
542                 return false;
543         }
544
545         return true;
546 }
547
548 /*
549   initialize network
550 */
551 bool setup_network(void) {
552         init_connections();
553         init_subnets();
554         init_nodes();
555         init_edges();
556         init_requests();
557
558         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
559                 if(pinginterval < 1) {
560                         pinginterval = 86400;
561                 }
562         } else
563                 pinginterval = 60;
564
565         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
566                 pingtimeout = 5;
567         if(pingtimeout < 1 || pingtimeout > pinginterval)
568                 pingtimeout = pinginterval;
569
570         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
571                 maxoutbufsize = 10 * MTU;
572
573         if(!setup_myself())
574                 return false;
575
576         return true;
577 }
578
579 /*
580   close all open network connections
581 */
582 void close_network_connections(void) {
583         splay_node_t *node, *next;
584         connection_t *c;
585         char *envp[5];
586         int i;
587
588         for(node = connection_tree->head; node; node = next) {
589                 next = node->next;
590                 c = node->data;
591                 c->outgoing = false;
592                 terminate_connection(c, false);
593         }
594
595         list_delete_list(outgoing_list);
596
597         if(myself && myself->connection) {
598                 subnet_update(myself, NULL, false);
599                 terminate_connection(myself->connection, false);
600                 free_connection(myself->connection);
601         }
602
603         for(i = 0; i < listen_sockets; i++) {
604                 close(listen_socket[i].tcp);
605                 close(listen_socket[i].udp);
606                 thread_destroy(&listen_socket[i].tcp_thread);
607                 thread_destroy(&listen_socket[i].udp_thread);
608         }
609
610         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
611         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
612         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
613         xasprintf(&envp[3], "NAME=%s", myself->name);
614         envp[4] = NULL;
615
616         exit_requests();
617         exit_edges();
618         exit_subnets();
619         exit_nodes();
620         exit_connections();
621
622         execute_script("tinc-down", envp);
623
624         if(myport) free(myport);
625
626         for(i = 0; i < 4; i++)
627                 free(envp[i]);
628
629         close_device();
630
631         return;
632 }