1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * Copyright (c) 2017 Richard Palethorpe <rpalethorpe@suse.com>
4 */
5/* Test for CVE-2017-7308 on a raw socket's ring buffer
6 *
7 * Try to set tpacket_req3.tp_sizeof_priv to a value with the high bit set. So
8 * that tp_block_size < tp_sizeof_priv. If the vulnerability is present then
9 * this will cause an integer arithmetic overflow and the absurd
10 * tp_sizeof_priv value will be allowed. If it has been fixed then setsockopt
11 * will fail with EINVAL.
12 *
13 * We also try a good configuration to make sure it is not failing with EINVAL
14 * for some other reason.
15 *
16 * For a better and more interesting discussion of this CVE see:
17 * https://googleprojectzero.blogspot.com/2017/05/exploiting-linux-kernel-via-packet.html
18 */
19
20#include <errno.h>
21#include "tst_test.h"
22#include "tst_safe_net.h"
23#include "lapi/if_packet.h"
24#include "lapi/if_ether.h"
25
26static int sk;
27static long pgsz;
28
29static void setup(void)
30{
31	pgsz = SAFE_SYSCONF(_SC_PAGESIZE);
32}
33
34static void cleanup(void)
35{
36	if (sk > 0)
37		SAFE_CLOSE(sk);
38}
39
40static int create_skbuf(unsigned int sizeof_priv)
41{
42	int ver = TPACKET_V3;
43	struct tpacket_req3 req = {};
44
45	req.tp_block_size = pgsz;
46	req.tp_block_nr = 2;
47	req.tp_frame_size = req.tp_block_size;
48	req.tp_frame_nr = req.tp_block_nr;
49	req.tp_retire_blk_tov = 100;
50
51	req.tp_sizeof_priv = sizeof_priv;
52
53	sk = SAFE_SOCKET(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
54	TEST(setsockopt(sk, SOL_PACKET, PACKET_VERSION, &ver, sizeof(ver)));
55	if (TST_RET && TST_ERR == EINVAL)
56		tst_brk(TCONF | TTERRNO, "TPACKET_V3 not supported");
57	if (TST_RET)
58		tst_brk(TBROK | TTERRNO, "setsockopt(sk, SOL_PACKET, PACKET_VERSION, TPACKET_V3)");
59
60	return setsockopt(sk, SOL_PACKET, PACKET_RX_RING, &req, sizeof(req));
61}
62
63static void good_size(void)
64{
65	TEST(create_skbuf(512));
66	if (TST_RET)
67		tst_brk(TBROK | TTERRNO, "Can't create ring buffer with good settings");
68
69	tst_res(TPASS, "Can create ring buffer with good settinegs");
70}
71
72static void bad_size(void)
73{
74	TEST(create_skbuf(3U << 30));
75	if (TST_RET && TST_ERR != EINVAL)
76		tst_brk(TBROK | TTERRNO, "Unexpected setsockopt() error");
77	if (TST_RET)
78		tst_res(TPASS | TTERRNO, "Refused bad tp_sizeof_priv value");
79	else
80		tst_res(TFAIL, "Allowed bad tp_sizeof_priv value");
81}
82
83static void run(unsigned int i)
84{
85	if (i == 0)
86		good_size();
87	else
88		bad_size();
89
90	SAFE_CLOSE(sk);
91}
92
93static struct tst_test test = {
94	.test = run,
95	.tcnt = 2,
96	.needs_root = 1,
97	.setup = setup,
98	.cleanup = cleanup,
99	.tags = (const struct tst_tag[]) {
100		{"CVE", "2017-7308"},
101		{}
102	}
103};
104