1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <time.h> 5 #include <arpa/inet.h> 6 7 #include <libmnl/libmnl.h> 8 #include <libnetfilter_conntrack/libnetfilter_conntrack.h> 9 10 #include <linux/netfilter/nf_conntrack_tcp.h> 11 12 int main(void) 13 { 14 struct mnl_socket *nl; 15 struct nlmsghdr *nlh; 16 struct nfgenmsg *nfh; 17 char buf[MNL_SOCKET_BUFFER_SIZE]; 18 unsigned int seq, portid; 19 struct nf_conntrack *ct; 20 int ret; 21 22 nl = mnl_socket_open(NETLINK_NETFILTER); 23 if (nl == NULL) { 24 perror("mnl_socket_open"); 25 exit(EXIT_FAILURE); 26 } 27 28 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) { 29 perror("mnl_socket_bind"); 30 exit(EXIT_FAILURE); 31 } 32 portid = mnl_socket_get_portid(nl); 33 34 nlh = mnl_nlmsg_put_header(buf); 35 nlh->nlmsg_type = (NFNL_SUBSYS_CTNETLINK << 8) | IPCTNL_MSG_CT_NEW; 36 nlh->nlmsg_flags = NLM_F_REQUEST|NLM_F_CREATE|NLM_F_EXCL|NLM_F_ACK; 37 nlh->nlmsg_seq = seq = time(NULL); 38 39 nfh = mnl_nlmsg_put_extra_header(nlh, sizeof(struct nfgenmsg)); 40 nfh->nfgen_family = AF_INET; 41 nfh->version = NFNETLINK_V0; 42 nfh->res_id = 0; 43 44 ct = nfct_new(); 45 if (ct == NULL) { 46 perror("nfct_new"); 47 return 0; 48 } 49 50 nfct_set_attr_u8(ct, ATTR_L3PROTO, AF_INET); 51 nfct_set_attr_u32(ct, ATTR_IPV4_SRC, inet_addr("1.1.1.1")); 52 nfct_set_attr_u32(ct, ATTR_IPV4_DST, inet_addr("2.2.2.2")); 53 54 nfct_set_attr_u8(ct, ATTR_L4PROTO, IPPROTO_TCP); 55 nfct_set_attr_u16(ct, ATTR_PORT_SRC, htons(20)); 56 nfct_set_attr_u16(ct, ATTR_PORT_DST, htons(10)); 57 58 nfct_setobjopt(ct, NFCT_SOPT_SETUP_REPLY); 59 60 nfct_set_attr_u8(ct, ATTR_TCP_STATE, TCP_CONNTRACK_SYN_SENT); 61 nfct_set_attr_u32(ct, ATTR_TIMEOUT, 100); 62 63 nfct_nlmsg_build(nlh, ct); 64 65 ret = mnl_socket_sendto(nl, nlh, nlh->nlmsg_len); 66 if (ret == -1) { 67 perror("mnl_socket_recvfrom"); 68 exit(EXIT_FAILURE); 69 } 70 71 ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); 72 while (ret > 0) { 73 ret = mnl_cb_run(buf, ret, seq, portid, NULL, NULL); 74 if (ret <= MNL_CB_STOP) 75 break; 76 ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); 77 } 78 if (ret == -1) { 79 perror("mnl_socket_recvfrom"); 80 exit(EXIT_FAILURE); 81 } 82 83 mnl_socket_close(nl); 84 85 return 0; 86 } 87