xref: /linux/tools/testing/selftests/bpf/progs/connect_force_port4.c (revision 0fc8f6200d2313278fbf4539bbab74677c685531)
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 
17 __u16 port = 0;
18 
19 struct svc_addr {
20 	__be32 addr;
21 	__be16 port;
22 };
23 
24 struct {
25 	__uint(type, BPF_MAP_TYPE_SK_STORAGE);
26 	__uint(map_flags, BPF_F_NO_PREALLOC);
27 	__type(key, int);
28 	__type(value, struct svc_addr);
29 } service_mapping SEC(".maps");
30 
31 SEC("cgroup/connect4")
32 int connect4(struct bpf_sock_addr *ctx)
33 {
34 	struct sockaddr_in sa = {};
35 	struct svc_addr *orig;
36 
37 	/* Force local address to 127.0.0.1:22222. */
38 	sa.sin_family = AF_INET;
39 	sa.sin_port = bpf_htons(22222);
40 	sa.sin_addr.s_addr = bpf_htonl(0x7f000001);
41 
42 	if (bpf_bind(ctx, (struct sockaddr *)&sa, sizeof(sa)) != 0)
43 		return 0;
44 
45 	/* Rewire service 1.2.3.4:60000 to backend 127.0.0.1:port. */
46 	if (ctx->user_port == bpf_htons(60000)) {
47 		orig = bpf_sk_storage_get(&service_mapping, ctx->sk, 0,
48 					  BPF_SK_STORAGE_GET_F_CREATE);
49 		if (!orig)
50 			return 0;
51 
52 		orig->addr = ctx->user_ip4;
53 		orig->port = ctx->user_port;
54 
55 		ctx->user_ip4 = bpf_htonl(0x7f000001);
56 		ctx->user_port = bpf_htons(port);
57 	}
58 	return 1;
59 }
60 
61 SEC("cgroup/getsockname4")
62 int getsockname4(struct bpf_sock_addr *ctx)
63 {
64 	if (!get_set_sk_priority(ctx))
65 		return 1;
66 
67 	/* Expose local server as 1.2.3.4:60000 to client. */
68 	if (ctx->user_port == bpf_htons(port)) {
69 		ctx->user_ip4 = bpf_htonl(0x01020304);
70 		ctx->user_port = bpf_htons(60000);
71 	}
72 	return 1;
73 }
74 
75 SEC("cgroup/getpeername4")
76 int getpeername4(struct bpf_sock_addr *ctx)
77 {
78 	struct svc_addr *orig;
79 
80 	if (!get_set_sk_priority(ctx))
81 		return 1;
82 
83 	/* Expose service 1.2.3.4:60000 as peer instead of backend. */
84 	if (ctx->user_port == bpf_htons(port)) {
85 		orig = bpf_sk_storage_get(&service_mapping, ctx->sk, 0, 0);
86 		if (orig) {
87 			ctx->user_ip4 = orig->addr;
88 			ctx->user_port = orig->port;
89 		}
90 	}
91 	return 1;
92 }
93