1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  Copyright IBM Corp. 2019
4  *  Author(s): Harald Freudenberger <freude@linux.ibm.com>
5  *	       Ingo Franzki <ifranzki@linux.ibm.com>
6  *
7  *  Collection of CCA misc functions used by zcrypt and pkey
8  */
9 
10 #define KMSG_COMPONENT "zcrypt"
11 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
12 
13 #include <linux/init.h>
14 #include <linux/module.h>
15 #include <linux/slab.h>
16 #include <linux/random.h>
17 #include <asm/zcrypt.h>
18 #include <asm/pkey.h>
19 
20 #include "ap_bus.h"
21 #include "zcrypt_api.h"
22 #include "zcrypt_debug.h"
23 #include "zcrypt_msgtype6.h"
24 #include "zcrypt_ccamisc.h"
25 
26 #define DEBUG_DBG(...)	ZCRYPT_DBF(DBF_DEBUG, ##__VA_ARGS__)
27 #define DEBUG_INFO(...) ZCRYPT_DBF(DBF_INFO, ##__VA_ARGS__)
28 #define DEBUG_WARN(...) ZCRYPT_DBF(DBF_WARN, ##__VA_ARGS__)
29 #define DEBUG_ERR(...)	ZCRYPT_DBF(DBF_ERR, ##__VA_ARGS__)
30 
31 /* Size of parameter block used for all cca requests/replies */
32 #define PARMBSIZE 512
33 
34 /* Size of vardata block used for some of the cca requests/replies */
35 #define VARDATASIZE 4096
36 
37 struct cca_info_list_entry {
38 	struct list_head list;
39 	u16 cardnr;
40 	u16 domain;
41 	struct cca_info info;
42 };
43 
44 /* a list with cca_info_list_entry entries */
45 static LIST_HEAD(cca_info_list);
46 static DEFINE_SPINLOCK(cca_info_list_lock);
47 
48 /*
49  * Simple check if the token is a valid CCA secure AES data key
50  * token. If keybitsize is given, the bitsize of the key is
51  * also checked. Returns 0 on success or errno value on failure.
52  */
53 int cca_check_secaeskeytoken(debug_info_t *dbg, int dbflvl,
54 			     const u8 *token, int keybitsize)
55 {
56 	struct secaeskeytoken *t = (struct secaeskeytoken *) token;
57 
58 #define DBF(...) debug_sprintf_event(dbg, dbflvl, ##__VA_ARGS__)
59 
60 	if (t->type != TOKTYPE_CCA_INTERNAL) {
61 		if (dbg)
62 			DBF("%s token check failed, type 0x%02x != 0x%02x\n",
63 			    __func__, (int) t->type, TOKTYPE_CCA_INTERNAL);
64 		return -EINVAL;
65 	}
66 	if (t->version != TOKVER_CCA_AES) {
67 		if (dbg)
68 			DBF("%s token check failed, version 0x%02x != 0x%02x\n",
69 			    __func__, (int) t->version, TOKVER_CCA_AES);
70 		return -EINVAL;
71 	}
72 	if (keybitsize > 0 && t->bitsize != keybitsize) {
73 		if (dbg)
74 			DBF("%s token check failed, bitsize %d != %d\n",
75 			    __func__, (int) t->bitsize, keybitsize);
76 		return -EINVAL;
77 	}
78 
79 #undef DBF
80 
81 	return 0;
82 }
83 EXPORT_SYMBOL(cca_check_secaeskeytoken);
84 
85 /*
86  * Simple check if the token is a valid CCA secure AES cipher key
87  * token. If keybitsize is given, the bitsize of the key is
88  * also checked. If checkcpacfexport is enabled, the key is also
89  * checked for the export flag to allow CPACF export.
90  * Returns 0 on success or errno value on failure.
91  */
92 int cca_check_secaescipherkey(debug_info_t *dbg, int dbflvl,
93 			      const u8 *token, int keybitsize,
94 			      int checkcpacfexport)
95 {
96 	struct cipherkeytoken *t = (struct cipherkeytoken *) token;
97 	bool keybitsizeok = true;
98 
99 #define DBF(...) debug_sprintf_event(dbg, dbflvl, ##__VA_ARGS__)
100 
101 	if (t->type != TOKTYPE_CCA_INTERNAL) {
102 		if (dbg)
103 			DBF("%s token check failed, type 0x%02x != 0x%02x\n",
104 			    __func__, (int) t->type, TOKTYPE_CCA_INTERNAL);
105 		return -EINVAL;
106 	}
107 	if (t->version != TOKVER_CCA_VLSC) {
108 		if (dbg)
109 			DBF("%s token check failed, version 0x%02x != 0x%02x\n",
110 			    __func__, (int) t->version, TOKVER_CCA_VLSC);
111 		return -EINVAL;
112 	}
113 	if (t->algtype != 0x02) {
114 		if (dbg)
115 			DBF("%s token check failed, algtype 0x%02x != 0x02\n",
116 			    __func__, (int) t->algtype);
117 		return -EINVAL;
118 	}
119 	if (t->keytype != 0x0001) {
120 		if (dbg)
121 			DBF("%s token check failed, keytype 0x%04x != 0x0001\n",
122 			    __func__, (int) t->keytype);
123 		return -EINVAL;
124 	}
125 	if (t->plfver != 0x00 && t->plfver != 0x01) {
126 		if (dbg)
127 			DBF("%s token check failed, unknown plfver 0x%02x\n",
128 			    __func__, (int) t->plfver);
129 		return -EINVAL;
130 	}
131 	if (t->wpllen != 512 && t->wpllen != 576 && t->wpllen != 640) {
132 		if (dbg)
133 			DBF("%s token check failed, unknown wpllen %d\n",
134 			    __func__, (int) t->wpllen);
135 		return -EINVAL;
136 	}
137 	if (keybitsize > 0) {
138 		switch (keybitsize) {
139 		case 128:
140 			if (t->wpllen != (t->plfver ? 640 : 512))
141 				keybitsizeok = false;
142 			break;
143 		case 192:
144 			if (t->wpllen != (t->plfver ? 640 : 576))
145 				keybitsizeok = false;
146 			break;
147 		case 256:
148 			if (t->wpllen != 640)
149 				keybitsizeok = false;
150 			break;
151 		default:
152 			keybitsizeok = false;
153 			break;
154 		}
155 		if (!keybitsizeok) {
156 			if (dbg)
157 				DBF("%s token check failed, bitsize %d\n",
158 				    __func__, keybitsize);
159 			return -EINVAL;
160 		}
161 	}
162 	if (checkcpacfexport && !(t->kmf1 & KMF1_XPRT_CPAC)) {
163 		if (dbg)
164 			DBF("%s token check failed, XPRT_CPAC bit is 0\n",
165 			    __func__);
166 		return -EINVAL;
167 	}
168 
169 #undef DBF
170 
171 	return 0;
172 }
173 EXPORT_SYMBOL(cca_check_secaescipherkey);
174 
175 /*
176  * Allocate consecutive memory for request CPRB, request param
177  * block, reply CPRB and reply param block and fill in values
178  * for the common fields. Returns 0 on success or errno value
179  * on failure.
180  */
181 static int alloc_and_prep_cprbmem(size_t paramblen,
182 				  u8 **pcprbmem,
183 				  struct CPRBX **preqCPRB,
184 				  struct CPRBX **prepCPRB)
185 {
186 	u8 *cprbmem;
187 	size_t cprbplusparamblen = sizeof(struct CPRBX) + paramblen;
188 	struct CPRBX *preqcblk, *prepcblk;
189 
190 	/*
191 	 * allocate consecutive memory for request CPRB, request param
192 	 * block, reply CPRB and reply param block
193 	 */
194 	cprbmem = kcalloc(2, cprbplusparamblen, GFP_KERNEL);
195 	if (!cprbmem)
196 		return -ENOMEM;
197 
198 	preqcblk = (struct CPRBX *) cprbmem;
199 	prepcblk = (struct CPRBX *) (cprbmem + cprbplusparamblen);
200 
201 	/* fill request cprb struct */
202 	preqcblk->cprb_len = sizeof(struct CPRBX);
203 	preqcblk->cprb_ver_id = 0x02;
204 	memcpy(preqcblk->func_id, "T2", 2);
205 	preqcblk->rpl_msgbl = cprbplusparamblen;
206 	if (paramblen) {
207 		preqcblk->req_parmb =
208 			((u8 *) preqcblk) + sizeof(struct CPRBX);
209 		preqcblk->rpl_parmb =
210 			((u8 *) prepcblk) + sizeof(struct CPRBX);
211 	}
212 
213 	*pcprbmem = cprbmem;
214 	*preqCPRB = preqcblk;
215 	*prepCPRB = prepcblk;
216 
217 	return 0;
218 }
219 
220 /*
221  * Free the cprb memory allocated with the function above.
222  * If the scrub value is not zero, the memory is filled
223  * with zeros before freeing (useful if there was some
224  * clear key material in there).
225  */
226 static void free_cprbmem(void *mem, size_t paramblen, int scrub)
227 {
228 	if (scrub)
229 		memzero_explicit(mem, 2 * (sizeof(struct CPRBX) + paramblen));
230 	kfree(mem);
231 }
232 
233 /*
234  * Helper function to prepare the xcrb struct
235  */
236 static inline void prep_xcrb(struct ica_xcRB *pxcrb,
237 			     u16 cardnr,
238 			     struct CPRBX *preqcblk,
239 			     struct CPRBX *prepcblk)
240 {
241 	memset(pxcrb, 0, sizeof(*pxcrb));
242 	pxcrb->agent_ID = 0x4341; /* 'CA' */
243 	pxcrb->user_defined = (cardnr == 0xFFFF ? AUTOSELECT : cardnr);
244 	pxcrb->request_control_blk_length =
245 		preqcblk->cprb_len + preqcblk->req_parml;
246 	pxcrb->request_control_blk_addr = (void __user *) preqcblk;
247 	pxcrb->reply_control_blk_length = preqcblk->rpl_msgbl;
248 	pxcrb->reply_control_blk_addr = (void __user *) prepcblk;
249 }
250 
251 /*
252  * Helper function which calls zcrypt_send_cprb with
253  * memory management segment adjusted to kernel space
254  * so that the copy_from_user called within this
255  * function do in fact copy from kernel space.
256  */
257 static inline int _zcrypt_send_cprb(struct ica_xcRB *xcrb)
258 {
259 	int rc;
260 	mm_segment_t old_fs = get_fs();
261 
262 	set_fs(KERNEL_DS);
263 	rc = zcrypt_send_cprb(xcrb);
264 	set_fs(old_fs);
265 
266 	return rc;
267 }
268 
269 /*
270  * Generate (random) CCA AES DATA secure key.
271  */
272 int cca_genseckey(u16 cardnr, u16 domain,
273 		  u32 keybitsize, u8 seckey[SECKEYBLOBSIZE])
274 {
275 	int i, rc, keysize;
276 	int seckeysize;
277 	u8 *mem;
278 	struct CPRBX *preqcblk, *prepcblk;
279 	struct ica_xcRB xcrb;
280 	struct kgreqparm {
281 		u8  subfunc_code[2];
282 		u16 rule_array_len;
283 		struct lv1 {
284 			u16 len;
285 			char  key_form[8];
286 			char  key_length[8];
287 			char  key_type1[8];
288 			char  key_type2[8];
289 		} lv1;
290 		struct lv2 {
291 			u16 len;
292 			struct keyid {
293 				u16 len;
294 				u16 attr;
295 				u8  data[SECKEYBLOBSIZE];
296 			} keyid[6];
297 		} lv2;
298 	} __packed * preqparm;
299 	struct kgrepparm {
300 		u8  subfunc_code[2];
301 		u16 rule_array_len;
302 		struct lv3 {
303 			u16 len;
304 			u16 keyblocklen;
305 			struct {
306 				u16 toklen;
307 				u16 tokattr;
308 				u8  tok[0];
309 				/* ... some more data ... */
310 			} keyblock;
311 		} lv3;
312 	} __packed * prepparm;
313 
314 	/* get already prepared memory for 2 cprbs with param block each */
315 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
316 	if (rc)
317 		return rc;
318 
319 	/* fill request cprb struct */
320 	preqcblk->domain = domain;
321 
322 	/* fill request cprb param block with KG request */
323 	preqparm = (struct kgreqparm *) preqcblk->req_parmb;
324 	memcpy(preqparm->subfunc_code, "KG", 2);
325 	preqparm->rule_array_len = sizeof(preqparm->rule_array_len);
326 	preqparm->lv1.len = sizeof(struct lv1);
327 	memcpy(preqparm->lv1.key_form,	 "OP      ", 8);
328 	switch (keybitsize) {
329 	case PKEY_SIZE_AES_128:
330 	case PKEY_KEYTYPE_AES_128: /* older ioctls used this */
331 		keysize = 16;
332 		memcpy(preqparm->lv1.key_length, "KEYLN16 ", 8);
333 		break;
334 	case PKEY_SIZE_AES_192:
335 	case PKEY_KEYTYPE_AES_192: /* older ioctls used this */
336 		keysize = 24;
337 		memcpy(preqparm->lv1.key_length, "KEYLN24 ", 8);
338 		break;
339 	case PKEY_SIZE_AES_256:
340 	case PKEY_KEYTYPE_AES_256: /* older ioctls used this */
341 		keysize = 32;
342 		memcpy(preqparm->lv1.key_length, "KEYLN32 ", 8);
343 		break;
344 	default:
345 		DEBUG_ERR("%s unknown/unsupported keybitsize %d\n",
346 			  __func__, keybitsize);
347 		rc = -EINVAL;
348 		goto out;
349 	}
350 	memcpy(preqparm->lv1.key_type1,  "AESDATA ", 8);
351 	preqparm->lv2.len = sizeof(struct lv2);
352 	for (i = 0; i < 6; i++) {
353 		preqparm->lv2.keyid[i].len = sizeof(struct keyid);
354 		preqparm->lv2.keyid[i].attr = (i == 2 ? 0x30 : 0x10);
355 	}
356 	preqcblk->req_parml = sizeof(struct kgreqparm);
357 
358 	/* fill xcrb struct */
359 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
360 
361 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
362 	rc = _zcrypt_send_cprb(&xcrb);
363 	if (rc) {
364 		DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, errno %d\n",
365 			  __func__, (int) cardnr, (int) domain, rc);
366 		goto out;
367 	}
368 
369 	/* check response returncode and reasoncode */
370 	if (prepcblk->ccp_rtcode != 0) {
371 		DEBUG_ERR("%s secure key generate failure, card response %d/%d\n",
372 			  __func__,
373 			  (int) prepcblk->ccp_rtcode,
374 			  (int) prepcblk->ccp_rscode);
375 		rc = -EIO;
376 		goto out;
377 	}
378 
379 	/* process response cprb param block */
380 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
381 	prepparm = (struct kgrepparm *) prepcblk->rpl_parmb;
382 
383 	/* check length of the returned secure key token */
384 	seckeysize = prepparm->lv3.keyblock.toklen
385 		- sizeof(prepparm->lv3.keyblock.toklen)
386 		- sizeof(prepparm->lv3.keyblock.tokattr);
387 	if (seckeysize != SECKEYBLOBSIZE) {
388 		DEBUG_ERR("%s secure token size mismatch %d != %d bytes\n",
389 			  __func__, seckeysize, SECKEYBLOBSIZE);
390 		rc = -EIO;
391 		goto out;
392 	}
393 
394 	/* check secure key token */
395 	rc = cca_check_secaeskeytoken(zcrypt_dbf_info, DBF_ERR,
396 				      prepparm->lv3.keyblock.tok, 8*keysize);
397 	if (rc) {
398 		rc = -EIO;
399 		goto out;
400 	}
401 
402 	/* copy the generated secure key token */
403 	memcpy(seckey, prepparm->lv3.keyblock.tok, SECKEYBLOBSIZE);
404 
405 out:
406 	free_cprbmem(mem, PARMBSIZE, 0);
407 	return rc;
408 }
409 EXPORT_SYMBOL(cca_genseckey);
410 
411 /*
412  * Generate an CCA AES DATA secure key with given key value.
413  */
414 int cca_clr2seckey(u16 cardnr, u16 domain, u32 keybitsize,
415 		   const u8 *clrkey, u8 seckey[SECKEYBLOBSIZE])
416 {
417 	int rc, keysize, seckeysize;
418 	u8 *mem;
419 	struct CPRBX *preqcblk, *prepcblk;
420 	struct ica_xcRB xcrb;
421 	struct cmreqparm {
422 		u8  subfunc_code[2];
423 		u16 rule_array_len;
424 		char  rule_array[8];
425 		struct lv1 {
426 			u16 len;
427 			u8  clrkey[0];
428 		} lv1;
429 		struct lv2 {
430 			u16 len;
431 			struct keyid {
432 				u16 len;
433 				u16 attr;
434 				u8  data[SECKEYBLOBSIZE];
435 			} keyid;
436 		} lv2;
437 	} __packed * preqparm;
438 	struct lv2 *plv2;
439 	struct cmrepparm {
440 		u8  subfunc_code[2];
441 		u16 rule_array_len;
442 		struct lv3 {
443 			u16 len;
444 			u16 keyblocklen;
445 			struct {
446 				u16 toklen;
447 				u16 tokattr;
448 				u8  tok[0];
449 				/* ... some more data ... */
450 			} keyblock;
451 		} lv3;
452 	} __packed * prepparm;
453 
454 	/* get already prepared memory for 2 cprbs with param block each */
455 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
456 	if (rc)
457 		return rc;
458 
459 	/* fill request cprb struct */
460 	preqcblk->domain = domain;
461 
462 	/* fill request cprb param block with CM request */
463 	preqparm = (struct cmreqparm *) preqcblk->req_parmb;
464 	memcpy(preqparm->subfunc_code, "CM", 2);
465 	memcpy(preqparm->rule_array, "AES     ", 8);
466 	preqparm->rule_array_len =
467 		sizeof(preqparm->rule_array_len) + sizeof(preqparm->rule_array);
468 	switch (keybitsize) {
469 	case PKEY_SIZE_AES_128:
470 	case PKEY_KEYTYPE_AES_128: /* older ioctls used this */
471 		keysize = 16;
472 		break;
473 	case PKEY_SIZE_AES_192:
474 	case PKEY_KEYTYPE_AES_192: /* older ioctls used this */
475 		keysize = 24;
476 		break;
477 	case PKEY_SIZE_AES_256:
478 	case PKEY_KEYTYPE_AES_256: /* older ioctls used this */
479 		keysize = 32;
480 		break;
481 	default:
482 		DEBUG_ERR("%s unknown/unsupported keybitsize %d\n",
483 			  __func__, keybitsize);
484 		rc = -EINVAL;
485 		goto out;
486 	}
487 	preqparm->lv1.len = sizeof(struct lv1) + keysize;
488 	memcpy(preqparm->lv1.clrkey, clrkey, keysize);
489 	plv2 = (struct lv2 *) (((u8 *) &preqparm->lv2) + keysize);
490 	plv2->len = sizeof(struct lv2);
491 	plv2->keyid.len = sizeof(struct keyid);
492 	plv2->keyid.attr = 0x30;
493 	preqcblk->req_parml = sizeof(struct cmreqparm) + keysize;
494 
495 	/* fill xcrb struct */
496 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
497 
498 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
499 	rc = _zcrypt_send_cprb(&xcrb);
500 	if (rc) {
501 		DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
502 			  __func__, (int) cardnr, (int) domain, rc);
503 		goto out;
504 	}
505 
506 	/* check response returncode and reasoncode */
507 	if (prepcblk->ccp_rtcode != 0) {
508 		DEBUG_ERR("%s clear key import failure, card response %d/%d\n",
509 			  __func__,
510 			  (int) prepcblk->ccp_rtcode,
511 			  (int) prepcblk->ccp_rscode);
512 		rc = -EIO;
513 		goto out;
514 	}
515 
516 	/* process response cprb param block */
517 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
518 	prepparm = (struct cmrepparm *) prepcblk->rpl_parmb;
519 
520 	/* check length of the returned secure key token */
521 	seckeysize = prepparm->lv3.keyblock.toklen
522 		- sizeof(prepparm->lv3.keyblock.toklen)
523 		- sizeof(prepparm->lv3.keyblock.tokattr);
524 	if (seckeysize != SECKEYBLOBSIZE) {
525 		DEBUG_ERR("%s secure token size mismatch %d != %d bytes\n",
526 			  __func__, seckeysize, SECKEYBLOBSIZE);
527 		rc = -EIO;
528 		goto out;
529 	}
530 
531 	/* check secure key token */
532 	rc = cca_check_secaeskeytoken(zcrypt_dbf_info, DBF_ERR,
533 				      prepparm->lv3.keyblock.tok, 8*keysize);
534 	if (rc) {
535 		rc = -EIO;
536 		goto out;
537 	}
538 
539 	/* copy the generated secure key token */
540 	if (seckey)
541 		memcpy(seckey, prepparm->lv3.keyblock.tok, SECKEYBLOBSIZE);
542 
543 out:
544 	free_cprbmem(mem, PARMBSIZE, 1);
545 	return rc;
546 }
547 EXPORT_SYMBOL(cca_clr2seckey);
548 
549 /*
550  * Derive proteced key from an CCA AES DATA secure key.
551  */
552 int cca_sec2protkey(u16 cardnr, u16 domain,
553 		    const u8 seckey[SECKEYBLOBSIZE],
554 		    u8 *protkey, u32 *protkeylen, u32 *protkeytype)
555 {
556 	int rc;
557 	u8 *mem;
558 	struct CPRBX *preqcblk, *prepcblk;
559 	struct ica_xcRB xcrb;
560 	struct uskreqparm {
561 		u8  subfunc_code[2];
562 		u16 rule_array_len;
563 		struct lv1 {
564 			u16 len;
565 			u16 attr_len;
566 			u16 attr_flags;
567 		} lv1;
568 		struct lv2 {
569 			u16 len;
570 			u16 attr_len;
571 			u16 attr_flags;
572 			u8  token[0];	      /* cca secure key token */
573 		} lv2;
574 	} __packed * preqparm;
575 	struct uskrepparm {
576 		u8  subfunc_code[2];
577 		u16 rule_array_len;
578 		struct lv3 {
579 			u16 len;
580 			u16 attr_len;
581 			u16 attr_flags;
582 			struct cpacfkeyblock {
583 				u8  version;  /* version of this struct */
584 				u8  flags[2];
585 				u8  algo;
586 				u8  form;
587 				u8  pad1[3];
588 				u16 len;
589 				u8  key[64];  /* the key (len bytes) */
590 				u16 keyattrlen;
591 				u8  keyattr[32];
592 				u8  pad2[1];
593 				u8  vptype;
594 				u8  vp[32];  /* verification pattern */
595 			} keyblock;
596 		} lv3;
597 	} __packed * prepparm;
598 
599 	/* get already prepared memory for 2 cprbs with param block each */
600 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
601 	if (rc)
602 		return rc;
603 
604 	/* fill request cprb struct */
605 	preqcblk->domain = domain;
606 
607 	/* fill request cprb param block with USK request */
608 	preqparm = (struct uskreqparm *) preqcblk->req_parmb;
609 	memcpy(preqparm->subfunc_code, "US", 2);
610 	preqparm->rule_array_len = sizeof(preqparm->rule_array_len);
611 	preqparm->lv1.len = sizeof(struct lv1);
612 	preqparm->lv1.attr_len = sizeof(struct lv1) - sizeof(preqparm->lv1.len);
613 	preqparm->lv1.attr_flags = 0x0001;
614 	preqparm->lv2.len = sizeof(struct lv2) + SECKEYBLOBSIZE;
615 	preqparm->lv2.attr_len = sizeof(struct lv2)
616 		- sizeof(preqparm->lv2.len) + SECKEYBLOBSIZE;
617 	preqparm->lv2.attr_flags = 0x0000;
618 	memcpy(preqparm->lv2.token, seckey, SECKEYBLOBSIZE);
619 	preqcblk->req_parml = sizeof(struct uskreqparm) + SECKEYBLOBSIZE;
620 
621 	/* fill xcrb struct */
622 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
623 
624 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
625 	rc = _zcrypt_send_cprb(&xcrb);
626 	if (rc) {
627 		DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
628 			  __func__, (int) cardnr, (int) domain, rc);
629 		goto out;
630 	}
631 
632 	/* check response returncode and reasoncode */
633 	if (prepcblk->ccp_rtcode != 0) {
634 		DEBUG_ERR("%s unwrap secure key failure, card response %d/%d\n",
635 			  __func__,
636 			  (int) prepcblk->ccp_rtcode,
637 			  (int) prepcblk->ccp_rscode);
638 		rc = -EIO;
639 		goto out;
640 	}
641 	if (prepcblk->ccp_rscode != 0) {
642 		DEBUG_WARN("%s unwrap secure key warning, card response %d/%d\n",
643 			   __func__,
644 			   (int) prepcblk->ccp_rtcode,
645 			   (int) prepcblk->ccp_rscode);
646 	}
647 
648 	/* process response cprb param block */
649 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
650 	prepparm = (struct uskrepparm *) prepcblk->rpl_parmb;
651 
652 	/* check the returned keyblock */
653 	if (prepparm->lv3.keyblock.version != 0x01) {
654 		DEBUG_ERR("%s reply param keyblock version mismatch 0x%02x != 0x01\n",
655 			  __func__, (int) prepparm->lv3.keyblock.version);
656 		rc = -EIO;
657 		goto out;
658 	}
659 
660 	/* copy the tanslated protected key */
661 	switch (prepparm->lv3.keyblock.len) {
662 	case 16+32:
663 		/* AES 128 protected key */
664 		if (protkeytype)
665 			*protkeytype = PKEY_KEYTYPE_AES_128;
666 		break;
667 	case 24+32:
668 		/* AES 192 protected key */
669 		if (protkeytype)
670 			*protkeytype = PKEY_KEYTYPE_AES_192;
671 		break;
672 	case 32+32:
673 		/* AES 256 protected key */
674 		if (protkeytype)
675 			*protkeytype = PKEY_KEYTYPE_AES_256;
676 		break;
677 	default:
678 		DEBUG_ERR("%s unknown/unsupported keylen %d\n",
679 			  __func__, prepparm->lv3.keyblock.len);
680 		rc = -EIO;
681 		goto out;
682 	}
683 	memcpy(protkey, prepparm->lv3.keyblock.key, prepparm->lv3.keyblock.len);
684 	if (protkeylen)
685 		*protkeylen = prepparm->lv3.keyblock.len;
686 
687 out:
688 	free_cprbmem(mem, PARMBSIZE, 0);
689 	return rc;
690 }
691 EXPORT_SYMBOL(cca_sec2protkey);
692 
693 /*
694  * AES cipher key skeleton created with CSNBKTB2 with these flags:
695  * INTERNAL, NO-KEY, AES, CIPHER, ANY-MODE, NOEX-SYM, NOEXAASY,
696  * NOEXUASY, XPRTCPAC, NOEX-RAW, NOEX-DES, NOEX-AES, NOEX-RSA
697  * used by cca_gencipherkey() and cca_clr2cipherkey().
698  */
699 static const u8 aes_cipher_key_skeleton[] = {
700 	0x01, 0x00, 0x00, 0x38, 0x05, 0x00, 0x00, 0x00,
701 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
702 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
703 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
704 	0x00, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
705 	0x00, 0x02, 0x00, 0x01, 0x02, 0xc0, 0x00, 0xff,
706 	0x00, 0x03, 0x08, 0xc8, 0x00, 0x00, 0x00, 0x00 };
707 #define SIZEOF_SKELETON (sizeof(aes_cipher_key_skeleton))
708 
709 /*
710  * Generate (random) CCA AES CIPHER secure key.
711  */
712 int cca_gencipherkey(u16 cardnr, u16 domain, u32 keybitsize, u32 keygenflags,
713 		     u8 *keybuf, size_t *keybufsize)
714 {
715 	int rc;
716 	u8 *mem;
717 	struct CPRBX *preqcblk, *prepcblk;
718 	struct ica_xcRB xcrb;
719 	struct gkreqparm {
720 		u8  subfunc_code[2];
721 		u16 rule_array_len;
722 		char rule_array[2*8];
723 		struct {
724 			u16 len;
725 			u8  key_type_1[8];
726 			u8  key_type_2[8];
727 			u16 clear_key_bit_len;
728 			u16 key_name_1_len;
729 			u16 key_name_2_len;
730 			u16 user_data_1_len;
731 			u16 user_data_2_len;
732 			u8  key_name_1[0];
733 			u8  key_name_2[0];
734 			u8  user_data_1[0];
735 			u8  user_data_2[0];
736 		} vud;
737 		struct {
738 			u16 len;
739 			struct {
740 				u16 len;
741 				u16 flag;
742 				u8  kek_id_1[0];
743 			} tlv1;
744 			struct {
745 				u16 len;
746 				u16 flag;
747 				u8  kek_id_2[0];
748 			} tlv2;
749 			struct {
750 				u16 len;
751 				u16 flag;
752 				u8  gen_key_id_1[SIZEOF_SKELETON];
753 			} tlv3;
754 			struct {
755 				u16 len;
756 				u16 flag;
757 				u8  gen_key_id_1_label[0];
758 			} tlv4;
759 			struct {
760 				u16 len;
761 				u16 flag;
762 				u8  gen_key_id_2[0];
763 			} tlv5;
764 			struct {
765 				u16 len;
766 				u16 flag;
767 				u8  gen_key_id_2_label[0];
768 			} tlv6;
769 		} kb;
770 	} __packed * preqparm;
771 	struct gkrepparm {
772 		u8  subfunc_code[2];
773 		u16 rule_array_len;
774 		struct {
775 			u16 len;
776 		} vud;
777 		struct {
778 			u16 len;
779 			struct {
780 				u16 len;
781 				u16 flag;
782 				u8  gen_key[0]; /* 120-136 bytes */
783 			} tlv1;
784 		} kb;
785 	} __packed * prepparm;
786 	struct cipherkeytoken *t;
787 
788 	/* get already prepared memory for 2 cprbs with param block each */
789 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
790 	if (rc)
791 		return rc;
792 
793 	/* fill request cprb struct */
794 	preqcblk->domain = domain;
795 	preqcblk->req_parml = sizeof(struct gkreqparm);
796 
797 	/* prepare request param block with GK request */
798 	preqparm = (struct gkreqparm *) preqcblk->req_parmb;
799 	memcpy(preqparm->subfunc_code, "GK", 2);
800 	preqparm->rule_array_len =  sizeof(uint16_t) + 2 * 8;
801 	memcpy(preqparm->rule_array, "AES     OP      ", 2*8);
802 
803 	/* prepare vud block */
804 	preqparm->vud.len = sizeof(preqparm->vud);
805 	switch (keybitsize) {
806 	case 128:
807 	case 192:
808 	case 256:
809 		break;
810 	default:
811 		DEBUG_ERR(
812 			"%s unknown/unsupported keybitsize %d\n",
813 			__func__, keybitsize);
814 		rc = -EINVAL;
815 		goto out;
816 	}
817 	preqparm->vud.clear_key_bit_len = keybitsize;
818 	memcpy(preqparm->vud.key_type_1, "TOKEN   ", 8);
819 	memset(preqparm->vud.key_type_2, ' ', sizeof(preqparm->vud.key_type_2));
820 
821 	/* prepare kb block */
822 	preqparm->kb.len = sizeof(preqparm->kb);
823 	preqparm->kb.tlv1.len = sizeof(preqparm->kb.tlv1);
824 	preqparm->kb.tlv1.flag = 0x0030;
825 	preqparm->kb.tlv2.len = sizeof(preqparm->kb.tlv2);
826 	preqparm->kb.tlv2.flag = 0x0030;
827 	preqparm->kb.tlv3.len = sizeof(preqparm->kb.tlv3);
828 	preqparm->kb.tlv3.flag = 0x0030;
829 	memcpy(preqparm->kb.tlv3.gen_key_id_1,
830 	       aes_cipher_key_skeleton, SIZEOF_SKELETON);
831 	preqparm->kb.tlv4.len = sizeof(preqparm->kb.tlv4);
832 	preqparm->kb.tlv4.flag = 0x0030;
833 	preqparm->kb.tlv5.len = sizeof(preqparm->kb.tlv5);
834 	preqparm->kb.tlv5.flag = 0x0030;
835 	preqparm->kb.tlv6.len = sizeof(preqparm->kb.tlv6);
836 	preqparm->kb.tlv6.flag = 0x0030;
837 
838 	/* patch the skeleton key token export flags inside the kb block */
839 	if (keygenflags) {
840 		t = (struct cipherkeytoken *) preqparm->kb.tlv3.gen_key_id_1;
841 		t->kmf1 |= (u16) (keygenflags & 0x0000FF00);
842 		t->kmf1 &= (u16) ~(keygenflags & 0x000000FF);
843 	}
844 
845 	/* prepare xcrb struct */
846 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
847 
848 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
849 	rc = _zcrypt_send_cprb(&xcrb);
850 	if (rc) {
851 		DEBUG_ERR(
852 			"%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
853 			__func__, (int) cardnr, (int) domain, rc);
854 		goto out;
855 	}
856 
857 	/* check response returncode and reasoncode */
858 	if (prepcblk->ccp_rtcode != 0) {
859 		DEBUG_ERR(
860 			"%s cipher key generate failure, card response %d/%d\n",
861 			__func__,
862 			(int) prepcblk->ccp_rtcode,
863 			(int) prepcblk->ccp_rscode);
864 		rc = -EIO;
865 		goto out;
866 	}
867 
868 	/* process response cprb param block */
869 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
870 	prepparm = (struct gkrepparm *) prepcblk->rpl_parmb;
871 
872 	/* do some plausibility checks on the key block */
873 	if (prepparm->kb.len < 120 + 5 * sizeof(uint16_t) ||
874 	    prepparm->kb.len > 136 + 5 * sizeof(uint16_t)) {
875 		DEBUG_ERR("%s reply with invalid or unknown key block\n",
876 			  __func__);
877 		rc = -EIO;
878 		goto out;
879 	}
880 
881 	/* and some checks on the generated key */
882 	rc = cca_check_secaescipherkey(zcrypt_dbf_info, DBF_ERR,
883 				       prepparm->kb.tlv1.gen_key,
884 				       keybitsize, 1);
885 	if (rc) {
886 		rc = -EIO;
887 		goto out;
888 	}
889 
890 	/* copy the generated vlsc key token */
891 	t = (struct cipherkeytoken *) prepparm->kb.tlv1.gen_key;
892 	if (keybuf) {
893 		if (*keybufsize >= t->len)
894 			memcpy(keybuf, t, t->len);
895 		else
896 			rc = -EINVAL;
897 	}
898 	*keybufsize = t->len;
899 
900 out:
901 	free_cprbmem(mem, PARMBSIZE, 0);
902 	return rc;
903 }
904 EXPORT_SYMBOL(cca_gencipherkey);
905 
906 /*
907  * Helper function, does a the CSNBKPI2 CPRB.
908  */
909 static int _ip_cprb_helper(u16 cardnr, u16 domain,
910 			   const char *rule_array_1,
911 			   const char *rule_array_2,
912 			   const char *rule_array_3,
913 			   const u8 *clr_key_value,
914 			   int clr_key_bit_size,
915 			   u8 *key_token,
916 			   int *key_token_size)
917 {
918 	int rc, n;
919 	u8 *mem;
920 	struct CPRBX *preqcblk, *prepcblk;
921 	struct ica_xcRB xcrb;
922 	struct rule_array_block {
923 		u8  subfunc_code[2];
924 		u16 rule_array_len;
925 		char rule_array[0];
926 	} __packed * preq_ra_block;
927 	struct vud_block {
928 		u16 len;
929 		struct {
930 			u16 len;
931 			u16 flag;	     /* 0x0064 */
932 			u16 clr_key_bit_len;
933 		} tlv1;
934 		struct {
935 			u16 len;
936 			u16 flag;	/* 0x0063 */
937 			u8  clr_key[0]; /* clear key value bytes */
938 		} tlv2;
939 	} __packed * preq_vud_block;
940 	struct key_block {
941 		u16 len;
942 		struct {
943 			u16 len;
944 			u16 flag;	  /* 0x0030 */
945 			u8  key_token[0]; /* key skeleton */
946 		} tlv1;
947 	} __packed * preq_key_block;
948 	struct iprepparm {
949 		u8  subfunc_code[2];
950 		u16 rule_array_len;
951 		struct {
952 			u16 len;
953 		} vud;
954 		struct {
955 			u16 len;
956 			struct {
957 				u16 len;
958 				u16 flag;	  /* 0x0030 */
959 				u8  key_token[0]; /* key token */
960 			} tlv1;
961 		} kb;
962 	} __packed * prepparm;
963 	struct cipherkeytoken *t;
964 	int complete = strncmp(rule_array_2, "COMPLETE", 8) ? 0 : 1;
965 
966 	/* get already prepared memory for 2 cprbs with param block each */
967 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
968 	if (rc)
969 		return rc;
970 
971 	/* fill request cprb struct */
972 	preqcblk->domain = domain;
973 	preqcblk->req_parml = 0;
974 
975 	/* prepare request param block with IP request */
976 	preq_ra_block = (struct rule_array_block *) preqcblk->req_parmb;
977 	memcpy(preq_ra_block->subfunc_code, "IP", 2);
978 	preq_ra_block->rule_array_len =  sizeof(uint16_t) + 2 * 8;
979 	memcpy(preq_ra_block->rule_array, rule_array_1, 8);
980 	memcpy(preq_ra_block->rule_array + 8, rule_array_2, 8);
981 	preqcblk->req_parml = sizeof(struct rule_array_block) + 2 * 8;
982 	if (rule_array_3) {
983 		preq_ra_block->rule_array_len += 8;
984 		memcpy(preq_ra_block->rule_array + 16, rule_array_3, 8);
985 		preqcblk->req_parml += 8;
986 	}
987 
988 	/* prepare vud block */
989 	preq_vud_block = (struct vud_block *)
990 		(preqcblk->req_parmb + preqcblk->req_parml);
991 	n = complete ? 0 : (clr_key_bit_size + 7) / 8;
992 	preq_vud_block->len = sizeof(struct vud_block) + n;
993 	preq_vud_block->tlv1.len = sizeof(preq_vud_block->tlv1);
994 	preq_vud_block->tlv1.flag = 0x0064;
995 	preq_vud_block->tlv1.clr_key_bit_len = complete ? 0 : clr_key_bit_size;
996 	preq_vud_block->tlv2.len = sizeof(preq_vud_block->tlv2) + n;
997 	preq_vud_block->tlv2.flag = 0x0063;
998 	if (!complete)
999 		memcpy(preq_vud_block->tlv2.clr_key, clr_key_value, n);
1000 	preqcblk->req_parml += preq_vud_block->len;
1001 
1002 	/* prepare key block */
1003 	preq_key_block = (struct key_block *)
1004 		(preqcblk->req_parmb + preqcblk->req_parml);
1005 	n = *key_token_size;
1006 	preq_key_block->len = sizeof(struct key_block) + n;
1007 	preq_key_block->tlv1.len = sizeof(preq_key_block->tlv1) + n;
1008 	preq_key_block->tlv1.flag = 0x0030;
1009 	memcpy(preq_key_block->tlv1.key_token, key_token, *key_token_size);
1010 	preqcblk->req_parml += preq_key_block->len;
1011 
1012 	/* prepare xcrb struct */
1013 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
1014 
1015 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
1016 	rc = _zcrypt_send_cprb(&xcrb);
1017 	if (rc) {
1018 		DEBUG_ERR(
1019 			"%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
1020 			__func__, (int) cardnr, (int) domain, rc);
1021 		goto out;
1022 	}
1023 
1024 	/* check response returncode and reasoncode */
1025 	if (prepcblk->ccp_rtcode != 0) {
1026 		DEBUG_ERR(
1027 			"%s CSNBKPI2 failure, card response %d/%d\n",
1028 			__func__,
1029 			(int) prepcblk->ccp_rtcode,
1030 			(int) prepcblk->ccp_rscode);
1031 		rc = -EIO;
1032 		goto out;
1033 	}
1034 
1035 	/* process response cprb param block */
1036 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
1037 	prepparm = (struct iprepparm *) prepcblk->rpl_parmb;
1038 
1039 	/* do some plausibility checks on the key block */
1040 	if (prepparm->kb.len < 120 + 3 * sizeof(uint16_t) ||
1041 	    prepparm->kb.len > 136 + 3 * sizeof(uint16_t)) {
1042 		DEBUG_ERR("%s reply with invalid or unknown key block\n",
1043 			  __func__);
1044 		rc = -EIO;
1045 		goto out;
1046 	}
1047 
1048 	/* do not check the key here, it may be incomplete */
1049 
1050 	/* copy the vlsc key token back */
1051 	t = (struct cipherkeytoken *) prepparm->kb.tlv1.key_token;
1052 	memcpy(key_token, t, t->len);
1053 	*key_token_size = t->len;
1054 
1055 out:
1056 	free_cprbmem(mem, PARMBSIZE, 0);
1057 	return rc;
1058 }
1059 
1060 /*
1061  * Build CCA AES CIPHER secure key with a given clear key value.
1062  */
1063 int cca_clr2cipherkey(u16 card, u16 dom, u32 keybitsize, u32 keygenflags,
1064 		      const u8 *clrkey, u8 *keybuf, size_t *keybufsize)
1065 {
1066 	int rc;
1067 	u8 *token;
1068 	int tokensize;
1069 	u8 exorbuf[32];
1070 	struct cipherkeytoken *t;
1071 
1072 	/* fill exorbuf with random data */
1073 	get_random_bytes(exorbuf, sizeof(exorbuf));
1074 
1075 	/* allocate space for the key token to build */
1076 	token = kmalloc(MAXCCAVLSCTOKENSIZE, GFP_KERNEL);
1077 	if (!token)
1078 		return -ENOMEM;
1079 
1080 	/* prepare the token with the key skeleton */
1081 	tokensize = SIZEOF_SKELETON;
1082 	memcpy(token, aes_cipher_key_skeleton, tokensize);
1083 
1084 	/* patch the skeleton key token export flags */
1085 	if (keygenflags) {
1086 		t = (struct cipherkeytoken *) token;
1087 		t->kmf1 |= (u16) (keygenflags & 0x0000FF00);
1088 		t->kmf1 &= (u16) ~(keygenflags & 0x000000FF);
1089 	}
1090 
1091 	/*
1092 	 * Do the key import with the clear key value in 4 steps:
1093 	 * 1/4 FIRST import with only random data
1094 	 * 2/4 EXOR the clear key
1095 	 * 3/4 EXOR the very same random data again
1096 	 * 4/4 COMPLETE the secure cipher key import
1097 	 */
1098 	rc = _ip_cprb_helper(card, dom, "AES     ", "FIRST   ", "MIN3PART",
1099 			     exorbuf, keybitsize, token, &tokensize);
1100 	if (rc) {
1101 		DEBUG_ERR(
1102 			"%s clear key import 1/4 with CSNBKPI2 failed, rc=%d\n",
1103 			__func__, rc);
1104 		goto out;
1105 	}
1106 	rc = _ip_cprb_helper(card, dom, "AES     ", "ADD-PART", NULL,
1107 			     clrkey, keybitsize, token, &tokensize);
1108 	if (rc) {
1109 		DEBUG_ERR(
1110 			"%s clear key import 2/4 with CSNBKPI2 failed, rc=%d\n",
1111 			__func__, rc);
1112 		goto out;
1113 	}
1114 	rc = _ip_cprb_helper(card, dom, "AES     ", "ADD-PART", NULL,
1115 			     exorbuf, keybitsize, token, &tokensize);
1116 	if (rc) {
1117 		DEBUG_ERR(
1118 			"%s clear key import 3/4 with CSNBKPI2 failed, rc=%d\n",
1119 			__func__, rc);
1120 		goto out;
1121 	}
1122 	rc = _ip_cprb_helper(card, dom, "AES     ", "COMPLETE", NULL,
1123 			     NULL, keybitsize, token, &tokensize);
1124 	if (rc) {
1125 		DEBUG_ERR(
1126 			"%s clear key import 4/4 with CSNBKPI2 failed, rc=%d\n",
1127 			__func__, rc);
1128 		goto out;
1129 	}
1130 
1131 	/* copy the generated key token */
1132 	if (keybuf) {
1133 		if (tokensize > *keybufsize)
1134 			rc = -EINVAL;
1135 		else
1136 			memcpy(keybuf, token, tokensize);
1137 	}
1138 	*keybufsize = tokensize;
1139 
1140 out:
1141 	kfree(token);
1142 	return rc;
1143 }
1144 EXPORT_SYMBOL(cca_clr2cipherkey);
1145 
1146 /*
1147  * Derive proteced key from CCA AES cipher secure key.
1148  */
1149 int cca_cipher2protkey(u16 cardnr, u16 domain, const u8 *ckey,
1150 		       u8 *protkey, u32 *protkeylen, u32 *protkeytype)
1151 {
1152 	int rc;
1153 	u8 *mem;
1154 	struct CPRBX *preqcblk, *prepcblk;
1155 	struct ica_xcRB xcrb;
1156 	struct aureqparm {
1157 		u8  subfunc_code[2];
1158 		u16 rule_array_len;
1159 		u8  rule_array[8];
1160 		struct {
1161 			u16 len;
1162 			u16 tk_blob_len;
1163 			u16 tk_blob_tag;
1164 			u8  tk_blob[66];
1165 		} vud;
1166 		struct {
1167 			u16 len;
1168 			u16 cca_key_token_len;
1169 			u16 cca_key_token_flags;
1170 			u8  cca_key_token[0]; // 64 or more
1171 		} kb;
1172 	} __packed * preqparm;
1173 	struct aurepparm {
1174 		u8  subfunc_code[2];
1175 		u16 rule_array_len;
1176 		struct {
1177 			u16 len;
1178 			u16 sublen;
1179 			u16 tag;
1180 			struct cpacfkeyblock {
1181 				u8  version;  /* version of this struct */
1182 				u8  flags[2];
1183 				u8  algo;
1184 				u8  form;
1185 				u8  pad1[3];
1186 				u16 keylen;
1187 				u8  key[64];  /* the key (keylen bytes) */
1188 				u16 keyattrlen;
1189 				u8  keyattr[32];
1190 				u8  pad2[1];
1191 				u8  vptype;
1192 				u8  vp[32];  /* verification pattern */
1193 			} ckb;
1194 		} vud;
1195 		struct {
1196 			u16 len;
1197 		} kb;
1198 	} __packed * prepparm;
1199 	int keytoklen = ((struct cipherkeytoken *)ckey)->len;
1200 
1201 	/* get already prepared memory for 2 cprbs with param block each */
1202 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
1203 	if (rc)
1204 		return rc;
1205 
1206 	/* fill request cprb struct */
1207 	preqcblk->domain = domain;
1208 
1209 	/* fill request cprb param block with AU request */
1210 	preqparm = (struct aureqparm *) preqcblk->req_parmb;
1211 	memcpy(preqparm->subfunc_code, "AU", 2);
1212 	preqparm->rule_array_len =
1213 		sizeof(preqparm->rule_array_len)
1214 		+ sizeof(preqparm->rule_array);
1215 	memcpy(preqparm->rule_array, "EXPT-SK ", 8);
1216 	/* vud, tk blob */
1217 	preqparm->vud.len = sizeof(preqparm->vud);
1218 	preqparm->vud.tk_blob_len = sizeof(preqparm->vud.tk_blob)
1219 		+ 2 * sizeof(uint16_t);
1220 	preqparm->vud.tk_blob_tag = 0x00C2;
1221 	/* kb, cca token */
1222 	preqparm->kb.len = keytoklen + 3 * sizeof(uint16_t);
1223 	preqparm->kb.cca_key_token_len = keytoklen + 2 * sizeof(uint16_t);
1224 	memcpy(preqparm->kb.cca_key_token, ckey, keytoklen);
1225 	/* now fill length of param block into cprb */
1226 	preqcblk->req_parml = sizeof(struct aureqparm) + keytoklen;
1227 
1228 	/* fill xcrb struct */
1229 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
1230 
1231 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
1232 	rc = _zcrypt_send_cprb(&xcrb);
1233 	if (rc) {
1234 		DEBUG_ERR(
1235 			"%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
1236 			__func__, (int) cardnr, (int) domain, rc);
1237 		goto out;
1238 	}
1239 
1240 	/* check response returncode and reasoncode */
1241 	if (prepcblk->ccp_rtcode != 0) {
1242 		DEBUG_ERR(
1243 			"%s unwrap secure key failure, card response %d/%d\n",
1244 			__func__,
1245 			(int) prepcblk->ccp_rtcode,
1246 			(int) prepcblk->ccp_rscode);
1247 		rc = -EIO;
1248 		goto out;
1249 	}
1250 	if (prepcblk->ccp_rscode != 0) {
1251 		DEBUG_WARN(
1252 			"%s unwrap secure key warning, card response %d/%d\n",
1253 			__func__,
1254 			(int) prepcblk->ccp_rtcode,
1255 			(int) prepcblk->ccp_rscode);
1256 	}
1257 
1258 	/* process response cprb param block */
1259 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
1260 	prepparm = (struct aurepparm *) prepcblk->rpl_parmb;
1261 
1262 	/* check the returned keyblock */
1263 	if (prepparm->vud.ckb.version != 0x01) {
1264 		DEBUG_ERR(
1265 			"%s reply param keyblock version mismatch 0x%02x != 0x01\n",
1266 			__func__, (int) prepparm->vud.ckb.version);
1267 		rc = -EIO;
1268 		goto out;
1269 	}
1270 	if (prepparm->vud.ckb.algo != 0x02) {
1271 		DEBUG_ERR(
1272 			"%s reply param keyblock algo mismatch 0x%02x != 0x02\n",
1273 			__func__, (int) prepparm->vud.ckb.algo);
1274 		rc = -EIO;
1275 		goto out;
1276 	}
1277 
1278 	/* copy the translated protected key */
1279 	switch (prepparm->vud.ckb.keylen) {
1280 	case 16+32:
1281 		/* AES 128 protected key */
1282 		if (protkeytype)
1283 			*protkeytype = PKEY_KEYTYPE_AES_128;
1284 		break;
1285 	case 24+32:
1286 		/* AES 192 protected key */
1287 		if (protkeytype)
1288 			*protkeytype = PKEY_KEYTYPE_AES_192;
1289 		break;
1290 	case 32+32:
1291 		/* AES 256 protected key */
1292 		if (protkeytype)
1293 			*protkeytype = PKEY_KEYTYPE_AES_256;
1294 		break;
1295 	default:
1296 		DEBUG_ERR("%s unknown/unsupported keylen %d\n",
1297 			  __func__, prepparm->vud.ckb.keylen);
1298 		rc = -EIO;
1299 		goto out;
1300 	}
1301 	memcpy(protkey, prepparm->vud.ckb.key, prepparm->vud.ckb.keylen);
1302 	if (protkeylen)
1303 		*protkeylen = prepparm->vud.ckb.keylen;
1304 
1305 out:
1306 	free_cprbmem(mem, PARMBSIZE, 0);
1307 	return rc;
1308 }
1309 EXPORT_SYMBOL(cca_cipher2protkey);
1310 
1311 /*
1312  * query cryptographic facility from CCA adapter
1313  */
1314 int cca_query_crypto_facility(u16 cardnr, u16 domain,
1315 			      const char *keyword,
1316 			      u8 *rarray, size_t *rarraylen,
1317 			      u8 *varray, size_t *varraylen)
1318 {
1319 	int rc;
1320 	u16 len;
1321 	u8 *mem, *ptr;
1322 	struct CPRBX *preqcblk, *prepcblk;
1323 	struct ica_xcRB xcrb;
1324 	struct fqreqparm {
1325 		u8  subfunc_code[2];
1326 		u16 rule_array_len;
1327 		char  rule_array[8];
1328 		struct lv1 {
1329 			u16 len;
1330 			u8  data[VARDATASIZE];
1331 		} lv1;
1332 		u16 dummylen;
1333 	} __packed * preqparm;
1334 	size_t parmbsize = sizeof(struct fqreqparm);
1335 	struct fqrepparm {
1336 		u8  subfunc_code[2];
1337 		u8  lvdata[0];
1338 	} __packed * prepparm;
1339 
1340 	/* get already prepared memory for 2 cprbs with param block each */
1341 	rc = alloc_and_prep_cprbmem(parmbsize, &mem, &preqcblk, &prepcblk);
1342 	if (rc)
1343 		return rc;
1344 
1345 	/* fill request cprb struct */
1346 	preqcblk->domain = domain;
1347 
1348 	/* fill request cprb param block with FQ request */
1349 	preqparm = (struct fqreqparm *) preqcblk->req_parmb;
1350 	memcpy(preqparm->subfunc_code, "FQ", 2);
1351 	memcpy(preqparm->rule_array, keyword, sizeof(preqparm->rule_array));
1352 	preqparm->rule_array_len =
1353 		sizeof(preqparm->rule_array_len) + sizeof(preqparm->rule_array);
1354 	preqparm->lv1.len = sizeof(preqparm->lv1);
1355 	preqparm->dummylen = sizeof(preqparm->dummylen);
1356 	preqcblk->req_parml = parmbsize;
1357 
1358 	/* fill xcrb struct */
1359 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
1360 
1361 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
1362 	rc = _zcrypt_send_cprb(&xcrb);
1363 	if (rc) {
1364 		DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
1365 			  __func__, (int) cardnr, (int) domain, rc);
1366 		goto out;
1367 	}
1368 
1369 	/* check response returncode and reasoncode */
1370 	if (prepcblk->ccp_rtcode != 0) {
1371 		DEBUG_ERR("%s unwrap secure key failure, card response %d/%d\n",
1372 			  __func__,
1373 			  (int) prepcblk->ccp_rtcode,
1374 			  (int) prepcblk->ccp_rscode);
1375 		rc = -EIO;
1376 		goto out;
1377 	}
1378 
1379 	/* process response cprb param block */
1380 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
1381 	prepparm = (struct fqrepparm *) prepcblk->rpl_parmb;
1382 	ptr = prepparm->lvdata;
1383 
1384 	/* check and possibly copy reply rule array */
1385 	len = *((u16 *) ptr);
1386 	if (len > sizeof(u16)) {
1387 		ptr += sizeof(u16);
1388 		len -= sizeof(u16);
1389 		if (rarray && rarraylen && *rarraylen > 0) {
1390 			*rarraylen = (len > *rarraylen ? *rarraylen : len);
1391 			memcpy(rarray, ptr, *rarraylen);
1392 		}
1393 		ptr += len;
1394 	}
1395 	/* check and possible copy reply var array */
1396 	len = *((u16 *) ptr);
1397 	if (len > sizeof(u16)) {
1398 		ptr += sizeof(u16);
1399 		len -= sizeof(u16);
1400 		if (varray && varraylen && *varraylen > 0) {
1401 			*varraylen = (len > *varraylen ? *varraylen : len);
1402 			memcpy(varray, ptr, *varraylen);
1403 		}
1404 		ptr += len;
1405 	}
1406 
1407 out:
1408 	free_cprbmem(mem, parmbsize, 0);
1409 	return rc;
1410 }
1411 EXPORT_SYMBOL(cca_query_crypto_facility);
1412 
1413 static int cca_info_cache_fetch(u16 cardnr, u16 domain, struct cca_info *ci)
1414 {
1415 	int rc = -ENOENT;
1416 	struct cca_info_list_entry *ptr;
1417 
1418 	spin_lock_bh(&cca_info_list_lock);
1419 	list_for_each_entry(ptr, &cca_info_list, list) {
1420 		if (ptr->cardnr == cardnr && ptr->domain == domain) {
1421 			memcpy(ci, &ptr->info, sizeof(*ci));
1422 			rc = 0;
1423 			break;
1424 		}
1425 	}
1426 	spin_unlock_bh(&cca_info_list_lock);
1427 
1428 	return rc;
1429 }
1430 
1431 static void cca_info_cache_update(u16 cardnr, u16 domain,
1432 				  const struct cca_info *ci)
1433 {
1434 	int found = 0;
1435 	struct cca_info_list_entry *ptr;
1436 
1437 	spin_lock_bh(&cca_info_list_lock);
1438 	list_for_each_entry(ptr, &cca_info_list, list) {
1439 		if (ptr->cardnr == cardnr &&
1440 		    ptr->domain == domain) {
1441 			memcpy(&ptr->info, ci, sizeof(*ci));
1442 			found = 1;
1443 			break;
1444 		}
1445 	}
1446 	if (!found) {
1447 		ptr = kmalloc(sizeof(*ptr), GFP_ATOMIC);
1448 		if (!ptr) {
1449 			spin_unlock_bh(&cca_info_list_lock);
1450 			return;
1451 		}
1452 		ptr->cardnr = cardnr;
1453 		ptr->domain = domain;
1454 		memcpy(&ptr->info, ci, sizeof(*ci));
1455 		list_add(&ptr->list, &cca_info_list);
1456 	}
1457 	spin_unlock_bh(&cca_info_list_lock);
1458 }
1459 
1460 static void cca_info_cache_scrub(u16 cardnr, u16 domain)
1461 {
1462 	struct cca_info_list_entry *ptr;
1463 
1464 	spin_lock_bh(&cca_info_list_lock);
1465 	list_for_each_entry(ptr, &cca_info_list, list) {
1466 		if (ptr->cardnr == cardnr &&
1467 		    ptr->domain == domain) {
1468 			list_del(&ptr->list);
1469 			kfree(ptr);
1470 			break;
1471 		}
1472 	}
1473 	spin_unlock_bh(&cca_info_list_lock);
1474 }
1475 
1476 static void __exit mkvp_cache_free(void)
1477 {
1478 	struct cca_info_list_entry *ptr, *pnext;
1479 
1480 	spin_lock_bh(&cca_info_list_lock);
1481 	list_for_each_entry_safe(ptr, pnext, &cca_info_list, list) {
1482 		list_del(&ptr->list);
1483 		kfree(ptr);
1484 	}
1485 	spin_unlock_bh(&cca_info_list_lock);
1486 }
1487 
1488 /*
1489  * Fetch cca_info values via query_crypto_facility from adapter.
1490  */
1491 static int fetch_cca_info(u16 cardnr, u16 domain, struct cca_info *ci)
1492 {
1493 	int rc, found = 0;
1494 	size_t rlen, vlen;
1495 	u8 *rarray, *varray, *pg;
1496 	struct zcrypt_device_status_ext devstat;
1497 
1498 	memset(ci, 0, sizeof(*ci));
1499 
1500 	/* get first info from zcrypt device driver about this apqn */
1501 	rc = zcrypt_device_status_ext(cardnr, domain, &devstat);
1502 	if (rc)
1503 		return rc;
1504 	ci->hwtype = devstat.hwtype;
1505 
1506 	/* prep page for rule array and var array use */
1507 	pg = (u8 *) __get_free_page(GFP_KERNEL);
1508 	if (!pg)
1509 		return -ENOMEM;
1510 	rarray = pg;
1511 	varray = pg + PAGE_SIZE/2;
1512 	rlen = vlen = PAGE_SIZE/2;
1513 
1514 	/* QF for this card/domain */
1515 	rc = cca_query_crypto_facility(cardnr, domain, "STATICSA",
1516 				       rarray, &rlen, varray, &vlen);
1517 	if (rc == 0 && rlen >= 10*8 && vlen >= 204) {
1518 		memcpy(ci->serial, rarray, 8);
1519 		ci->new_mk_state = (char) rarray[7*8];
1520 		ci->cur_mk_state = (char) rarray[8*8];
1521 		ci->old_mk_state = (char) rarray[9*8];
1522 		if (ci->old_mk_state == '2')
1523 			memcpy(&ci->old_mkvp, varray + 172, 8);
1524 		if (ci->cur_mk_state == '2')
1525 			memcpy(&ci->cur_mkvp, varray + 184, 8);
1526 		if (ci->new_mk_state == '3')
1527 			memcpy(&ci->new_mkvp, varray + 196, 8);
1528 		found = 1;
1529 	}
1530 
1531 	free_page((unsigned long) pg);
1532 
1533 	return found ? 0 : -ENOENT;
1534 }
1535 
1536 /*
1537  * Fetch cca information about a CCA queue.
1538  */
1539 int cca_get_info(u16 card, u16 dom, struct cca_info *ci, int verify)
1540 {
1541 	int rc;
1542 
1543 	rc = cca_info_cache_fetch(card, dom, ci);
1544 	if (rc || verify) {
1545 		rc = fetch_cca_info(card, dom, ci);
1546 		if (rc == 0)
1547 			cca_info_cache_update(card, dom, ci);
1548 	}
1549 
1550 	return rc;
1551 }
1552 EXPORT_SYMBOL(cca_get_info);
1553 
1554 /*
1555  * Search for a matching crypto card based on the
1556  * Master Key Verification Pattern given.
1557  */
1558 static int findcard(u64 mkvp, u16 *pcardnr, u16 *pdomain,
1559 		    int verify, int minhwtype)
1560 {
1561 	struct zcrypt_device_status_ext *device_status;
1562 	u16 card, dom;
1563 	struct cca_info ci;
1564 	int i, rc, oi = -1;
1565 
1566 	/* mkvp must not be zero, minhwtype needs to be >= 0 */
1567 	if (mkvp == 0 || minhwtype < 0)
1568 		return -EINVAL;
1569 
1570 	/* fetch status of all crypto cards */
1571 	device_status = kmalloc_array(MAX_ZDEV_ENTRIES_EXT,
1572 				      sizeof(struct zcrypt_device_status_ext),
1573 				      GFP_KERNEL);
1574 	if (!device_status)
1575 		return -ENOMEM;
1576 	zcrypt_device_status_mask_ext(device_status);
1577 
1578 	/* walk through all crypto cards */
1579 	for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
1580 		card = AP_QID_CARD(device_status[i].qid);
1581 		dom = AP_QID_QUEUE(device_status[i].qid);
1582 		if (device_status[i].online &&
1583 		    device_status[i].functions & 0x04) {
1584 			/* enabled CCA card, check current mkvp from cache */
1585 			if (cca_info_cache_fetch(card, dom, &ci) == 0 &&
1586 			    ci.hwtype >= minhwtype &&
1587 			    ci.cur_mk_state == '2' &&
1588 			    ci.cur_mkvp == mkvp) {
1589 				if (!verify)
1590 					break;
1591 				/* verify: refresh card info */
1592 				if (fetch_cca_info(card, dom, &ci) == 0) {
1593 					cca_info_cache_update(card, dom, &ci);
1594 					if (ci.hwtype >= minhwtype &&
1595 					    ci.cur_mk_state == '2' &&
1596 					    ci.cur_mkvp == mkvp)
1597 						break;
1598 				}
1599 			}
1600 		} else {
1601 			/* Card is offline and/or not a CCA card. */
1602 			/* del mkvp entry from cache if it exists */
1603 			cca_info_cache_scrub(card, dom);
1604 		}
1605 	}
1606 	if (i >= MAX_ZDEV_ENTRIES_EXT) {
1607 		/* nothing found, so this time without cache */
1608 		for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
1609 			if (!(device_status[i].online &&
1610 			      device_status[i].functions & 0x04))
1611 				continue;
1612 			card = AP_QID_CARD(device_status[i].qid);
1613 			dom = AP_QID_QUEUE(device_status[i].qid);
1614 			/* fresh fetch mkvp from adapter */
1615 			if (fetch_cca_info(card, dom, &ci) == 0) {
1616 				cca_info_cache_update(card, dom, &ci);
1617 				if (ci.hwtype >= minhwtype &&
1618 				    ci.cur_mk_state == '2' &&
1619 				    ci.cur_mkvp == mkvp)
1620 					break;
1621 				if (ci.hwtype >= minhwtype &&
1622 				    ci.old_mk_state == '2' &&
1623 				    ci.old_mkvp == mkvp &&
1624 				    oi < 0)
1625 					oi = i;
1626 			}
1627 		}
1628 		if (i >= MAX_ZDEV_ENTRIES_EXT && oi >= 0) {
1629 			/* old mkvp matched, use this card then */
1630 			card = AP_QID_CARD(device_status[oi].qid);
1631 			dom = AP_QID_QUEUE(device_status[oi].qid);
1632 		}
1633 	}
1634 	if (i < MAX_ZDEV_ENTRIES_EXT || oi >= 0) {
1635 		if (pcardnr)
1636 			*pcardnr = card;
1637 		if (pdomain)
1638 			*pdomain = dom;
1639 		rc = (i < MAX_ZDEV_ENTRIES_EXT ? 0 : 1);
1640 	} else
1641 		rc = -ENODEV;
1642 
1643 	kfree(device_status);
1644 	return rc;
1645 }
1646 
1647 /*
1648  * Search for a matching crypto card based on the Master Key
1649  * Verification Pattern provided inside a secure key token.
1650  */
1651 int cca_findcard(const u8 *key, u16 *pcardnr, u16 *pdomain, int verify)
1652 {
1653 	u64 mkvp;
1654 	int minhwtype = 0;
1655 	const struct keytoken_header *hdr = (struct keytoken_header *) key;
1656 
1657 	if (hdr->type != TOKTYPE_CCA_INTERNAL)
1658 		return -EINVAL;
1659 
1660 	switch (hdr->version) {
1661 	case TOKVER_CCA_AES:
1662 		mkvp = ((struct secaeskeytoken *)key)->mkvp;
1663 		break;
1664 	case TOKVER_CCA_VLSC:
1665 		mkvp = ((struct cipherkeytoken *)key)->mkvp0;
1666 		minhwtype = AP_DEVICE_TYPE_CEX6;
1667 		break;
1668 	default:
1669 		return -EINVAL;
1670 	}
1671 
1672 	return findcard(mkvp, pcardnr, pdomain, verify, minhwtype);
1673 }
1674 EXPORT_SYMBOL(cca_findcard);
1675 
1676 int cca_findcard2(u32 **apqns, u32 *nr_apqns, u16 cardnr, u16 domain,
1677 		  int minhwtype, u64 cur_mkvp, u64 old_mkvp, int verify)
1678 {
1679 	struct zcrypt_device_status_ext *device_status;
1680 	int i, n, card, dom, curmatch, oldmatch, rc = 0;
1681 	struct cca_info ci;
1682 
1683 	*apqns = NULL;
1684 	*nr_apqns = 0;
1685 
1686 	/* fetch status of all crypto cards */
1687 	device_status = kmalloc_array(MAX_ZDEV_ENTRIES_EXT,
1688 				      sizeof(struct zcrypt_device_status_ext),
1689 				      GFP_KERNEL);
1690 	if (!device_status)
1691 		return -ENOMEM;
1692 	zcrypt_device_status_mask_ext(device_status);
1693 
1694 	/* loop two times: first gather eligible apqns, then store them */
1695 	while (1) {
1696 		n = 0;
1697 		/* walk through all the crypto cards */
1698 		for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
1699 			card = AP_QID_CARD(device_status[i].qid);
1700 			dom = AP_QID_QUEUE(device_status[i].qid);
1701 			/* check online state */
1702 			if (!device_status[i].online)
1703 				continue;
1704 			/* check for cca functions */
1705 			if (!(device_status[i].functions & 0x04))
1706 				continue;
1707 			/* check cardnr */
1708 			if (cardnr != 0xFFFF && card != cardnr)
1709 				continue;
1710 			/* check domain */
1711 			if (domain != 0xFFFF && dom != domain)
1712 				continue;
1713 			/* get cca info on this apqn */
1714 			if (cca_get_info(card, dom, &ci, verify))
1715 				continue;
1716 			/* current master key needs to be valid */
1717 			if (ci.cur_mk_state != '2')
1718 				continue;
1719 			/* check min hardware type */
1720 			if (minhwtype > 0 && minhwtype > ci.hwtype)
1721 				continue;
1722 			if (cur_mkvp || old_mkvp) {
1723 				/* check mkvps */
1724 				curmatch = oldmatch = 0;
1725 				if (cur_mkvp && cur_mkvp == ci.cur_mkvp)
1726 					curmatch = 1;
1727 				if (old_mkvp && ci.old_mk_state == '2' &&
1728 				    old_mkvp == ci.old_mkvp)
1729 					oldmatch = 1;
1730 				if ((cur_mkvp || old_mkvp) &&
1731 				    (curmatch + oldmatch < 1))
1732 					continue;
1733 			}
1734 			/* apqn passed all filtering criterons */
1735 			if (*apqns && n < *nr_apqns)
1736 				(*apqns)[n] = (((u16)card) << 16) | ((u16) dom);
1737 			n++;
1738 		}
1739 		/* loop 2nd time: array has been filled */
1740 		if (*apqns)
1741 			break;
1742 		/* loop 1st time: have # of eligible apqns in n */
1743 		if (!n) {
1744 			rc = -ENODEV; /* no eligible apqns found */
1745 			break;
1746 		}
1747 		*nr_apqns = n;
1748 		/* allocate array to store n apqns into */
1749 		*apqns = kmalloc_array(n, sizeof(u32), GFP_KERNEL);
1750 		if (!*apqns) {
1751 			rc = -ENOMEM;
1752 			break;
1753 		}
1754 		verify = 0;
1755 	}
1756 
1757 	kfree(device_status);
1758 	return rc;
1759 }
1760 EXPORT_SYMBOL(cca_findcard2);
1761 
1762 void __exit zcrypt_ccamisc_exit(void)
1763 {
1764 	mkvp_cache_free();
1765 }
1766