1 // SPDX-License-Identifier: GPL-2.0
2 #include <string.h>
3
4 #include <linux/bpf.h>
5 #include <linux/in.h>
6 #include <linux/in6.h>
7 #include <sys/socket.h>
8
9 #include <bpf/bpf_helpers.h>
10 #include <bpf/bpf_endian.h>
11
12 #include <bpf_sockopt_helpers.h>
13
14 char _license[] SEC("license") = "GPL";
15 int _version SEC("version") = 1;
16
17 struct svc_addr {
18 __be32 addr[4];
19 __be16 port;
20 };
21
22 struct {
23 __uint(type, BPF_MAP_TYPE_SK_STORAGE);
24 __uint(map_flags, BPF_F_NO_PREALLOC);
25 __type(key, int);
26 __type(value, struct svc_addr);
27 } service_mapping SEC(".maps");
28
29 SEC("cgroup/connect6")
connect6(struct bpf_sock_addr * ctx)30 int connect6(struct bpf_sock_addr *ctx)
31 {
32 struct sockaddr_in6 sa = {};
33 struct svc_addr *orig;
34
35 /* Force local address to [::1]:22223. */
36 sa.sin6_family = AF_INET6;
37 sa.sin6_port = bpf_htons(22223);
38 sa.sin6_addr.s6_addr32[3] = bpf_htonl(1);
39
40 if (bpf_bind(ctx, (struct sockaddr *)&sa, sizeof(sa)) != 0)
41 return 0;
42
43 /* Rewire service [fc00::1]:60000 to backend [::1]:60124. */
44 if (ctx->user_port == bpf_htons(60000)) {
45 orig = bpf_sk_storage_get(&service_mapping, ctx->sk, 0,
46 BPF_SK_STORAGE_GET_F_CREATE);
47 if (!orig)
48 return 0;
49
50 orig->addr[0] = ctx->user_ip6[0];
51 orig->addr[1] = ctx->user_ip6[1];
52 orig->addr[2] = ctx->user_ip6[2];
53 orig->addr[3] = ctx->user_ip6[3];
54 orig->port = ctx->user_port;
55
56 ctx->user_ip6[0] = 0;
57 ctx->user_ip6[1] = 0;
58 ctx->user_ip6[2] = 0;
59 ctx->user_ip6[3] = bpf_htonl(1);
60 ctx->user_port = bpf_htons(60124);
61 }
62 return 1;
63 }
64
65 SEC("cgroup/getsockname6")
getsockname6(struct bpf_sock_addr * ctx)66 int getsockname6(struct bpf_sock_addr *ctx)
67 {
68 if (!get_set_sk_priority(ctx))
69 return 1;
70
71 /* Expose local server as [fc00::1]:60000 to client. */
72 if (ctx->user_port == bpf_htons(60124)) {
73 ctx->user_ip6[0] = bpf_htonl(0xfc000000);
74 ctx->user_ip6[1] = 0;
75 ctx->user_ip6[2] = 0;
76 ctx->user_ip6[3] = bpf_htonl(1);
77 ctx->user_port = bpf_htons(60000);
78 }
79 return 1;
80 }
81
82 SEC("cgroup/getpeername6")
getpeername6(struct bpf_sock_addr * ctx)83 int getpeername6(struct bpf_sock_addr *ctx)
84 {
85 struct svc_addr *orig;
86
87 if (!get_set_sk_priority(ctx))
88 return 1;
89
90 /* Expose service [fc00::1]:60000 as peer instead of backend. */
91 if (ctx->user_port == bpf_htons(60124)) {
92 orig = bpf_sk_storage_get(&service_mapping, ctx->sk, 0, 0);
93 if (orig) {
94 ctx->user_ip6[0] = orig->addr[0];
95 ctx->user_ip6[1] = orig->addr[1];
96 ctx->user_ip6[2] = orig->addr[2];
97 ctx->user_ip6[3] = orig->addr[3];
98 ctx->user_port = orig->port;
99 }
100 }
101 return 1;
102 }
103