xref: /linux/arch/s390/kernel/cert_store.c (revision 23a04cb4f2bdbfc87fc4e1c15450e7f8cfc9842a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * DIAG 0x320 support and certificate store handling
4  *
5  * Copyright IBM Corp. 2023
6  * Author(s):	Anastasia Eskova <anastasia.eskova@ibm.com>
7  */
8 
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10 
11 #include <linux/delay.h>
12 #include <linux/device.h>
13 #include <linux/fs.h>
14 #include <linux/init.h>
15 #include <linux/kernel.h>
16 #include <linux/key-type.h>
17 #include <linux/key.h>
18 #include <linux/keyctl.h>
19 #include <linux/kobject.h>
20 #include <linux/module.h>
21 #include <linux/rwsem.h>
22 #include <linux/seq_file.h>
23 #include <linux/slab.h>
24 #include <linux/sysfs.h>
25 #include <linux/vmalloc.h>
26 #include <crypto/sha2.h>
27 #include <keys/user-type.h>
28 #include <asm/debug.h>
29 #include <asm/diag.h>
30 #include <asm/ebcdic.h>
31 #include <asm/sclp.h>
32 
33 #define DIAG_MAX_RETRIES		10
34 
35 #define VCE_FLAGS_VALID_MASK		0x80
36 
37 #define ISM_LEN_DWORDS			4
38 #define VCSSB_LEN_BYTES			128
39 #define VCSSB_LEN_NO_CERTS		4
40 #define VCB_LEN_NO_CERTS		64
41 #define VC_NAME_LEN_BYTES		64
42 
43 #define CERT_STORE_KEY_TYPE_NAME	"cert_store_key"
44 #define CERT_STORE_KEYRING_NAME		"cert_store"
45 
46 static debug_info_t *cert_store_dbf;
47 static debug_info_t *cert_store_hexdump;
48 
49 /* Task currently running refresh_store(). Written under cs_refresh_lock. */
50 static struct task_struct *cs_refresh_task;
51 
52 #define pr_dbf_msg(fmt, ...) \
53 	debug_sprintf_event(cert_store_dbf, 3, fmt "\n", ## __VA_ARGS__)
54 
55 enum diag320_subcode {
56 	DIAG320_SUBCODES	= 0,
57 	DIAG320_STORAGE		= 1,
58 	DIAG320_CERT_BLOCK	= 2,
59 };
60 
61 enum diag320_rc {
62 	DIAG320_RC_OK		= 0x0001,
63 	DIAG320_RC_CS_NOMATCH	= 0x0306,
64 };
65 
66 /* Verification Certificates Store Support Block (VCSSB). */
67 struct vcssb {
68 	u32 vcssb_length;
69 	u8  pad_0x04[3];
70 	u8  version;
71 	u8  pad_0x08[8];
72 	u32 cs_token;
73 	u8  pad_0x14[12];
74 	u16 total_vc_index_count;
75 	u16 max_vc_index_count;
76 	u8  pad_0x24[28];
77 	u32 max_vce_length;
78 	u32 max_vcxe_length;
79 	u8  pad_0x48[8];
80 	u32 max_single_vcb_length;
81 	u32 total_vcb_length;
82 	u32 max_single_vcxb_length;
83 	u32 total_vcxb_length;
84 	u8  pad_0x60[32];
85 } __packed __aligned(8);
86 
87 /* Verification Certificate Entry (VCE) Header. */
88 struct vce_header {
89 	u32 vce_length;
90 	u8  flags;
91 	u8  key_type;
92 	u16 vc_index;
93 	u8  vc_name[VC_NAME_LEN_BYTES]; /* EBCDIC */
94 	u8  vc_format;
95 	u8  pad_0x49;
96 	u16 key_id_length;
97 	u8  pad_0x4c;
98 	u8  vc_hash_type;
99 	u16 vc_hash_length;
100 	u8  pad_0x50[4];
101 	u32 vc_length;
102 	u8  pad_0x58[8];
103 	u16 vc_hash_offset;
104 	u16 vc_offset;
105 	u8  pad_0x64[28];
106 } __packed __aligned(4);
107 
108 /* Verification Certificate Block (VCB) Header. */
109 struct vcb_header {
110 	u32 vcb_input_length;
111 	u8  pad_0x04[4];
112 	u16 first_vc_index;
113 	u16 last_vc_index;
114 	u32 pad_0x0c;
115 	u32 cs_token;
116 	u8  pad_0x14[12];
117 	u32 vcb_output_length;
118 	u8  pad_0x24[3];
119 	u8  version;
120 	u16 stored_vc_count;
121 	u16 remaining_vc_count;
122 	u8  pad_0x2c[20];
123 } __packed __aligned(4);
124 
125 /* Verification Certificate Block (VCB). */
126 struct vcb {
127 	struct vcb_header vcb_hdr;
128 	u8 vcb_buf[];
129 } __packed __aligned(4);
130 
131 /* Verification Certificate Entry (VCE). */
132 struct vce {
133 	struct vce_header vce_hdr;
134 	u8 cert_data_buf[];
135 } __packed __aligned(4);
136 
137 static void cert_store_key_describe(const struct key *key, struct seq_file *m)
138 {
139 	char ascii[VC_NAME_LEN_BYTES + 1];
140 
141 	/*
142 	 * First 64 bytes of the key description is key name in EBCDIC CP 500.
143 	 * Convert it to ASCII for displaying in /proc/keys.
144 	 */
145 	strscpy(ascii, key->description);
146 	EBCASC_500(ascii, VC_NAME_LEN_BYTES);
147 	seq_puts(m, ascii);
148 
149 	seq_puts(m, &key->description[VC_NAME_LEN_BYTES]);
150 	if (key_is_positive(key))
151 		seq_printf(m, ": %u", key->datalen);
152 }
153 
154 /*
155  * Only the kernel may create keys of this type. Accept the task which runs
156  * refresh_store(), as it cannot execute userspace during the refresh.
157  */
158 static int cert_store_key_vet_description(const char *description)
159 {
160 	if (READ_ONCE(cs_refresh_task) != current)
161 		return -EPERM;
162 	return 0;
163 }
164 
165 /*
166  * Certificate store key type takes over properties of
167  * user key but cannot be updated.
168  */
169 static struct key_type key_type_cert_store_key = {
170 	.name		= CERT_STORE_KEY_TYPE_NAME,
171 	.vet_description = cert_store_key_vet_description,
172 	.preparse	= user_preparse,
173 	.free_preparse	= user_free_preparse,
174 	.instantiate	= generic_key_instantiate,
175 	.revoke		= user_revoke,
176 	.destroy	= user_destroy,
177 	.describe	= cert_store_key_describe,
178 	.read		= user_read,
179 };
180 
181 /* Logging functions. */
182 static void pr_dbf_vcb(const struct vcb *b)
183 {
184 	pr_dbf_msg("VCB Header:");
185 	pr_dbf_msg("vcb_input_length: %d", b->vcb_hdr.vcb_input_length);
186 	pr_dbf_msg("first_vc_index: %d", b->vcb_hdr.first_vc_index);
187 	pr_dbf_msg("last_vc_index: %d", b->vcb_hdr.last_vc_index);
188 	pr_dbf_msg("cs_token: %d", b->vcb_hdr.cs_token);
189 	pr_dbf_msg("vcb_output_length: %d", b->vcb_hdr.vcb_output_length);
190 	pr_dbf_msg("version: %d", b->vcb_hdr.version);
191 	pr_dbf_msg("stored_vc_count: %d", b->vcb_hdr.stored_vc_count);
192 	pr_dbf_msg("remaining_vc_count: %d", b->vcb_hdr.remaining_vc_count);
193 }
194 
195 static void pr_dbf_vce(const struct vce *e)
196 {
197 	unsigned char vc_name[VC_NAME_LEN_BYTES + 1];
198 	char log_string[VC_NAME_LEN_BYTES + 40];
199 	u32 data_len = 0;
200 
201 	pr_dbf_msg("VCE Header:");
202 	pr_dbf_msg("vce_hdr.vce_length: %d", e->vce_hdr.vce_length);
203 	pr_dbf_msg("vce_hdr.flags: %d", e->vce_hdr.flags);
204 	pr_dbf_msg("vce_hdr.key_type: %d", e->vce_hdr.key_type);
205 	pr_dbf_msg("vce_hdr.vc_index: %d", e->vce_hdr.vc_index);
206 	pr_dbf_msg("vce_hdr.vc_format: %d", e->vce_hdr.vc_format);
207 	pr_dbf_msg("vce_hdr.key_id_length: %d", e->vce_hdr.key_id_length);
208 	pr_dbf_msg("vce_hdr.vc_hash_type: %d", e->vce_hdr.vc_hash_type);
209 	pr_dbf_msg("vce_hdr.vc_hash_length: %d", e->vce_hdr.vc_hash_length);
210 	pr_dbf_msg("vce_hdr.vc_hash_offset: %d", e->vce_hdr.vc_hash_offset);
211 	pr_dbf_msg("vce_hdr.vc_length: %d", e->vce_hdr.vc_length);
212 	pr_dbf_msg("vce_hdr.vc_offset: %d", e->vce_hdr.vc_offset);
213 
214 	/* Certificate name in ASCII. */
215 	memcpy(vc_name, e->vce_hdr.vc_name, VC_NAME_LEN_BYTES);
216 	EBCASC_500(vc_name, VC_NAME_LEN_BYTES);
217 	vc_name[VC_NAME_LEN_BYTES] = '\0';
218 
219 	snprintf(log_string, sizeof(log_string),
220 		 "index: %d vce_hdr.vc_name (ASCII): %s",
221 		 e->vce_hdr.vc_index, vc_name);
222 	debug_text_event(cert_store_hexdump, 3, log_string);
223 
224 	/* Certificate data. */
225 	if (e->vce_hdr.vce_length > sizeof(e->vce_hdr))
226 		data_len = e->vce_hdr.vce_length - sizeof(e->vce_hdr);
227 	debug_text_event(cert_store_hexdump, 3, "VCE: Certificate data start");
228 	debug_event(cert_store_hexdump, 3, (u8 *)e->cert_data_buf, min(data_len, 128U));
229 	debug_text_event(cert_store_hexdump, 3, "VCE: Certificate data end");
230 	if (data_len > 128)
231 		debug_event(cert_store_hexdump, 3, (u8 *)e + e->vce_hdr.vce_length - 128, 128);
232 }
233 
234 static void pr_dbf_vcssb(const struct vcssb *s)
235 {
236 	debug_text_event(cert_store_hexdump, 3, "DIAG320 Subcode1");
237 	debug_event(cert_store_hexdump, 3, (u8 *)s, VCSSB_LEN_BYTES);
238 
239 	pr_dbf_msg("VCSSB:");
240 	pr_dbf_msg("vcssb_length: %u", s->vcssb_length);
241 	pr_dbf_msg("version: %u", s->version);
242 	pr_dbf_msg("cs_token: %u", s->cs_token);
243 	pr_dbf_msg("total_vc_index_count: %u", s->total_vc_index_count);
244 	pr_dbf_msg("max_vc_index_count: %u", s->max_vc_index_count);
245 	pr_dbf_msg("max_vce_length: %u", s->max_vce_length);
246 	pr_dbf_msg("max_vcxe_length: %u", s->max_vcxe_length);
247 	pr_dbf_msg("max_single_vcb_length: %u", s->max_single_vcb_length);
248 	pr_dbf_msg("total_vcb_length: %u", s->total_vcb_length);
249 	pr_dbf_msg("max_single_vcxb_length: %u", s->max_single_vcxb_length);
250 	pr_dbf_msg("total_vcxb_length: %u", s->total_vcxb_length);
251 }
252 
253 static int __diag320(unsigned long subcode, void *addr)
254 {
255 	union register_pair rp = { .even = (unsigned long)addr, };
256 
257 	asm_inline volatile(
258 		"0:	diag	%[rp],%[subcode],0x320\n"
259 		"1:\n"
260 		EX_TABLE_INSN(0b, 1b)
261 		: [rp] "+d" (rp.pair)
262 		: [subcode] "d" (subcode)
263 		: "cc", "memory");
264 
265 	return rp.odd;
266 }
267 
268 static int diag320(unsigned long subcode, void *addr)
269 {
270 	diag_stat_inc(DIAG_STAT_X320);
271 
272 	return __diag320(subcode, addr);
273 }
274 
275 /*
276  * Calculate SHA256 hash of the VCE certificate and compare it to hash stored in
277  * VCE. Return -EINVAL if hashes don't match.
278  */
279 static int check_certificate_hash(const struct vce *vce)
280 {
281 	u8 hash[SHA256_DIGEST_SIZE];
282 	u8 *vce_hash;
283 
284 	vce_hash = (u8 *)vce + vce->vce_hdr.vc_hash_offset;
285 	sha256((u8 *)vce + vce->vce_hdr.vc_offset, vce->vce_hdr.vc_length, hash);
286 	if (memcmp(vce_hash, hash, sizeof(hash)) == 0)
287 		return 0;
288 
289 	pr_dbf_msg("SHA256 hash of received certificate does not match");
290 	debug_text_event(cert_store_hexdump, 3, "VCE hash:");
291 	debug_event(cert_store_hexdump, 3, vce_hash, SHA256_DIGEST_SIZE);
292 	debug_text_event(cert_store_hexdump, 3, "Calculated hash:");
293 	debug_event(cert_store_hexdump, 3, hash, SHA256_DIGEST_SIZE);
294 
295 	return -EINVAL;
296 }
297 
298 static int check_certificate_valid(const struct vce *vce)
299 {
300 	if (!(vce->vce_hdr.flags & VCE_FLAGS_VALID_MASK)) {
301 		pr_dbf_msg("Certificate entry is invalid");
302 		return -EINVAL;
303 	}
304 	if (vce->vce_hdr.vc_format != 1) {
305 		pr_dbf_msg("Certificate format is not supported");
306 		return -EINVAL;
307 	}
308 	if (vce->vce_hdr.vc_hash_type != 1) {
309 		pr_dbf_msg("Hash type is not supported");
310 		return -EINVAL;
311 	}
312 	if (vce->vce_hdr.vc_hash_length != SHA256_DIGEST_SIZE) {
313 		pr_dbf_msg("Hash length is not supported");
314 		return -EINVAL;
315 	}
316 
317 	return check_certificate_hash(vce);
318 }
319 
320 static struct key *get_user_session_keyring(void)
321 {
322 	key_ref_t us_keyring_ref;
323 
324 	us_keyring_ref = lookup_user_key(KEY_SPEC_USER_SESSION_KEYRING,
325 					 KEY_LOOKUP_CREATE, KEY_NEED_LINK);
326 	if (IS_ERR(us_keyring_ref)) {
327 		pr_dbf_msg("Couldn't get user session keyring: %ld",
328 			   PTR_ERR(us_keyring_ref));
329 		return ERR_PTR(-ENOKEY);
330 	}
331 	return key_ref_to_ptr(us_keyring_ref);
332 }
333 
334 /* Invalidate all keys from cert_store keyring. */
335 static int invalidate_keyring_keys(struct key *keyring)
336 {
337 	unsigned long num_keys, key_index;
338 	long keyring_payload_len, rc;
339 	key_serial_t *key_array;
340 	struct key *current_key;
341 
342 	scoped_guard(rwsem_read, &keyring->sem) {
343 		keyring_payload_len = key_type_keyring.read(keyring, NULL, 0);
344 		if (keyring_payload_len <= 0)
345 			return keyring_payload_len;
346 
347 		num_keys = keyring_payload_len / sizeof(key_serial_t);
348 		key_array = kzalloc_objs(key_serial_t, num_keys);
349 		if (!key_array)
350 			return -ENOMEM;
351 
352 		rc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len);
353 	}
354 
355 	if (rc != keyring_payload_len) {
356 		pr_dbf_msg("Couldn't read keyring payload");
357 		rc = rc < 0 ? rc : -EINVAL;
358 		goto out;
359 	}
360 
361 	rc = 0;
362 	for (key_index = 0; key_index < num_keys; key_index++) {
363 		current_key = key_lookup(key_array[key_index]);
364 		if (IS_ERR(current_key))
365 			continue;
366 		pr_dbf_msg("Invalidating key %08x", current_key->serial);
367 
368 		rc = key_unlink(keyring, current_key);
369 		if (rc)
370 			pr_dbf_msg("Couldn't unlink key %08x: %ld", current_key->serial, rc);
371 		key_invalidate(current_key);
372 		key_put(current_key);
373 		if (rc)
374 			break;
375 	}
376 out:
377 	kfree(key_array);
378 	return rc;
379 }
380 
381 static struct key *find_cs_keyring(void)
382 {
383 	struct key *us_keyring;
384 	key_ref_t cs_keyring_ref;
385 
386 	us_keyring = get_user_session_keyring();
387 	if (!IS_ERR(us_keyring)) {
388 		cs_keyring_ref = keyring_search(make_key_ref(us_keyring, true),
389 						&key_type_keyring,
390 						CERT_STORE_KEYRING_NAME,
391 						false);
392 		key_put(us_keyring);
393 		if (!IS_ERR(cs_keyring_ref))
394 			return key_ref_to_ptr(cs_keyring_ref);
395 	}
396 	return NULL;
397 }
398 
399 static void cleanup_cs_keys(void)
400 {
401 	struct key *cs_keyring, *us_keyring;
402 
403 	cs_keyring = find_cs_keyring();
404 	if (!cs_keyring)
405 		return;
406 
407 	pr_dbf_msg("Found cert_store keyring. Purging...");
408 	/*
409 	 * Remove cert_store_key_type in case invalidation
410 	 * of old cert_store keys failed (= severe error).
411 	 */
412 	if (invalidate_keyring_keys(cs_keyring))
413 		unregister_key_type(&key_type_cert_store_key);
414 
415 	keyring_clear(cs_keyring);
416 	key_invalidate(cs_keyring);
417 	us_keyring = get_user_session_keyring();
418 	if (!IS_ERR(us_keyring)) {
419 		key_unlink(us_keyring, cs_keyring);
420 		key_put(us_keyring);
421 	}
422 	key_put(cs_keyring);
423 }
424 
425 static struct key *create_cs_keyring(void)
426 {
427 	struct key_restriction *restriction;
428 	struct key *cs_keyring, *us_keyring;
429 
430 	/* Cleanup previous cs_keyring and all associated keys if any. */
431 	cleanup_cs_keys();
432 	us_keyring = get_user_session_keyring();
433 	if (IS_ERR(us_keyring))
434 		return NULL;
435 	restriction = kzalloc_obj(*restriction);
436 	if (!restriction) {
437 		key_put(us_keyring);
438 		return NULL;
439 	}
440 	/* Reject all links, the kernel bypasses the restriction. */
441 	restriction->check = restrict_link_reject;
442 	cs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID,
443 				   GLOBAL_ROOT_GID, current_cred(),
444 				   (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ,
445 				   KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP,
446 				   restriction, us_keyring);
447 	key_put(us_keyring);
448 	if (IS_ERR(cs_keyring)) {
449 		kfree(restriction);
450 		pr_dbf_msg("Can't allocate cert_store keyring");
451 		return NULL;
452 	}
453 
454 	pr_dbf_msg("Successfully allocated cert_store keyring: %08x", cs_keyring->serial);
455 
456 	/*
457 	 * In case a previous clean-up ran into an
458 	 * error and unregistered key type.
459 	 */
460 	register_key_type(&key_type_cert_store_key);
461 
462 	return cs_keyring;
463 }
464 
465 /*
466  * Allocate memory and create key description in format
467  * [key name in EBCDIC]:[VCE index]:[CS token].
468  * Return a pointer to key description or NULL if memory
469  * allocation failed. Memory should be freed by caller.
470  */
471 static char *get_key_description(struct vcssb *vcssb, const struct vce *vce)
472 {
473 	size_t len, name_len;
474 	u32 cs_token;
475 	char *desc;
476 
477 	cs_token = vcssb->cs_token;
478 	/* Description string contains "%64s:%05u:%010u\0". */
479 	name_len = sizeof(vce->vce_hdr.vc_name);
480 	len = name_len + 1 + 5 + 1 + 10 + 1;
481 	desc = kmalloc(len, GFP_KERNEL);
482 	if (!desc)
483 		return NULL;
484 
485 	memcpy(desc, vce->vce_hdr.vc_name, name_len);
486 	snprintf(desc + name_len, len - name_len, ":%05u:%010u",
487 		 vce->vce_hdr.vc_index, cs_token);
488 
489 	return desc;
490 }
491 
492 /*
493  * Create a key of type "cert_store_key" using the data from VCE for key
494  * payload and key description. Link the key to "cert_store" keyring.
495  */
496 static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce,
497 			       struct key *keyring)
498 {
499 	key_ref_t newkey;
500 	char *desc;
501 	int rc;
502 
503 	desc = get_key_description(vcssb, vce);
504 	if (!desc)
505 		return -ENOMEM;
506 
507 	newkey = key_create_or_update(
508 		make_key_ref(keyring, true), CERT_STORE_KEY_TYPE_NAME,
509 		desc, (u8 *)vce + vce->vce_hdr.vc_offset,
510 		vce->vce_hdr.vc_length,
511 		(KEY_POS_ALL & ~KEY_POS_SETATTR)  | KEY_USR_VIEW | KEY_USR_READ,
512 		KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_BYPASS_RESTRICTION);
513 
514 	rc = PTR_ERR_OR_ZERO(newkey);
515 	if (rc) {
516 		pr_dbf_msg("Couldn't create a key from Certificate Entry (%d)", rc);
517 		rc = -ENOKEY;
518 		goto out;
519 	}
520 
521 	key_ref_put(newkey);
522 out:
523 	kfree(desc);
524 	return rc;
525 }
526 
527 /* Get Verification Certificate Storage Size block with DIAG320 subcode2. */
528 static int get_vcssb(struct vcssb *vcssb)
529 {
530 	int diag320_rc;
531 
532 	memset(vcssb, 0, sizeof(*vcssb));
533 	vcssb->vcssb_length = VCSSB_LEN_BYTES;
534 	diag320_rc = diag320(DIAG320_STORAGE, vcssb);
535 	pr_dbf_vcssb(vcssb);
536 
537 	if (diag320_rc != DIAG320_RC_OK) {
538 		pr_dbf_msg("Diag 320 Subcode 1 returned bad RC: %04x", diag320_rc);
539 		return -EIO;
540 	}
541 	if (vcssb->vcssb_length == VCSSB_LEN_NO_CERTS) {
542 		pr_dbf_msg("No certificates available for current configuration");
543 		return -ENOKEY;
544 	}
545 
546 	return 0;
547 }
548 
549 static u32 get_4k_mult_vcb_size(struct vcssb *vcssb)
550 {
551 	return round_up(vcssb->max_single_vcb_length, PAGE_SIZE);
552 }
553 
554 /* Fill input fields of single-entry VCB that will be read by LPAR. */
555 static void fill_vcb_input(struct vcssb *vcssb, struct vcb *vcb, u16 index)
556 {
557 	memset(vcb, 0, sizeof(*vcb));
558 	vcb->vcb_hdr.vcb_input_length = get_4k_mult_vcb_size(vcssb);
559 	vcb->vcb_hdr.cs_token = vcssb->cs_token;
560 
561 	/* Request single entry. */
562 	vcb->vcb_hdr.first_vc_index = index;
563 	vcb->vcb_hdr.last_vc_index = index;
564 }
565 
566 static void extract_vce_from_sevcb(struct vcb *vcb, struct vce *vce)
567 {
568 	struct vce *extracted_vce;
569 
570 	extracted_vce = (struct vce *)vcb->vcb_buf;
571 	memcpy(vce, vcb->vcb_buf, extracted_vce->vce_hdr.vce_length);
572 	pr_dbf_vce(vce);
573 }
574 
575 static int get_sevcb(struct vcssb *vcssb, u16 index, struct vcb *vcb)
576 {
577 	int rc, diag320_rc;
578 
579 	fill_vcb_input(vcssb, vcb, index);
580 
581 	diag320_rc = diag320(DIAG320_CERT_BLOCK, vcb);
582 	pr_dbf_msg("Diag 320 Subcode2 RC %2x", diag320_rc);
583 	pr_dbf_vcb(vcb);
584 
585 	switch (diag320_rc) {
586 	case DIAG320_RC_OK:
587 		rc = 0;
588 		if (vcb->vcb_hdr.vcb_output_length == VCB_LEN_NO_CERTS) {
589 			pr_dbf_msg("No certificate entry for index %u", index);
590 			rc = -ENOKEY;
591 		} else if (vcb->vcb_hdr.remaining_vc_count != 0) {
592 			/* Retry on insufficient space. */
593 			pr_dbf_msg("Couldn't get all requested certificates");
594 			rc = -EAGAIN;
595 		}
596 		break;
597 	case DIAG320_RC_CS_NOMATCH:
598 		pr_dbf_msg("Certificate Store token mismatch");
599 		rc = -EAGAIN;
600 		break;
601 	default:
602 		pr_dbf_msg("Diag 320 Subcode2 returned bad rc (0x%4x)", diag320_rc);
603 		rc = -EINVAL;
604 		break;
605 	}
606 
607 	return rc;
608 }
609 
610 /*
611  * Allocate memory for single-entry VCB, get VCB via DIAG320 subcode 2 call,
612  * extract VCE and create a key from its' certificate.
613  */
614 static int create_key_from_sevcb(struct vcssb *vcssb, u16 index,
615 				 struct key *keyring)
616 {
617 	struct vcb *vcb;
618 	struct vce *vce;
619 	int rc;
620 
621 	rc = -ENOMEM;
622 	vcb = vmalloc(get_4k_mult_vcb_size(vcssb));
623 	vce = vmalloc(vcssb->max_single_vcb_length - sizeof(vcb->vcb_hdr));
624 	if (!vcb || !vce)
625 		goto out;
626 
627 	rc = get_sevcb(vcssb, index, vcb);
628 	if (rc)
629 		goto out;
630 
631 	extract_vce_from_sevcb(vcb, vce);
632 	rc = check_certificate_valid(vce);
633 	if (rc)
634 		goto out;
635 
636 	rc = create_key_from_vce(vcssb, vce, keyring);
637 	if (rc)
638 		goto out;
639 
640 	pr_dbf_msg("Successfully created key from Certificate Entry %d", index);
641 out:
642 	vfree(vce);
643 	vfree(vcb);
644 	return rc;
645 }
646 
647 /*
648  * Request a single-entry VCB for each VCE available for the partition.
649  * Create a key from it and link it to cert_store keyring. If no keys
650  * could be created (i.e. VCEs were invalid) return -ENOKEY.
651  */
652 static int add_certificates_to_keyring(struct vcssb *vcssb, struct key *keyring)
653 {
654 	int rc, index, count, added;
655 
656 	count = 0;
657 	added = 0;
658 	/* Certificate Store entries indices start with 1 and have no gaps. */
659 	for (index = 1; index < vcssb->total_vc_index_count + 1; index++) {
660 		pr_dbf_msg("Creating key from VCE %u", index);
661 		rc = create_key_from_sevcb(vcssb, index, keyring);
662 		count++;
663 
664 		if (rc == -EAGAIN)
665 			return rc;
666 
667 		if (rc)
668 			pr_dbf_msg("Creating key from VCE %u failed (%d)", index, rc);
669 		else
670 			added++;
671 	}
672 
673 	if (added == 0) {
674 		pr_dbf_msg("Processed %d entries. No keys created", count);
675 		return -ENOKEY;
676 	}
677 
678 	pr_info("Added %d of %d keys to cert_store keyring", added, count);
679 
680 	return 0;
681 }
682 
683 /*
684  * Check which DIAG320 subcodes are installed.
685  * Return -ENOENT if subcodes 1 or 2 are not available.
686  */
687 static int query_diag320_subcodes(void)
688 {
689 	unsigned long ism[ISM_LEN_DWORDS] = {};
690 	int rc;
691 
692 	rc = diag320(0, ism);
693 	if (rc != DIAG320_RC_OK) {
694 		pr_dbf_msg("DIAG320 subcode query returned %04x", rc);
695 		return -ENOENT;
696 	}
697 
698 	debug_text_event(cert_store_hexdump, 3, "DIAG320 Subcode 0");
699 	debug_event(cert_store_hexdump, 3, ism, sizeof(ism));
700 
701 	if (!test_bit_inv(1, ism) || !test_bit_inv(2, ism)) {
702 		pr_dbf_msg("Not all required DIAG320 subcodes are installed");
703 		return -ENOENT;
704 	}
705 
706 	return 0;
707 }
708 
709 /*
710  * Check if Certificate Store is supported by the firmware and DIAG320 subcodes
711  * 1 and 2 are installed. Create cert_store keyring and link all certificates
712  * available for the current partition to it as "cert_store_key" type
713  * keys. On refresh or error invalidate cert_store keyring and destroy
714  * all keys of "cert_store_key" type.
715  */
716 static int fill_cs_keyring(void)
717 {
718 	struct key *cs_keyring;
719 	struct vcssb *vcssb;
720 	int rc;
721 
722 	rc = -ENOMEM;
723 	vcssb = kmalloc(VCSSB_LEN_BYTES, GFP_KERNEL);
724 	if (!vcssb)
725 		goto cleanup_keys;
726 
727 	rc = -ENOENT;
728 	if (!sclp.has_diag320) {
729 		pr_dbf_msg("Certificate Store is not supported");
730 		goto cleanup_keys;
731 	}
732 
733 	rc = query_diag320_subcodes();
734 	if (rc)
735 		goto cleanup_keys;
736 
737 	rc = get_vcssb(vcssb);
738 	if (rc)
739 		goto cleanup_keys;
740 
741 	rc = -ENOMEM;
742 	cs_keyring = create_cs_keyring();
743 	if (!cs_keyring)
744 		goto cleanup_keys;
745 
746 	rc = add_certificates_to_keyring(vcssb, cs_keyring);
747 	key_put(cs_keyring);
748 	if (rc)
749 		goto cleanup_keys;
750 
751 	goto out;
752 
753 cleanup_keys:
754 	cleanup_cs_keys();
755 out:
756 	kfree(vcssb);
757 	return rc;
758 }
759 
760 static DEFINE_MUTEX(cs_refresh_lock);
761 static int cs_status_val = -1;
762 
763 static ssize_t cs_status_show(struct kobject *kobj,
764 			      struct kobj_attribute *attr, char *buf)
765 {
766 	if (cs_status_val == -1)
767 		return sysfs_emit(buf, "uninitialized\n");
768 	else if (cs_status_val == 0)
769 		return sysfs_emit(buf, "ok\n");
770 
771 	return sysfs_emit(buf, "failed (%d)\n", cs_status_val);
772 }
773 
774 static struct kobj_attribute cs_status_attr = __ATTR_RO(cs_status);
775 
776 static ssize_t refresh_store(struct kobject *kobj, struct kobj_attribute *attr,
777 			     const char *buf, size_t count)
778 {
779 	int rc, retries;
780 
781 	pr_dbf_msg("Refresh certificate store information requested");
782 	rc = mutex_lock_interruptible(&cs_refresh_lock);
783 	if (rc)
784 		return rc;
785 
786 	WRITE_ONCE(cs_refresh_task, current);
787 	for (retries = 0; retries < DIAG_MAX_RETRIES; retries++) {
788 		/* Request certificates from certificate store. */
789 		rc = fill_cs_keyring();
790 		if (rc)
791 			pr_dbf_msg("Failed to refresh certificate store information (%d)", rc);
792 		if (rc != -EAGAIN)
793 			break;
794 	}
795 	WRITE_ONCE(cs_refresh_task, NULL);
796 	cs_status_val = rc;
797 	mutex_unlock(&cs_refresh_lock);
798 
799 	return rc ?: count;
800 }
801 
802 static struct kobj_attribute refresh_attr = __ATTR_WO(refresh);
803 
804 static const struct attribute *cert_store_attrs[] __initconst = {
805 	&cs_status_attr.attr,
806 	&refresh_attr.attr,
807 	NULL,
808 };
809 
810 static struct kobject *cert_store_kobj;
811 
812 static int __init cert_store_init(void)
813 {
814 	int rc = -ENOMEM;
815 
816 	cert_store_dbf = debug_register("cert_store_msg", 10, 1, 64);
817 	if (!cert_store_dbf)
818 		goto cleanup_dbf;
819 
820 	cert_store_hexdump = debug_register("cert_store_hexdump", 3, 1, 128);
821 	if (!cert_store_hexdump)
822 		goto cleanup_dbf;
823 
824 	debug_register_view(cert_store_hexdump, &debug_hex_ascii_view);
825 	debug_register_view(cert_store_dbf, &debug_sprintf_view);
826 
827 	/* Create directory /sys/firmware/cert_store. */
828 	cert_store_kobj = kobject_create_and_add("cert_store", firmware_kobj);
829 	if (!cert_store_kobj)
830 		goto cleanup_dbf;
831 
832 	rc = sysfs_create_files(cert_store_kobj, cert_store_attrs);
833 	if (rc)
834 		goto cleanup_kobj;
835 
836 	register_key_type(&key_type_cert_store_key);
837 
838 	return rc;
839 
840 cleanup_kobj:
841 	kobject_put(cert_store_kobj);
842 cleanup_dbf:
843 	debug_unregister(cert_store_dbf);
844 	debug_unregister(cert_store_hexdump);
845 
846 	return rc;
847 }
848 device_initcall(cert_store_init);
849