// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Copyright (c) 2017 FUJITSU LIMITED
 * Author: Guangwen Feng <fenggw-fnst@cn.fujitsu.com>
 */

/*
 * Test for CVE-2017-2618, this regression test can crash
 * the buggy kernel, and the bug was fixed in:
 *
 *  commit 0c461cb727d146c9ef2d3e86214f498b78b7d125
 *  Author: Stephen Smalley <sds@tycho.nsa.gov>
 *  Date:   Tue Jan 31 11:54:04 2017 -0500
 *
 *  selinux: fix off-by-one in setprocattr
 */

#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include "tst_test.h"

#define LOOPS	100
#define PATH_ATTRFS	"/proc/self/attr/fscreate"

static void setup(void)
{
	if (access(PATH_ATTRFS, F_OK))
		tst_brk(TCONF, "%s does not exist", PATH_ATTRFS);
}

static void do_test(void)
{
	int i, fd;

	for (i = 0; i < LOOPS; i++) {
		if (!SAFE_FORK()) {
			fd = SAFE_OPEN(PATH_ATTRFS, O_WRONLY);
			write(fd, "\n", 1);
			SAFE_CLOSE(fd);
			exit(0);
		}

		tst_reap_children();
	}

	tst_res(TPASS, "Bug not reproduced");
}

static struct tst_test test = {
	.forks_child = 1,
	.setup = setup,
	.test_all = do_test,
	.tags = (const struct tst_tag[]) {
		{"linux-git", "0c461cb727d1"},
		{"CVE", "2017-2618"},
		{}
	}
};
