This repository has been archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ifn.c
3600 lines (3093 loc) · 88.4 KB
/
ifn.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) 2018, 2019, 2020 Tim Kuijsten
*
* Permission to use, copy, modify, and distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright
* notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/queue.h>
#include <sys/event.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <net/if.h>
#include <net/if_tun.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet6/in6_var.h>
#include <openssl/evp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "antireplay.h"
#include "util.h"
#include "wiresep.h"
#include "wireprot.h"
#define ND6_INFINITE_LIFETIME 0xffffffff
/* Times in microseconds */
#define REJECT_AFTER_MESSAGES (((uint64_t) 2<<60) - 1)
#define REJECT_AFTER_TIME 180000000
#define REKEY_AFTER_MESSAGES (((uint64_t) 2<<48) - 1)
#define REKEY_AFTER_TIME 120000000
#define REKEY_ATTEMPT_TIME 90000000
#define REKEY_TIMEOUT 5000000
#define KEEPALIVE_TIMEOUT 10000000
#define MINIP6HDR 40
#define MINIP4HDR 20
#define MINIPHDR 20
#define MAXIPHDR 40 /* ip6 header without options */
#define TUNHDRSIZ 4
#define WSTUNMTU 1408
#define TAGLEN 16
#define DATAHEADERLEN 16
#define MAXQUEUEPACKETS 50
#define MAXQUEUEPACKETSDATASZ ((size_t)(MAXSCRATCH * MAXQUEUEPACKETS))
#define MINDATA (1 << 21) /* minimum dynamic memory without peers / packets */
#define MAXSTACK (1 << 15) /* 32 KB should be enough */
#define MAXCONNRETRY 10
#ifdef DEBUG
#define MAXCORE MAXQUEUEPACKETSDATASZ
#else
#define MAXCORE 0
#endif
/*
* 64-bit integer that represents microseconds.
*/
typedef uint64_t utime_t;
extern int background, verbose;
union inet_addr {
struct in6_addr addr6;
struct in_addr addr4;
};
/*
* All session ids in the sesstent, sessnext and session structures are in 64
* bits in host byte order. This is to represent the inactive session -1. All 32
* bit session ids are in wire format, which is little-endian. Also the different
* timers used use a session id in host byte order.
*/
/*
* Tentative sessions are used when we have data to send to a peer but no active
* current session. A rekey timer will be set until rekey-attempt-time or a
* session is established.
*/
struct sesstent {
enum { STINACTIVE, INITREQ, INITSENT, RESPRECVD } state;
int64_t id; /* host byte order */
utime_t lastreq;
};
/*
* Used when a peer started negotiating a new session.
*/
struct sessnext {
enum { SNINACTIVE, GOTKEYS, RESPSENT } state;
utime_t lastvrfyinit;
utime_t start;
int64_t id; /* host byte order */
int64_t peerid; /* host byte order */
EVP_AEAD_CTX sendctx;
EVP_AEAD_CTX recvctx;
};
/*
* The "start" field indicates when a session is started after the handshake
* completes. While the handshake is still in progress it signifies the moment
* the first handshake init was sent.
* Note: an "id" of 0 is a valid, although unlikely, session id.
*/
struct session {
struct antireplay arrecv; /* receive counter bitmap */
EVP_AEAD_CTX sendctx;
EVP_AEAD_CTX recvctx;
struct peer *peer;
utime_t start; /* whenever handshake completes (or
* first hs while still tentative) */
utime_t expack; /* time before either data or a
* keepalive is expected from the peer
*/
uint64_t nextnonce; /* next number for the next packet to
* send */
uint32_t id; /* wire format, little-endian */
uint32_t peerid; /* wire format, little-endian */
char initiator;
char kaset; /* is the keepalive timer set? */
};
struct cidraddr {
union sockaddr_inet addr;
struct in6_addr v6addrmasked;
struct in6_addr v6mask;
struct in_addr v4addrmasked;
struct in_addr v4mask;
size_t prefixlen;
};
/* queued packet */
struct qpacket {
uint8_t *data;
size_t datasize;
SIMPLEQ_ENTRY(qpacket) qpackets;
};
/*
* A connected socket plus its local port.
*/
struct portsock {
int s; /* socket */
in_port_t p; /* transport layer port in network byte order */
};
struct peer {
char *name;
uint32_t id; /* peer id */
int sock; /* active socket */
int sockisv6;
size_t prefixlen;
union sockaddr_inet fsa;
struct sesstent sesstent;
struct sessnext sessnext;
struct session *scurr;
struct session *sprev;
SIMPLEQ_HEAD(, qpacket) qpacketlist;
size_t qpackets;
size_t qpacketsdatasz;
struct cidraddr **allowedips;
size_t allowedipssize;
struct portsock *portsock6;
size_t portsock6count;
struct portsock *portsock4;
size_t portsock4count;
};
struct ifn {
uint32_t id;
char *ifname;
char *ifdesc;
struct cidraddr **ifaddrs;
size_t ifaddrssize;
struct sockaddr_in6 *laddr6; /* local IPv6 address to port mapping */
size_t laddr6count;
struct sockaddr_in *laddr4; /* local IPv4 address to port mapping */
size_t laddr4count;
wskey mac1key;
wskey cookiekey;
struct peer **peers;
size_t peerssize;
};
static uid_t uid;
static gid_t gid;
/* stats */
static struct {
size_t devin; size_t devinerr; size_t devout; size_t devouterr;
size_t devinsz; size_t devoutsz;
size_t queuein; size_t queueinerr; size_t queueout; size_t queueouterr;
size_t queueinsz; size_t queueoutsz;
size_t sockin; size_t sockinerr; size_t sockout; size_t sockouterr;
size_t sockinsz; size_t sockoutsz;
size_t initin; size_t initinerr; size_t initout; size_t initouterr;
size_t respin; size_t respinerr; size_t respout; size_t respouterr;
size_t proxin; size_t proxinerr; size_t proxout; size_t proxouterr;
size_t enclin; size_t enclinerr; size_t enclout; size_t enclouterr;
size_t corrupted;
size_t invalidmac;
size_t invalidpeer;
} stats;
static int kq, tund, pport, eport, doterm, logstats;
static struct ifn *ifn;
static uint8_t msg[MAXSCRATCH];
static utime_t now;
static uint8_t nonce[16] = { 0 };
static size_t sesscounter;
static const EVP_AEAD *aead;
static void
handlesig(int signo)
{
switch (signo) {
case SIGUSR1:
logstats = 1;
break;
case SIGINT:
/* FALLTHROUGH */
case SIGTERM:
doterm = 1;
break;
default:
logwarnx("%s unexpected signal %d %s", ifn->ifname, signo,
strsignal(signo));
break;
}
}
static void
logsessinfo(const char *pre, const struct session *sess)
{
if (sess == NULL) {
logwarnx("%s %s NULL", ifn->ifname, pre ? pre : "");
return;
}
logwarnx("%s %s %c %08x:%08x %llu/%llu %lld %lld %s",
ifn->ifname,
pre ? pre : "",
sess->initiator ? 'I' : 'R',
le32toh(sess->id),
le32toh(sess->peerid),
sess->arrecv.maxseqnum,
sess->nextnonce,
sess->start,
sess->expack,
sess->kaset ? "keepalive" : "");
}
static void
logpeerinfo(const struct peer *peer)
{
char addrstr[MAXADDRSTR];
size_t n;
logwarnx("%s peer %u %s", ifn->ifname, peer->id, peer->name);
logwarnx("%s sock %d", ifn->ifname, peer->sock);
if (addrtostr(addrstr, sizeof(addrstr), (struct sockaddr *)&peer->fsa,
0) != -1)
logwarnx("%s fsa %s", ifn->ifname, addrstr);
logwarnx("%s allowed ips %zu", ifn->ifname, peer->allowedipssize);
for (n = 0; n < peer->allowedipssize; n++) {
if (addrtostr(addrstr, sizeof(addrstr),
(struct sockaddr *)&peer->allowedips[n]->addr, 1) != -1) {
logwarnx("%s %s/%zu", ifn->ifname, addrstr,
peer->allowedips[n]->prefixlen);
}
}
logwarnx("%s queue %zu %zu bytes", ifn->ifname, peer->qpackets, peer->qpacketsdatasz);
logsessinfo(" sess curr", peer->scurr);
logsessinfo(" sess prev", peer->sprev);
}
static void
ifn_loginfo(void)
{
char addrstr[MAXADDRSTR];
size_t n;
logwarnx("%s id %u", ifn->ifname, ifn->id);
for (n = 0; n < ifn->ifaddrssize; n++) {
if (addrtostr(addrstr, sizeof(addrstr),
(struct sockaddr *)&ifn->ifaddrs[n]->addr, 1) != -1) {
logwarnx("%s ifaddr %s/%zu", ifn->ifname, addrstr,
ifn->ifaddrs[n]->prefixlen);
}
}
for (n = 0; n < ifn->laddr6count; n++) {
if (addrtostr(addrstr, sizeof(addrstr),
(struct sockaddr *)&ifn->laddr6[n], 0) != -1) {
logwarnx("%s local ip6 %s", ifn->ifname, addrstr);
}
}
for (n = 0; n < ifn->laddr4count; n++) {
if (addrtostr(addrstr, sizeof(addrstr),
(struct sockaddr *)&ifn->laddr4[n], 0) != -1) {
logwarnx("%s local ip4 %s", ifn->ifname, addrstr);
}
}
for (n = 0; n < ifn->peerssize; n++)
logpeerinfo(ifn->peers[n]);
logwarnx("%s stats packets in/out (errors in/out) [bytes in/out]", ifn->ifname);
logwarnx("%s dev %zu/%zu (%zu/%zu) %zu/%zu", ifn->ifname, stats.devin, stats.devout,
stats.devinerr, stats.devouterr, stats.devinsz, stats.devoutsz);
logwarnx("%s queue %zu/%zu (%zu/%zu) %zu/%zu", ifn->ifname, stats.queuein,
stats.queueout, stats.queueinerr, stats.queueouterr,
stats.queueinsz, stats.queueoutsz);
logwarnx("%s sock %zu/%zu (%zu/%zu) %zu/%zu", ifn->ifname, stats.sockin,
stats.sockout, stats.sockinerr, stats.sockouterr, stats.sockinsz,
stats.sockoutsz);
logwarnx("%s init %zu/%zu (%zu/%zu)", ifn->ifname, stats.initin, stats.initout,
stats.initinerr, stats.initouterr);
logwarnx("%s resp %zu/%zu (%zu/%zu)", ifn->ifname, stats.respin, stats.respout,
stats.respinerr, stats.respouterr);
logwarnx("%s encl %zu/%zu (%zu/%zu)", ifn->ifname, stats.enclin, stats.enclout,
stats.enclinerr, stats.enclouterr);
logwarnx("%s prox %zu/%zu (%zu/%zu)", ifn->ifname, stats.proxin, stats.proxout,
stats.proxinerr, stats.proxouterr);
logwarnx("%s total corrupted/invalid mac/invalid peer %zu/%zu/%zu", ifn->ifname,
stats.corrupted, stats.invalidmac, stats.invalidpeer);
}
/*
* Set the primary address and destination address of an interface.
*
* Return 0 on success and -1 on failure with errno set.
*/
static int
assignaddr6(const char *ifname, const struct cidraddr *ca)
{
struct in6_aliasreq addreq;
struct sockaddr_in6 mask;
int s;
if (ifname == NULL || ca == NULL) {
errno = EINVAL;
return -1;
}
memset(&addreq, 0, sizeof(addreq));
if (strlcpy(addreq.ifra_name, ifname, sizeof(addreq.ifra_name)) >=
sizeof(addreq.ifra_name)) {
errno = EINVAL;
return -1;
}
addreq.ifra_lifetime.ia6t_pltime = ND6_INFINITE_LIFETIME;
addreq.ifra_lifetime.ia6t_vltime = ND6_INFINITE_LIFETIME;
memset(&mask, 0, sizeof(mask));
mask.sin6_len = sizeof(mask);
mask.sin6_family = AF_INET6;
mask.sin6_addr = ca->v6mask;
memcpy(&addreq.ifra_addr, &ca->addr,
MIN(sizeof addreq.ifra_addr, sizeof ca->addr));
memcpy(&addreq.ifra_prefixmask, &mask,
MIN(sizeof addreq.ifra_prefixmask, sizeof mask));
if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) == -1) {
logwarnx("%s %s socket", ifn->ifname, __func__);
exit(1);
}
if (ioctl(s, SIOCAIFADDR_IN6, &addreq) == -1) {
logwarn("%s %s ioctl", ifn->ifname, __func__);
exit(1);
}
if (close(s) == -1) {
logwarn("%s %s close", ifn->ifname, __func__);
exit(1);
}
return 0;
}
/*
* Set the primary address and destination address of an interface.
*
* Return 0 on success and -1 on failure with errno set.
*/
static int
assignaddr4(const char *ifname, const struct cidraddr *ca)
{
struct ifaliasreq addreq;
struct sockaddr_in mask;
int s;
if (ifname == NULL || ca == NULL) {
errno = EINVAL;
return -1;
}
memset(&addreq, 0, sizeof(addreq));
if (strlcpy(addreq.ifra_name, ifname, sizeof(addreq.ifra_name)) >=
sizeof(addreq.ifra_name)) {
errno = EINVAL;
return -1;
}
memset(&mask, 0, sizeof(mask));
mask.sin_len = sizeof(mask);
mask.sin_family = AF_INET;
mask.sin_addr = ca->v4mask;
memcpy(&addreq.ifra_addr, &ca->addr,
MIN(sizeof addreq.ifra_addr, sizeof ca->addr));
memcpy(&addreq.ifra_mask, &mask,
MIN(sizeof addreq.ifra_mask, sizeof mask));
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
logwarnx("%s %s socket", ifn->ifname, __func__);
exit(1);
}
if (ioctl(s, SIOCAIFADDR, &addreq) == -1) {
logwarn("%s %s ioctl", ifn->ifname, __func__);
exit(1);
}
if (close(s) == -1) {
logwarn("%s %s close", ifn->ifname, __func__);
exit(1);
}
return 0;
}
/*
* Assign a v4 or v6 address to an interface.
*
* Return 0 on success or -1 on failure with errno set.
*/
static int
assignaddr(const char *ifname, const struct cidraddr *ca)
{
if (ifname == NULL || ca == NULL) {
errno = EINVAL;
return -1;
}
if (ca->addr.h.family == AF_INET6) {
return assignaddr6(ifname, ca);
} else if (ca->addr.h.family == AF_INET) {
return assignaddr4(ifname, ca);
} else {
errno = EINVAL;
return -1;
}
}
/*
* Find a peer by "sessid". Return 1 if found and updates "peer" to point to it.
* 0 if not found.
*
* XXX log(n)
*/
static int
findpeerbysessid(uint32_t sessid, struct peer **peer)
{
struct peer *p;
size_t n;
for (n = 0; n < ifn->peerssize; n++) {
p = ifn->peers[n];
if (p->sesstent.id >= 0 && le32toh(sessid) == p->sesstent.id) {
*peer = p;
return 1;
}
if (p->sessnext.id >= 0 && le32toh(sessid) == p->sessnext.id) {
*peer = p;
return 1;
}
if (p->scurr && sessid == p->scurr->id) {
*peer = p;
return 1;
}
if (p->sprev && sessid == p->sprev->id) {
*peer = p;
return 1;
}
}
return 0;
}
/*
* Locate the start and length of the payload of a transport data message.
*
* "mwdhdr" must be a pointer to the start of the received packet. "mwdsize"
* must be the complete packet size including the size of "mwdhdr".
*
* Updates "payload" to point to the start of the payload that follows after
* "mwdhdr".
* "payloadsize" is updated to contain the length of the payload including the
* authentication tag.
*
* Return 0 on success, -1 on failure.
*
* XXX might merge into decryptpacket()
*/
static int
payloadoffset(uint8_t **payload, size_t *payloadsize,
const struct msgwgdatahdr *mwdhdr, size_t mwdsize)
{
assert(sizeof(*mwdhdr) == DATAHEADERLEN);
if (mwdsize < DATAHEADERLEN)
return -1;
/*
* At the very least expect an empty packet which contains only an
* authentication tag (keepalive).
*/
if (mwdsize - DATAHEADERLEN < TAGLEN)
return -1;
*payload = (uint8_t *)mwdhdr + DATAHEADERLEN;
*payloadsize = mwdsize - DATAHEADERLEN;
return 0;
}
/*
* Find a socket by port.
*
* Return the socket if found or -1 if not found.
*
* XXX logn
*/
static int
findsockbyport(const struct peer *peer, in_port_t port, int isv6)
{
struct portsock *psp;
size_t n, pspcount;
if (isv6) {
psp = peer->portsock6;
pspcount = peer->portsock6count;
} else {
psp = peer->portsock4;
pspcount = peer->portsock4count;
}
for (n = 0; n < pspcount; n++) {
if (psp[n].p == port)
return psp[n].s;
}
return -1;
}
/*
* Find a peer by id. Return 1 if found and updates "p" to point to it. 0 if not
* found and updates "p" to NULL.
*/
static int
findpeer(uint32_t peerid, struct peer **p)
{
*p = NULL;
if (peerid >= ifn->peerssize)
return 0;
*p = ifn->peers[peerid];
return 1;
}
/*
* Mask ip6 address "in" to "prefixlen" and write the result in "out".
*
* "zero" is a boolean to indicate whether trailing bytes should be zeroed.
*/
static void
maskip6(struct in6_addr *out, const struct in6_addr *in, size_t prefixlen,
int zero)
{
size_t cut;
uint8_t *op, *ip;
assert(prefixlen <= 128);
cut = prefixlen / 8;
memmove(out, in, cut);
if (prefixlen == 128)
return;
ip = (uint8_t *)in;
op = (uint8_t *)out;
op[cut] = ip[cut] & (0xff << (8 - (prefixlen - cut * 8)));
if (zero && cut < 15)
memset(&op[cut + 1], 0, 15 - cut);
}
/*
* Find a peer with most specific "allowedips" by a remote address. "fa" must
* be a pointer to the foreign address. If multiple allowedips match the same
* mask or prefix length, the last one is choosen.
*
* Return 1 if a peer with a matching route is found and updates "peer" to point
* to it as well as "addr" to the addr that matched. Returns 0 if no peer is
* found and updates "peer" and "addr" to NULL.
*
* XXX log(n)
*/
static int
peerbyroute6(struct peer **peer, struct cidraddr **addr,
const struct in6_addr *fa)
{
struct cidraddr *allowedip;
struct in6_addr famasked;
struct peer *p;
size_t maxprefixlen;
size_t n, o;
maxprefixlen = 0;
*peer = NULL;
*addr = NULL;
for (n = 0; n < ifn->peerssize; n++) {
p = ifn->peers[n];
for (o = 0; o < p->allowedipssize; o++) {
allowedip = p->allowedips[o];
if (allowedip->addr.h.family != AF_INET6)
continue;
/* XXX once it works, don't zero out postfix */
maskip6(&famasked, fa, allowedip->prefixlen, 1);
if (memcmp(&famasked, &allowedip->v6addrmasked, 16) == 0
&& allowedip->prefixlen >= maxprefixlen) {
*peer = p;
*addr = allowedip;
maxprefixlen = allowedip->prefixlen;
}
}
}
if (*peer != NULL)
return 1;
return 0;
}
/*
* Find a peer based on its allowed ips and the address "fa". "fa" must be in
* network byte order. The first most-specific match is returned.
*
* Return 1 if a peer with a matching route is found and updates "peer" to point
* to it as well as "addr" to the addr that matched. Returns 0 if no peer is
* found and updates "peer" and "addr" to NULL.
*
* XXX log(n)
*/
static int
peerbyroute4(struct peer **peer, struct cidraddr **addr,
const struct in_addr *fa)
{
struct cidraddr *allowedip;
struct peer *p;
size_t maxprefixlen;
size_t n, o;
maxprefixlen = 0;
*peer = NULL;
*addr = NULL;
for (n = 0; n < ifn->peerssize; n++) {
p = ifn->peers[n];
for (o = 0; o < p->allowedipssize; o++) {
allowedip = p->allowedips[o];
if (allowedip->addr.h.family != AF_INET)
continue;
if ((fa->s_addr & allowedip->v4mask.s_addr) ==
allowedip->v4addrmasked.s_addr &&
allowedip->prefixlen >= maxprefixlen) {
*peer = p;
*addr = allowedip;
maxprefixlen = allowedip->prefixlen;
}
}
}
if (*peer != NULL)
return 1;
return 0;
}
/*
* Fill in an IPv6 socket addresss structure.
*
* "port" must be in network byte order. If "addr" is NULL the wildcard address
* is used. If "port" is 0 the wildcard port is used.
*/
static void
setsockaddr6(struct sockaddr_in6 *out, const struct in6_addr *addr,
in_port_t port)
{
memset(out, 0, sizeof(*out));
out->sin6_len = sizeof(*out);
out->sin6_family = AF_INET6;
out->sin6_port = port;
if (addr == NULL) {
out->sin6_addr = in6addr_any;
} else {
out->sin6_addr = *(struct in6_addr *)addr;
}
}
/*
* Fill in an IPv4 socket addresss structure.
*
* "port" must be in network byte order. If "addr" is NULL the wildcard address
* is used. If "port" is 0 the wildcard port is used.
*/
static void
setsockaddr4(struct sockaddr_in *out, const struct in_addr *addr,
in_port_t port)
{
memset(out, 0, sizeof(*out));
out->sin_len = sizeof(*out);
out->sin_family = AF_INET;
out->sin_port = port;
if (addr == NULL) {
out->sin_addr.s_addr = INADDR_ANY;
} else {
out->sin_addr = *(struct in_addr *)addr;
}
}
/*
* Fill in a socket address structure.
*
* "ip" must be an in6_addr or in_addr structure, and "ipisv6" a boolean to
* indicate which one of the two. "port" must be in network byte order. If "ip"
* is NULL the wildcard address is used. If "port" is 0 the wildcard port is
* used.
*/
static void
setsockaddr(struct sockaddr *out, const void *ip, int ipisv6, in_port_t port)
{
if (ipisv6) {
setsockaddr6((struct sockaddr_in6 *)out, ip, port);
} else {
setsockaddr4((struct sockaddr_in *)out, ip, port);
}
}
/*
* Check which port should have be used for a given an address. The address must
* match while the porthint is only used to keep searching as long as only an
* address is matched.
*
* "porthint" must be in network byte order.
*
* Return which port should have been used, or 0 if none found for the given
* address.
*/
static in_port_t
addrtoport(const struct sockaddr *addr, int isv6, in_port_t porthint)
{
const struct sockaddr_in6 *src6;
const struct sockaddr_in *src4;
struct sockaddr_in6 *laddr6;
struct sockaddr_in *laddr4;
size_t n;
int score, advport;
/*
* Find the local address with best match:
* wildcard address match = 1
* if porthint is given and matches = 2
* exact address match = 3
* if porthint is given and matches = 4
*/
score = advport = 0;
if (isv6) {
src6 = (struct sockaddr_in6 *)addr;
for (n = 0; n < ifn->laddr6count; n++) {
laddr6 = &ifn->laddr6[n];
if (memcmp(&laddr6->sin6_addr, &in6addr_any,
sizeof(in6addr_any)) == 0) {
/* wildcard address match */
if (score < 1) {
score = 1;
advport = laddr6->sin6_port;
}
if (score < 2) {
if (porthint > 0 &&
porthint == laddr6->sin6_port) {
score = 2;
advport = laddr6->sin6_port;
}
}
} else if (memcmp(&laddr6->sin6_addr, &src6->sin6_addr,
sizeof(src6->sin6_addr)) == 0) {
/* exact address match */
if (score < 3) {
score = 3;
advport = laddr6->sin6_port;
}
if (score < 4) {
if (porthint > 0 &&
porthint == laddr6->sin6_port) {
score = 4;
advport = laddr6->sin6_port;
}
}
}
}
} else {
src4 = (struct sockaddr_in *)addr;
for (n = 0; n < ifn->laddr4count; n++) {
laddr4 = &ifn->laddr4[n];
if (laddr4->sin_addr.s_addr == INADDR_ANY) {
/* wildcard address match */
if (score < 1) {
score = 1;
advport = laddr4->sin_port;
}
if (score < 2) {
if (porthint > 0 &&
porthint == laddr4->sin_port) {
score = 2;
advport = laddr4->sin_port;
}
}
} else if (laddr4->sin_addr.s_addr ==
src4->sin_addr.s_addr) {
/* exact address match */
if (score < 3) {
score = 3;
advport = laddr4->sin_port;
}
if (score < 4) {
if (porthint > 0 &&
porthint == laddr4->sin_port) {
score = 4;
advport = laddr4->sin_port;
}
}
}
}
}
return advport;
}
/*
* Disconnect and deregister the active socket of a peer by connecting it to a
* reserved port on the localhost so that it can be used later to connect to a
* new address, and stop listening for any events that might happen (triggered
* by a /rogue/ local process).
*
* Return 0 on success, -1 on failure with errno set.
*/
static int
peerpark(struct peer *peer)
{
char addrstr1[MAXADDRSTR], addrstr2[MAXADDRSTR];
union sockaddr_inet si;
union inet_addr addr;
struct kevent ev;
int retries;
socklen_t len;
in_port_t rport;
if (peer->sock == -1) {
errno = ENOTSOCK;
return -1;
}
/*
* Stop listening for anything that might be sent to this
* socket. If no read filter was set (yet) on a descriptor EBADF is
* returned by kevent(), ignore this.
*/
EV_SET(&ev, peer->sock, EVFILT_READ, EV_DELETE, 0, 0, NULL);
if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1 && errno != EBADF)
logwarn("%s %s could not clear socket event listener",
ifn->ifname, peer->name);
if (peer->sockisv6) {
if (inet_pton(AF_INET6, "::1", &addr.addr6) != 1)
logwarn("%s %s inet_pton ::1 error", ifn->ifname,
peer->name);
} else {
if (inet_pton(AF_INET, "127.0.0.1", &addr.addr4) != 1)
logwarn("%s %s inet_pton 127.0.0.1 error", ifn->ifname,
peer->name);
}
retries = 0;
retry:
rport = htons(arc4random_uniform(IPPORT_RESERVED - 1) + 1);
setsockaddr((struct sockaddr *)&si, &addr, peer->sockisv6, rport);
if (connect(peer->sock, (struct sockaddr *)&si, si.h.len) == -1) {
if (errno == EINTR)
goto retry;
if (errno == EADDRINUSE) {
if (retries < MAXCONNRETRY) {
if (verbose > 0)
lognoticex("%s %s can't connect to "
"localhost port %d, retrying... "
"(%d)", ifn->ifname, peer->name,
ntohs(rport), retries + 1);
sleep(1);
retries++;
goto retry;
}
logwarn("%s %s can't connect to localhost port %d, "
"giving up", ifn->ifname, peer->name, ntohs(rport));
}
peer->sock = -1;
peer->sockisv6 = 0;
logwarn("%s %s park error", ifn->ifname, peer->name);
return -1;
}
len = sizeof si;
if (getsockname(peer->sock, (struct sockaddr *)&si, &len) == -1) {
logwarn("%s %s %s getsockname error", ifn->ifname, peer->name,
__func__);
peerpark(peer);
return -1;
}
addrtostr(addrstr1, sizeof(addrstr1), (struct sockaddr *)&si, 0);
len = sizeof si;
if (getpeername(peer->sock, (struct sockaddr *)&si, &len) == -1) {
logwarn("%s %s %s getpeername error", ifn->ifname, peer->name,
__func__);
peerpark(peer);
return -1;
}
addrtostr(addrstr2, sizeof(addrstr2), (struct sockaddr *)&si, 0);
if (verbose > 2)
logdebugx("%s %s parked socket %s -> %s", ifn->ifname,
peer->name, addrstr1, addrstr2);