1 // SPDX-License-Identifier: GPL-2.0
5 #include <linux/stddef.h>
9 #include <sys/socket.h>
10 #include <netinet/tcp.h>
14 #include <bpf/bpf_helpers.h>
15 #include <bpf/bpf_endian.h>
17 #define SERV6_IP_0 0xfaceb00c /* face:b00c:1234:5678::abcd */
18 #define SERV6_IP_1 0x12345678
19 #define SERV6_IP_2 0x00000000
20 #define SERV6_IP_3 0x0000abcd
21 #define SERV6_PORT 6060
22 #define SERV6_REWRITE_IP_0 0x00000000
23 #define SERV6_REWRITE_IP_1 0x00000000
24 #define SERV6_REWRITE_IP_2 0x00000000
25 #define SERV6_REWRITE_IP_3 0x00000001
26 #define SERV6_REWRITE_PORT 6666
32 static __inline
int bind_to_device(struct bpf_sock_addr
*ctx
)
34 char veth1
[IFNAMSIZ
] = "test_sock_addr1";
35 char veth2
[IFNAMSIZ
] = "test_sock_addr2";
36 char missing
[IFNAMSIZ
] = "nonexistent_dev";
37 char del_bind
[IFNAMSIZ
] = "";
39 if (bpf_setsockopt(ctx
, SOL_SOCKET
, SO_BINDTODEVICE
,
40 &veth1
, sizeof(veth1
)))
42 if (bpf_setsockopt(ctx
, SOL_SOCKET
, SO_BINDTODEVICE
,
43 &veth2
, sizeof(veth2
)))
45 if (bpf_setsockopt(ctx
, SOL_SOCKET
, SO_BINDTODEVICE
,
46 &missing
, sizeof(missing
)) != -ENODEV
)
48 if (bpf_setsockopt(ctx
, SOL_SOCKET
, SO_BINDTODEVICE
,
49 &del_bind
, sizeof(del_bind
)))
56 int bind_v6_prog(struct bpf_sock_addr
*ctx
)
67 if (sk
->family
!= AF_INET6
)
70 if (ctx
->type
!= SOCK_STREAM
&& ctx
->type
!= SOCK_DGRAM
)
73 if (ctx
->user_ip6
[0] != bpf_htonl(SERV6_IP_0
) ||
74 ctx
->user_ip6
[1] != bpf_htonl(SERV6_IP_1
) ||
75 ctx
->user_ip6
[2] != bpf_htonl(SERV6_IP_2
) ||
76 ctx
->user_ip6
[3] != bpf_htonl(SERV6_IP_3
) ||
77 ctx
->user_port
!= bpf_htons(SERV6_PORT
))
81 for (i
= 0; i
< 4; i
++) {
83 user_ip6
|= ((volatile __u8
*)&ctx
->user_ip6
[i
])[0] << 0;
84 user_ip6
|= ((volatile __u8
*)&ctx
->user_ip6
[i
])[1] << 8;
85 user_ip6
|= ((volatile __u8
*)&ctx
->user_ip6
[i
])[2] << 16;
86 user_ip6
|= ((volatile __u8
*)&ctx
->user_ip6
[i
])[3] << 24;
87 if (ctx
->user_ip6
[i
] != user_ip6
)
92 user_port
|= ((volatile __u8
*)&ctx
->user_port
)[0] << 0;
93 user_port
|= ((volatile __u8
*)&ctx
->user_port
)[1] << 8;
94 if (ctx
->user_port
!= user_port
)
98 for (i
= 0; i
< 4; i
++) {
100 user_ip6
|= ((volatile __u16
*)&ctx
->user_ip6
[i
])[0] << 0;
101 user_ip6
|= ((volatile __u16
*)&ctx
->user_ip6
[i
])[1] << 16;
102 if (ctx
->user_ip6
[i
] != user_ip6
)
106 /* Bind to device and unbind it. */
107 if (bind_to_device(ctx
))
110 ctx
->user_ip6
[0] = bpf_htonl(SERV6_REWRITE_IP_0
);
111 ctx
->user_ip6
[1] = bpf_htonl(SERV6_REWRITE_IP_1
);
112 ctx
->user_ip6
[2] = bpf_htonl(SERV6_REWRITE_IP_2
);
113 ctx
->user_ip6
[3] = bpf_htonl(SERV6_REWRITE_IP_3
);
114 ctx
->user_port
= bpf_htons(SERV6_REWRITE_PORT
);
119 char _license
[] SEC("license") = "GPL";