xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/keyctl/keyctl06.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2017 Google, Inc.
4  * Copyright (c) Linux Test Project, 2017-2024
5  */
6 
7 /*\
8  * [Description]
9  *
10  * Regression test for commit:
11  *
12  * e645016abc80 ("KEYS: fix writing past end of user-supplied buffer in keyring_read()")
13  *
14  * as well as its follow-on fix:
15  *
16  * commit 3239b6f29bdf ("KEYS: return full count in keyring_read() if buffer is too small")
17  */
18 
19 #include <errno.h>
20 
21 #include "tst_test.h"
22 #include "lapi/keyctl.h"
23 
add_test_key(const char * description)24 static void add_test_key(const char *description)
25 {
26 	TEST(add_key("user", description, "payload", 7,
27 		     KEY_SPEC_PROCESS_KEYRING));
28 	if (TST_RET < 0)
29 		tst_brk(TBROK | TTERRNO, "Failed to add test key");
30 }
31 
do_test(void)32 static void do_test(void)
33 {
34 	key_serial_t key_ids[2];
35 
36 	add_test_key("key1");
37 	add_test_key("key2");
38 
39 	memset(key_ids, 0, sizeof(key_ids));
40 	TEST(keyctl(KEYCTL_READ, KEY_SPEC_PROCESS_KEYRING,
41 		    (char *)key_ids, sizeof(key_serial_t)));
42 	if (TST_RET < 0)
43 		tst_brk(TBROK | TTERRNO, "KEYCTL_READ failed");
44 
45 	/*
46 	 * Do not check key_ids[0], as the contents of the buffer are
47 	 * unspecified if it was too small.  However, key_ids[1] must not have
48 	 * been written to, as it was outside the buffer.
49 	 */
50 
51 	if (key_ids[1] != 0)
52 		tst_brk(TFAIL, "KEYCTL_READ overran the buffer");
53 
54 	if (TST_RET != sizeof(key_ids)) {
55 		tst_brk(TFAIL, "KEYCTL_READ returned %ld but expected %zu",
56 			TST_RET, sizeof(key_ids));
57 	}
58 
59 	tst_res(TPASS,
60 		"KEYCTL_READ returned full count but didn't overrun the buffer");
61 }
62 
63 static struct tst_test test = {
64 	.test_all = do_test,
65 	.tags = (const struct tst_tag[]) {
66 		{"linux-git", "e645016abc80"},
67 		{"linux-git", "3239b6f29bdf"},
68 		{}
69 	}
70 };
71