Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 #include <string.h>
0003 #include <stdbool.h>
0004 
0005 #include <linux/bpf.h>
0006 #include <linux/in.h>
0007 #include <linux/in6.h>
0008 #include <sys/socket.h>
0009 
0010 #include <bpf/bpf_helpers.h>
0011 #include <bpf/bpf_endian.h>
0012 
0013 #include <bpf_sockopt_helpers.h>
0014 
0015 char _license[] SEC("license") = "GPL";
0016 
0017 struct svc_addr {
0018     __be32 addr;
0019     __be16 port;
0020 };
0021 
0022 struct {
0023     __uint(type, BPF_MAP_TYPE_SK_STORAGE);
0024     __uint(map_flags, BPF_F_NO_PREALLOC);
0025     __type(key, int);
0026     __type(value, struct svc_addr);
0027 } service_mapping SEC(".maps");
0028 
0029 SEC("cgroup/connect4")
0030 int connect4(struct bpf_sock_addr *ctx)
0031 {
0032     struct sockaddr_in sa = {};
0033     struct svc_addr *orig;
0034 
0035     /* Force local address to 127.0.0.1:22222. */
0036     sa.sin_family = AF_INET;
0037     sa.sin_port = bpf_htons(22222);
0038     sa.sin_addr.s_addr = bpf_htonl(0x7f000001);
0039 
0040     if (bpf_bind(ctx, (struct sockaddr *)&sa, sizeof(sa)) != 0)
0041         return 0;
0042 
0043     /* Rewire service 1.2.3.4:60000 to backend 127.0.0.1:60123. */
0044     if (ctx->user_port == bpf_htons(60000)) {
0045         orig = bpf_sk_storage_get(&service_mapping, ctx->sk, 0,
0046                       BPF_SK_STORAGE_GET_F_CREATE);
0047         if (!orig)
0048             return 0;
0049 
0050         orig->addr = ctx->user_ip4;
0051         orig->port = ctx->user_port;
0052 
0053         ctx->user_ip4 = bpf_htonl(0x7f000001);
0054         ctx->user_port = bpf_htons(60123);
0055     }
0056     return 1;
0057 }
0058 
0059 SEC("cgroup/getsockname4")
0060 int getsockname4(struct bpf_sock_addr *ctx)
0061 {
0062     if (!get_set_sk_priority(ctx))
0063         return 1;
0064 
0065     /* Expose local server as 1.2.3.4:60000 to client. */
0066     if (ctx->user_port == bpf_htons(60123)) {
0067         ctx->user_ip4 = bpf_htonl(0x01020304);
0068         ctx->user_port = bpf_htons(60000);
0069     }
0070     return 1;
0071 }
0072 
0073 SEC("cgroup/getpeername4")
0074 int getpeername4(struct bpf_sock_addr *ctx)
0075 {
0076     struct svc_addr *orig;
0077 
0078     if (!get_set_sk_priority(ctx))
0079         return 1;
0080 
0081     /* Expose service 1.2.3.4:60000 as peer instead of backend. */
0082     if (ctx->user_port == bpf_htons(60123)) {
0083         orig = bpf_sk_storage_get(&service_mapping, ctx->sk, 0, 0);
0084         if (orig) {
0085             ctx->user_ip4 = orig->addr;
0086             ctx->user_port = orig->port;
0087         }
0088     }
0089     return 1;
0090 }