xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/request_key/request_key02.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2016 Fujitsu Ltd.
4  * Copyright (c) 2017 Petr Vorel <[email protected]>
5  *
6  * Author: Xiao Yang <[email protected]>
7  */
8 
9 /*
10  * Test Name: request_key02
11  *
12  * Description:
13  * 1) request_key(2) fails if no matching key was found.
14  * 2) request_key(2) fails if A revoked key was found.
15  * 3) request_key(2) fails if An expired key was found.
16  *
17  * Expected Result:
18  * 1) request_key(2) should return -1 and set errno to ENOKEY.
19  * 2) request_key(2) should return -1 and set errno to EKEYREVOKED.
20  * 3) request_key(2) should return -1 and set errno to EKEYEXPIRED.
21  */
22 
23 #include <errno.h>
24 
25 #include "tst_test.h"
26 #include "lapi/keyctl.h"
27 
28 static int key1;
29 static int key2;
30 static int key3;
31 
32 static struct test_case {
33 	const char *des;
34 	int exp_err;
35 	int *id;
36 } tcases[] = {
37 	{"ltp1", ENOKEY, &key1},
38 	{"ltp2", EKEYREVOKED, &key2},
39 	{"ltp3", EKEYEXPIRED, &key3}
40 };
41 
verify_request_key(unsigned int n)42 static void verify_request_key(unsigned int n)
43 {
44 	struct test_case *tc = tcases + n;
45 
46 	TEST(request_key("keyring", tc->des, NULL, *tc->id));
47 	if (TST_RET != -1) {
48 		tst_res(TFAIL, "request_key() succeed unexpectly");
49 		return;
50 	}
51 
52 	if (TST_ERR == tc->exp_err) {
53 		tst_res(TPASS | TTERRNO, "request_key() failed expectly");
54 		return;
55 	}
56 
57 	tst_res(TFAIL | TTERRNO, "request_key() failed unexpectly, "
58 		"expected %s", tst_strerrno(tc->exp_err));
59 }
60 
init_key(char * name,int cmd)61 static int init_key(char *name, int cmd)
62 {
63 	int n;
64 	int sec = 1;
65 
66 	n = add_key("keyring", name, NULL, 0, KEY_SPEC_THREAD_KEYRING);
67 	if (n == -1)
68 		tst_brk(TBROK | TERRNO, "add_key() failed");
69 
70 	if (cmd == KEYCTL_REVOKE) {
71 		if (keyctl(cmd, n) == -1) {
72 			tst_brk(TBROK | TERRNO,	"failed to revoke a key");
73 		}
74 	}
75 
76 	if (cmd == KEYCTL_SET_TIMEOUT) {
77 		if (keyctl(cmd, n, sec) == -1) {
78 			tst_brk(TBROK | TERRNO,
79 				"failed to set timeout for a key");
80 		}
81 
82 		sleep(sec + 1);
83 	}
84 
85 	return n;
86 }
87 
setup(void)88 static void setup(void)
89 {
90 	key1 = KEY_REQKEY_DEFL_DEFAULT;
91 	key2 = init_key("ltp2", KEYCTL_REVOKE);
92 	key3 = init_key("ltp3", KEYCTL_SET_TIMEOUT);
93 }
94 
95 static struct tst_test test = {
96 	.setup = setup,
97 	.tcnt = ARRAY_SIZE(tcases),
98 	.test = verify_request_key,
99 };
100