[root@c7-1 ~]# bpftool prog |grep sock
1653: type 18 name sock6_connect tag d526fd1cb49a372e gpl
1657: cgroup_sock name sock6_post_bind tag e46a7916c9c72e67 gpl
1661: type 18 name sock6_sendmsg tag 19094f9c26d4dddf gpl
1665: type 18 name sock6_recvmsg tag 282bf4c10eff7f73 gpl
1669: type 18 name sock4_connect tag 57eae2cf019378cc gpl
1673: cgroup_sock name sock4_post_bind tag ddd7183184f2e6e9 gpl
1677: type 18 name sock4_sendmsg tag 570ef9d580ce0589 gpl
1681: type 18 name sock4_recvmsg tag 0bdebe7409ceb49f gpl
[root@c7-1 ~]# bpftool prog |grep connect
1653: type 18 name sock6_connect tag d526fd1cb49a372e gpl
1669: type 18 name sock4_connect tag 57eae2cf019378cc gpl
#include <bpf/ctx/unspec.h>
#include <bpf/api.h>
#define SKIP_POLICY_MAP 1
#define SKIP_CALLS_MAP 1
#define SYS_REJECT 0
#define SYS_PROCEED 1
# define printk(fmt, ...) \
({ \
const char ____fmt[] = fmt; \
trace_printk(____fmt, sizeof(____fmt), \
##__VA_ARGS__); \
})
__section("cgroup/connect4")
int sock4_connect(struct bpf_sock_addr *ctx )
{
if (ctx->user_ip4 != 0x04030201) { // des ip is 1.2.3.4
return SYS_PROCEED;
}
printk("aa %x ", ctx->user_ip4);
ctx->user_ip4=0x19280a0a; // set to 10.10.40.25
printk("set ok %x,%x", ctx->user_ip4, ctx->user_port);
return SYS_PROCEED;
}
BPF_LICENSE("Dual BSD/GPL");
程序說明:
判斷目標ip是1.2.3.4才處理(對應16進制順序相反,是因為系統為小端模式)。
輸出目的ip,方便debug。
修改目的ip為指定的ip。
輸出設置的結果。
入參bpf_sock_addr,可從cilium的源碼中找到相關定義。
mysock.c
/* User bpf_sock_addr struct to access socket fields and sockaddr struct passed
* by user and intended to be used by socket (e.g. to bind to, depends on
* attach type).
*/
struct bpf_sock_addr {
__u32 user_family; /* Allows 4-byte read, but no write. */
__u32 user_ip4; /* Allows 1,2,4-byte read and 4-byte write.
* Stored in network byte order.
*/
__u32 user_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write.
* Stored in network byte order.
*/
__u32 user_port; /* Allows 1,2,4-byte read and 4-byte write.
* Stored in network byte order
*/
__u32 family; /* Allows 4-byte read, but no write */
__u32 type; /* Allows 4-byte read, but no write */
__u32 protocol; /* Allows 4-byte read, but no write */
__u32 msg_src_ip4; /* Allows 1,2,4-byte read and 4-byte write.
* Stored in network byte order.
*/
__u32 msg_src_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write.
* Stored in network byte order.
*/
__bpf_md_ptr(struct bpf_sock *, sk);
};