我的主要想法是在有效负载中搜索特定单词,无论它是否存在。我编写此代码是为了在 unsigned char
(foo
) 中搜索关键字 (search_for_string
)。
问题是 foo
是一个指向 unsigned char
的指针。如何将指针 foo
的值保存在新的字符串变量中并在 strstr
中使用它?
对于 iptables,我通过终端设置了此规则:
sudo iptables -t filter -I OUTPUT --proto tcp -j NFQUEUE --queue-num 1
这是我运行代码之前的测试 nping:
sudo nping -c 10 --tcp -p 80,433 --data-string helloWorld 185.60.216.35
编译我另外使用的文件:
gcc -o output input.c -lnetfilter_queue -lnfnetlink
代码文件
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <libnetfilter_queue/libnetfilter_queue.h>
#include <linux/netfilter.h>
#include <sys/stat.h>
#include <sys/types.h>
static int cb(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg,
struct nfq_data *nfa, void *data) {
size_t payloadLen = 0;
unsigned char *foo;
payloadLen = nfq_get_payload(nfa, &foo);
struct iphdr *ip_header;
ip_header = (struct iphdr *)foo;
struct nfqnl_msg_packet_hdr *ph;
ph = nfq_get_msg_packet_hdr(nfa);
char search_for_string[] = "helloWorld";
if (strstr((char *)foo, search_for_string)) {
printf("\nThe Payload contains the keyword.");
} else {
printf("\nPayload does not contain the keyword.");
}
最佳答案
foo 可能等于 NULL,这在传递给 strstr 时会导致 SEGFAULT。您应该在调用 strstr 之前添加 NULL 检查。
nfq_get_payload 出错时将返回 -1,因此您应该使用有符号类型而不是 size_t 作为有效负载长度并进行检查。
这是一个可能的解决方案:
static int cb(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct
nfq_data *nfa, void *data) {
ssize_t payloadLen; //Note: Signed type
unsigned char *foo = NULL; //Note: Init with NULL
payloadLen = nfq_get_payload(nfa, &foo);
if(payloadLen < 0){
//TODO: Do something...
}
struct iphdr *ip_header;
ip_header = (struct iphdr *)foo;
struct nfqnl_msg_packet_hdr *ph;
ph = nfq_get_msg_packet_hdr(nfa);
char search_for_string[] = "helloWorld";
if((foo == NULL) || (payloadLen < 0)){
//TODO: print something if you want
}
else if (memmem((void*)foo, payloadLen, search_for_string, strlen(search_for_string)))
{
printf("\nThe Payload contains the keyword.");
}
else
{
printf("\nPayload does not contain the keyword.");
}
关于c - 在 C 中的 unsigned char 中搜索关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55088452/