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