forked from adrienverge/openfortivpn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipv4.c
1400 lines (1233 loc) · 39.7 KB
/
ipv4.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2015 Adrien Vergé
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ipv4.h"
#include "tunnel.h"
#include "config.h"
#include "log.h"
#include "xml.h"
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#define IPV4_GET_ROUTE_BUFFER_CHUNK_SIZE 65536
#define SHOW_ROUTE_BUFFER_SIZE 128
static char show_route_buffer[SHOW_ROUTE_BUFFER_SIZE];
#define ERR_IPV4_SEE_ERRNO -1
#define ERR_IPV4_NO_MEM -2
#define ERR_IPV4_PERMISSION -3
#define ERR_IPV4_NO_SUCH_ROUTE -4
#define ERR_IPV4_PROC_NET_ROUTE -5
static inline const char *err_ipv4_str(int code)
{
if (code == ERR_IPV4_SEE_ERRNO)
return strerror(errno);
else if (code == ERR_IPV4_NO_MEM)
return "Not enough memory";
else if (code == ERR_IPV4_PERMISSION)
return "Permission denied";
else if (code == ERR_IPV4_NO_SUCH_ROUTE)
return "Route not found";
else if (code == ERR_IPV4_PROC_NET_ROUTE)
return "Parsing /proc/net/route failed";
return "unknown";
}
/*
* Returns a string representation of the route, such as:
* to 192.168.1.0/255.255.255.0 via 172.16.0.1 dev eth0
*
* Warning: the returned buffer is static, so multiple calls will overwrite it.
*/
static char *ipv4_show_route(struct rtentry *route)
{
strcpy(show_route_buffer, "to ");
strncat(show_route_buffer, inet_ntoa(route_dest(route)), 15);
strcat(show_route_buffer, "/");
strncat(show_route_buffer, inet_ntoa(route_mask(route)), 15);
if (route->rt_flags & RTF_GATEWAY) {
strcat(show_route_buffer, " via ");
strncat(show_route_buffer, inet_ntoa(route_gtw(route)), 15);
}
if (route_iface(route) != NULL) {
strcat(show_route_buffer, " dev ");
strncat(show_route_buffer, route_iface(route),
SHOW_ROUTE_BUFFER_SIZE - strlen(show_route_buffer) - 1);
}
return show_route_buffer;
}
static inline int route_init(struct rtentry *route)
{
memset(route, 0, sizeof(*route));
cast_addr(&(route)->rt_dst)->sin_family = AF_INET;
cast_addr(&(route)->rt_genmask)->sin_family = AF_INET;
cast_addr(&(route)->rt_gateway)->sin_family = AF_INET;
return 0;
}
static inline void route_destroy(struct rtentry *route)
{
free(route_iface(route));
route_iface(route) = NULL;
}
/*
* Finds system IP route to a destination.
*
* The passed route must have dest and mask set. If the route is found,
* the function searches for a match in the routing table and returns
* that one. Note that dest and mask contain the network address and
* the mask of the corresponding routing table entry after calling.
* After calling ipv4_get_route it might be necessary to set dest
* and mask again to the desired values for further processing.
*/
static int ipv4_get_route(struct rtentry *route)
{
size_t buffer_size = IPV4_GET_ROUTE_BUFFER_CHUNK_SIZE;
char *buffer;
char *realloc_buffer;
int err = 0;
char *start, *line;
char *saveptr1 = NULL, *saveptr2 = NULL;
uint32_t rtdest, rtmask, rtgtw;
int rtfound = 0;
/*
* initialize the buffer with zeroes, aiming to address the
* coverity issue "TAINTED_SCALAR passed to a tainted sink"
*
* Later on, the routing table is read into this buffer using
* read() and therefore the content of the buffer is considered
* tainted. strtok_r internally uses it in a loop boundary.
* The theoretical problem is that the loop could iterate forever,
* if the buffer contains a huge string which doesn't contain
* the token character, which we are parsing for.
*
* We can declare this as a false positive, because
* - the routing table is to some extent trusted input,
* - it's not that large,
* - and the loop in strtok_r increments the pointer in each
* iteration until it reaches the area where we have ensured
* that there is a delimiting '\0' character by proper
* initialization. We ensure this also when growing the buffer.
*/
buffer = calloc(1, buffer_size);
if (!buffer) {
err = ERR_IPV4_SEE_ERRNO;
goto end;
}
log_debug("ip route show %s\n", ipv4_show_route(route));
// store what we are looking for
rtdest = route_dest(route).s_addr;
rtmask = route_mask(route).s_addr;
rtgtw = route_gtw(route).s_addr;
// initialize the output record
route_dest(route).s_addr = inet_addr("0.0.0.0");
route_mask(route).s_addr = inet_addr("0.0.0.0");
route_gtw(route).s_addr = inet_addr("0.0.0.0");
#if HAVE_PROC_NET_ROUTE
/* this is not present on Mac OS X and FreeBSD */
int fd;
uint32_t total_bytes_read = 0;
// Cannot stat, mmap not lseek this special /proc file
fd = open("/proc/net/route", O_RDONLY);
if (fd == -1) {
err = ERR_IPV4_SEE_ERRNO;
goto end;
}
int bytes_read;
while ((bytes_read = read(fd, buffer + total_bytes_read,
buffer_size - total_bytes_read - 1)) > 0) {
total_bytes_read += bytes_read;
if ((buffer_size - total_bytes_read) < 1) {
buffer_size += IPV4_GET_ROUTE_BUFFER_CHUNK_SIZE;
realloc_buffer = realloc(buffer, buffer_size);
if (realloc_buffer) {
buffer = realloc_buffer;
} else {
err = ERR_IPV4_SEE_ERRNO;
goto cleanup;
}
buffer[buffer_size-1] = '\0';
}
}
cleanup:
if (close(fd))
log_warn("Could not close /proc/net/route (%s).\n", strerror(errno));
if (err)
goto end;
if (bytes_read < 0) {
err = ERR_IPV4_SEE_ERRNO;
goto end;
}
#else
FILE *fp;
uint32_t total_bytes_read = 0;
char *saveptr3 = NULL;
int have_ref = 0;
int have_use = 0;
static const char netstat_path[] = NETSTAT_PATH;
if (access(netstat_path, F_OK) != 0) {
log_error("%s: %s.\n", netstat_path, strerror(errno));
return 1;
}
log_debug("netstat_path: %s\n", netstat_path);
// Open the command for reading
fp = popen(NETSTAT_PATH " -f inet -rn", "r");
if (fp == NULL) {
err = ERR_IPV4_SEE_ERRNO;
goto end;
}
line = buffer;
// Read the output a line at a time
while (fgets(line, buffer_size - total_bytes_read - 1, fp) != NULL) {
uint32_t bytes_read = strlen(line);
total_bytes_read += bytes_read;
if (bytes_read > 0 && line[bytes_read - 1] != '\n') {
buffer_size += IPV4_GET_ROUTE_BUFFER_CHUNK_SIZE;
realloc_buffer = realloc(buffer, buffer_size);
if (realloc_buffer) {
buffer = realloc_buffer;
} else {
err = ERR_IPV4_SEE_ERRNO;
goto cleanup;
}
}
line = buffer + total_bytes_read;
}
cleanup:
if (pclose(fp))
log_warn("Could not close netstat pipe (%s).\n", strerror(errno));
if (err)
goto end;
// reserve enough memory (256 shorts)
// to make sure not to access out of bounds later,
// for ipv4 only unsigned short is allowed
unsigned short flag_table[256] = { 0 };
/*
* Fill the flag_table now. Unfortunately it is not easy
* to do this in a more elegant way. The problem here
* is that these are already preprocessor macros and
* we can't use them as arguments for another macro which
* would include the #ifdef statements.
*
* Also, not all flags might be allowed in the context
* of ipv4, and the code depends on which ones are
* actually implemented on the target platform, which
* might also be varying between Mac OS X versions.
*
*/
#ifdef RTF_PROTO1 // Protocol specific routing flag #1
flag_table['1'] = RTF_PROTO1 & USHRT_MAX;
#endif
#ifdef RTF_PROTO2 // Protocol specific routing flag #2
flag_table['2'] = RTF_PROTO2 & USHRT_MAX;
#endif
#ifdef RTF_PROTO3 // Protocol specific routing flag #3
flag_table['3'] = RTF_PROTO3 & USHRT_MAX;
#endif
#ifdef RTF_BLACKHOLE // Just discard packets (during updates)
flag_table['B'] = RTF_BLACKHOLE & USHRT_MAX;
#endif
#ifdef RTF_BROADCAST // The route represents a broadcast address
flag_table['b'] = RTF_BROADCAST & USHRT_MAX;
#endif
#ifdef RTF_CLONING // Generate new routes on use
flag_table['C'] = RTF_CLONING & USHRT_MAX;
#endif
#ifdef RTF_PRCLONING // Protocol-specified generate new routes on use
flag_table['c'] = RTF_PRCLONING & USHRT_MAX;
#endif
#ifdef RTF_DYNAMIC // Created dynamically (by redirect)
flag_table['D'] = RTF_DYNAMIC & USHRT_MAX;
#endif
#ifdef RTF_GATEWAY // Destination requires forwarding by intermediary
flag_table['G'] = RTF_GATEWAY & USHRT_MAX;
#endif
#ifdef RTF_HOST // Host entry (net otherwise)
flag_table['H'] = RTF_HOST & USHRT_MAX;
#endif
#ifdef RTF_IFSCOPE // Route is associated with an interface scope
flag_table['I'] = RTF_IFSCOPE & USHRT_MAX;
#endif
#ifdef RTF_IFREF // Route is holding a reference to the interface
flag_table['i'] = RTF_IFREF & USHRT_MAX;
#endif
#ifdef RTF_LLINFO // Valid protocol to link address translation
flag_table['L'] = RTF_LLINFO & USHRT_MAX;
#endif
#ifdef RTF_MODIFIED // Modified dynamically (by redirect)
flag_table['M'] = RTF_MODIFIED & USHRT_MAX;
#endif
#ifdef RTF_MULTICAST // The route represents a multicast address
flag_table['m'] = RTF_MULTICAST & USHRT_MAX;
#endif
#ifdef RTF_REJECT // Host or net unreachable
flag_table['R'] = RTF_REJECT & USHRT_MAX;
#endif
#ifdef RTF_ROUTER // Host is a default router
flag_table['r'] = RTF_ROUTER & USHRT_MAX;
#endif
#ifdef RTF_STATIC // Manually added
flag_table['S'] = RTF_STATIC & USHRT_MAX;
#endif
#ifdef RTF_UP // Route usable
flag_table['U'] = RTF_UP & USHRT_MAX;
#endif
#ifdef RTF_WASCLONED // Route was generated as a result of cloning
flag_table['W'] = RTF_WASCLONED & USHRT_MAX;
#endif
#ifdef RTF_XRESOLVE // External daemon translates proto to link address
flag_table['X'] = RTF_XRESOLVE & USHRT_MAX;
#endif
#ifdef RTF_PROXY // Proxying; cloned routes will not be scoped
flag_table['Y'] = RTF_PROXY & USHRT_MAX;
#endif
#endif
if (total_bytes_read == 0) {
log_debug("Routing table is empty.\n");
err = ERR_IPV4_PROC_NET_ROUTE;
goto end;
}
buffer[total_bytes_read] = '\0';
// Skip first line
start = strchr(buffer, '\n');
if (start == NULL) {
log_debug("Routing table is malformed.\n");
err = ERR_IPV4_PROC_NET_ROUTE;
goto end;
}
start++;
#if !HAVE_PROC_NET_ROUTE
if (strstr(buffer, "Ref") != NULL)
have_ref = 1;
if (strstr(buffer, "Use") != NULL)
have_use = 1;
// Skip 3 more lines from netstat output on Mac OS X and on FreeBSD
start = strchr(start, '\n');
start = strchr(++start, '\n');
start = strchr(++start, '\n');
if (start == NULL) {
log_debug("Routing table is malformed.\n");
err = ERR_IPV4_PROC_NET_ROUTE;
goto end;
}
#endif
if (strchr(start, '\n') == NULL) {
log_debug("Routing table is malformed.\n");
err = ERR_IPV4_PROC_NET_ROUTE;
goto end;
}
// Look for the route
line = strtok_r(start, "\n", &saveptr1);
while (line != NULL) {
char *iface;
uint32_t dest, mask, gtw;
unsigned short flags;
#if HAVE_PROC_NET_ROUTE
unsigned short irtt;
short metric;
unsigned long mtu, window;
iface = strtok_r(line, "\t", &saveptr2);
dest = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16);
gtw = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16);
flags = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16);
strtok_r(NULL, "\t", &saveptr2); // "RefCnt"
strtok_r(NULL, "\t", &saveptr2); // "Use"
metric = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16);
mask = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16);
mtu = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16);
window = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16);
irtt = strtoul(strtok_r(NULL, "\t", &saveptr2), NULL, 16);
#else
/* parse netstat output on Mac OS X and BSD */
char tmp_ip_string[16];
struct in_addr dstaddr;
int pos;
char *tmpstr;
log_debug_details("\n");
log_debug_details("line: %s\n", line);
saveptr3 = NULL;
dest = UINT32_MAX;
mask = UINT32_MAX;
// "Destination"
tmpstr = strtok_r(line, " ", &saveptr2);
if (strncmp(tmpstr, "Internet6", 9) == 0) {
// we have arrived at the end of ipv4 output
goto end;
}
log_debug_details("- Destination: %s\n", tmpstr);
// replace literal "default" route by IPV4 numbers-and-dots notation
if (strncmp(tmpstr, "default", 7) == 0) {
dest = 0;
mask = 0;
} else {
int is_mask_set = 0;
char *tmp_position;
int dot_count = -1;
if (strchr(tmpstr, '/') != NULL) {
// 123.123.123.123/30 style
// 123.123.123/24 style
// 123.123/24 style
// break CIDR up into address and mask part
strcpy(tmp_ip_string, strtok_r(tmpstr, "/", &saveptr3));
mask = strtoul(saveptr3, NULL, 10);
// convert from CIDR to ipv4 mask
mask = 0xffffffff << (32-mask);
is_mask_set = 1;
} else if (inet_aton(tmpstr, &dstaddr)) {
// 123.123.123.123 style
// 123.123.123 style
// 123.123 style
strcpy(tmp_ip_string, tmpstr);
is_mask_set = 0;
}
// Process Destination IP Expression
tmp_position = tmp_ip_string;
while (tmp_position != NULL) {
++dot_count;
tmp_position = strchr(++tmp_position, '.');
}
for (int i = dot_count; i < 3; i++)
strcat(tmp_ip_string, ".0");
if (inet_aton(tmp_ip_string, &dstaddr))
dest = dstaddr.s_addr;
if (!is_mask_set) {
// convert from CIDR to ipv4 mask
mask = 0xffffffff << (32-((dot_count + 1) * 8));
}
// convert mask to reversed byte order
mask = ((mask & 0xff000000) >> 24)
| ((mask & 0xff0000) >> 8)
| ((mask & 0xff00) << 8)
| ((mask & 0xff) << 24);
}
log_debug_details("- Destination IP Hex: %x\n", dest);
log_debug_details("- Destination Mask Hex: %x\n", mask);
// "Gateway"
gtw = 0;
if (inet_aton(strtok_r(NULL, " ", &saveptr2), &dstaddr)) {
gtw = dstaddr.s_addr;
log_debug_details("- Gateway Mask Hex: %x\n", gtw);
}
// "Flags"
tmpstr = strtok_r(NULL, " ", &saveptr2);
flags = 0;
// this is the reason for the 256 entries mentioned above
for (pos = 0; pos < strlen(tmpstr); pos++)
flags |= flag_table[(unsigned char)tmpstr[pos]];
if (have_ref)
strtok_r(NULL, " ", &saveptr2); // "Ref"
if (have_use)
strtok_r(NULL, " ", &saveptr2); // "Use"
iface = strtok_r(NULL, " ", &saveptr2); // "Netif"
log_debug_details("- Interface: %s\n", iface);
#endif
/*
* Now that we have parsed a routing entry, check if it
* matches the current argument to the function call.
* In rtentry we have integer representation, i.e.
* the most significant byte corresponds to the last
* number of dotted-number representation and vice versa.
* In this representation ( address & mask ) is the network
* address.
* The routing algorithm does the following:
* First, check if the network address we are looking for
* falls into the network for the current route.
* Therefore, calculate the network address for both, the
* current route and for the destination we are searching.
* If the destination is a smaller network (for instance a
* single host), we have to mask again with the netmask of
* the routing entry that we are checking in order to obtain
* the network address in the context of the current route.
* If both network addresses match, we have found a candidate
* for a route.
* However, there might be another route for a smaller network,
* therefore repeat this and only store the resulting route
* when the mask is at least as large as the one we may
* have already found in a previous iteration (a larger
* netmask corresponds to a smaller network in this
* representation, and has a higher priority by default).
* Also, only consider routing entries for which the
* netmask is not larger than the netmask used in the
* argument when calling the function - so that we can
* distinguish between different routing entries for subnets
* of different size but with the same network address.
* For routing entries with the same destination and
* the same netmask the metric can be used for adjusting
* the priority (this is not supported on mac).
* If the metric is larger than one found for this network
* size, skip the current route (smaller numbers denote
* less hops and therefore have a higher priority).
*/
if (((dest & mask) == (rtdest & rtmask & mask))
&& (mask >= route_mask(route).s_addr)
&& (mask <= rtmask)
&& ((route_iface(route) == NULL)
|| (strcmp(iface, route_iface(route)) == 0)
|| (strlen(route_iface(route)) > 0
&& route_iface(route)[0] == '!'
&& strcmp(iface, &route_iface(route)[1]) != 0)
)) {
#if HAVE_PROC_NET_ROUTE
if (((mask == route_mask(route).s_addr)
&& (metric <= route->rt_metric))
|| (rtfound == 0)
|| (mask > route_mask(route).s_addr)) {
#endif
rtfound = 1;
// Requested route has been found
route_dest(route).s_addr = dest;
route_mask(route).s_addr = mask;
route_gtw(route).s_addr = gtw;
route->rt_flags = flags;
free(route_iface(route));
route_iface(route) = strdup(iface);
if (!route_iface(route)) {
err = ERR_IPV4_NO_MEM;
goto end;
}
#if HAVE_PROC_NET_ROUTE
// we do not have these values from Mac OS X netstat,
// so stay with defaults denoted by values of 0
route->rt_metric = metric;
route->rt_mtu = mtu;
route->rt_window = window;
route->rt_irtt = irtt;
}
#else
log_debug_details("- route matches\n");
#endif
}
line = strtok_r(NULL, "\n", &saveptr1);
}
end:
free(buffer);
if (err)
return err;
if (rtfound == 0) {
// should not occur anymore unless there is no default route
log_debug("Route not found.\n");
// at least restore input values
route_dest(route).s_addr = rtdest;
route_mask(route).s_addr = rtmask;
route_gtw(route).s_addr = rtgtw;
return ERR_IPV4_NO_SUCH_ROUTE;
}
return 0;
}
static int ipv4_set_route(struct rtentry *route)
{
#ifdef HAVE_RT_ENTRY_WITH_RT_DST
/* we can copy rtentry struct directly between openfortivpn and kernel */
log_debug("ip route add %s\n", ipv4_show_route(route));
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
return ERR_IPV4_SEE_ERRNO;
if (ioctl(sockfd, SIOCADDRT, route) == -1) {
if (close(sockfd))
log_warn("Could not close socket for setting route (%s).\n",
strerror(errno));
return ERR_IPV4_SEE_ERRNO;
}
if (close(sockfd))
log_warn("Could not close socket for setting route: %s\n",
strerror(errno));
#else
/* we have to use the route command as tool for route manipulation */
char cmd[SHOW_ROUTE_BUFFER_SIZE];
if (access("/sbin/route", F_OK) != 0) {
log_error("/sbin/route: %s.\n", strerror(errno));
return 1;
}
strcpy(cmd, "/sbin/route -n add ");
if (route->rt_flags & RTF_HOST)
strcat(cmd, "-host ");
else
strcat(cmd, "-net ");
strncat(cmd, inet_ntoa(route_dest(route)), 15);
if (!(route->rt_flags & RTF_HOST)) {
strcat(cmd, " -netmask ");
strncat(cmd, inet_ntoa(route_mask(route)), 15);
}
if (route->rt_flags & RTF_GATEWAY) {
strcat(cmd, " ");
strncat(cmd, inet_ntoa(route_gtw(route)), 15);
} else {
strcat(cmd, " -interface ");
strncat(cmd, route_iface(route),
SHOW_ROUTE_BUFFER_SIZE - strlen(cmd) - 1);
}
log_debug("%s\n", cmd);
int res = system(cmd);
if (res == -1)
return ERR_IPV4_SEE_ERRNO;
#endif
return 0;
}
static int ipv4_del_route(struct rtentry *route)
{
#ifdef HAVE_RT_ENTRY_WITH_RT_DST
/* we can copy rtentry struct directly between openfortivpn and kernel */
struct rtentry tmp;
int sockfd;
log_debug("ip route del %s\n", ipv4_show_route(route));
// Copy route to a temp variable to clear some of its properties
memcpy(&tmp, route, sizeof(tmp));
tmp.rt_metric = 0;
tmp.rt_mtu = 0;
tmp.rt_window = 0;
tmp.rt_irtt = 0;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
return ERR_IPV4_SEE_ERRNO;
if (ioctl(sockfd, SIOCDELRT, &tmp) == -1) {
if (close(sockfd))
log_warn("Could not close socket for deleting route (%s).\n",
strerror(errno));
return ERR_IPV4_SEE_ERRNO;
}
if (close(sockfd))
log_warn("Could not close socket for deleting route (%s).\n",
strerror(errno));
#else
char cmd[SHOW_ROUTE_BUFFER_SIZE];
if (access("/sbin/route", F_OK) != 0) {
log_error("/sbin/route: %s.\n", strerror(errno));
return 1;
}
strcpy(cmd, "/sbin/route -n delete ");
if (route->rt_flags & RTF_HOST)
strcat(cmd, "-host ");
else
strcat(cmd, "-net ");
strncat(cmd, inet_ntoa(route_dest(route)), 15);
if (!(route->rt_flags & RTF_HOST)) {
strcat(cmd, " -netmask ");
strncat(cmd, inet_ntoa(route_mask(route)), 15);
}
if (route->rt_flags & RTF_GATEWAY) {
strcat(cmd, " ");
strncat(cmd, inet_ntoa(route_gtw(route)), 15);
} else {
strcat(cmd, " -interface ");
strncat(cmd, route_iface(route),
SHOW_ROUTE_BUFFER_SIZE - strlen(cmd) - 1);
}
log_debug("%s\n", cmd);
int res = system(cmd);
if (res == -1)
return ERR_IPV4_SEE_ERRNO;
#endif
return 0;
}
int ipv4_protect_tunnel_route(struct tunnel *tunnel)
{
struct rtentry *gtw_rt = &tunnel->ipv4.gtw_rt;
struct rtentry *def_rt = &tunnel->ipv4.def_rt;
int ret;
route_init(def_rt);
route_init(gtw_rt);
// Back up default route
route_dest(def_rt).s_addr = inet_addr("0.0.0.0");
route_mask(def_rt).s_addr = inet_addr("0.0.0.0");
route_iface(def_rt) = malloc(strlen(tunnel->ppp_iface) + 2);
if (!route_iface(def_rt)) {
log_error("malloc: %s\n", strerror(errno));
return ERR_IPV4_SEE_ERRNO;
}
sprintf(route_iface(def_rt), "!%s", tunnel->ppp_iface);
ret = ipv4_get_route(def_rt);
if (ret != 0) {
log_warn("Could not get current default route (%s).\n",
err_ipv4_str(ret));
log_warn("Protecting tunnel route has failed. But this can be working except for some cases.\n");
goto err_destroy_def_rt;
}
// Set the up a route to the tunnel gateway
route_dest(gtw_rt).s_addr = tunnel->config->gateway_ip.s_addr;
route_mask(gtw_rt).s_addr = inet_addr("255.255.255.255");
route_iface(gtw_rt) = malloc(strlen(tunnel->ppp_iface) + 2);
if (!route_iface(gtw_rt)) {
log_error("malloc: %s\n", strerror(errno));
return ERR_IPV4_SEE_ERRNO;
}
sprintf(route_iface(gtw_rt), "%s", tunnel->ppp_iface);
ret = ipv4_get_route(gtw_rt);
if ((ret == 0)
&& (route_dest(gtw_rt).s_addr == tunnel->config->gateway_ip.s_addr)
&& (route_mask(gtw_rt).s_addr == inet_addr("255.255.255.255"))) {
log_debug("Removing wrong route to vpn server...\n");
log_debug("ip route show %s\n", ipv4_show_route(gtw_rt));
ipv4_del_route(gtw_rt);
}
sprintf(route_iface(gtw_rt), "!%s", tunnel->ppp_iface);
ret = ipv4_get_route(gtw_rt);
if (ret != 0) {
log_warn("Could not get route to gateway (%s).\n",
err_ipv4_str(ret));
log_warn("Protecting tunnel route has failed. But this can be working except for some cases.\n");
goto err_destroy_gtw_rt;
}
route_dest(gtw_rt).s_addr = tunnel->config->gateway_ip.s_addr;
route_mask(gtw_rt).s_addr = inet_addr("255.255.255.255");
gtw_rt->rt_flags |= RTF_HOST;
gtw_rt->rt_metric = 0;
tunnel->ipv4.route_to_vpn_is_added = 1;
log_debug("Setting route to vpn server...\n");
log_debug("ip route show %s\n", ipv4_show_route(gtw_rt));
ret = ipv4_set_route(gtw_rt);
if (ret == ERR_IPV4_SEE_ERRNO && errno == EEXIST) {
log_warn("Route to vpn server exists already.\n");
tunnel->ipv4.route_to_vpn_is_added = 0;
} else if (ret != 0)
log_warn("Could not set route to vpn server (%s).\n",
err_ipv4_str(ret));
return 0;
err_destroy_gtw_rt:
route_destroy(gtw_rt);
err_destroy_def_rt:
route_destroy(def_rt);
tunnel->ipv4.route_to_vpn_is_added = 0;
return ret;
}
#if HAVE_USR_SBIN_PPPD
static void add_text_route(struct tunnel *tunnel, const char *dest,
const char *mask, const char *gw)
{
size_t l0, l1;
static const char fmt[] = ",%s/%s/%s";
static const char trigger[] = "openfortivpn";
char **target = &tunnel->config->pppd_ipparam;
char *ptr;
if (*target == NULL || strncmp(*target, trigger, strlen(trigger)))
return;
if (!dest || !mask || !gw)
return;
log_info("Registering route %s/%s via %s\n", dest, mask, gw);
l0 = strlen(*target);
l1 = strlen(fmt) + strlen(dest) + strlen(mask) + strlen(gw) + 1;
ptr = realloc(*target, l0 + l1);
if (ptr) {
*target = ptr;
snprintf(*target + l0, l1, fmt, dest, mask, gw);
} else {
log_error("realloc: %s\n", strerror(errno));
}
}
#endif
int ipv4_add_split_vpn_route(struct tunnel *tunnel, char *dest, char *mask,
char *gateway)
{
struct rtentry *route;
char env_var[24]; // strlen("VPN_ROUTE_GATEWAY_") + strlen("65535") + 1
#if HAVE_USR_SBIN_PPPD
add_text_route(tunnel, dest, mask, gateway);
#endif
if (tunnel->ipv4.split_routes == MAX_SPLIT_ROUTES)
return ERR_IPV4_NO_MEM;
if ((tunnel->ipv4.split_rt == NULL)
|| ((tunnel->ipv4.split_routes % STEP_SPLIT_ROUTES) == 0)) {
void *new_ptr
= realloc(tunnel->ipv4.split_rt,
(size_t) (tunnel->ipv4.split_routes + STEP_SPLIT_ROUTES)
* sizeof(*(tunnel->ipv4.split_rt)));
if (new_ptr == NULL)
return ERR_IPV4_NO_MEM;
tunnel->ipv4.split_rt = new_ptr;
}
assert(tunnel->ipv4.split_routes >= 0 &&
tunnel->ipv4.split_routes < MAX_SPLIT_ROUTES);
sprintf(env_var, "VPN_ROUTE_DEST_%d", tunnel->ipv4.split_routes);
setenv(env_var, dest, 0);
sprintf(env_var, "VPN_ROUTE_MASK_%d", tunnel->ipv4.split_routes);
setenv(env_var, mask, 0);
if (gateway != NULL) {
sprintf(env_var, "VPN_ROUTE_GATEWAY_%d", tunnel->ipv4.split_routes);
setenv(env_var, gateway, 0);
}
route = &tunnel->ipv4.split_rt[tunnel->ipv4.split_routes++];
route_init(route);
route_dest(route).s_addr = inet_addr(dest);
route_mask(route).s_addr = inet_addr(mask);
if (gateway != NULL) {
route_gtw(route).s_addr = inet_addr(gateway);
route->rt_flags |= RTF_GATEWAY;
} else {
free(route_iface(route));
route_iface(route) = strdup(tunnel->ppp_iface);
if (!route_iface(route))
return ERR_IPV4_NO_MEM;
}
return 0;
}
static int ipv4_set_split_routes(struct tunnel *tunnel)
{
for (int i = 0; i < tunnel->ipv4.split_routes; i++) {
struct rtentry *route;
int ret;
route = &tunnel->ipv4.split_rt[i];
// check if the route to be added is not the one to the gateway itself
if (route_dest(route).s_addr == route_dest(&tunnel->ipv4.gtw_rt).s_addr) {
log_debug("Skipping route to tunnel gateway (%s).\n",
ipv4_show_route(route));
continue;
}
free(route_iface(route));
route_iface(route) = strdup(tunnel->ppp_iface);
if (!route_iface(route))
return ERR_IPV4_NO_MEM;
if (route_gtw(route).s_addr == tunnel->ipv4.ip_addr.s_addr)
route_gtw(route).s_addr = 0;
if (route_gtw(route).s_addr == 0)
route->rt_flags &= ~RTF_GATEWAY;
if (route_gtw(route).s_addr != 0)
route->rt_flags |= RTF_GATEWAY;
ret = ipv4_set_route(route);
if (ret == ERR_IPV4_SEE_ERRNO && errno == EEXIST)
log_info("Route to gateway exists already.\n");
else if (ret != 0)
log_warn("Could not set route to tunnel gateway (%s).\n",
err_ipv4_str(ret));
}
return 0;
}
static int ipv4_set_default_routes(struct tunnel *tunnel)
{
int ret;
struct rtentry *def_rt = &tunnel->ipv4.def_rt;
struct rtentry *ppp_rt = &tunnel->ipv4.ppp_rt;
struct vpn_config *cfg = tunnel->config;
route_init(ppp_rt);
if (cfg->half_internet_routes == 0) {
// Delete the current default route
log_debug("Deleting the current default route...\n");
ret = ipv4_del_route(def_rt);
if (ret != 0)
log_warn("Could not delete the current default route (%s).\n",
err_ipv4_str(ret));
// Set the new default route
// ip route add to 0/0 dev ppp0
route_dest(ppp_rt).s_addr = inet_addr("0.0.0.0");
route_mask(ppp_rt).s_addr = inet_addr("0.0.0.0");
route_gtw(ppp_rt).s_addr = inet_addr("0.0.0.0");
log_debug("Setting new default route...\n");
free(route_iface(ppp_rt));
route_iface(ppp_rt) = strdup(tunnel->ppp_iface);
if (!route_iface(ppp_rt))
return ERR_IPV4_NO_MEM;
if (route_gtw(ppp_rt).s_addr == tunnel->ipv4.ip_addr.s_addr)
route_gtw(ppp_rt).s_addr = 0;
if (route_gtw(ppp_rt).s_addr == 0)
ppp_rt->rt_flags &= ~RTF_GATEWAY;
if (route_gtw(ppp_rt).s_addr != 0)
ppp_rt->rt_flags |= RTF_GATEWAY;
ret = ipv4_set_route(ppp_rt);
if (ret == ERR_IPV4_SEE_ERRNO && errno == EEXIST) {
log_warn("Default route exists already.\n");
} else if (ret != 0) {
log_warn("Could not set the new default route (%s).\n",
err_ipv4_str(ret));
}
} else {
// Emulate default routes as two "half internet" routes
// This allows for e.g. DHCP renewing default routes without
// breaking the tunnel
log_debug("Setting new half-internet routes...\n");
route_dest(ppp_rt).s_addr = inet_addr("0.0.0.0");
route_mask(ppp_rt).s_addr = inet_addr("128.0.0.0");
free(route_iface(ppp_rt));
route_iface(ppp_rt) = strdup(tunnel->ppp_iface);
if (!route_iface(ppp_rt))
return ERR_IPV4_NO_MEM;
if (route_gtw(ppp_rt).s_addr == tunnel->ipv4.ip_addr.s_addr)
route_gtw(ppp_rt).s_addr = 0;
if (route_gtw(ppp_rt).s_addr == 0)
ppp_rt->rt_flags &= ~RTF_GATEWAY;
if (route_gtw(ppp_rt).s_addr != 0)
ppp_rt->rt_flags |= RTF_GATEWAY;
ret = ipv4_set_route(ppp_rt);
if (ret == ERR_IPV4_SEE_ERRNO && errno == EEXIST) {
log_warn("0.0.0.0/1 route exists already.\n");
} else if (ret != 0) {
log_warn("Could not set the new 0.0.0.0/1 route (%s).\n",
err_ipv4_str(ret));
}
route_dest(ppp_rt).s_addr = inet_addr("128.0.0.0");
ret = ipv4_set_route(ppp_rt);
if (ret == ERR_IPV4_SEE_ERRNO && errno == EEXIST) {
log_warn("128.0.0.0/1 route exists already.\n");
} else if (ret != 0) {
log_warn("Could not set the new 128.0.0.0/1 route (%s).\n",
err_ipv4_str(ret));
}
}
return 0;
}