Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 // Copyright (c) 2018 Facebook
0003 
0004 #include <linux/stddef.h>
0005 #include <linux/bpf.h>
0006 #include <sys/socket.h>
0007 
0008 #include <bpf/bpf_helpers.h>
0009 #include <bpf/bpf_endian.h>
0010 
0011 #include <bpf_sockopt_helpers.h>
0012 
0013 #define SRC1_IP4        0xAC100001U /* 172.16.0.1 */
0014 #define SRC2_IP4        0x00000000U
0015 #define SRC_REWRITE_IP4     0x7f000004U
0016 #define DST_IP4         0xC0A801FEU /* 192.168.1.254 */
0017 #define DST_REWRITE_IP4     0x7f000001U
0018 #define DST_PORT        4040
0019 #define DST_REWRITE_PORT4   4444
0020 
0021 SEC("cgroup/sendmsg4")
0022 int sendmsg_v4_prog(struct bpf_sock_addr *ctx)
0023 {
0024     int prio;
0025 
0026     if (ctx->type != SOCK_DGRAM)
0027         return 0;
0028 
0029     if (!get_set_sk_priority(ctx))
0030         return 0;
0031 
0032     /* Rewrite source. */
0033     if (ctx->msg_src_ip4 == bpf_htonl(SRC1_IP4) ||
0034         ctx->msg_src_ip4 == bpf_htonl(SRC2_IP4)) {
0035         ctx->msg_src_ip4 = bpf_htonl(SRC_REWRITE_IP4);
0036     } else {
0037         /* Unexpected source. Reject sendmsg. */
0038         return 0;
0039     }
0040 
0041     /* Rewrite destination. */
0042     if ((ctx->user_ip4 >> 24) == (bpf_htonl(DST_IP4) >> 24) &&
0043          ctx->user_port == bpf_htons(DST_PORT)) {
0044         ctx->user_ip4 = bpf_htonl(DST_REWRITE_IP4);
0045         ctx->user_port = bpf_htons(DST_REWRITE_PORT4);
0046     } else {
0047         /* Unexpected source. Reject sendmsg. */
0048         return 0;
0049     }
0050 
0051     return 1;
0052 }
0053 
0054 char _license[] SEC("license") = "GPL";