1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2018 Facebook
6 #include <linux/stddef.h>
10 #include <sys/socket.h>
12 #include <bpf/bpf_helpers.h>
13 #include <bpf/bpf_endian.h>
15 #define SRC_REWRITE_IP4 0x7f000004U
16 #define DST_REWRITE_IP4 0x7f000001U
17 #define DST_REWRITE_PORT4 4444
19 int _version SEC("version") = 1;
21 __attribute__ ((noinline))
22 int do_bind(struct bpf_sock_addr *ctx)
24 struct sockaddr_in sa = {};
26 sa.sin_family = AF_INET;
27 sa.sin_port = bpf_htons(0);
28 sa.sin_addr.s_addr = bpf_htonl(SRC_REWRITE_IP4);
30 if (bpf_bind(ctx, (struct sockaddr *)&sa, sizeof(sa)) != 0)
36 SEC("cgroup/connect4")
37 int connect_v4_prog(struct bpf_sock_addr *ctx)
39 struct bpf_sock_tuple tuple = {};
42 /* Verify that new destination is available. */
43 memset(&tuple.ipv4.saddr, 0, sizeof(tuple.ipv4.saddr));
44 memset(&tuple.ipv4.sport, 0, sizeof(tuple.ipv4.sport));
46 tuple.ipv4.daddr = bpf_htonl(DST_REWRITE_IP4);
47 tuple.ipv4.dport = bpf_htons(DST_REWRITE_PORT4);
49 if (ctx->type != SOCK_STREAM && ctx->type != SOCK_DGRAM)
51 else if (ctx->type == SOCK_STREAM)
52 sk = bpf_sk_lookup_tcp(ctx, &tuple, sizeof(tuple.ipv4),
53 BPF_F_CURRENT_NETNS, 0);
55 sk = bpf_sk_lookup_udp(ctx, &tuple, sizeof(tuple.ipv4),
56 BPF_F_CURRENT_NETNS, 0);
61 if (sk->src_ip4 != tuple.ipv4.daddr ||
62 sk->src_port != DST_REWRITE_PORT4) {
69 /* Rewrite destination. */
70 ctx->user_ip4 = bpf_htonl(DST_REWRITE_IP4);
71 ctx->user_port = bpf_htons(DST_REWRITE_PORT4);
73 return do_bind(ctx) ? 1 : 0;
76 char _license[] SEC("license") = "GPL";