60b6bec21c323f50d51152a6a5c10e93072f07c5
[linux-2.6-microblaze.git] / drivers / s390 / crypto / zcrypt_ep11misc.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  Copyright IBM Corp. 2019
4  *  Author(s): Harald Freudenberger <freude@linux.ibm.com>
5  *
6  *  Collection of EP11 misc functions used by zcrypt and pkey
7  */
8
9 #define KMSG_COMPONENT "zcrypt"
10 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
11
12 #include <linux/init.h>
13 #include <linux/module.h>
14 #include <linux/slab.h>
15 #include <linux/random.h>
16 #include <asm/zcrypt.h>
17 #include <asm/pkey.h>
18
19 #include "ap_bus.h"
20 #include "zcrypt_api.h"
21 #include "zcrypt_debug.h"
22 #include "zcrypt_msgtype6.h"
23 #include "zcrypt_ep11misc.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 /* default iv used here */
32 static const u8 def_iv[16] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
33                                0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
34
35 /* ep11 card info cache */
36 struct card_list_entry {
37         struct list_head list;
38         u16 cardnr;
39         struct ep11_card_info info;
40 };
41 static LIST_HEAD(card_list);
42 static DEFINE_SPINLOCK(card_list_lock);
43
44 static int card_cache_fetch(u16 cardnr, struct ep11_card_info *ci)
45 {
46         int rc = -ENOENT;
47         struct card_list_entry *ptr;
48
49         spin_lock_bh(&card_list_lock);
50         list_for_each_entry(ptr, &card_list, list) {
51                 if (ptr->cardnr == cardnr) {
52                         memcpy(ci, &ptr->info, sizeof(*ci));
53                         rc = 0;
54                         break;
55                 }
56         }
57         spin_unlock_bh(&card_list_lock);
58
59         return rc;
60 }
61
62 static void card_cache_update(u16 cardnr, const struct ep11_card_info *ci)
63 {
64         int found = 0;
65         struct card_list_entry *ptr;
66
67         spin_lock_bh(&card_list_lock);
68         list_for_each_entry(ptr, &card_list, list) {
69                 if (ptr->cardnr == cardnr) {
70                         memcpy(&ptr->info, ci, sizeof(*ci));
71                         found = 1;
72                         break;
73                 }
74         }
75         if (!found) {
76                 ptr = kmalloc(sizeof(*ptr), GFP_ATOMIC);
77                 if (!ptr) {
78                         spin_unlock_bh(&card_list_lock);
79                         return;
80                 }
81                 ptr->cardnr = cardnr;
82                 memcpy(&ptr->info, ci, sizeof(*ci));
83                 list_add(&ptr->list, &card_list);
84         }
85         spin_unlock_bh(&card_list_lock);
86 }
87
88 static void card_cache_scrub(u16 cardnr)
89 {
90         struct card_list_entry *ptr;
91
92         spin_lock_bh(&card_list_lock);
93         list_for_each_entry(ptr, &card_list, list) {
94                 if (ptr->cardnr == cardnr) {
95                         list_del(&ptr->list);
96                         kfree(ptr);
97                         break;
98                 }
99         }
100         spin_unlock_bh(&card_list_lock);
101 }
102
103 static void __exit card_cache_free(void)
104 {
105         struct card_list_entry *ptr, *pnext;
106
107         spin_lock_bh(&card_list_lock);
108         list_for_each_entry_safe(ptr, pnext, &card_list, list) {
109                 list_del(&ptr->list);
110                 kfree(ptr);
111         }
112         spin_unlock_bh(&card_list_lock);
113 }
114
115 /*
116  * Simple check if the key blob is a valid EP11 secure AES key.
117  */
118 int ep11_check_aeskeyblob(debug_info_t *dbg, int dbflvl,
119                           const u8 *key, int keybitsize,
120                           int checkcpacfexport)
121 {
122         struct ep11keyblob *kb = (struct ep11keyblob *) key;
123
124 #define DBF(...) debug_sprintf_event(dbg, dbflvl, ##__VA_ARGS__)
125
126         if (kb->head.type != TOKTYPE_NON_CCA) {
127                 if (dbg)
128                         DBF("%s key check failed, type 0x%02x != 0x%02x\n",
129                             __func__, (int) kb->head.type, TOKTYPE_NON_CCA);
130                 return -EINVAL;
131         }
132         if (kb->head.version != TOKVER_EP11_AES) {
133                 if (dbg)
134                         DBF("%s key check failed, version 0x%02x != 0x%02x\n",
135                             __func__, (int) kb->head.version, TOKVER_EP11_AES);
136                 return -EINVAL;
137         }
138         if (kb->version != EP11_STRUCT_MAGIC) {
139                 if (dbg)
140                         DBF("%s key check failed, magic 0x%04x != 0x%04x\n",
141                             __func__, (int) kb->version, EP11_STRUCT_MAGIC);
142                 return -EINVAL;
143         }
144         switch (kb->head.keybitlen) {
145         case 128:
146         case 192:
147         case 256:
148                 break;
149         default:
150                 if (dbg)
151                         DBF("%s key check failed, keybitlen %d invalid\n",
152                             __func__, (int) kb->head.keybitlen);
153                 return -EINVAL;
154         }
155         if (keybitsize > 0 && keybitsize != (int) kb->head.keybitlen) {
156                 DBF("%s key check failed, keybitsize %d\n",
157                     __func__, keybitsize);
158                 return -EINVAL;
159         }
160         if (checkcpacfexport && !(kb->attr & EP11_BLOB_PKEY_EXTRACTABLE)) {
161                 if (dbg)
162                         DBF("%s key check failed, PKEY_EXTRACTABLE is 0\n",
163                             __func__);
164                 return -EINVAL;
165         }
166 #undef DBF
167
168         return 0;
169 }
170 EXPORT_SYMBOL(ep11_check_aeskeyblob);
171
172 /*
173  * Allocate and prepare ep11 cprb plus additional payload.
174  */
175 static inline struct ep11_cprb *alloc_cprb(size_t payload_len)
176 {
177         size_t len = sizeof(struct ep11_cprb) + payload_len;
178         struct ep11_cprb *cprb;
179
180         cprb = kzalloc(len, GFP_KERNEL);
181         if (!cprb)
182                 return NULL;
183
184         cprb->cprb_len = sizeof(struct ep11_cprb);
185         cprb->cprb_ver_id = 0x04;
186         memcpy(cprb->func_id, "T4", 2);
187         cprb->ret_code = 0xFFFFFFFF;
188         cprb->payload_len = payload_len;
189
190         return cprb;
191 }
192
193 /*
194  * Some helper functions related to ASN1 encoding.
195  * Limited to length info <= 2 byte.
196  */
197
198 #define ASN1TAGLEN(x) (2 + (x) + ((x) > 127 ? 1 : 0) + ((x) > 255 ? 1 : 0))
199
200 static int asn1tag_write(u8 *ptr, u8 tag, const u8 *pvalue, u16 valuelen)
201 {
202         ptr[0] = tag;
203         if (valuelen > 255) {
204                 ptr[1] = 0x82;
205                 *((u16 *)(ptr + 2)) = valuelen;
206                 memcpy(ptr + 4, pvalue, valuelen);
207                 return 4 + valuelen;
208         }
209         if (valuelen > 127) {
210                 ptr[1] = 0x81;
211                 ptr[2] = (u8) valuelen;
212                 memcpy(ptr + 3, pvalue, valuelen);
213                 return 3 + valuelen;
214         }
215         ptr[1] = (u8) valuelen;
216         memcpy(ptr + 2, pvalue, valuelen);
217         return 2 + valuelen;
218 }
219
220 /* EP11 payload > 127 bytes starts with this struct */
221 struct pl_head {
222         u8  tag;
223         u8  lenfmt;
224         u16 len;
225         u8  func_tag;
226         u8  func_len;
227         u32 func;
228         u8  dom_tag;
229         u8  dom_len;
230         u32 dom;
231 } __packed;
232
233 /* prep ep11 payload head helper function */
234 static inline void prep_head(struct pl_head *h,
235                              size_t pl_size, int api, int func)
236 {
237         h->tag = 0x30;
238         h->lenfmt = 0x82;
239         h->len = pl_size - 4;
240         h->func_tag = 0x04;
241         h->func_len = sizeof(u32);
242         h->func = (api << 16) + func;
243         h->dom_tag = 0x04;
244         h->dom_len = sizeof(u32);
245 }
246
247 /* prep urb helper function */
248 static inline void prep_urb(struct ep11_urb *u,
249                             struct ep11_target_dev *t, int nt,
250                             struct ep11_cprb *req, size_t req_len,
251                             struct ep11_cprb *rep, size_t rep_len)
252 {
253         u->targets = (u8 __user *) t;
254         u->targets_num = nt;
255         u->req = (u8 __user *) req;
256         u->req_len = req_len;
257         u->resp = (u8 __user *) rep;
258         u->resp_len = rep_len;
259 }
260
261 /* Check ep11 reply payload, return 0 or suggested errno value. */
262 static int check_reply_pl(const u8 *pl, const char *func)
263 {
264         int len;
265         u32 ret;
266
267         /* start tag */
268         if (*pl++ != 0x30) {
269                 DEBUG_ERR("%s reply start tag mismatch\n", func);
270                 return -EIO;
271         }
272
273         /* payload length format */
274         if (*pl < 127) {
275                 len = *pl;
276                 pl++;
277         } else if (*pl == 0x81) {
278                 pl++;
279                 len = *pl;
280                 pl++;
281         } else if (*pl == 0x82) {
282                 pl++;
283                 len = *((u16 *)pl);
284                 pl += 2;
285         } else {
286                 DEBUG_ERR("%s reply start tag lenfmt mismatch 0x%02hhx\n",
287                           func, *pl);
288                 return -EIO;
289         }
290
291         /* len should cover at least 3 fields with 32 bit value each */
292         if (len < 3 * 6) {
293                 DEBUG_ERR("%s reply length %d too small\n", func, len);
294                 return -EIO;
295         }
296
297         /* function tag, length and value */
298         if (pl[0] != 0x04 || pl[1] != 0x04) {
299                 DEBUG_ERR("%s function tag or length mismatch\n", func);
300                 return -EIO;
301         }
302         pl += 6;
303
304         /* dom tag, length and value */
305         if (pl[0] != 0x04 || pl[1] != 0x04) {
306                 DEBUG_ERR("%s dom tag or length mismatch\n", func);
307                 return -EIO;
308         }
309         pl += 6;
310
311         /* return value tag, length and value */
312         if (pl[0] != 0x04 || pl[1] != 0x04) {
313                 DEBUG_ERR("%s return value tag or length mismatch\n", func);
314                 return -EIO;
315         }
316         pl += 2;
317         ret = *((u32 *)pl);
318         if (ret != 0) {
319                 DEBUG_ERR("%s return value 0x%04x != 0\n", func, ret);
320                 return -EIO;
321         }
322
323         return 0;
324 }
325
326
327 /*
328  * Helper function which does an ep11 query with given query type.
329  */
330 static int ep11_query_info(u16 cardnr, u16 domain, u32 query_type,
331                            size_t buflen, u8 *buf)
332 {
333         struct ep11_info_req_pl {
334                 struct pl_head head;
335                 u8  query_type_tag;
336                 u8  query_type_len;
337                 u32 query_type;
338                 u8  query_subtype_tag;
339                 u8  query_subtype_len;
340                 u32 query_subtype;
341         } __packed * req_pl;
342         struct ep11_info_rep_pl {
343                 struct pl_head head;
344                 u8  rc_tag;
345                 u8  rc_len;
346                 u32 rc;
347                 u8  data_tag;
348                 u8  data_lenfmt;
349                 u16 data_len;
350         } __packed * rep_pl;
351         struct ep11_cprb *req = NULL, *rep = NULL;
352         struct ep11_target_dev target;
353         struct ep11_urb *urb = NULL;
354         int api = 1, rc = -ENOMEM;
355
356         /* request cprb and payload */
357         req = alloc_cprb(sizeof(struct ep11_info_req_pl));
358         if (!req)
359                 goto out;
360         req_pl = (struct ep11_info_req_pl *) (((u8 *) req) + sizeof(*req));
361         prep_head(&req_pl->head, sizeof(*req_pl), api, 38); /* get xcp info */
362         req_pl->query_type_tag = 0x04;
363         req_pl->query_type_len = sizeof(u32);
364         req_pl->query_type = query_type;
365         req_pl->query_subtype_tag = 0x04;
366         req_pl->query_subtype_len = sizeof(u32);
367
368         /* reply cprb and payload */
369         rep = alloc_cprb(sizeof(struct ep11_info_rep_pl) + buflen);
370         if (!rep)
371                 goto out;
372         rep_pl = (struct ep11_info_rep_pl *) (((u8 *) rep) + sizeof(*rep));
373
374         /* urb and target */
375         urb = kmalloc(sizeof(struct ep11_urb), GFP_KERNEL);
376         if (!urb)
377                 goto out;
378         target.ap_id = cardnr;
379         target.dom_id = domain;
380         prep_urb(urb, &target, 1,
381                  req, sizeof(*req) + sizeof(*req_pl),
382                  rep, sizeof(*rep) + sizeof(*rep_pl) + buflen);
383
384         rc = zcrypt_send_ep11_cprb(urb);
385         if (rc) {
386                 DEBUG_ERR(
387                         "%s zcrypt_send_ep11_cprb(card=%d dom=%d) failed, rc=%d\n",
388                         __func__, (int) cardnr, (int) domain, rc);
389                 goto out;
390         }
391
392         rc = check_reply_pl((u8 *)rep_pl, __func__);
393         if (rc)
394                 goto out;
395         if (rep_pl->data_tag != 0x04 || rep_pl->data_lenfmt != 0x82) {
396                 DEBUG_ERR("%s unknown reply data format\n", __func__);
397                 rc = -EIO;
398                 goto out;
399         }
400         if (rep_pl->data_len > buflen) {
401                 DEBUG_ERR("%s mismatch between reply data len and buffer len\n",
402                           __func__);
403                 rc = -ENOSPC;
404                 goto out;
405         }
406
407         memcpy(buf, ((u8 *) rep_pl) + sizeof(*rep_pl), rep_pl->data_len);
408
409 out:
410         kfree(req);
411         kfree(rep);
412         kfree(urb);
413         return rc;
414 }
415
416 /*
417  * Provide information about an EP11 card.
418  */
419 int ep11_get_card_info(u16 card, struct ep11_card_info *info, int verify)
420 {
421         int rc;
422         struct ep11_module_query_info {
423                 u32 API_ord_nr;
424                 u32 firmware_id;
425                 u8  FW_major_vers;
426                 u8  FW_minor_vers;
427                 u8  CSP_major_vers;
428                 u8  CSP_minor_vers;
429                 u8  fwid[32];
430                 u8  xcp_config_hash[32];
431                 u8  CSP_config_hash[32];
432                 u8  serial[16];
433                 u8  module_date_time[16];
434                 u64 op_mode;
435                 u32 PKCS11_flags;
436                 u32 ext_flags;
437                 u32 domains;
438                 u32 sym_state_bytes;
439                 u32 digest_state_bytes;
440                 u32 pin_blob_bytes;
441                 u32 SPKI_bytes;
442                 u32 priv_key_blob_bytes;
443                 u32 sym_blob_bytes;
444                 u32 max_payload_bytes;
445                 u32 CP_profile_bytes;
446                 u32 max_CP_index;
447         } __packed * pmqi = NULL;
448
449         rc = card_cache_fetch(card, info);
450         if (rc || verify) {
451                 pmqi = kmalloc(sizeof(*pmqi), GFP_KERNEL);
452                 if (!pmqi)
453                         return -ENOMEM;
454                 rc = ep11_query_info(card, AUTOSEL_DOM,
455                                      0x01 /* module info query */,
456                                      sizeof(*pmqi), (u8 *) pmqi);
457                 if (rc) {
458                         if (rc == -ENODEV)
459                                 card_cache_scrub(card);
460                         goto out;
461                 }
462                 memset(info, 0, sizeof(*info));
463                 info->API_ord_nr = pmqi->API_ord_nr;
464                 info->FW_version =
465                         (pmqi->FW_major_vers << 8) + pmqi->FW_minor_vers;
466                 memcpy(info->serial, pmqi->serial, sizeof(info->serial));
467                 info->op_mode = pmqi->op_mode;
468                 card_cache_update(card, info);
469         }
470
471 out:
472         kfree(pmqi);
473         return rc;
474 }
475 EXPORT_SYMBOL(ep11_get_card_info);
476
477 /*
478  * Provide information about a domain within an EP11 card.
479  */
480 int ep11_get_domain_info(u16 card, u16 domain, struct ep11_domain_info *info)
481 {
482         int rc;
483         struct ep11_domain_query_info {
484                 u32 dom_index;
485                 u8  cur_WK_VP[32];
486                 u8  new_WK_VP[32];
487                 u32 dom_flags;
488                 u64 op_mode;
489         } __packed * p_dom_info;
490
491         p_dom_info = kmalloc(sizeof(*p_dom_info), GFP_KERNEL);
492         if (!p_dom_info)
493                 return -ENOMEM;
494
495         rc = ep11_query_info(card, domain, 0x03 /* domain info query */,
496                              sizeof(*p_dom_info), (u8 *) p_dom_info);
497         if (rc)
498                 goto out;
499
500         memset(info, 0, sizeof(*info));
501         info->cur_wk_state = '0';
502         info->new_wk_state = '0';
503         if (p_dom_info->dom_flags & 0x10 /* left imprint mode */) {
504                 if (p_dom_info->dom_flags & 0x02 /* cur wk valid */) {
505                         info->cur_wk_state = '1';
506                         memcpy(info->cur_wkvp, p_dom_info->cur_WK_VP, 32);
507                 }
508                 if (p_dom_info->dom_flags & 0x04 /* new wk present */
509                     || p_dom_info->dom_flags & 0x08 /* new wk committed */) {
510                         info->new_wk_state =
511                                 p_dom_info->dom_flags & 0x08 ? '2' : '1';
512                         memcpy(info->new_wkvp, p_dom_info->new_WK_VP, 32);
513                 }
514         }
515         info->op_mode = p_dom_info->op_mode;
516
517 out:
518         kfree(p_dom_info);
519         return rc;
520 }
521 EXPORT_SYMBOL(ep11_get_domain_info);
522
523 /*
524  * Default EP11 AES key generate attributes, used when no keygenflags given:
525  * XCP_BLOB_ENCRYPT | XCP_BLOB_DECRYPT | XCP_BLOB_PROTKEY_EXTRACTABLE
526  */
527 #define KEY_ATTR_DEFAULTS 0x00200c00
528
529 int ep11_genaeskey(u16 card, u16 domain, u32 keybitsize, u32 keygenflags,
530                    u8 *keybuf, size_t *keybufsize)
531 {
532         struct keygen_req_pl {
533                 struct pl_head head;
534                 u8  var_tag;
535                 u8  var_len;
536                 u32 var;
537                 u8  keybytes_tag;
538                 u8  keybytes_len;
539                 u32 keybytes;
540                 u8  mech_tag;
541                 u8  mech_len;
542                 u32 mech;
543                 u8  attr_tag;
544                 u8  attr_len;
545                 u32 attr_header;
546                 u32 attr_bool_mask;
547                 u32 attr_bool_bits;
548                 u32 attr_val_len_type;
549                 u32 attr_val_len_value;
550                 u8  pin_tag;
551                 u8  pin_len;
552         } __packed * req_pl;
553         struct keygen_rep_pl {
554                 struct pl_head head;
555                 u8  rc_tag;
556                 u8  rc_len;
557                 u32 rc;
558                 u8  data_tag;
559                 u8  data_lenfmt;
560                 u16 data_len;
561                 u8  data[512];
562         } __packed * rep_pl;
563         struct ep11_cprb *req = NULL, *rep = NULL;
564         struct ep11_target_dev target;
565         struct ep11_urb *urb = NULL;
566         struct ep11keyblob *kb;
567         int api, rc = -ENOMEM;
568
569         switch (keybitsize) {
570         case 128:
571         case 192:
572         case 256:
573                 break;
574         default:
575                 DEBUG_ERR(
576                         "%s unknown/unsupported keybitsize %d\n",
577                         __func__, keybitsize);
578                 rc = -EINVAL;
579                 goto out;
580         }
581
582         /* request cprb and payload */
583         req = alloc_cprb(sizeof(struct keygen_req_pl));
584         if (!req)
585                 goto out;
586         req_pl = (struct keygen_req_pl *) (((u8 *) req) + sizeof(*req));
587         api = (!keygenflags || keygenflags & 0x00200000) ? 4 : 1;
588         prep_head(&req_pl->head, sizeof(*req_pl), api, 21); /* GenerateKey */
589         req_pl->var_tag = 0x04;
590         req_pl->var_len = sizeof(u32);
591         req_pl->keybytes_tag = 0x04;
592         req_pl->keybytes_len = sizeof(u32);
593         req_pl->keybytes = keybitsize / 8;
594         req_pl->mech_tag = 0x04;
595         req_pl->mech_len = sizeof(u32);
596         req_pl->mech = 0x00001080; /* CKM_AES_KEY_GEN */
597         req_pl->attr_tag = 0x04;
598         req_pl->attr_len = 5 * sizeof(u32);
599         req_pl->attr_header = 0x10010000;
600         req_pl->attr_bool_mask = keygenflags ? keygenflags : KEY_ATTR_DEFAULTS;
601         req_pl->attr_bool_bits = keygenflags ? keygenflags : KEY_ATTR_DEFAULTS;
602         req_pl->attr_val_len_type = 0x00000161; /* CKA_VALUE_LEN */
603         req_pl->attr_val_len_value = keybitsize / 8;
604         req_pl->pin_tag = 0x04;
605
606         /* reply cprb and payload */
607         rep = alloc_cprb(sizeof(struct keygen_rep_pl));
608         if (!rep)
609                 goto out;
610         rep_pl = (struct keygen_rep_pl *) (((u8 *) rep) + sizeof(*rep));
611
612         /* urb and target */
613         urb = kmalloc(sizeof(struct ep11_urb), GFP_KERNEL);
614         if (!urb)
615                 goto out;
616         target.ap_id = card;
617         target.dom_id = domain;
618         prep_urb(urb, &target, 1,
619                  req, sizeof(*req) + sizeof(*req_pl),
620                  rep, sizeof(*rep) + sizeof(*rep_pl));
621
622         rc = zcrypt_send_ep11_cprb(urb);
623         if (rc) {
624                 DEBUG_ERR(
625                         "%s zcrypt_send_ep11_cprb(card=%d dom=%d) failed, rc=%d\n",
626                         __func__, (int) card, (int) domain, rc);
627                 goto out;
628         }
629
630         rc = check_reply_pl((u8 *)rep_pl, __func__);
631         if (rc)
632                 goto out;
633         if (rep_pl->data_tag != 0x04 || rep_pl->data_lenfmt != 0x82) {
634                 DEBUG_ERR("%s unknown reply data format\n", __func__);
635                 rc = -EIO;
636                 goto out;
637         }
638         if (rep_pl->data_len > *keybufsize) {
639                 DEBUG_ERR("%s mismatch reply data len / key buffer len\n",
640                           __func__);
641                 rc = -ENOSPC;
642                 goto out;
643         }
644
645         /* copy key blob and set header values */
646         memcpy(keybuf, rep_pl->data, rep_pl->data_len);
647         *keybufsize = rep_pl->data_len;
648         kb = (struct ep11keyblob *) keybuf;
649         kb->head.type = TOKTYPE_NON_CCA;
650         kb->head.len = rep_pl->data_len;
651         kb->head.version = TOKVER_EP11_AES;
652         kb->head.keybitlen = keybitsize;
653
654 out:
655         kfree(req);
656         kfree(rep);
657         kfree(urb);
658         return rc;
659 }
660 EXPORT_SYMBOL(ep11_genaeskey);
661
662 static int ep11_cryptsingle(u16 card, u16 domain,
663                             u16 mode, u32 mech, const u8 *iv,
664                             const u8 *key, size_t keysize,
665                             const u8 *inbuf, size_t inbufsize,
666                             u8 *outbuf, size_t *outbufsize)
667 {
668         struct crypt_req_pl {
669                 struct pl_head head;
670                 u8  var_tag;
671                 u8  var_len;
672                 u32 var;
673                 u8  mech_tag;
674                 u8  mech_len;
675                 u32 mech;
676                 /*
677                  * maybe followed by iv data
678                  * followed by key tag + key blob
679                  * followed by plaintext tag + plaintext
680                  */
681         } __packed * req_pl;
682         struct crypt_rep_pl {
683                 struct pl_head head;
684                 u8  rc_tag;
685                 u8  rc_len;
686                 u32 rc;
687                 u8  data_tag;
688                 u8  data_lenfmt;
689                 /* data follows */
690         } __packed * rep_pl;
691         struct ep11_cprb *req = NULL, *rep = NULL;
692         struct ep11_target_dev target;
693         struct ep11_urb *urb = NULL;
694         size_t req_pl_size, rep_pl_size;
695         int n, api = 1, rc = -ENOMEM;
696         u8 *p;
697
698         /* the simple asn1 coding used has length limits */
699         if (keysize > 0xFFFF || inbufsize > 0xFFFF)
700                 return -EINVAL;
701
702         /* request cprb and payload */
703         req_pl_size = sizeof(struct crypt_req_pl) + (iv ? 16 : 0)
704                 + ASN1TAGLEN(keysize) + ASN1TAGLEN(inbufsize);
705         req = alloc_cprb(req_pl_size);
706         if (!req)
707                 goto out;
708         req_pl = (struct crypt_req_pl *) (((u8 *) req) + sizeof(*req));
709         prep_head(&req_pl->head, req_pl_size, api, (mode ? 20 : 19));
710         req_pl->var_tag = 0x04;
711         req_pl->var_len = sizeof(u32);
712         /* mech is mech + mech params (iv here) */
713         req_pl->mech_tag = 0x04;
714         req_pl->mech_len = sizeof(u32) + (iv ? 16 : 0);
715         req_pl->mech = (mech ? mech : 0x00001085); /* CKM_AES_CBC_PAD */
716         p = ((u8 *) req_pl) + sizeof(*req_pl);
717         if (iv) {
718                 memcpy(p, iv, 16);
719                 p += 16;
720         }
721         /* key and input data */
722         p += asn1tag_write(p, 0x04, key, keysize);
723         p += asn1tag_write(p, 0x04, inbuf, inbufsize);
724
725         /* reply cprb and payload, assume out data size <= in data size + 32 */
726         rep_pl_size = sizeof(struct crypt_rep_pl) + ASN1TAGLEN(inbufsize + 32);
727         rep = alloc_cprb(rep_pl_size);
728         if (!rep)
729                 goto out;
730         rep_pl = (struct crypt_rep_pl *) (((u8 *) rep) + sizeof(*rep));
731
732         /* urb and target */
733         urb = kmalloc(sizeof(struct ep11_urb), GFP_KERNEL);
734         if (!urb)
735                 goto out;
736         target.ap_id = card;
737         target.dom_id = domain;
738         prep_urb(urb, &target, 1,
739                  req, sizeof(*req) + req_pl_size,
740                  rep, sizeof(*rep) + rep_pl_size);
741
742         rc = zcrypt_send_ep11_cprb(urb);
743         if (rc) {
744                 DEBUG_ERR(
745                         "%s zcrypt_send_ep11_cprb(card=%d dom=%d) failed, rc=%d\n",
746                         __func__, (int) card, (int) domain, rc);
747                 goto out;
748         }
749
750         rc = check_reply_pl((u8 *)rep_pl, __func__);
751         if (rc)
752                 goto out;
753         if (rep_pl->data_tag != 0x04) {
754                 DEBUG_ERR("%s unknown reply data format\n", __func__);
755                 rc = -EIO;
756                 goto out;
757         }
758         p = ((u8 *) rep_pl) + sizeof(*rep_pl);
759         if (rep_pl->data_lenfmt <= 127)
760                 n = rep_pl->data_lenfmt;
761         else if (rep_pl->data_lenfmt == 0x81)
762                 n = *p++;
763         else if (rep_pl->data_lenfmt == 0x82) {
764                 n = *((u16 *) p);
765                 p += 2;
766         } else {
767                 DEBUG_ERR("%s unknown reply data length format 0x%02hhx\n",
768                           __func__, rep_pl->data_lenfmt);
769                 rc = -EIO;
770                 goto out;
771         }
772         if (n > *outbufsize) {
773                 DEBUG_ERR("%s mismatch reply data len %d / output buffer %zu\n",
774                           __func__, n, *outbufsize);
775                 rc = -ENOSPC;
776                 goto out;
777         }
778
779         memcpy(outbuf, p, n);
780         *outbufsize = n;
781
782 out:
783         kfree(req);
784         kfree(rep);
785         kfree(urb);
786         return rc;
787 }
788
789 static int ep11_unwrapkey(u16 card, u16 domain,
790                           const u8 *kek, size_t keksize,
791                           const u8 *enckey, size_t enckeysize,
792                           u32 mech, const u8 *iv,
793                           u32 keybitsize, u32 keygenflags,
794                           u8 *keybuf, size_t *keybufsize)
795 {
796         struct uw_req_pl {
797                 struct pl_head head;
798                 u8  attr_tag;
799                 u8  attr_len;
800                 u32 attr_header;
801                 u32 attr_bool_mask;
802                 u32 attr_bool_bits;
803                 u32 attr_key_type;
804                 u32 attr_key_type_value;
805                 u32 attr_val_len;
806                 u32 attr_val_len_value;
807                 u8  mech_tag;
808                 u8  mech_len;
809                 u32 mech;
810                 /*
811                  * maybe followed by iv data
812                  * followed by kek tag + kek blob
813                  * followed by empty mac tag
814                  * followed by empty pin tag
815                  * followed by encryted key tag + bytes
816                  */
817         } __packed * req_pl;
818         struct uw_rep_pl {
819                 struct pl_head head;
820                 u8  rc_tag;
821                 u8  rc_len;
822                 u32 rc;
823                 u8  data_tag;
824                 u8  data_lenfmt;
825                 u16 data_len;
826                 u8  data[512];
827         } __packed * rep_pl;
828         struct ep11_cprb *req = NULL, *rep = NULL;
829         struct ep11_target_dev target;
830         struct ep11_urb *urb = NULL;
831         struct ep11keyblob *kb;
832         size_t req_pl_size;
833         int api, rc = -ENOMEM;
834         u8 *p;
835
836         /* request cprb and payload */
837         req_pl_size = sizeof(struct uw_req_pl) + (iv ? 16 : 0)
838                 + ASN1TAGLEN(keksize) + 4 + ASN1TAGLEN(enckeysize);
839         req = alloc_cprb(req_pl_size);
840         if (!req)
841                 goto out;
842         req_pl = (struct uw_req_pl *) (((u8 *) req) + sizeof(*req));
843         api = (!keygenflags || keygenflags & 0x00200000) ? 4 : 1;
844         prep_head(&req_pl->head, req_pl_size, api, 34); /* UnwrapKey */
845         req_pl->attr_tag = 0x04;
846         req_pl->attr_len = 7 * sizeof(u32);
847         req_pl->attr_header = 0x10020000;
848         req_pl->attr_bool_mask = keygenflags ? keygenflags : KEY_ATTR_DEFAULTS;
849         req_pl->attr_bool_bits = keygenflags ? keygenflags : KEY_ATTR_DEFAULTS;
850         req_pl->attr_key_type = 0x00000100; /* CKA_KEY_TYPE */
851         req_pl->attr_key_type_value = 0x0000001f; /* CKK_AES */
852         req_pl->attr_val_len = 0x00000161; /* CKA_VALUE_LEN */
853         req_pl->attr_val_len_value = keybitsize / 8;
854         /* mech is mech + mech params (iv here) */
855         req_pl->mech_tag = 0x04;
856         req_pl->mech_len = sizeof(u32) + (iv ? 16 : 0);
857         req_pl->mech = (mech ? mech : 0x00001085); /* CKM_AES_CBC_PAD */
858         p = ((u8 *) req_pl) + sizeof(*req_pl);
859         if (iv) {
860                 memcpy(p, iv, 16);
861                 p += 16;
862         }
863         /* kek */
864         p += asn1tag_write(p, 0x04, kek, keksize);
865         /* empty mac key tag */
866         *p++ = 0x04;
867         *p++ = 0;
868         /* empty pin tag */
869         *p++ = 0x04;
870         *p++ = 0;
871         /* encrypted key value tag and bytes */
872         p += asn1tag_write(p, 0x04, enckey, enckeysize);
873
874         /* reply cprb and payload */
875         rep = alloc_cprb(sizeof(struct uw_rep_pl));
876         if (!rep)
877                 goto out;
878         rep_pl = (struct uw_rep_pl *) (((u8 *) rep) + sizeof(*rep));
879
880         /* urb and target */
881         urb = kmalloc(sizeof(struct ep11_urb), GFP_KERNEL);
882         if (!urb)
883                 goto out;
884         target.ap_id = card;
885         target.dom_id = domain;
886         prep_urb(urb, &target, 1,
887                  req, sizeof(*req) + req_pl_size,
888                  rep, sizeof(*rep) + sizeof(*rep_pl));
889
890         rc = zcrypt_send_ep11_cprb(urb);
891         if (rc) {
892                 DEBUG_ERR(
893                         "%s zcrypt_send_ep11_cprb(card=%d dom=%d) failed, rc=%d\n",
894                         __func__, (int) card, (int) domain, rc);
895                 goto out;
896         }
897
898         rc = check_reply_pl((u8 *)rep_pl, __func__);
899         if (rc)
900                 goto out;
901         if (rep_pl->data_tag != 0x04 || rep_pl->data_lenfmt != 0x82) {
902                 DEBUG_ERR("%s unknown reply data format\n", __func__);
903                 rc = -EIO;
904                 goto out;
905         }
906         if (rep_pl->data_len > *keybufsize) {
907                 DEBUG_ERR("%s mismatch reply data len / key buffer len\n",
908                           __func__);
909                 rc = -ENOSPC;
910                 goto out;
911         }
912
913         /* copy key blob and set header values */
914         memcpy(keybuf, rep_pl->data, rep_pl->data_len);
915         *keybufsize = rep_pl->data_len;
916         kb = (struct ep11keyblob *) keybuf;
917         kb->head.type = TOKTYPE_NON_CCA;
918         kb->head.len = rep_pl->data_len;
919         kb->head.version = TOKVER_EP11_AES;
920         kb->head.keybitlen = keybitsize;
921
922 out:
923         kfree(req);
924         kfree(rep);
925         kfree(urb);
926         return rc;
927 }
928
929 static int ep11_wrapkey(u16 card, u16 domain,
930                         const u8 *key, size_t keysize,
931                         u32 mech, const u8 *iv,
932                         u8 *databuf, size_t *datasize)
933 {
934         struct wk_req_pl {
935                 struct pl_head head;
936                 u8  var_tag;
937                 u8  var_len;
938                 u32 var;
939                 u8  mech_tag;
940                 u8  mech_len;
941                 u32 mech;
942                 /*
943                  * followed by iv data
944                  * followed by key tag + key blob
945                  * followed by dummy kek param
946                  * followed by dummy mac param
947                  */
948         } __packed * req_pl;
949         struct wk_rep_pl {
950                 struct pl_head head;
951                 u8  rc_tag;
952                 u8  rc_len;
953                 u32 rc;
954                 u8  data_tag;
955                 u8  data_lenfmt;
956                 u16 data_len;
957                 u8  data[512];
958         } __packed * rep_pl;
959         struct ep11_cprb *req = NULL, *rep = NULL;
960         struct ep11_target_dev target;
961         struct ep11_urb *urb = NULL;
962         struct ep11keyblob *kb;
963         size_t req_pl_size;
964         int api, rc = -ENOMEM;
965         u8 *p;
966
967         /* request cprb and payload */
968         req_pl_size = sizeof(struct wk_req_pl) + (iv ? 16 : 0)
969                 + ASN1TAGLEN(keysize) + 4;
970         req = alloc_cprb(req_pl_size);
971         if (!req)
972                 goto out;
973         if (!mech || mech == 0x80060001)
974                 req->flags |= 0x20; /* CPACF_WRAP needs special bit */
975         req_pl = (struct wk_req_pl *) (((u8 *) req) + sizeof(*req));
976         api = (!mech || mech == 0x80060001) ? 4 : 1; /* CKM_IBM_CPACF_WRAP */
977         prep_head(&req_pl->head, req_pl_size, api, 33); /* WrapKey */
978         req_pl->var_tag = 0x04;
979         req_pl->var_len = sizeof(u32);
980         /* mech is mech + mech params (iv here) */
981         req_pl->mech_tag = 0x04;
982         req_pl->mech_len = sizeof(u32) + (iv ? 16 : 0);
983         req_pl->mech = (mech ? mech : 0x80060001); /* CKM_IBM_CPACF_WRAP */
984         p = ((u8 *) req_pl) + sizeof(*req_pl);
985         if (iv) {
986                 memcpy(p, iv, 16);
987                 p += 16;
988         }
989         /* key blob */
990         p += asn1tag_write(p, 0x04, key, keysize);
991         /* maybe the key argument needs the head data cleaned out */
992         kb = (struct ep11keyblob *)(p - keysize);
993         if (kb->head.version == TOKVER_EP11_AES)
994                 memset(&kb->head, 0, sizeof(kb->head));
995         /* empty kek tag */
996         *p++ = 0x04;
997         *p++ = 0;
998         /* empty mac tag */
999         *p++ = 0x04;
1000         *p++ = 0;
1001
1002         /* reply cprb and payload */
1003         rep = alloc_cprb(sizeof(struct wk_rep_pl));
1004         if (!rep)
1005                 goto out;
1006         rep_pl = (struct wk_rep_pl *) (((u8 *) rep) + sizeof(*rep));
1007
1008         /* urb and target */
1009         urb = kmalloc(sizeof(struct ep11_urb), GFP_KERNEL);
1010         if (!urb)
1011                 goto out;
1012         target.ap_id = card;
1013         target.dom_id = domain;
1014         prep_urb(urb, &target, 1,
1015                  req, sizeof(*req) + req_pl_size,
1016                  rep, sizeof(*rep) + sizeof(*rep_pl));
1017
1018         rc = zcrypt_send_ep11_cprb(urb);
1019         if (rc) {
1020                 DEBUG_ERR(
1021                         "%s zcrypt_send_ep11_cprb(card=%d dom=%d) failed, rc=%d\n",
1022                         __func__, (int) card, (int) domain, rc);
1023                 goto out;
1024         }
1025
1026         rc = check_reply_pl((u8 *)rep_pl, __func__);
1027         if (rc)
1028                 goto out;
1029         if (rep_pl->data_tag != 0x04 || rep_pl->data_lenfmt != 0x82) {
1030                 DEBUG_ERR("%s unknown reply data format\n", __func__);
1031                 rc = -EIO;
1032                 goto out;
1033         }
1034         if (rep_pl->data_len > *datasize) {
1035                 DEBUG_ERR("%s mismatch reply data len / data buffer len\n",
1036                           __func__);
1037                 rc = -ENOSPC;
1038                 goto out;
1039         }
1040
1041         /* copy the data from the cprb to the data buffer */
1042         memcpy(databuf, rep_pl->data, rep_pl->data_len);
1043         *datasize = rep_pl->data_len;
1044
1045 out:
1046         kfree(req);
1047         kfree(rep);
1048         kfree(urb);
1049         return rc;
1050 }
1051
1052 int ep11_clr2keyblob(u16 card, u16 domain, u32 keybitsize, u32 keygenflags,
1053                      const u8 *clrkey, u8 *keybuf, size_t *keybufsize)
1054 {
1055         int rc;
1056         struct ep11keyblob *kb;
1057         u8 encbuf[64], *kek = NULL;
1058         size_t clrkeylen, keklen, encbuflen = sizeof(encbuf);
1059
1060         if (keybitsize == 128 || keybitsize == 192 || keybitsize == 256)
1061                 clrkeylen = keybitsize / 8;
1062         else {
1063                 DEBUG_ERR(
1064                         "%s unknown/unsupported keybitsize %d\n",
1065                         __func__, keybitsize);
1066                 return -EINVAL;
1067         }
1068
1069         /* allocate memory for the temp kek */
1070         keklen = MAXEP11AESKEYBLOBSIZE;
1071         kek = kmalloc(keklen, GFP_ATOMIC);
1072         if (!kek) {
1073                 rc = -ENOMEM;
1074                 goto out;
1075         }
1076
1077         /* Step 1: generate AES 256 bit random kek key */
1078         rc = ep11_genaeskey(card, domain, 256,
1079                             0x00006c00, /* EN/DECRYPT, WRAP/UNWRAP */
1080                             kek, &keklen);
1081         if (rc) {
1082                 DEBUG_ERR(
1083                         "%s generate kek key failed, rc=%d\n",
1084                         __func__, rc);
1085                 goto out;
1086         }
1087         kb = (struct ep11keyblob *) kek;
1088         memset(&kb->head, 0, sizeof(kb->head));
1089
1090         /* Step 2: encrypt clear key value with the kek key */
1091         rc = ep11_cryptsingle(card, domain, 0, 0, def_iv, kek, keklen,
1092                               clrkey, clrkeylen, encbuf, &encbuflen);
1093         if (rc) {
1094                 DEBUG_ERR(
1095                         "%s encrypting key value with kek key failed, rc=%d\n",
1096                         __func__, rc);
1097                 goto out;
1098         }
1099
1100         /* Step 3: import the encrypted key value as a new key */
1101         rc = ep11_unwrapkey(card, domain, kek, keklen,
1102                             encbuf, encbuflen, 0, def_iv,
1103                             keybitsize, 0, keybuf, keybufsize);
1104         if (rc) {
1105                 DEBUG_ERR(
1106                         "%s importing key value as new key failed,, rc=%d\n",
1107                         __func__, rc);
1108                 goto out;
1109         }
1110
1111 out:
1112         kfree(kek);
1113         return rc;
1114 }
1115 EXPORT_SYMBOL(ep11_clr2keyblob);
1116
1117 int ep11_key2protkey(u16 card, u16 dom, const u8 *key, size_t keylen,
1118                      u8 *protkey, u32 *protkeylen, u32 *protkeytype)
1119 {
1120         int rc = -EIO;
1121         u8 *wkbuf = NULL;
1122         size_t wkbuflen = 256;
1123         struct wk_info {
1124                 u16 version;
1125                 u8  res1[16];
1126                 u32 pkeytype;
1127                 u32 pkeybitsize;
1128                 u64 pkeysize;
1129                 u8  res2[8];
1130                 u8  pkey[0];
1131         } __packed * wki;
1132
1133         /* alloc temp working buffer */
1134         wkbuf = kmalloc(wkbuflen, GFP_ATOMIC);
1135         if (!wkbuf)
1136                 return -ENOMEM;
1137
1138         /* ep11 secure key -> protected key + info */
1139         rc = ep11_wrapkey(card, dom, key, keylen,
1140                           0, def_iv, wkbuf, &wkbuflen);
1141         if (rc) {
1142                 DEBUG_ERR(
1143                         "%s rewrapping ep11 key to pkey failed, rc=%d\n",
1144                         __func__, rc);
1145                 goto out;
1146         }
1147         wki = (struct wk_info *) wkbuf;
1148
1149         /* check struct version and pkey type */
1150         if (wki->version != 1 || wki->pkeytype != 1) {
1151                 DEBUG_ERR("%s wk info version %d or pkeytype %d mismatch.\n",
1152                           __func__, (int) wki->version, (int) wki->pkeytype);
1153                 rc = -EIO;
1154                 goto out;
1155         }
1156
1157         /* copy the tanslated protected key */
1158         switch (wki->pkeysize) {
1159         case 16+32:
1160                 /* AES 128 protected key */
1161                 if (protkeytype)
1162                         *protkeytype = PKEY_KEYTYPE_AES_128;
1163                 break;
1164         case 24+32:
1165                 /* AES 192 protected key */
1166                 if (protkeytype)
1167                         *protkeytype = PKEY_KEYTYPE_AES_192;
1168                 break;
1169         case 32+32:
1170                 /* AES 256 protected key */
1171                 if (protkeytype)
1172                         *protkeytype = PKEY_KEYTYPE_AES_256;
1173                 break;
1174         default:
1175                 DEBUG_ERR("%s unknown/unsupported pkeysize %d\n",
1176                           __func__, (int) wki->pkeysize);
1177                 rc = -EIO;
1178                 goto out;
1179         }
1180         memcpy(protkey, wki->pkey, wki->pkeysize);
1181         if (protkeylen)
1182                 *protkeylen = (u32) wki->pkeysize;
1183         rc = 0;
1184
1185 out:
1186         kfree(wkbuf);
1187         return rc;
1188 }
1189 EXPORT_SYMBOL(ep11_key2protkey);
1190
1191 int ep11_findcard2(u32 **apqns, u32 *nr_apqns, u16 cardnr, u16 domain,
1192                    int minhwtype, int minapi, const u8 *wkvp)
1193 {
1194         struct zcrypt_device_status_ext *device_status;
1195         u32 *_apqns = NULL, _nr_apqns = 0;
1196         int i, card, dom, rc = -ENOMEM;
1197         struct ep11_domain_info edi;
1198         struct ep11_card_info eci;
1199
1200         /* fetch status of all crypto cards */
1201         device_status = kvmalloc_array(MAX_ZDEV_ENTRIES_EXT,
1202                                        sizeof(struct zcrypt_device_status_ext),
1203                                        GFP_KERNEL);
1204         if (!device_status)
1205                 return -ENOMEM;
1206         zcrypt_device_status_mask_ext(device_status);
1207
1208         /* allocate 1k space for up to 256 apqns */
1209         _apqns = kmalloc_array(256, sizeof(u32), GFP_KERNEL);
1210         if (!_apqns) {
1211                 kvfree(device_status);
1212                 return -ENOMEM;
1213         }
1214
1215         /* walk through all the crypto apqnss */
1216         for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
1217                 card = AP_QID_CARD(device_status[i].qid);
1218                 dom = AP_QID_QUEUE(device_status[i].qid);
1219                 /* check online state */
1220                 if (!device_status[i].online)
1221                         continue;
1222                 /* check for ep11 functions */
1223                 if (!(device_status[i].functions & 0x01))
1224                         continue;
1225                 /* check cardnr */
1226                 if (cardnr != 0xFFFF && card != cardnr)
1227                         continue;
1228                 /* check domain */
1229                 if (domain != 0xFFFF && dom != domain)
1230                         continue;
1231                 /* check min hardware type */
1232                 if (minhwtype && device_status[i].hwtype < minhwtype)
1233                         continue;
1234                 /* check min api version if given */
1235                 if (minapi > 0) {
1236                         if (ep11_get_card_info(card, &eci, 0))
1237                                 continue;
1238                         if (minapi > eci.API_ord_nr)
1239                                 continue;
1240                 }
1241                 /* check wkvp if given */
1242                 if (wkvp) {
1243                         if (ep11_get_domain_info(card, dom, &edi))
1244                                 continue;
1245                         if (edi.cur_wk_state != '1')
1246                                 continue;
1247                         if (memcmp(wkvp, edi.cur_wkvp, 16))
1248                                 continue;
1249                 }
1250                 /* apqn passed all filtering criterons, add to the array */
1251                 if (_nr_apqns < 256)
1252                         _apqns[_nr_apqns++] = (((u16)card) << 16) | ((u16) dom);
1253         }
1254
1255         /* nothing found ? */
1256         if (!_nr_apqns) {
1257                 kfree(_apqns);
1258                 rc = -ENODEV;
1259         } else {
1260                 /* no re-allocation, simple return the _apqns array */
1261                 *apqns = _apqns;
1262                 *nr_apqns = _nr_apqns;
1263                 rc = 0;
1264         }
1265
1266         kvfree(device_status);
1267         return rc;
1268 }
1269 EXPORT_SYMBOL(ep11_findcard2);
1270
1271 void __exit zcrypt_ep11misc_exit(void)
1272 {
1273         card_cache_free();
1274 }