1 // SPDX-License-Identifier: GPL-2.0
8 #include <sys/socket.h>
10 #include <bpf/bpf_helpers.h>
11 #include <bpf/bpf_endian.h>
13 #include <bpf_sockopt_helpers.h>
15 char _license[] SEC("license") = "GPL";
23 __uint(type, BPF_MAP_TYPE_SK_STORAGE);
24 __uint(map_flags, BPF_F_NO_PREALLOC);
26 __type(value, struct svc_addr);
27 } service_mapping SEC(".maps");
29 SEC("cgroup/connect4")
30 int connect4(struct bpf_sock_addr *ctx)
32 struct sockaddr_in sa = {};
33 struct svc_addr *orig;
35 /* Force local address to 127.0.0.1:22222. */
36 sa.sin_family = AF_INET;
37 sa.sin_port = bpf_htons(22222);
38 sa.sin_addr.s_addr = bpf_htonl(0x7f000001);
40 if (bpf_bind(ctx, (struct sockaddr *)&sa, sizeof(sa)) != 0)
43 /* Rewire service 1.2.3.4:60000 to backend 127.0.0.1:60123. */
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);
50 orig->addr = ctx->user_ip4;
51 orig->port = ctx->user_port;
53 ctx->user_ip4 = bpf_htonl(0x7f000001);
54 ctx->user_port = bpf_htons(60123);
59 SEC("cgroup/getsockname4")
60 int getsockname4(struct bpf_sock_addr *ctx)
62 if (!get_set_sk_priority(ctx))
65 /* Expose local server as 1.2.3.4:60000 to client. */
66 if (ctx->user_port == bpf_htons(60123)) {
67 ctx->user_ip4 = bpf_htonl(0x01020304);
68 ctx->user_port = bpf_htons(60000);
73 SEC("cgroup/getpeername4")
74 int getpeername4(struct bpf_sock_addr *ctx)
76 struct svc_addr *orig;
78 if (!get_set_sk_priority(ctx))
81 /* Expose service 1.2.3.4:60000 as peer instead of backend. */
82 if (ctx->user_port == bpf_htons(60123)) {
83 orig = bpf_sk_storage_get(&service_mapping, ctx->sk, 0, 0);
85 ctx->user_ip4 = orig->addr;
86 ctx->user_port = orig->port;