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