xref: /linux/tools/testing/selftests/bpf/progs/connect_force_port6.c (revision 0fc8f6200d2313278fbf4539bbab74677c685531)
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 #include <bpf_sockopt_helpers.h>
13 
14 char _license[] SEC("license") = "GPL";
15 
16 __u16 port = 0;
17 
18 struct svc_addr {
19 	__be32 addr[4];
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/connect6")
31 int connect6(struct bpf_sock_addr *ctx)
32 {
33 	struct sockaddr_in6 sa = {};
34 	struct svc_addr *orig;
35 
36 	/* Force local address to [::1]:22223. */
37 	sa.sin6_family = AF_INET6;
38 	sa.sin6_port = bpf_htons(22223);
39 	sa.sin6_addr.s6_addr32[3] = bpf_htonl(1);
40 
41 	if (bpf_bind(ctx, (struct sockaddr *)&sa, sizeof(sa)) != 0)
42 		return 0;
43 
44 	/* Rewire service [fc00::1]:60000 to backend [::1]:port. */
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[0] = ctx->user_ip6[0];
52 		orig->addr[1] = ctx->user_ip6[1];
53 		orig->addr[2] = ctx->user_ip6[2];
54 		orig->addr[3] = ctx->user_ip6[3];
55 		orig->port = ctx->user_port;
56 
57 		ctx->user_ip6[0] = 0;
58 		ctx->user_ip6[1] = 0;
59 		ctx->user_ip6[2] = 0;
60 		ctx->user_ip6[3] = bpf_htonl(1);
61 		ctx->user_port = bpf_htons(port);
62 	}
63 	return 1;
64 }
65 
66 SEC("cgroup/getsockname6")
67 int getsockname6(struct bpf_sock_addr *ctx)
68 {
69 	if (!get_set_sk_priority(ctx))
70 		return 1;
71 
72 	/* Expose local server as [fc00::1]:60000 to client. */
73 	if (ctx->user_port == bpf_htons(port)) {
74 		ctx->user_ip6[0] = bpf_htonl(0xfc000000);
75 		ctx->user_ip6[1] = 0;
76 		ctx->user_ip6[2] = 0;
77 		ctx->user_ip6[3] = bpf_htonl(1);
78 		ctx->user_port = bpf_htons(60000);
79 	}
80 	return 1;
81 }
82 
83 SEC("cgroup/getpeername6")
84 int getpeername6(struct bpf_sock_addr *ctx)
85 {
86 	struct svc_addr *orig;
87 
88 	if (!get_set_sk_priority(ctx))
89 		return 1;
90 
91 	/* Expose service [fc00::1]:60000 as peer instead of backend. */
92 	if (ctx->user_port == bpf_htons(port)) {
93 		orig = bpf_sk_storage_get(&service_mapping, ctx->sk, 0, 0);
94 		if (orig) {
95 			ctx->user_ip6[0] = orig->addr[0];
96 			ctx->user_ip6[1] = orig->addr[1];
97 			ctx->user_ip6[2] = orig->addr[2];
98 			ctx->user_ip6[3] = orig->addr[3];
99 			ctx->user_port = orig->port;
100 		}
101 	}
102 	return 1;
103 }
104