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