xref: /linux/tools/testing/selftests/net/netfilter/nf_queue.c (revision abacaf559950eec0d99d37ff6b92049409af5943)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <errno.h>
4 #include <stdbool.h>
5 #include <stdio.h>
6 #include <stdint.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <string.h>
10 #include <time.h>
11 #include <arpa/inet.h>
12 
13 #include <libmnl/libmnl.h>
14 #include <linux/netfilter.h>
15 #include <linux/netfilter/nfnetlink.h>
16 #include <linux/netfilter/nfnetlink_queue.h>
17 
18 struct options {
19 	bool count_packets;
20 	bool gso_enabled;
21 	bool failopen;
22 	int verbose;
23 	unsigned int queue_num;
24 	unsigned int timeout;
25 	uint32_t verdict;
26 	uint32_t delay_ms;
27 };
28 
29 static unsigned int queue_stats[5];
30 static struct options opts;
31 
help(const char * p)32 static void help(const char *p)
33 {
34 	printf("Usage: %s [-c|-v [-vv] ] [-o] [-t timeout] [-q queue_num] [-Qdst_queue ] [ -d ms_delay ] [-G]\n", p);
35 }
36 
parse_attr_cb(const struct nlattr * attr,void * data)37 static int parse_attr_cb(const struct nlattr *attr, void *data)
38 {
39 	const struct nlattr **tb = data;
40 	int type = mnl_attr_get_type(attr);
41 
42 	/* skip unsupported attribute in user-space */
43 	if (mnl_attr_type_valid(attr, NFQA_MAX) < 0)
44 		return MNL_CB_OK;
45 
46 	switch (type) {
47 	case NFQA_MARK:
48 	case NFQA_IFINDEX_INDEV:
49 	case NFQA_IFINDEX_OUTDEV:
50 	case NFQA_IFINDEX_PHYSINDEV:
51 	case NFQA_IFINDEX_PHYSOUTDEV:
52 		if (mnl_attr_validate(attr, MNL_TYPE_U32) < 0) {
53 			perror("mnl_attr_validate");
54 			return MNL_CB_ERROR;
55 		}
56 		break;
57 	case NFQA_TIMESTAMP:
58 		if (mnl_attr_validate2(attr, MNL_TYPE_UNSPEC,
59 		    sizeof(struct nfqnl_msg_packet_timestamp)) < 0) {
60 			perror("mnl_attr_validate2");
61 			return MNL_CB_ERROR;
62 		}
63 		break;
64 	case NFQA_HWADDR:
65 		if (mnl_attr_validate2(attr, MNL_TYPE_UNSPEC,
66 		    sizeof(struct nfqnl_msg_packet_hw)) < 0) {
67 			perror("mnl_attr_validate2");
68 			return MNL_CB_ERROR;
69 		}
70 		break;
71 	case NFQA_PAYLOAD:
72 		break;
73 	}
74 	tb[type] = attr;
75 	return MNL_CB_OK;
76 }
77 
queue_cb(const struct nlmsghdr * nlh,void * data)78 static int queue_cb(const struct nlmsghdr *nlh, void *data)
79 {
80 	struct nlattr *tb[NFQA_MAX+1] = { 0 };
81 	struct nfqnl_msg_packet_hdr *ph = NULL;
82 	uint32_t id = 0;
83 
84 	(void)data;
85 
86 	mnl_attr_parse(nlh, sizeof(struct nfgenmsg), parse_attr_cb, tb);
87 	if (tb[NFQA_PACKET_HDR]) {
88 		ph = mnl_attr_get_payload(tb[NFQA_PACKET_HDR]);
89 		id = ntohl(ph->packet_id);
90 
91 		if (opts.verbose > 0)
92 			printf("packet hook=%u, hwproto 0x%x",
93 				ntohs(ph->hw_protocol), ph->hook);
94 
95 		if (ph->hook >= 5) {
96 			fprintf(stderr, "Unknown hook %d\n", ph->hook);
97 			return MNL_CB_ERROR;
98 		}
99 
100 		if (opts.verbose > 0) {
101 			uint32_t skbinfo = 0;
102 
103 			if (tb[NFQA_SKB_INFO])
104 				skbinfo = ntohl(mnl_attr_get_u32(tb[NFQA_SKB_INFO]));
105 			if (skbinfo & NFQA_SKB_CSUMNOTREADY)
106 				printf(" csumnotready");
107 			if (skbinfo & NFQA_SKB_GSO)
108 				printf(" gso");
109 			if (skbinfo & NFQA_SKB_CSUM_NOTVERIFIED)
110 				printf(" csumnotverified");
111 			puts("");
112 		}
113 
114 		if (opts.count_packets)
115 			queue_stats[ph->hook]++;
116 	}
117 
118 	return MNL_CB_OK + id;
119 }
120 
121 static struct nlmsghdr *
nfq_build_cfg_request(char * buf,uint8_t command,int queue_num)122 nfq_build_cfg_request(char *buf, uint8_t command, int queue_num)
123 {
124 	struct nlmsghdr *nlh = mnl_nlmsg_put_header(buf);
125 	struct nfqnl_msg_config_cmd cmd = {
126 		.command = command,
127 		.pf = htons(AF_INET),
128 	};
129 	struct nfgenmsg *nfg;
130 
131 	nlh->nlmsg_type	= (NFNL_SUBSYS_QUEUE << 8) | NFQNL_MSG_CONFIG;
132 	nlh->nlmsg_flags = NLM_F_REQUEST;
133 
134 	nfg = mnl_nlmsg_put_extra_header(nlh, sizeof(*nfg));
135 
136 	nfg->nfgen_family = AF_UNSPEC;
137 	nfg->version = NFNETLINK_V0;
138 	nfg->res_id = htons(queue_num);
139 
140 	mnl_attr_put(nlh, NFQA_CFG_CMD, sizeof(cmd), &cmd);
141 
142 	return nlh;
143 }
144 
145 static struct nlmsghdr *
nfq_build_cfg_params(char * buf,uint8_t mode,int range,int queue_num)146 nfq_build_cfg_params(char *buf, uint8_t mode, int range, int queue_num)
147 {
148 	struct nlmsghdr *nlh = mnl_nlmsg_put_header(buf);
149 	struct nfqnl_msg_config_params params = {
150 		.copy_range = htonl(range),
151 		.copy_mode = mode,
152 	};
153 	struct nfgenmsg *nfg;
154 
155 	nlh->nlmsg_type	= (NFNL_SUBSYS_QUEUE << 8) | NFQNL_MSG_CONFIG;
156 	nlh->nlmsg_flags = NLM_F_REQUEST;
157 
158 	nfg = mnl_nlmsg_put_extra_header(nlh, sizeof(*nfg));
159 	nfg->nfgen_family = AF_UNSPEC;
160 	nfg->version = NFNETLINK_V0;
161 	nfg->res_id = htons(queue_num);
162 
163 	mnl_attr_put(nlh, NFQA_CFG_PARAMS, sizeof(params), &params);
164 
165 	return nlh;
166 }
167 
168 static struct nlmsghdr *
nfq_build_verdict(char * buf,int id,int queue_num,uint32_t verd)169 nfq_build_verdict(char *buf, int id, int queue_num, uint32_t verd)
170 {
171 	struct nfqnl_msg_verdict_hdr vh = {
172 		.verdict = htonl(verd),
173 		.id = htonl(id),
174 	};
175 	struct nlmsghdr *nlh;
176 	struct nfgenmsg *nfg;
177 
178 	nlh = mnl_nlmsg_put_header(buf);
179 	nlh->nlmsg_type = (NFNL_SUBSYS_QUEUE << 8) | NFQNL_MSG_VERDICT;
180 	nlh->nlmsg_flags = NLM_F_REQUEST;
181 	nfg = mnl_nlmsg_put_extra_header(nlh, sizeof(*nfg));
182 	nfg->nfgen_family = AF_UNSPEC;
183 	nfg->version = NFNETLINK_V0;
184 	nfg->res_id = htons(queue_num);
185 
186 	mnl_attr_put(nlh, NFQA_VERDICT_HDR, sizeof(vh), &vh);
187 
188 	return nlh;
189 }
190 
print_stats(void)191 static void print_stats(void)
192 {
193 	unsigned int last, total;
194 	int i;
195 
196 	total = 0;
197 	last = queue_stats[0];
198 
199 	for (i = 0; i < 5; i++) {
200 		printf("hook %d packets %08u\n", i, queue_stats[i]);
201 		last = queue_stats[i];
202 		total += last;
203 	}
204 
205 	printf("%u packets total\n", total);
206 }
207 
open_queue(void)208 struct mnl_socket *open_queue(void)
209 {
210 	char buf[MNL_SOCKET_BUFFER_SIZE];
211 	unsigned int queue_num;
212 	struct mnl_socket *nl;
213 	struct nlmsghdr *nlh;
214 	struct timeval tv;
215 	uint32_t flags;
216 
217 	nl = mnl_socket_open(NETLINK_NETFILTER);
218 	if (nl == NULL) {
219 		perror("mnl_socket_open");
220 		exit(EXIT_FAILURE);
221 	}
222 
223 	if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
224 		perror("mnl_socket_bind");
225 		exit(EXIT_FAILURE);
226 	}
227 
228 	queue_num = opts.queue_num;
229 	nlh = nfq_build_cfg_request(buf, NFQNL_CFG_CMD_BIND, queue_num);
230 
231 	if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
232 		perror("mnl_socket_sendto");
233 		exit(EXIT_FAILURE);
234 	}
235 
236 	nlh = nfq_build_cfg_params(buf, NFQNL_COPY_PACKET, 0xFFFF, queue_num);
237 
238 	flags = opts.gso_enabled ? NFQA_CFG_F_GSO : 0;
239 	flags |= NFQA_CFG_F_UID_GID;
240 	if (opts.failopen)
241 		flags |= NFQA_CFG_F_FAIL_OPEN;
242 	mnl_attr_put_u32(nlh, NFQA_CFG_FLAGS, htonl(flags));
243 	mnl_attr_put_u32(nlh, NFQA_CFG_MASK, htonl(flags));
244 
245 	if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
246 		perror("mnl_socket_sendto");
247 		exit(EXIT_FAILURE);
248 	}
249 
250 	memset(&tv, 0, sizeof(tv));
251 	tv.tv_sec = opts.timeout;
252 	if (opts.timeout && setsockopt(mnl_socket_get_fd(nl),
253 				       SOL_SOCKET, SO_RCVTIMEO,
254 				       &tv, sizeof(tv))) {
255 		perror("setsockopt(SO_RCVTIMEO)");
256 		exit(EXIT_FAILURE);
257 	}
258 
259 	return nl;
260 }
261 
sleep_ms(uint32_t delay)262 static void sleep_ms(uint32_t delay)
263 {
264 	struct timespec ts = { .tv_sec = delay / 1000 };
265 
266 	delay %= 1000;
267 
268 	ts.tv_nsec = delay * 1000llu * 1000llu;
269 
270 	nanosleep(&ts, NULL);
271 }
272 
mainloop(void)273 static int mainloop(void)
274 {
275 	unsigned int buflen = 64 * 1024 + MNL_SOCKET_BUFFER_SIZE;
276 	struct mnl_socket *nl;
277 	struct nlmsghdr *nlh;
278 	unsigned int portid;
279 	char *buf;
280 	int ret;
281 
282 	buf = malloc(buflen);
283 	if (!buf) {
284 		perror("malloc");
285 		exit(EXIT_FAILURE);
286 	}
287 
288 	nl = open_queue();
289 	portid = mnl_socket_get_portid(nl);
290 
291 	for (;;) {
292 		uint32_t id;
293 
294 		ret = mnl_socket_recvfrom(nl, buf, buflen);
295 		if (ret == -1) {
296 			if (errno == ENOBUFS || errno == EINTR)
297 				continue;
298 
299 			if (errno == EAGAIN) {
300 				errno = 0;
301 				ret = 0;
302 				break;
303 			}
304 
305 			perror("mnl_socket_recvfrom");
306 			exit(EXIT_FAILURE);
307 		}
308 
309 		ret = mnl_cb_run(buf, ret, 0, portid, queue_cb, NULL);
310 		if (ret < 0) {
311 			perror("mnl_cb_run");
312 			exit(EXIT_FAILURE);
313 		}
314 
315 		id = ret - MNL_CB_OK;
316 		if (opts.delay_ms)
317 			sleep_ms(opts.delay_ms);
318 
319 		nlh = nfq_build_verdict(buf, id, opts.queue_num, opts.verdict);
320 		if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
321 			perror("mnl_socket_sendto");
322 			exit(EXIT_FAILURE);
323 		}
324 	}
325 
326 	mnl_socket_close(nl);
327 
328 	return ret;
329 }
330 
parse_opts(int argc,char ** argv)331 static void parse_opts(int argc, char **argv)
332 {
333 	int c;
334 
335 	while ((c = getopt(argc, argv, "chvot:q:Q:d:G")) != -1) {
336 		switch (c) {
337 		case 'c':
338 			opts.count_packets = true;
339 			break;
340 		case 'h':
341 			help(argv[0]);
342 			exit(0);
343 			break;
344 		case 'q':
345 			opts.queue_num = atoi(optarg);
346 			if (opts.queue_num > 0xffff)
347 				opts.queue_num = 0;
348 			break;
349 		case 'Q':
350 			opts.verdict = atoi(optarg);
351 			if (opts.verdict > 0xffff) {
352 				fprintf(stderr, "Expected destination queue number\n");
353 				exit(1);
354 			}
355 
356 			opts.verdict <<= 16;
357 			opts.verdict |= NF_QUEUE;
358 			break;
359 		case 'd':
360 			opts.delay_ms = atoi(optarg);
361 			if (opts.delay_ms == 0) {
362 				fprintf(stderr, "Expected nonzero delay (in milliseconds)\n");
363 				exit(1);
364 			}
365 			break;
366 		case 't':
367 			opts.timeout = atoi(optarg);
368 			break;
369 		case 'G':
370 			opts.gso_enabled = false;
371 			break;
372 		case 'o':
373 			opts.failopen = true;
374 			break;
375 		case 'v':
376 			opts.verbose++;
377 			break;
378 		}
379 	}
380 
381 	if (opts.verdict != NF_ACCEPT && (opts.verdict >> 16 == opts.queue_num)) {
382 		fprintf(stderr, "Cannot use same destination and source queue\n");
383 		exit(1);
384 	}
385 }
386 
main(int argc,char * argv[])387 int main(int argc, char *argv[])
388 {
389 	int ret;
390 
391 	opts.verdict = NF_ACCEPT;
392 	opts.gso_enabled = true;
393 
394 	parse_opts(argc, argv);
395 
396 	ret = mainloop();
397 	if (opts.count_packets)
398 		print_stats();
399 
400 	return ret;
401 }
402