Don't disconnect clients in TunnelServer mode who send unauthorised ADD_SUBNETs.
[oweals/tinc.git] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2009 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6
7     This program is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15     GNU General Public License for more details.
16
17     You should have received a copy of the GNU General Public License along
18     with this program; if not, write to the Free Software Foundation, Inc.,
19     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 */
21
22 #include "system.h"
23
24 #include <openssl/pem.h>
25 #include <openssl/rsa.h>
26 #include <openssl/rand.h>
27 #include <openssl/err.h>
28 #include <openssl/evp.h>
29
30 #include "avl_tree.h"
31 #include "conf.h"
32 #include "connection.h"
33 #include "device.h"
34 #include "event.h"
35 #include "graph.h"
36 #include "logger.h"
37 #include "net.h"
38 #include "netutl.h"
39 #include "process.h"
40 #include "protocol.h"
41 #include "route.h"
42 #include "subnet.h"
43 #include "utils.h"
44 #include "xalloc.h"
45
46 char *myport;
47
48 bool read_rsa_public_key(connection_t *c) {
49         FILE *fp;
50         char *fname;
51         char *key;
52
53         if(!c->rsa_key) {
54                 c->rsa_key = RSA_new();
55 //              RSA_blinding_on(c->rsa_key, NULL);
56         }
57
58         /* First, check for simple PublicKey statement */
59
60         if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
61                 BN_hex2bn(&c->rsa_key->n, key);
62                 BN_hex2bn(&c->rsa_key->e, "FFFF");
63                 free(key);
64                 return true;
65         }
66
67         /* Else, check for PublicKeyFile statement and read it */
68
69         if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) {
70                 fp = fopen(fname, "r");
71
72                 if(!fp) {
73                         logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
74                                    fname, strerror(errno));
75                         free(fname);
76                         return false;
77                 }
78
79                 free(fname);
80                 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
81                 fclose(fp);
82
83                 if(c->rsa_key)
84                         return true;            /* Woohoo. */
85
86                 /* If it fails, try PEM_read_RSA_PUBKEY. */
87                 fp = fopen(fname, "r");
88
89                 if(!fp) {
90                         logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
91                                    fname, strerror(errno));
92                         free(fname);
93                         return false;
94                 }
95
96                 free(fname);
97                 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
98                 fclose(fp);
99
100                 if(c->rsa_key) {
101 //                              RSA_blinding_on(c->rsa_key, NULL);
102                         return true;
103                 }
104
105                 logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s",
106                            fname, strerror(errno));
107                 return false;
108         }
109
110         /* Else, check if a harnessed public key is in the config file */
111
112         xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
113         fp = fopen(fname, "r");
114
115         if(fp) {
116                 c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
117                 fclose(fp);
118         }
119
120         free(fname);
121
122         if(c->rsa_key)
123                 return true;
124
125         /* Try again with PEM_read_RSA_PUBKEY. */
126
127         xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
128         fp = fopen(fname, "r");
129
130         if(fp) {
131                 c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
132 //              RSA_blinding_on(c->rsa_key, NULL);
133                 fclose(fp);
134         }
135
136         free(fname);
137
138         if(c->rsa_key)
139                 return true;
140
141         logger(LOG_ERR, "No public key for %s specified!", c->name);
142
143         return false;
144 }
145
146 bool read_rsa_private_key(void) {
147         FILE *fp;
148         char *fname, *key, *pubkey;
149         struct stat s;
150
151         if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
152                 if(!get_config_string(lookup_config(myself->connection->config_tree, "PublicKey"), &pubkey)) {
153                         logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
154                         return false;
155                 }
156                 myself->connection->rsa_key = RSA_new();
157 //              RSA_blinding_on(myself->connection->rsa_key, NULL);
158                 BN_hex2bn(&myself->connection->rsa_key->d, key);
159                 BN_hex2bn(&myself->connection->rsa_key->n, pubkey);
160                 BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
161                 free(key);
162                 free(pubkey);
163                 return true;
164         }
165
166         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
167                 xasprintf(&fname, "%s/rsa_key.priv", confbase);
168
169         fp = fopen(fname, "r");
170
171         if(!fp) {
172                 logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
173                            fname, strerror(errno));
174                 free(fname);
175                 return false;
176         }
177
178 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
179         if(fstat(fileno(fp), &s)) {
180                 logger(LOG_ERR, "Could not stat RSA private key file `%s': %s'",
181                                 fname, strerror(errno));
182                 free(fname);
183                 return false;
184         }
185
186         if(s.st_mode & ~0100700)
187                 logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
188 #endif
189
190         myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
191         fclose(fp);
192
193         if(!myself->connection->rsa_key) {
194                 logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
195                            fname, strerror(errno));
196                 free(fname);
197                 return false;
198         }
199
200         free(fname);
201         return true;
202 }
203
204 /*
205   Configure node_t myself and set up the local sockets (listen only)
206 */
207 bool setup_myself(void) {
208         config_t *cfg;
209         subnet_t *subnet;
210         char *name, *hostname, *mode, *afname, *cipher, *digest;
211         char *address = NULL;
212         char *envp[5];
213         struct addrinfo *ai, *aip, hint = {0};
214         bool choice;
215         int i, err;
216
217         myself = new_node();
218         myself->connection = new_connection();
219         init_configuration(&myself->connection->config_tree);
220
221         xasprintf(&myself->hostname, "MYSELF");
222         xasprintf(&myself->connection->hostname, "MYSELF");
223
224         myself->connection->options = 0;
225         myself->connection->protocol_version = PROT_CURRENT;
226
227         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
228                 logger(LOG_ERR, "Name for tinc daemon required!");
229                 return false;
230         }
231
232         if(!check_id(name)) {
233                 logger(LOG_ERR, "Invalid name for myself!");
234                 free(name);
235                 return false;
236         }
237
238         myself->name = name;
239         myself->connection->name = xstrdup(name);
240
241         if(!read_connection_config(myself->connection)) {
242                 logger(LOG_ERR, "Cannot open host configuration file for myself!");
243                 return false;
244         }
245
246         if(!read_rsa_private_key())
247                 return false;
248
249         if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
250                 xasprintf(&myport, "655");
251
252         /* Read in all the subnets specified in the host configuration file */
253
254         cfg = lookup_config(myself->connection->config_tree, "Subnet");
255
256         while(cfg) {
257                 if(!get_config_subnet(cfg, &subnet))
258                         return false;
259
260                 subnet_add(myself, subnet);
261
262                 cfg = lookup_config_next(myself->connection->config_tree, cfg);
263         }
264
265         /* Check some options */
266
267         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
268                 myself->options |= OPTION_INDIRECT;
269
270         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
271                 myself->options |= OPTION_TCPONLY;
272
273         if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
274                 myself->options |= OPTION_INDIRECT;
275
276         if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice) && choice)
277                 myself->options |= OPTION_TCPONLY;
278
279         if(myself->options & OPTION_TCPONLY)
280                 myself->options |= OPTION_INDIRECT;
281
282         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
283
284         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
285                 if(!strcasecmp(mode, "router"))
286                         routing_mode = RMODE_ROUTER;
287                 else if(!strcasecmp(mode, "switch"))
288                         routing_mode = RMODE_SWITCH;
289                 else if(!strcasecmp(mode, "hub"))
290                         routing_mode = RMODE_HUB;
291                 else {
292                         logger(LOG_ERR, "Invalid routing mode!");
293                         return false;
294                 }
295                 free(mode);
296         } else
297                 routing_mode = RMODE_ROUTER;
298
299         // Enable PMTUDiscovery by default if we are in router mode.
300
301         choice = routing_mode == RMODE_ROUTER;
302         get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice);
303         if(choice)      
304                 myself->options |= OPTION_PMTU_DISCOVERY;
305
306         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
307
308 #if !defined(SOL_IP) || !defined(IP_TOS)
309         if(priorityinheritance)
310                 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
311 #endif
312
313         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
314                 macexpire = 600;
315
316         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
317                 if(maxtimeout <= 0) {
318                         logger(LOG_ERR, "Bogus maximum timeout!");
319                         return false;
320                 }
321         } else
322                 maxtimeout = 900;
323
324         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
325                 if(!strcasecmp(afname, "IPv4"))
326                         addressfamily = AF_INET;
327                 else if(!strcasecmp(afname, "IPv6"))
328                         addressfamily = AF_INET6;
329                 else if(!strcasecmp(afname, "any"))
330                         addressfamily = AF_UNSPEC;
331                 else {
332                         logger(LOG_ERR, "Invalid address family!");
333                         return false;
334                 }
335                 free(afname);
336         }
337
338         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
339
340         /* Generate packet encryption key */
341
342         if(get_config_string
343            (lookup_config(myself->connection->config_tree, "Cipher"), &cipher)) {
344                 if(!strcasecmp(cipher, "none")) {
345                         myself->incipher = NULL;
346                 } else {
347                         myself->incipher = EVP_get_cipherbyname(cipher);
348
349                         if(!myself->incipher) {
350                                 logger(LOG_ERR, "Unrecognized cipher type!");
351                                 return false;
352                         }
353                 }
354         } else
355                 myself->incipher = EVP_aes_256_cbc();
356
357         if(myself->incipher)
358                 myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
359         else
360                 myself->inkeylength = 1;
361
362         myself->connection->outcipher = EVP_aes_256_ofb();
363
364         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
365                 keylifetime = 3600;
366
367         keyexpires = now + keylifetime;
368         
369         /* Check if we want to use message authentication codes... */
370
371         if(get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest)) {
372                 if(!strcasecmp(digest, "none")) {
373                         myself->indigest = NULL;
374                 } else {
375                         myself->indigest = EVP_get_digestbyname(digest);
376
377                         if(!myself->indigest) {
378                                 logger(LOG_ERR, "Unrecognized digest type!");
379                                 return false;
380                         }
381                 }
382         } else
383                 myself->indigest = EVP_sha256();
384
385         myself->connection->outdigest = EVP_sha256();
386
387         if(get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &myself->inmaclength)) {
388                 if(myself->indigest) {
389                         if(myself->inmaclength > myself->indigest->md_size) {
390                                 logger(LOG_ERR, "MAC length exceeds size of digest!");
391                                 return false;
392                         } else if(myself->inmaclength < 0) {
393                                 logger(LOG_ERR, "Bogus MAC length!");
394                                 return false;
395                         }
396                 }
397         } else
398                 myself->inmaclength = 4;
399
400         myself->connection->outmaclength = 0;
401
402         /* Compression */
403
404         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->incompression)) {
405                 if(myself->incompression < 0 || myself->incompression > 11) {
406                         logger(LOG_ERR, "Bogus compression level!");
407                         return false;
408                 }
409         } else
410                 myself->incompression = 0;
411
412         myself->connection->outcompression = 0;
413
414         /* Done */
415
416         myself->nexthop = myself;
417         myself->via = myself;
418         myself->status.reachable = true;
419         node_add(myself);
420
421         graph();
422
423         /* Open device */
424
425         if(!setup_device())
426                 return false;
427
428         /* Run tinc-up script to further initialize the tap interface */
429         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
430         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
431         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
432         xasprintf(&envp[3], "NAME=%s", myself->name);
433         envp[4] = NULL;
434
435         execute_script("tinc-up", envp);
436
437         for(i = 0; i < 5; i++)
438                 free(envp[i]);
439
440         /* Run subnet-up scripts for our own subnets */
441
442         subnet_update(myself, NULL, true);
443
444         /* Open sockets */
445
446         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
447
448         hint.ai_family = addressfamily;
449         hint.ai_socktype = SOCK_STREAM;
450         hint.ai_protocol = IPPROTO_TCP;
451         hint.ai_flags = AI_PASSIVE;
452
453         err = getaddrinfo(address, myport, &hint, &ai);
454
455         if(err || !ai) {
456                 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
457                            gai_strerror(err));
458                 return false;
459         }
460
461         listen_sockets = 0;
462
463         for(aip = ai; aip; aip = aip->ai_next) {
464                 listen_socket[listen_sockets].tcp =
465                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
466
467                 if(listen_socket[listen_sockets].tcp < 0)
468                         continue;
469
470                 listen_socket[listen_sockets].udp =
471                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
472
473                 if(listen_socket[listen_sockets].udp < 0)
474                         continue;
475
476                 ifdebug(CONNECTIONS) {
477                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
478                         logger(LOG_NOTICE, "Listening on %s", hostname);
479                         free(hostname);
480                 }
481
482                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
483                 listen_sockets++;
484         }
485
486         freeaddrinfo(ai);
487
488         if(listen_sockets)
489                 logger(LOG_NOTICE, "Ready");
490         else {
491                 logger(LOG_ERR, "Unable to create any listening socket!");
492                 return false;
493         }
494
495         return true;
496 }
497
498 /*
499   initialize network
500 */
501 bool setup_network(void) {
502         now = time(NULL);
503
504         init_events();
505         init_connections();
506         init_subnets();
507         init_nodes();
508         init_edges();
509         init_requests();
510
511         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
512                 if(pinginterval < 1) {
513                         pinginterval = 86400;
514                 }
515         } else
516                 pinginterval = 60;
517
518         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
519                 pingtimeout = 5;
520         if(pingtimeout < 1 || pingtimeout > pinginterval)
521                 pingtimeout = pinginterval;
522
523         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
524                 maxoutbufsize = 10 * MTU;
525
526         if(!setup_myself())
527                 return false;
528
529         return true;
530 }
531
532 /*
533   close all open network connections
534 */
535 void close_network_connections(void) {
536         avl_node_t *node, *next;
537         connection_t *c;
538         char *envp[5];
539         int i;
540
541         for(node = connection_tree->head; node; node = next) {
542                 next = node->next;
543                 c = node->data;
544                 c->outgoing = false;
545                 terminate_connection(c, false);
546         }
547
548         list_delete_list(outgoing_list);
549
550         if(myself && myself->connection) {
551                 subnet_update(myself, NULL, false);
552                 terminate_connection(myself->connection, false);
553                 free_connection(myself->connection);
554         }
555
556         for(i = 0; i < listen_sockets; i++) {
557                 close(listen_socket[i].tcp);
558                 close(listen_socket[i].udp);
559         }
560
561         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
562         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
563         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
564         xasprintf(&envp[3], "NAME=%s", myself->name);
565         envp[4] = NULL;
566
567         exit_requests();
568         exit_edges();
569         exit_subnets();
570         exit_nodes();
571         exit_connections();
572         exit_events();
573
574         execute_script("tinc-down", envp);
575
576         if(myport) free(myport);
577
578         for(i = 0; i < 4; i++)
579                 free(envp[i]);
580
581         close_device();
582
583         return;
584 }