]> git.meshlink.io Git - meshlink/blob - src/net_setup.c
Fix pointer arithmetic when creating and verifying message authentication codes.
[meshlink] / 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
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         if(timeout_initialized(&keyexpire_event)) {
152                 ifdebug(STATUS) logger(LOG_INFO, _("Expiring symmetric keys"));
153                 event_del(&keyexpire_event);
154                 send_key_changed(broadcast, myself);
155         } else {
156                 timeout_set(&keyexpire_event, keyexpire_handler, NULL);
157         }
158
159         event_add(&keyexpire_event, &(struct timeval){keylifetime, 0});
160 }
161
162 /*
163   Configure node_t myself and set up the local sockets (listen only)
164 */
165 bool setup_myself(void) {
166         config_t *cfg;
167         subnet_t *subnet;
168         char *name, *hostname, *mode, *afname, *cipher, *digest;
169         char *address = NULL;
170         char *envp[5];
171         struct addrinfo *ai, *aip, hint = {0};
172         bool choice;
173         int i, err;
174
175         cp();
176
177         myself = new_node();
178         myself->connection = new_connection();
179         init_configuration(&myself->connection->config_tree);
180
181         asprintf(&myself->hostname, _("MYSELF"));
182         asprintf(&myself->connection->hostname, _("MYSELF"));
183
184         myself->connection->options = 0;
185         myself->connection->protocol_version = PROT_CURRENT;
186
187         if(!get_config_string(lookup_config(config_tree, "Name"), &name)) {     /* Not acceptable */
188                 logger(LOG_ERR, _("Name for tinc daemon required!"));
189                 return false;
190         }
191
192         if(!check_id(name)) {
193                 logger(LOG_ERR, _("Invalid name for myself!"));
194                 free(name);
195                 return false;
196         }
197
198         myself->name = name;
199         myself->connection->name = xstrdup(name);
200
201         if(!read_connection_config(myself->connection)) {
202                 logger(LOG_ERR, _("Cannot open host configuration file for myself!"));
203                 return false;
204         }
205
206         if(!read_rsa_private_key())
207                 return false;
208
209         if(!get_config_string(lookup_config(myself->connection->config_tree, "Port"), &myport))
210                 asprintf(&myport, "655");
211
212         /* Read in all the subnets specified in the host configuration file */
213
214         cfg = lookup_config(myself->connection->config_tree, "Subnet");
215
216         while(cfg) {
217                 if(!get_config_subnet(cfg, &subnet))
218                         return false;
219
220                 subnet_add(myself, subnet);
221
222                 cfg = lookup_config_next(myself->connection->config_tree, cfg);
223         }
224
225         /* Check some options */
226
227         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
228                 myself->options |= OPTION_INDIRECT;
229
230         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
231                 myself->options |= OPTION_TCPONLY;
232
233         if(get_config_bool(lookup_config(myself->connection->config_tree, "IndirectData"), &choice) && choice)
234                 myself->options |= OPTION_INDIRECT;
235
236         if(get_config_bool(lookup_config(myself->connection->config_tree, "TCPOnly"), &choice) && choice)
237                 myself->options |= OPTION_TCPONLY;
238
239         if(myself->options & OPTION_TCPONLY)
240                 myself->options |= OPTION_INDIRECT;
241
242         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
243
244         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
245                 if(!strcasecmp(mode, "router"))
246                         routing_mode = RMODE_ROUTER;
247                 else if(!strcasecmp(mode, "switch"))
248                         routing_mode = RMODE_SWITCH;
249                 else if(!strcasecmp(mode, "hub"))
250                         routing_mode = RMODE_HUB;
251                 else {
252                         logger(LOG_ERR, _("Invalid routing mode!"));
253                         return false;
254                 }
255                 free(mode);
256         } else
257                 routing_mode = RMODE_ROUTER;
258
259         if(routing_mode == RMODE_ROUTER)
260                 if(!get_config_bool(lookup_config(myself->connection->config_tree, "PMTUDiscovery"), &choice) || choice)
261                         myself->options |= OPTION_PMTU_DISCOVERY;
262
263         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
264
265 #if !defined(SOL_IP) || !defined(IP_TOS)
266         if(priorityinheritance)
267                 logger(LOG_WARNING, _("%s not supported on this platform"), "PriorityInheritance");
268 #endif
269
270         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
271                 macexpire = 600;
272
273         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
274                 if(maxtimeout <= 0) {
275                         logger(LOG_ERR, _("Bogus maximum timeout!"));
276                         return false;
277                 }
278         } else
279                 maxtimeout = 900;
280
281         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
282                 if(!strcasecmp(afname, "IPv4"))
283                         addressfamily = AF_INET;
284                 else if(!strcasecmp(afname, "IPv6"))
285                         addressfamily = AF_INET6;
286                 else if(!strcasecmp(afname, "any"))
287                         addressfamily = AF_UNSPEC;
288                 else {
289                         logger(LOG_ERR, _("Invalid address family!"));
290                         return false;
291                 }
292                 free(afname);
293         }
294
295         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
296
297         /* Generate packet encryption key */
298
299         if(!get_config_string(lookup_config(myself->connection->config_tree, "Cipher"), &cipher))
300                 cipher = xstrdup("blowfish");
301
302         if(!cipher_open_by_name(&myself->incipher, cipher)) {
303                 logger(LOG_ERR, _("Unrecognized cipher type!"));
304                 return false;
305         }
306
307         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
308                 keylifetime = 3600;
309
310         regenerate_key();
311
312         /* Check if we want to use message authentication codes... */
313
314         if(!get_config_string(lookup_config(myself->connection->config_tree, "Digest"), &digest))
315                 digest = xstrdup("sha1");
316
317         int maclength = 4;
318         get_config_int(lookup_config(myself->connection->config_tree, "MACLength"), &maclength);
319
320         if(maclength < 0) {
321                 logger(LOG_ERR, _("Bogus MAC length!"));
322                 return false;
323         }
324
325         if(!digest_open_by_name(&myself->indigest, digest, maclength)) {
326                 logger(LOG_ERR, _("Unrecognized digest type!"));
327                 return false;
328         }
329
330         /* Compression */
331
332         if(get_config_int(lookup_config(myself->connection->config_tree, "Compression"), &myself->incompression)) {
333                 if(myself->incompression < 0 || myself->incompression > 11) {
334                         logger(LOG_ERR, _("Bogus compression level!"));
335                         return false;
336                 }
337         } else
338                 myself->incompression = 0;
339
340         myself->connection->outcompression = 0;
341
342         /* Done */
343
344         myself->nexthop = myself;
345         myself->via = myself;
346         myself->status.reachable = true;
347         node_add(myself);
348
349         graph();
350
351         /* Open device */
352
353         if(!setup_device())
354                 return false;
355
356         event_set(&device_ev, device_fd, EV_READ|EV_PERSIST, handle_device_data, NULL);
357
358         if (event_add(&device_ev, NULL) < 0) {
359                 logger(LOG_ERR, _("event_add failed: %s"), strerror(errno));
360                 close_device();
361                 return false;
362         }
363
364         /* Run tinc-up script to further initialize the tap interface */
365         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
366         asprintf(&envp[1], "DEVICE=%s", device ? : "");
367         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
368         asprintf(&envp[3], "NAME=%s", myself->name);
369         envp[4] = NULL;
370
371         execute_script("tinc-up", envp);
372
373         for(i = 0; i < 5; i++)
374                 free(envp[i]);
375
376         /* Run subnet-up scripts for our own subnets */
377
378         subnet_update(myself, NULL, true);
379
380         /* Open sockets */
381
382         get_config_string(lookup_config(config_tree, "BindToAddress"), &address);
383
384         hint.ai_family = addressfamily;
385         hint.ai_socktype = SOCK_STREAM;
386         hint.ai_protocol = IPPROTO_TCP;
387         hint.ai_flags = AI_PASSIVE;
388
389         err = getaddrinfo(address, myport, &hint, &ai);
390
391         if(err || !ai) {
392                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo",
393                            gai_strerror(err));
394                 return false;
395         }
396
397         listen_sockets = 0;
398
399         for(aip = ai; aip; aip = aip->ai_next) {
400                 listen_socket[listen_sockets].tcp =
401                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
402
403                 if(listen_socket[listen_sockets].tcp < 0)
404                         continue;
405
406                 listen_socket[listen_sockets].udp =
407                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
408
409                 if(listen_socket[listen_sockets].udp < 0) {
410                         close(listen_socket[listen_sockets].tcp);
411                         continue;
412                 }
413
414                 event_set(&listen_socket[listen_sockets].ev_tcp,
415                                   listen_socket[listen_sockets].tcp,
416                                   EV_READ|EV_PERSIST,
417                                   handle_new_meta_connection, NULL);
418                 if(event_add(&listen_socket[listen_sockets].ev_tcp, NULL) < 0) {
419                         logger(LOG_EMERG, _("event_add failed: %s"), strerror(errno));
420                         abort();
421                 }
422
423                 event_set(&listen_socket[listen_sockets].ev_udp,
424                                   listen_socket[listen_sockets].udp,
425                                   EV_READ|EV_PERSIST,
426                                   handle_incoming_vpn_data, NULL);
427                 if(event_add(&listen_socket[listen_sockets].ev_udp, NULL) < 0) {
428                         logger(LOG_EMERG, _("event_add failed: %s"), strerror(errno));
429                         abort();
430                 }
431
432                 ifdebug(CONNECTIONS) {
433                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
434                         logger(LOG_NOTICE, _("Listening on %s"), hostname);
435                         free(hostname);
436                 }
437
438                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
439                 listen_sockets++;
440
441                 if(listen_sockets >= MAXSOCKETS) {
442                         logger(LOG_WARNING, _("Maximum of %d listening sockets reached"), MAXSOCKETS);
443                         break;
444                 }
445         }
446
447         freeaddrinfo(ai);
448
449         if(listen_sockets)
450                 logger(LOG_NOTICE, _("Ready"));
451         else {
452                 logger(LOG_ERR, _("Unable to create any listening socket!"));
453                 return false;
454         }
455
456         return true;
457 }
458
459 /*
460   initialize network
461 */
462 bool setup_network(void)
463 {
464         cp();
465
466         init_connections();
467         init_subnets();
468         init_nodes();
469         init_edges();
470         init_requests();
471
472         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
473                 if(pinginterval < 1) {
474                         pinginterval = 86400;
475                 }
476         } else
477                 pinginterval = 60;
478
479         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
480                 pingtimeout = 5;
481         if(pingtimeout < 1 || pingtimeout > pinginterval)
482                 pingtimeout = pinginterval;
483
484         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
485                 maxoutbufsize = 10 * MTU;
486
487         if(!setup_myself())
488                 return false;
489
490         return true;
491 }
492
493 /*
494   close all open network connections
495 */
496 void close_network_connections(void) {
497         splay_node_t *node, *next;
498         connection_t *c;
499         char *envp[5];
500         int i;
501
502         cp();
503
504         for(node = connection_tree->head; node; node = next) {
505                 next = node->next;
506                 c = node->data;
507                 c->outgoing = false;
508                 terminate_connection(c, false);
509         }
510
511         list_delete_list(outgoing_list);
512
513         if(myself && myself->connection) {
514                 subnet_update(myself, NULL, false);
515                 terminate_connection(myself->connection, false);
516                 free_connection(myself->connection);
517         }
518
519         for(i = 0; i < listen_sockets; i++) {
520                 event_del(&listen_socket[i].ev_tcp);
521                 event_del(&listen_socket[i].ev_udp);
522                 close(listen_socket[i].tcp);
523                 close(listen_socket[i].udp);
524         }
525
526         asprintf(&envp[0], "NETNAME=%s", netname ? : "");
527         asprintf(&envp[1], "DEVICE=%s", device ? : "");
528         asprintf(&envp[2], "INTERFACE=%s", iface ? : "");
529         asprintf(&envp[3], "NAME=%s", myself->name);
530         envp[4] = NULL;
531
532         exit_requests();
533         exit_edges();
534         exit_subnets();
535         exit_nodes();
536         exit_connections();
537
538         execute_script("tinc-down", envp);
539
540         if(myport) free(myport);
541
542         for(i = 0; i < 4; i++)
543                 free(envp[i]);
544
545         close_device();
546
547         return;
548 }