]> git.ipfire.org Git - ipfire-2.x.git/blob - src/misc-progs/openvpnctrl.c
openvpn: Properly remove all RRDs after a connection is removed
[ipfire-2.x.git] / src / misc-progs / openvpnctrl.c
1 #define _XOPEN_SOURCE 500
2 #include <signal.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <stdlib.h>
7 #include <sys/types.h>
8 #include <arpa/inet.h>
9 #include <netinet/in.h>
10 #include <fcntl.h>
11 #include <ftw.h>
12 #include "setuid.h"
13 #include "netutil.h"
14 #include "libsmooth.h"
15
16 #define noovpndebug
17
18 // global vars
19 struct keyvalue *kv = NULL;
20 FILE *ifacefile = NULL;
21
22 char redif[STRING_SIZE];
23 char blueif[STRING_SIZE];
24 char orangeif[STRING_SIZE];
25 char enablered[STRING_SIZE] = "off";
26 char enableblue[STRING_SIZE] = "off";
27 char enableorange[STRING_SIZE] = "off";
28
29 // consts
30 char OVPNINPUT[STRING_SIZE] = "OVPNINPUT";
31 char OVPNBLOCK[STRING_SIZE] = "OVPNBLOCK";
32 char OVPNNAT[STRING_SIZE] = "OVPNNAT";
33 char WRAPPERVERSION[STRING_SIZE] = "ipfire-2.2.4";
34
35 struct connection_struct {
36 char name[STRING_SIZE];
37 char type[STRING_SIZE];
38 char proto[STRING_SIZE];
39 char status[STRING_SIZE];
40 char local_subnet[STRING_SIZE];
41 char transfer_subnet[STRING_SIZE];
42 char role[STRING_SIZE];
43 char port[STRING_SIZE];
44 struct connection_struct *next;
45 };
46
47 typedef struct connection_struct connection;
48
49 void exithandler(void)
50 {
51 if(kv)
52 freekeyvalues(kv);
53 if (ifacefile)
54 fclose(ifacefile);
55 }
56
57 void usage(void)
58 {
59 #ifdef ovpndebug
60 printf("Wrapper for OpenVPN %s-debug\n", WRAPPERVERSION);
61 #else
62 printf("Wrapper for OpenVPN %s\n", WRAPPERVERSION);
63 #endif
64 printf("openvpnctrl <option>\n");
65 printf(" Valid options are:\n");
66 printf(" -s --start\n");
67 printf(" starts OpenVPN (implicitly creates chains and firewall rules)\n");
68 printf(" -k --kill\n");
69 printf(" kills/stops OpenVPN\n");
70 printf(" -r --restart\n");
71 printf(" restarts OpenVPN (implicitly creates chains and firewall rules)\n");
72 printf(" -sn2n --start-net-2-net\n");
73 printf(" starts all net2net connections\n");
74 printf(" you may pass a connection name to the switch to only start a specific one\n");
75 printf(" -kn2n --kill-net-2-net\n");
76 printf(" kills all net2net connections\n");
77 printf(" you may pass a connection name to the switch to only start a specific one\n");
78 printf(" -drrd --delete-rrd\n");
79 printf(" Deletes the RRD data for a specific client\n");
80 printf(" you need to pass a connection name (RW) to the switch to delete the directory (case sensitive)\n");
81 printf(" -d --display\n");
82 printf(" displays OpenVPN status to syslog\n");
83 printf(" -fwr --firewall-rules\n");
84 printf(" removes current OpenVPN chains and rules and resets them according to the config\n");
85 printf(" -sdo --start-daemon-only\n");
86 printf(" starts OpenVPN daemon only\n");
87 exit(1);
88 }
89
90 connection *getConnections() {
91 FILE *fp = NULL;
92
93 if (!(fp = fopen(CONFIG_ROOT "/ovpn/ovpnconfig", "r"))) {
94 fprintf(stderr, "Could not open openvpn n2n configuration file.\n");
95 exit(1);
96 }
97
98 char line[STRING_SIZE] = "";
99 char result[STRING_SIZE] = "";
100 char *resultptr;
101 int count;
102 connection *conn_first = NULL;
103 connection *conn_last = NULL;
104 connection *conn_curr;
105
106 while ((fgets(line, STRING_SIZE, fp) != NULL)) {
107 if (line[strlen(line) - 1] == '\n')
108 line[strlen(line) - 1] = '\0';
109
110 conn_curr = (connection *)malloc(sizeof(connection));
111 memset(conn_curr, 0, sizeof(connection));
112
113 if (conn_first == NULL) {
114 conn_first = conn_curr;
115 } else {
116 conn_last->next = conn_curr;
117 }
118 conn_last = conn_curr;
119
120 count = 0;
121 char *lineptr = &line;
122 while (1) {
123 if (*lineptr == NULL)
124 break;
125
126 resultptr = result;
127 while (*lineptr != NULL) {
128 if (*lineptr == ',') {
129 lineptr++;
130 break;
131 }
132 *resultptr++ = *lineptr++;
133 }
134 *resultptr = '\0';
135
136 if (count == 1) {
137 strcpy(conn_curr->status, result);
138 } else if (count == 2) {
139 strcpy(conn_curr->name, result);
140 } else if (count == 4) {
141 strcpy(conn_curr->type, result);
142 } else if (count == 7) {
143 strcpy(conn_curr->role, result);
144 } else if (count == 9) {
145 strcpy(conn_curr->local_subnet, result);
146 } else if (count == 28) {
147 strcpy(conn_curr->transfer_subnet, result);
148 } else if (count == 29) {
149 strcpy(conn_curr->proto, result);
150 } else if (count == 30) {
151 strcpy(conn_curr->port, result);
152 }
153
154 count++;
155 }
156 }
157
158 fclose(fp);
159
160 return conn_first;
161 }
162
163 int readPidFile(const char *pidfile) {
164 FILE *fp = fopen(pidfile, "r");
165 if (fp == NULL) {
166 exit(1);
167 }
168
169 int pid = 0;
170 fscanf(fp, "%d", &pid);
171 fclose(fp);
172
173 return pid;
174 }
175
176 int readExternalAddress(char* address) {
177 FILE *fp = fopen("/var/ipfire/red/local-ipaddress", "r");
178 if (!fp)
179 goto ERROR;
180
181 int r = fscanf(fp, "%s", address);
182 fclose(fp);
183
184 if (r < 0)
185 goto ERROR;
186
187 /* In case the read IP address is not valid, we empty
188 * the content of address and return non-zero. */
189 if (!VALID_IP(address))
190 goto ERROR;
191
192 return 0;
193
194 ERROR:
195 address = NULL;
196 return 1;
197 }
198
199 void ovpnInit(void) {
200 // Read OpenVPN configuration
201 kv = initkeyvalues();
202 if (!readkeyvalues(kv, CONFIG_ROOT "/ovpn/settings")) {
203 fprintf(stderr, "Cannot read ovpn settings\n");
204 exit(1);
205 }
206
207 if (!findkey(kv, "ENABLED", enablered)) {
208 exit(1);
209 }
210
211 if (!findkey(kv, "ENABLED_BLUE", enableblue)){
212 exit(1);
213 }
214
215 if (!findkey(kv, "ENABLED_ORANGE", enableorange)){
216 exit(1);
217 }
218 freekeyvalues(kv);
219
220 // read interface settings
221
222 // details for the red int
223 memset(redif, 0, STRING_SIZE);
224 if ((ifacefile = fopen(CONFIG_ROOT "/red/iface", "r")))
225 {
226 if (fgets(redif, STRING_SIZE, ifacefile))
227 {
228 if (redif[strlen(redif) - 1] == '\n')
229 redif[strlen(redif) - 1] = '\0';
230 }
231 fclose (ifacefile);
232 ifacefile = NULL;
233
234 if (!VALID_DEVICE(redif))
235 {
236 memset(redif, 0, STRING_SIZE);
237 }
238 }
239
240 kv=initkeyvalues();
241 if (!readkeyvalues(kv, CONFIG_ROOT "/ethernet/settings")) {
242 fprintf(stderr, "Cannot read ethernet settings\n");
243 exit(1);
244 }
245
246 if (strcmp(enableblue, "on") == 0) {
247 if (!findkey(kv, "BLUE_DEV", blueif)) {
248 exit(1);
249 }
250 }
251
252 if (strcmp(enableorange, "on") == 0) {
253 if (!findkey(kv, "ORANGE_DEV", orangeif)) {
254 exit(1);
255 }
256 }
257 freekeyvalues(kv);
258 }
259
260 void executeCommand(char *command) {
261 #ifdef ovpndebug
262 printf(strncat(command, "\n", 2));
263 #endif
264 safe_system(strncat(command, " >/dev/null 2>&1", 17));
265 }
266
267 void addRule(const char *chain, const char *interface, const char *protocol, const char *port) {
268 char command[STRING_SIZE];
269
270 snprintf(command, STRING_SIZE - 1, "/sbin/iptables -A %s -i %s -p %s --dport %s -j ACCEPT",
271 chain, interface, protocol, port);
272 executeCommand(command);
273 }
274
275 void flushChain(char *chain) {
276 char str[STRING_SIZE];
277
278 snprintf(str, STRING_SIZE - 1, "/sbin/iptables -F %s", chain);
279 executeCommand(str);
280 }
281
282 void flushChainNAT(char *chain) {
283 char str[STRING_SIZE];
284
285 snprintf(str, STRING_SIZE - 1, "/sbin/iptables -t nat -F %s", chain);
286 executeCommand(str);
287 }
288
289 char* calcTransferNetAddress(const connection* conn) {
290 char *subnetmask = strdup(conn->transfer_subnet);
291 char *address = strsep(&subnetmask, "/");
292
293 if ((address == NULL) || (subnetmask == NULL)) {
294 goto ERROR;
295 }
296
297 in_addr_t _address = inet_addr(address);
298 in_addr_t _subnetmask = inet_addr(subnetmask);
299 _address &= _subnetmask;
300
301 if (strcmp(conn->role, "server") == 0) {
302 _address += 1 << 24;
303 } else if (strcmp(conn->role, "client") == 0) {
304 _address += 2 << 24;
305 } else {
306 goto ERROR;
307 }
308
309 struct in_addr address_info;
310 address_info.s_addr = _address;
311
312 return inet_ntoa(address_info);
313
314 ERROR:
315 fprintf(stderr, "Could not determine transfer net address: %s\n", conn->name);
316
317 free(address);
318 return NULL;
319 }
320
321 char* getLocalSubnetAddress(const connection* conn) {
322 kv = initkeyvalues();
323 if (!readkeyvalues(kv, CONFIG_ROOT "/ethernet/settings")) {
324 fprintf(stderr, "Cannot read ethernet settings\n");
325 exit(1);
326 }
327
328 const char *zones[] = {"GREEN", "BLUE", "ORANGE", NULL};
329 char *zone = NULL;
330
331 // Get net address of the local openvpn subnet.
332 char *subnetmask = strdup(conn->local_subnet);
333 char *address = strsep(&subnetmask, "/");
334
335 if ((address == NULL) || (subnetmask == NULL)) {
336 goto ERROR;
337 }
338
339 in_addr_t _address = inet_addr(address);
340 in_addr_t _subnetmask = inet_addr(subnetmask);
341
342 in_addr_t _netaddr = (_address & _subnetmask);
343 in_addr_t _broadcast = (_address | ~_subnetmask);
344
345 char zone_address_key[STRING_SIZE];
346 char zone_address[STRING_SIZE];
347 in_addr_t zone_addr;
348
349 int i = 0;
350 while (zones[i]) {
351 zone = zones[i++];
352 snprintf(zone_address_key, STRING_SIZE, "%s_ADDRESS", zone);
353
354 if (!findkey(kv, zone_address_key, zone_address))
355 continue;
356
357 zone_addr = inet_addr(zone_address);
358 if ((zone_addr > _netaddr) && (zone_addr < _broadcast)) {
359 freekeyvalues(kv);
360
361 return strdup(zone_address);
362 }
363 }
364
365 ERROR:
366 fprintf(stderr, "Could not determine local subnet address: %s\n", conn->name);
367
368 freekeyvalues(kv);
369 return NULL;
370 }
371
372 void setFirewallRules(void) {
373 char command[STRING_SIZE];
374 char protocol[STRING_SIZE] = "";
375 char dport[STRING_SIZE] = "";
376 char dovpnip[STRING_SIZE] = "";
377
378 kv = initkeyvalues();
379 if (!readkeyvalues(kv, CONFIG_ROOT "/ovpn/settings"))
380 {
381 fprintf(stderr, "Cannot read ovpn settings\n");
382 exit(1);
383 }
384
385 /* we got one device, so lets proceed further */
386 if (!findkey(kv, "DDEST_PORT", dport)){
387 fprintf(stderr, "Cannot read DDEST_PORT\n");
388 exit(1);
389 }
390
391 if (!findkey(kv, "DPROTOCOL", protocol)){
392 fprintf(stderr, "Cannot read DPROTOCOL\n");
393 exit(1);
394 }
395
396 if (!findkey(kv, "VPN_IP", dovpnip)){
397 fprintf(stderr, "Cannot read VPN_IP\n");
398 }
399 freekeyvalues(kv);
400
401 // Flush all chains.
402 flushChain(OVPNINPUT);
403 flushChain(OVPNBLOCK);
404 flushChainNAT(OVPNNAT);
405
406 // set firewall rules
407 if (!strcmp(enablered, "on") && strlen(redif))
408 addRule(OVPNINPUT, redif, protocol, dport);
409 if (!strcmp(enableblue, "on") && strlen(blueif))
410 addRule(OVPNINPUT, blueif, protocol, dport);
411 if (!strcmp(enableorange, "on") && strlen(orangeif))
412 addRule(OVPNINPUT, orangeif, protocol, dport);
413
414 /* Allow ICMP error messages to pass. */
415 snprintf(command, STRING_SIZE - 1, "/sbin/iptables -A %s -p icmp"
416 " -m conntrack --ctstate RELATED -j RETURN", OVPNBLOCK);
417 executeCommand(command);
418
419 // read connection configuration
420 connection *conn = getConnections();
421
422 // set firewall rules for n2n connections
423 char *local_subnet_address = NULL;
424 char *transfer_subnet_address = NULL;
425 while (conn != NULL) {
426 if (strcmp(conn->type, "net") == 0) {
427 addRule(OVPNINPUT, redif, conn->proto, conn->port);
428
429 /* Block all communication from the transfer nets. */
430 snprintf(command, STRING_SIZE - 1, "/sbin/iptables -A %s -s %s -j DROP",
431 OVPNBLOCK, conn->transfer_subnet);
432 executeCommand(command);
433
434 local_subnet_address = getLocalSubnetAddress(conn);
435 transfer_subnet_address = calcTransferNetAddress(conn);
436
437 if ((local_subnet_address) && (transfer_subnet_address)) {
438 snprintf(command, STRING_SIZE - 1, "/sbin/iptables -t nat -A %s -s %s -j SNAT --to-source %s",
439 OVPNNAT, transfer_subnet_address, local_subnet_address);
440 executeCommand(command);
441 }
442 }
443
444 conn = conn->next;
445 }
446 }
447
448 void stopDaemon(void) {
449 char command[STRING_SIZE];
450
451 int pid = readPidFile("/var/run/openvpn.pid");
452 if (!pid > 0) {
453 exit(1);
454 }
455
456 fprintf(stderr, "Killing PID %d.\n", pid);
457 kill(pid, SIGTERM);
458
459 snprintf(command, STRING_SIZE - 1, "/bin/rm -f /var/run/openvpn.pid");
460 executeCommand(command);
461 }
462
463 void startDaemon(void) {
464 char command[STRING_SIZE];
465
466 if (!((strcmp(enablered, "on") == 0) || (strcmp(enableblue, "on") == 0) || (strcmp(enableorange, "on") == 0))) {
467 fprintf(stderr, "OpenVPN is not enabled on any interface\n");
468 exit(1);
469 } else {
470 snprintf(command, STRING_SIZE-1, "/sbin/modprobe tun");
471 executeCommand(command);
472 snprintf(command, STRING_SIZE-1, "/usr/sbin/openvpn --config /var/ipfire/ovpn/server.conf");
473 executeCommand(command);
474 snprintf(command, STRING_SIZE-1, "/bin/chown root.nobody /var/run/ovpnserver.log");
475 executeCommand(command);
476 snprintf(command, STRING_SIZE-1, "/bin/chmod 644 /var/run/ovpnserver.log");
477 executeCommand(command);
478 }
479 }
480
481 int startNet2Net(char *name) {
482 connection *conn = NULL;
483 connection *conn_iter;
484
485 conn_iter = getConnections();
486
487 while (conn_iter) {
488 if ((strcmp(conn_iter->type, "net") == 0) && (strcmp(conn_iter->name, name) == 0)) {
489 conn = conn_iter;
490 break;
491 }
492 conn_iter = conn_iter->next;
493 }
494
495 if (conn == NULL) {
496 fprintf(stderr, "Connection not found.\n");
497 return 1;
498 }
499
500 if (strcmp(conn->status, "on") != 0) {
501 fprintf(stderr, "Connection '%s' is not enabled.\n", conn->name);
502 return 1;
503 }
504
505 fprintf(stderr, "Starting connection %s...\n", conn->name);
506
507 char configfile[STRING_SIZE];
508 snprintf(configfile, STRING_SIZE - 1, CONFIG_ROOT "/ovpn/n2nconf/%s/%s.conf",
509 conn->name, conn->name);
510
511 FILE *fp = fopen(configfile, "r");
512 if (fp == NULL) {
513 fprintf(stderr, "Could not find configuration file for connection '%s' at '%s'.\n",
514 conn->name, configfile);
515 return 2;
516 }
517 fclose(fp);
518
519 // Make sure all firewall rules are up to date.
520 setFirewallRules();
521
522 // Get the external IP address.
523 char address[STRING_SIZE] = "";
524 int r = readExternalAddress(address);
525 if (r) {
526 fprintf(stderr, "Could not read the external address\n");
527 exit(1);
528 }
529
530 char command[STRING_SIZE];
531 snprintf(command, STRING_SIZE-1, "/sbin/modprobe tun");
532 executeCommand(command);
533 snprintf(command, STRING_SIZE-1, "/usr/sbin/openvpn --local %s --config %s", address, configfile);
534 executeCommand(command);
535
536 return 0;
537 }
538
539 int killNet2Net(char *name) {
540 connection *conn = NULL;
541 connection *conn_iter;
542
543 conn_iter = getConnections();
544
545 while (conn_iter) {
546 if (strcmp(conn_iter->name, name) == 0) {
547 conn = conn_iter;
548 break;
549 }
550 conn_iter = conn_iter->next;
551 }
552
553 if (conn == NULL) {
554 fprintf(stderr, "Connection not found.\n");
555 return 1;
556 }
557
558 char pidfile[STRING_SIZE];
559 snprintf(pidfile, STRING_SIZE - 1, "/var/run/%sn2n.pid", conn->name);
560
561 int pid = readPidFile(pidfile);
562 if (!pid > 0) {
563 fprintf(stderr, "Could not read pid file of connection %s.", conn->name);
564 return 1;
565 }
566
567 fprintf(stderr, "Killing connection %s (PID %d)...\n", conn->name, pid);
568 kill(pid, SIGTERM);
569
570 char command[STRING_SIZE];
571 snprintf(command, STRING_SIZE - 1, "/bin/rm -f %s", pidfile);
572 executeCommand(command);
573
574 return 0;
575 }
576
577
578 static int recursive_remove_callback(const char* fpath, const struct stat* sb, int typeflag, struct FTW* ftwbuf) {
579 int rv = remove(fpath);
580 if (rv)
581 perror(fpath);
582
583 return rv;
584 }
585
586 static int recursive_remove(const char* path) {
587 return nftw(path, recursive_remove_callback, 64, FTW_DEPTH | FTW_PHYS);
588 }
589
590 int deleterrd(char *name) {
591 char rrd_dir[STRING_SIZE];
592
593 connection *conn = getConnections();
594 while(conn) {
595 if (strcmp(conn->name, name) != 0) {
596 conn = conn->next;
597 continue;
598 }
599
600 // Handle RW connections
601 if (strcmp(conn->type, "host") == 0) {
602 snprintf(rrd_dir, STRING_SIZE - 1, "/var/log/rrd/collectd/localhost/openvpn-%s", name);
603
604 // Handle N2N connections
605 } else if (strcmp(conn->type, "net") == 0) {
606 snprintf(rrd_dir, STRING_SIZE - 1, "/var/log/rrd/collectd/localhost/openvpn-%s-n2n/", name);
607
608 // Unhandled connection type
609 } else {
610 conn = conn->next;
611 continue;
612 }
613
614 return recursive_remove(rrd_dir);
615 }
616
617 return 1;
618 }
619
620 void startAllNet2Net() {
621 int exitcode = 0, _exitcode = 0;
622
623 connection *conn = getConnections();
624
625 while(conn) {
626 /* Skip all connections that are not of type "net" or disabled. */
627 if ((strcmp(conn->type, "net") != 0) || (strcmp(conn->status, "on") != 0)) {
628 conn = conn->next;
629 continue;
630 }
631
632 _exitcode = startNet2Net(conn->name);
633 conn = conn->next;
634
635 if (_exitcode > exitcode) {
636 exitcode = _exitcode;
637 }
638 }
639
640 exit(exitcode);
641 }
642
643 void killAllNet2Net() {
644 int exitcode = 0, _exitcode = 0;
645
646 connection *conn = getConnections();
647
648 while(conn) {
649 /* Skip all connections that are not of type "net". */
650 if (strcmp(conn->type, "net") != 0) {
651 conn = conn->next;
652 continue;
653 }
654
655 _exitcode = killNet2Net(conn->name);
656 conn = conn->next;
657
658 if (_exitcode > exitcode) {
659 exitcode = _exitcode;
660 }
661 }
662
663 exit(exitcode);
664 }
665
666 void displayopenvpn(void) {
667 char command[STRING_SIZE];
668
669 snprintf(command, STRING_SIZE - 1, "/bin/killall -sSIGUSR2 openvpn");
670 executeCommand(command);
671 }
672
673 int main(int argc, char *argv[]) {
674 if (!(initsetuid()))
675 exit(1);
676 if(argc < 2)
677 usage();
678
679 if(argc == 3) {
680 ovpnInit();
681
682 if( (strcmp(argv[1], "-sn2n") == 0) || (strcmp(argv[1], "--start-net-2-net") == 0) ) {
683 startNet2Net(argv[2]);
684 return 0;
685 }
686 else if( (strcmp(argv[1], "-kn2n") == 0) || (strcmp(argv[1], "--kill-net-2-net") == 0) ) {
687 killNet2Net(argv[2]);
688 return 0;
689 }
690 else if( (strcmp(argv[1], "-drrd") == 0) || (strcmp(argv[1], "--delete-rrd") == 0) ) {
691 deleterrd(argv[2]);
692 return 0;
693 } else {
694 usage();
695 return 1;
696 }
697 }
698 else if(argc == 2) {
699 if( (strcmp(argv[1], "-k") == 0) || (strcmp(argv[1], "--kill") == 0) ) {
700 stopDaemon();
701 return 0;
702 }
703 else if( (strcmp(argv[1], "-d") == 0) || (strcmp(argv[1], "--display") == 0) ) {
704 displayopenvpn();
705 return 0;
706 }
707 else {
708 ovpnInit();
709
710 if( (strcmp(argv[1], "-s") == 0) || (strcmp(argv[1], "--start") == 0) ) {
711 setFirewallRules();
712 startDaemon();
713 return 0;
714 }
715 else if( (strcmp(argv[1], "-sn2n") == 0) || (strcmp(argv[1], "--start-net-2-net") == 0) ) {
716 startAllNet2Net();
717 return 0;
718 }
719 else if( (strcmp(argv[1], "-kn2n") == 0) || (strcmp(argv[1], "--kill-net-2-net") == 0) ) {
720 killAllNet2Net();
721 return 0;
722 }
723 else if( (strcmp(argv[1], "-sdo") == 0) || (strcmp(argv[1], "--start-daemon-only") == 0) ) {
724 startDaemon();
725 return 0;
726 }
727 else if( (strcmp(argv[1], "-r") == 0) || (strcmp(argv[1], "--restart") == 0) ) {
728 stopDaemon();
729 setFirewallRules();
730 startDaemon();
731 return 0;
732 }
733 else if( (strcmp(argv[1], "-fwr") == 0) || (strcmp(argv[1], "--firewall-rules") == 0) ) {
734 setFirewallRules();
735 return 0;
736 }
737 else {
738 usage();
739 return 0;
740 }
741 }
742 }
743 else {
744 usage();
745 return 0;
746 }
747 return 0;
748 }
749