Check the return values from BN_hex2bn() and RAND_load_file().
[tinc] / src / conf.c
1 /*
2     conf.c -- configuration code
3     Copyright (C) 1998 Robert van der Meulen
4                   1998-2005 Ivo Timmermans
5                   2000-2014 Guus Sliepen <guus@tinc-vpn.org>
6                   2010-2011 Julien Muchembled <jm@jmuchemb.eu>
7                   2000 Cris van Pelt
8
9     This program is free software; you can redistribute it and/or modify
10     it under the terms of the GNU General Public License as published by
11     the Free Software Foundation; either version 2 of the License, or
12     (at your option) any later version.
13
14     This program is distributed in the hope that it will be useful,
15     but WITHOUT ANY WARRANTY; without even the implied warranty of
16     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17     GNU General Public License for more details.
18
19     You should have received a copy of the GNU General Public License along
20     with this program; if not, write to the Free Software Foundation, Inc.,
21     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 */
23
24 #include "system.h"
25
26 #include "avl_tree.h"
27 #include "connection.h"
28 #include "conf.h"
29 #include "list.h"
30 #include "logger.h"
31 #include "netutl.h"                             /* for str2address */
32 #include "protocol.h"
33 #include "utils.h"                              /* for cp */
34 #include "xalloc.h"
35
36 avl_tree_t *config_tree;
37
38 int pinginterval = 0;                   /* seconds between pings */
39 int pingtimeout = 0;                    /* seconds to wait for response */
40 char *confbase = NULL;                  /* directory in which all config files are */
41 char *netname = NULL;                   /* name of the vpn network */
42 list_t *cmdline_conf = NULL;    /* global/host configuration values given at the command line */
43
44
45 static int config_compare(const config_t *a, const config_t *b) {
46         int result;
47
48         result = strcasecmp(a->variable, b->variable);
49
50         if(result) {
51                 return result;
52         }
53
54         /* give priority to command line options */
55         result = !b->file - !a->file;
56
57         if(result) {
58                 return result;
59         }
60
61         result = a->line - b->line;
62
63         if(result) {
64                 return result;
65         } else {
66                 return a->file ? strcmp(a->file, b->file) : 0;
67         }
68 }
69
70 void init_configuration(avl_tree_t **config_tree) {
71         *config_tree = avl_alloc_tree((avl_compare_t) config_compare, (avl_action_t) free_config);
72 }
73
74 void exit_configuration(avl_tree_t **config_tree) {
75         avl_delete_tree(*config_tree);
76         *config_tree = NULL;
77 }
78
79 config_t *new_config(void) {
80         return xmalloc_and_zero(sizeof(config_t));
81 }
82
83 void free_config(config_t *cfg) {
84         if(cfg->variable) {
85                 free(cfg->variable);
86         }
87
88         if(cfg->value) {
89                 free(cfg->value);
90         }
91
92         if(cfg->file) {
93                 free(cfg->file);
94         }
95
96         free(cfg);
97 }
98
99 void config_add(avl_tree_t *config_tree, config_t *cfg) {
100         avl_insert(config_tree, cfg);
101 }
102
103 config_t *lookup_config(const avl_tree_t *config_tree, char *variable) {
104         config_t cfg, *found;
105
106         cfg.variable = variable;
107         cfg.file = NULL;
108         cfg.line = 0;
109
110         found = avl_search_closest_greater(config_tree, &cfg);
111
112         if(!found) {
113                 return NULL;
114         }
115
116         if(strcasecmp(found->variable, variable)) {
117                 return NULL;
118         }
119
120         return found;
121 }
122
123 config_t *lookup_config_next(const avl_tree_t *config_tree, const config_t *cfg) {
124         avl_node_t *node;
125         config_t *found;
126
127         node = avl_search_node(config_tree, cfg);
128
129         if(node) {
130                 if(node->next) {
131                         found = node->next->data;
132
133                         if(!strcasecmp(found->variable, cfg->variable)) {
134                                 return found;
135                         }
136                 }
137         }
138
139         return NULL;
140 }
141
142 bool get_config_bool(const config_t *cfg, bool *result) {
143         if(!cfg) {
144                 return false;
145         }
146
147         if(!strcasecmp(cfg->value, "yes")) {
148                 *result = true;
149                 return true;
150         } else if(!strcasecmp(cfg->value, "no")) {
151                 *result = false;
152                 return true;
153         }
154
155         logger(LOG_ERR, "\"yes\" or \"no\" expected for configuration variable %s in %s line %d",
156                cfg->variable, cfg->file, cfg->line);
157
158         return false;
159 }
160
161 bool get_config_int(const config_t *cfg, int *result) {
162         if(!cfg) {
163                 return false;
164         }
165
166         if(sscanf(cfg->value, "%d", result) == 1) {
167                 return true;
168         }
169
170         logger(LOG_ERR, "Integer expected for configuration variable %s in %s line %d",
171                cfg->variable, cfg->file, cfg->line);
172
173         return false;
174 }
175
176 bool get_config_string(const config_t *cfg, char **result) {
177         if(!cfg) {
178                 return false;
179         }
180
181         *result = xstrdup(cfg->value);
182
183         return true;
184 }
185
186 bool get_config_address(const config_t *cfg, struct addrinfo **result) {
187         struct addrinfo *ai;
188
189         if(!cfg) {
190                 return false;
191         }
192
193         ai = str2addrinfo(cfg->value, NULL, 0);
194
195         if(ai) {
196                 *result = ai;
197                 return true;
198         }
199
200         logger(LOG_ERR, "Hostname or IP address expected for configuration variable %s in %s line %d",
201                cfg->variable, cfg->file, cfg->line);
202
203         return false;
204 }
205
206 bool get_config_subnet(const config_t *cfg, subnet_t **result) {
207         subnet_t subnet = {};
208
209         if(!cfg) {
210                 return false;
211         }
212
213         if(!str2net(&subnet, cfg->value)) {
214                 logger(LOG_ERR, "Subnet expected for configuration variable %s in %s line %d",
215                        cfg->variable, cfg->file, cfg->line);
216                 return false;
217         }
218
219         /* Teach newbies what subnets are... */
220
221         if(((subnet.type == SUBNET_IPV4)
222                         && !maskcheck(&subnet.net.ipv4.address, subnet.net.ipv4.prefixlength, sizeof(ipv4_t)))
223                         || ((subnet.type == SUBNET_IPV6)
224                             && !maskcheck(&subnet.net.ipv6.address, subnet.net.ipv6.prefixlength, sizeof(ipv6_t)))) {
225                 logger(LOG_ERR, "Network address and prefix length do not match for configuration variable %s in %s line %d",
226                        cfg->variable, cfg->file, cfg->line);
227                 return false;
228         }
229
230         *(*result = new_subnet()) = subnet;
231
232         return true;
233 }
234
235 /*
236   Read exactly one line and strip the trailing newline if any.
237 */
238 static char *readline(FILE *fp, char *buf, size_t buflen) {
239         char *newline = NULL;
240         char *p;
241
242         if(feof(fp)) {
243                 return NULL;
244         }
245
246         p = fgets(buf, buflen, fp);
247
248         if(!p) {
249                 return NULL;
250         }
251
252         newline = strchr(p, '\n');
253
254         if(!newline) {
255                 return buf;
256         }
257
258         *newline = '\0';        /* kill newline */
259
260         if(newline > p && newline[-1] == '\r') { /* and carriage return if necessary */
261                 newline[-1] = '\0';
262         }
263
264         return buf;
265 }
266
267 config_t *parse_config_line(char *line, const char *fname, int lineno) {
268         config_t *cfg;
269         int len;
270         char *variable, *value, *eol;
271         variable = value = line;
272
273         eol = line + strlen(line);
274
275         while(strchr("\t ", *--eol)) {
276                 *eol = '\0';
277         }
278
279         len = strcspn(value, "\t =");
280         value += len;
281         value += strspn(value, "\t ");
282
283         if(*value == '=') {
284                 value++;
285                 value += strspn(value, "\t ");
286         }
287
288         variable[len] = '\0';
289
290         if(!*value) {
291                 const char err[] = "No value for variable";
292
293                 if(fname)
294                         logger(LOG_ERR, "%s `%s' on line %d while reading config file %s",
295                                err, variable, lineno, fname);
296                 else
297                         logger(LOG_ERR, "%s `%s' in command line option %d",
298                                err, variable, lineno);
299
300                 return NULL;
301         }
302
303         cfg = new_config();
304         cfg->variable = xstrdup(variable);
305         cfg->value = xstrdup(value);
306         cfg->file = fname ? xstrdup(fname) : NULL;
307         cfg->line = lineno;
308
309         return cfg;
310 }
311
312 /*
313   Parse a configuration file and put the results in the configuration tree
314   starting at *base.
315 */
316 bool read_config_file(avl_tree_t *config_tree, const char *fname) {
317         FILE *fp;
318         char buffer[MAX_STRING_SIZE];
319         char *line;
320         int lineno = 0;
321         bool ignore = false;
322         config_t *cfg;
323         bool result = false;
324
325         fp = fopen(fname, "r");
326
327         if(!fp) {
328                 logger(LOG_ERR, "Cannot open config file %s: %s", fname, strerror(errno));
329                 return false;
330         }
331
332         for(;;) {
333                 line = readline(fp, buffer, sizeof(buffer));
334
335                 if(!line) {
336                         if(feof(fp)) {
337                                 result = true;
338                         }
339
340                         break;
341                 }
342
343                 lineno++;
344
345                 if(!*line || *line == '#') {
346                         continue;
347                 }
348
349                 if(ignore) {
350                         if(!strncmp(line, "-----END", 8)) {
351                                 ignore = false;
352                         }
353
354                         continue;
355                 }
356
357                 if(!strncmp(line, "-----BEGIN", 10)) {
358                         ignore = true;
359                         continue;
360                 }
361
362                 cfg = parse_config_line(line, fname, lineno);
363
364                 if(!cfg) {
365                         break;
366                 }
367
368                 config_add(config_tree, cfg);
369         }
370
371         fclose(fp);
372
373         return result;
374 }
375
376 void read_config_options(avl_tree_t *config_tree, const char *prefix) {
377         size_t prefix_len = prefix ? strlen(prefix) : 0;
378
379         for(const list_node_t *node = cmdline_conf->tail; node; node = node->prev) {
380                 const config_t *cfg = node->data;
381
382                 if(!prefix) {
383                         if(strchr(cfg->variable, '.')) {
384                                 continue;
385                         }
386                 } else {
387                         if(strncmp(prefix, cfg->variable, prefix_len) ||
388                                         cfg->variable[prefix_len] != '.') {
389                                 continue;
390                         }
391                 }
392
393                 config_t *new = new_config();
394
395                 if(prefix) {
396                         new->variable = xstrdup(cfg->variable + prefix_len + 1);
397                 } else {
398                         new->variable = xstrdup(cfg->variable);
399                 }
400
401                 new->value = xstrdup(cfg->value);
402                 new->file = NULL;
403                 new->line = cfg->line;
404
405                 config_add(config_tree, new);
406         }
407 }
408
409 bool read_server_config(void) {
410         char fname[PATH_MAX];
411         bool x;
412
413         read_config_options(config_tree, NULL);
414
415         snprintf(fname, sizeof(fname), "%s/tinc.conf", confbase);
416         errno = 0;
417         x = read_config_file(config_tree, fname);
418
419         // We will try to read the conf files in the "conf.d" dir
420         if(x) {
421                 char dname[PATH_MAX];
422                 snprintf(dname, sizeof(dname), "%s/conf.d", confbase);
423                 DIR *dir = opendir(dname);
424
425                 // If we can find this dir
426                 if(dir) {
427                         struct dirent *ep;
428
429                         // We list all the files in it
430                         while(x && (ep = readdir(dir))) {
431                                 size_t l = strlen(ep->d_name);
432
433                                 // And we try to read the ones that end with ".conf"
434                                 if(l > 5 && !strcmp(".conf", & ep->d_name[ l - 5 ])) {
435                                         if(snprintf(fname, sizeof(fname), "%s/%s", dname, ep->d_name) >= sizeof(fname)) {
436                                                 logger(LOG_ERR, "Pathname too long: %s/%s", dname, ep->d_name);
437                                                 return false;
438                                         }
439
440                                         x = read_config_file(config_tree, fname);
441                                 }
442                         }
443
444                         closedir(dir);
445                 }
446         }
447
448         if(!x && errno) {
449                 logger(LOG_ERR, "Failed to read `%s': %s", fname, strerror(errno));
450         }
451
452         return x;
453 }
454
455 bool read_connection_config(connection_t *c) {
456         char fname[PATH_MAX];
457         bool x;
458
459         read_config_options(c->config_tree, c->name);
460
461         snprintf(fname, sizeof(fname), "%s/hosts/%s", confbase, c->name);
462         x = read_config_file(c->config_tree, fname);
463
464         return x;
465 }
466
467 static void disable_old_keys(const char *filename) {
468         char tmpfile[PATH_MAX] = "";
469         char buf[1024];
470         bool disabled = false;
471         FILE *r, *w;
472
473         r = fopen(filename, "r");
474
475         if(!r) {
476                 return;
477         }
478
479         snprintf(tmpfile, sizeof(tmpfile), "%s.tmp", filename);
480
481         w = fopen(tmpfile, "w");
482
483         while(fgets(buf, sizeof(buf), r)) {
484                 if(!strncmp(buf, "-----BEGIN RSA", 14)) {
485                         buf[11] = 'O';
486                         buf[12] = 'L';
487                         buf[13] = 'D';
488                         disabled = true;
489                 } else if(!strncmp(buf, "-----END RSA", 12)) {
490                         buf[ 9] = 'O';
491                         buf[10] = 'L';
492                         buf[11] = 'D';
493                         disabled = true;
494                 }
495
496                 if(w && fputs(buf, w) < 0) {
497                         disabled = false;
498                         break;
499                 }
500         }
501
502         if(w) {
503                 fclose(w);
504         }
505
506         fclose(r);
507
508         if(!w && disabled) {
509                 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
510                 return;
511         }
512
513         if(disabled) {
514 #ifdef HAVE_MINGW
515                 // We cannot atomically replace files on Windows.
516                 char bakfile[PATH_MAX] = "";
517                 snprintf(bakfile, sizeof(bakfile), "%s.bak", filename);
518
519                 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
520                         rename(bakfile, filename);
521 #else
522
523                 if(rename(tmpfile, filename)) {
524 #endif
525                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
526                 } else  {
527 #ifdef HAVE_MINGW
528                         unlink(bakfile);
529 #endif
530                         fprintf(stderr, "Warning: old key(s) found and disabled.\n");
531                 }
532         }
533
534         unlink(tmpfile);
535 }
536
537 FILE *ask_and_open(const char *filename, const char *what) {
538         FILE *r;
539         char directory[PATH_MAX];
540         char line[PATH_MAX];
541         char abspath[PATH_MAX];
542         const char *fn;
543
544         /* Check stdin and stdout */
545         if(!isatty(0) || !isatty(1)) {
546                 /* Argh, they are running us from a script or something.  Write
547                    the files to the current directory and let them burn in hell
548                    for ever. */
549                 fn = filename;
550         } else {
551                 /* Ask for a file and/or directory name. */
552                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
553                         what, filename);
554                 fflush(stdout);
555
556                 fn = readline(stdin, line, sizeof(line));
557
558                 if(!fn) {
559                         fprintf(stderr, "Error while reading stdin: %s\n",
560                                 strerror(errno));
561                         return NULL;
562                 }
563
564                 if(!strlen(fn))
565                         /* User just pressed enter. */
566                 {
567                         fn = filename;
568                 }
569         }
570
571 #ifdef HAVE_MINGW
572
573         if(fn[0] != '\\' && fn[0] != '/' && !strchr(fn, ':')) {
574 #else
575
576         if(fn[0] != '/') {
577 #endif
578                 /* The directory is a relative path or a filename. */
579                 getcwd(directory, sizeof(directory));
580
581                 if(snprintf(abspath, sizeof(abspath), "%s/%s", directory, fn) >= sizeof(abspath)) {
582                         fprintf(stderr, "Pathname too long: %s/%s\n", directory, fn);
583                         return NULL;
584                 }
585
586                 fn = abspath;
587         }
588
589         umask(0077);                            /* Disallow everything for group and other */
590
591         disable_old_keys(fn);
592
593         /* Open it first to keep the inode busy */
594
595         r = fopen(fn, "a");
596
597         if(!r) {
598                 fprintf(stderr, "Error opening file `%s': %s\n",
599                         fn, strerror(errno));
600                 return NULL;
601         }
602
603         return r;
604 }
605
606