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