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