xref: /titanic_44/usr/src/uts/common/crypto/api/kcf_miscapi.c (revision e824d57f8160a27ac5e650005c7a4f037109c2be)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/types.h>
29 #include <sys/sunddi.h>
30 #include <sys/disp.h>
31 #include <sys/modctl.h>
32 #include <sys/sysmacros.h>
33 #include <sys/crypto/common.h>
34 #include <sys/crypto/api.h>
35 #include <sys/crypto/impl.h>
36 #include <sys/crypto/sched_impl.h>
37 
38 #define	isspace(ch)	(((ch) == ' ') || ((ch) == '\r') || ((ch) == '\n') || \
39 			((ch) == '\t') || ((ch) == '\f'))
40 
41 #define	CRYPTO_OPS_OFFSET(f)		offsetof(crypto_ops_t, co_##f)
42 #define	CRYPTO_KEY_OFFSET(f)		offsetof(crypto_key_ops_t, f)
43 #define	CRYPTO_PROVIDER_OFFSET(f)	\
44 	offsetof(crypto_provider_management_ops_t, f)
45 
46 /* Miscellaneous exported entry points */
47 
48 /*
49  * All event subscribers are put on a list. kcf_notify_list_lock
50  * protects changes to this list.
51  *
52  * The following locking order is maintained in the code - The
53  * global kcf_notify_list_lock followed by the individual lock
54  * in a kcf_ntfy_elem structure (kn_lock).
55  */
56 kmutex_t		ntfy_list_lock;
57 kcondvar_t		ntfy_list_cv;   /* cv the service thread waits on */
58 static kcf_ntfy_elem_t *ntfy_list_head;
59 static kcf_ntfy_elem_t *ntfy_list_tail;
60 
61 /* count all the hardware and software providers */
62 #define	PROV_COUNT(me) \
63 	(((me)->me_sw_prov != NULL ? 1 : 0) + (me)->me_num_hwprov)
64 
65 /*
66  * crypto_mech2id()
67  *
68  * Arguments:
69  *	. mechname: A null-terminated string identifying the mechanism name.
70  *
71  * Description:
72  *	Walks the mechanisms tables, looking for an entry that matches the
73  *	mechname. Once it find it, it builds the 64-bit mech_type and returns
74  *	it.  If there are no hardware or software providers for the mechanism,
75  *	but there is an unloaded software provider, this routine will attempt
76  *	to load it.
77  *
78  * Context:
79  *	Process and interruption.
80  *
81  * Returns:
82  *	The unique mechanism identified by 'mechname', if found.
83  *	CRYPTO_MECH_INVALID otherwise.
84  */
85 crypto_mech_type_t
86 crypto_mech2id(char *mechname)
87 {
88 	return (crypto_mech2id_common(mechname, B_TRUE));
89 }
90 
91 /*
92  * crypto_get_mech_list()
93  *
94  * Arguments:
95  *	. countp: pointer to contain the number of mech names returned
96  *	. kmflag: memory allocation flag.
97  *
98  * Description:
99  *	Allocates an array of crypto_mech_name_t containing all the mechanisms
100  *	currently available on the system. Sets *countp with the number of
101  *	mechanism names returned.
102  *
103  *	We get a list of mech names which have a hardware provider by walking
104  *	all the mechanism tables. We merge them with mech names obtained from
105  *	the hint list. A mech name in the hint list is considered only if it
106  *	is not disabled for the provider. Note that the hint list contains only
107  *	software providers and the mech names supported by them.
108  *
109  * Context:
110  *	Process and interruption. kmflag should be KM_NOSLEEP when called
111  *	from an interruption context.
112  *
113  * Returns:
114  *	The array of the crypto_mech_t allocated.
115  *	NULL otherwise.
116  */
117 crypto_mech_name_t *
118 crypto_get_mech_list(uint_t *countp, int kmflag)
119 {
120 	uint_t count = 0, me_tab_size, i, j;
121 	kcf_ops_class_t cl;
122 	kcf_mech_entry_t *me, *me_tab;
123 	crypto_mech_name_t *mech_name_tab, *tmp_mech_name_tab;
124 	char *mech_name, *hint_mech, *end;
125 	kcf_soft_conf_entry_t *p;
126 	size_t n;
127 
128 	/*
129 	 * Count the maximum possible mechanisms that can come from the
130 	 * hint list.
131 	 */
132 	mutex_enter(&soft_config_mutex);
133 	p = soft_config_list;
134 	while (p != NULL) {
135 		count += p->ce_count;
136 		p = p->ce_next;
137 	}
138 	mutex_exit(&soft_config_mutex);
139 
140 	/* First let's count'em, for mem allocation */
141 	for (cl = KCF_FIRST_OPSCLASS; cl <= KCF_LAST_OPSCLASS; cl++) {
142 		me_tab_size = kcf_mech_tabs_tab[cl].met_size;
143 		me_tab = kcf_mech_tabs_tab[cl].met_tab;
144 		for (i = 0; i < me_tab_size; i++) {
145 			me = &me_tab[i];
146 			mutex_enter(&(me->me_mutex));
147 			if ((me->me_name[0] != 0) && (me->me_num_hwprov >= 1)) {
148 				ASSERT(me->me_hw_prov_chain != NULL);
149 				count++;
150 			}
151 			mutex_exit(&(me->me_mutex));
152 		}
153 	}
154 
155 	/*
156 	 * Allocate a buffer to hold the mechanisms from
157 	 * mech tabs and mechanisms from the hint list.
158 	 */
159 	n = count * CRYPTO_MAX_MECH_NAME;
160 
161 again:
162 	count = 0;
163 	tmp_mech_name_tab = kmem_zalloc(n, kmflag);
164 	if (tmp_mech_name_tab == NULL) {
165 		*countp = 0;
166 		return (NULL);
167 	}
168 
169 	/*
170 	 * Second round, fill in the table
171 	 */
172 
173 	mech_name = (char *)tmp_mech_name_tab;
174 	end = mech_name + n;
175 
176 	for (cl = KCF_FIRST_OPSCLASS; cl <= KCF_LAST_OPSCLASS; cl++) {
177 		me_tab_size = kcf_mech_tabs_tab[cl].met_size;
178 		me_tab = kcf_mech_tabs_tab[cl].met_tab;
179 		for (i = 0; i < me_tab_size; i++) {
180 			me = &me_tab[i];
181 			mutex_enter(&(me->me_mutex));
182 			if ((me->me_name[0] != 0) && (me->me_num_hwprov >= 1)) {
183 				ASSERT(me->me_hw_prov_chain != NULL);
184 				if ((mech_name + CRYPTO_MAX_MECH_NAME) > end) {
185 					mutex_exit(&(me->me_mutex));
186 					kmem_free(tmp_mech_name_tab, n);
187 					n = n << 1;
188 					goto again;
189 				}
190 				(void) strncpy(mech_name, me->me_name,
191 				    CRYPTO_MAX_MECH_NAME);
192 
193 				mech_name += CRYPTO_MAX_MECH_NAME;
194 				count++;
195 			}
196 			mutex_exit(&(me->me_mutex));
197 		}
198 	}
199 
200 	/*
201 	 * Search tmp_mech_name_tab for each mechanism in the hint list. We
202 	 * have to add any new mechanisms found in the hint list. Note that we
203 	 * should not modload the providers here as it will be too early. It
204 	 * may be the case that the caller never uses a provider.
205 	 */
206 	mutex_enter(&soft_config_mutex);
207 	p = soft_config_list;
208 	while (p != NULL) {
209 		for (i = 0; i < p->ce_count; i++) {
210 			hint_mech = p->ce_mechs[i];
211 
212 			/* Do not consider the mechanism if it is disabled. */
213 			if (is_mech_disabled_byname(CRYPTO_SW_PROVIDER,
214 			    p->ce_name, 0, hint_mech))
215 				continue;
216 
217 			/*
218 			 * There may be duplicate mechanisms in the hint list.
219 			 * So, we need to search all the entries that have been
220 			 * added so far. That number would be count.
221 			 */
222 			for (j = 0; j < count; j++) {
223 				if (strcmp(hint_mech,
224 				    tmp_mech_name_tab[j]) == 0)
225 					break;
226 			}
227 
228 			if (j == count) {	/* This is a new one. Add it. */
229 				ASSERT((char *)&tmp_mech_name_tab[count] ==
230 				    mech_name);
231 				if ((mech_name + CRYPTO_MAX_MECH_NAME) > end) {
232 					mutex_exit(&soft_config_mutex);
233 					kmem_free(tmp_mech_name_tab, n);
234 					n = n << 1;
235 					goto again;
236 				}
237 				(void) strncpy(tmp_mech_name_tab[count],
238 				    hint_mech, CRYPTO_MAX_MECH_NAME);
239 				mech_name += CRYPTO_MAX_MECH_NAME;
240 				count++;
241 			}
242 		}
243 		p = p->ce_next;
244 	}
245 	mutex_exit(&soft_config_mutex);
246 
247 	/*
248 	 * Check if we have consumed all of the space. We are done if
249 	 * this is the case.
250 	 */
251 	ASSERT(mech_name <= end);
252 	if (mech_name == end) {
253 		mech_name_tab = tmp_mech_name_tab;
254 		goto done;
255 	}
256 
257 	/*
258 	 * Allocate a buffer of the right size now that we have the
259 	 * correct count.
260 	 */
261 	mech_name_tab = kmem_zalloc(count * CRYPTO_MAX_MECH_NAME, kmflag);
262 	if (mech_name_tab == NULL) {
263 		kmem_free(tmp_mech_name_tab, n);
264 		*countp = 0;
265 		return (NULL);
266 	}
267 
268 	bcopy(tmp_mech_name_tab, mech_name_tab, count * CRYPTO_MAX_MECH_NAME);
269 	kmem_free(tmp_mech_name_tab, n);
270 
271 done:
272 	*countp = count;
273 	return (mech_name_tab);
274 }
275 
276 /*
277  * crypto_free_mech_list()
278  *
279  * Arguments:
280  *	. mech_names: An array of crypto_mech_name_t previously allocated by
281  *	  crypto_get_mech_list.
282  *	. count: the number of mech names in mech_names
283  *
284  * Description:
285  *	Frees the the mech_names array.
286  *
287  * Context:
288  *	Process and interruption.
289  */
290 void
291 crypto_free_mech_list(crypto_mech_name_t *mech_names, uint_t count)
292 {
293 	if ((mech_names != NULL) && (count > 0))
294 		kmem_free(mech_names, count * CRYPTO_MAX_MECH_NAME);
295 }
296 
297 /*
298  * crypto_notify_events()
299  *
300  * Arguments:
301  *	. nf: Callback function to invoke when event occurs.
302  *	. event_mask: Mask of events.
303  *
304  * Description:
305  *	Allocates a new element and inserts it in to the notification
306  *	list.
307  *
308  * Context:
309  *	Process context.
310  *
311  * Returns:
312  *	A handle is returned if the client is put on the notification list.
313  *	NULL is returned otherwise.
314  */
315 crypto_notify_handle_t
316 crypto_notify_events(crypto_notify_callback_t nf, uint32_t event_mask)
317 {
318 	kcf_ntfy_elem_t *nep;
319 	crypto_notify_handle_t hndl;
320 
321 	/*
322 	 * The only valid value for event_mask is CRYPTO_EVENT_PROVIDERS_CHANGE.
323 	 */
324 	if (nf == NULL || !(event_mask & CRYPTO_EVENT_PROVIDERS_CHANGE)) {
325 		return (NULL);
326 	}
327 
328 	nep = kmem_zalloc(sizeof (kcf_ntfy_elem_t), KM_SLEEP);
329 	mutex_init(&nep->kn_lock, NULL, MUTEX_DEFAULT, NULL);
330 	cv_init(&nep->kn_cv, NULL, CV_DEFAULT, NULL);
331 	nep->kn_state = NTFY_WAITING;
332 	nep->kn_func = nf;
333 	nep->kn_event_mask = event_mask;
334 
335 	mutex_enter(&ntfy_list_lock);
336 	if (ntfy_list_head == NULL) {
337 		ntfy_list_head = ntfy_list_tail = nep;
338 	} else {
339 		ntfy_list_tail->kn_next = nep;
340 		nep->kn_prev = ntfy_list_tail;
341 		ntfy_list_tail = nep;
342 	}
343 
344 	hndl = (crypto_notify_handle_t)nep;
345 	mutex_exit(&ntfy_list_lock);
346 
347 	return (hndl);
348 }
349 
350 /*
351  * crypto_unnotify_events()
352  *
353  * Arguments:
354  *	. hndl - Handle returned from an earlier crypto_notify_events().
355  *
356  * Description:
357  *	Removes the element specified by hndl from the notification list.
358  *	We wait for the notification routine to complete, if the routine
359  *	is currently being called. We also free the element.
360  *
361  * Context:
362  *	Process context.
363  */
364 void
365 crypto_unnotify_events(crypto_notify_handle_t hndl)
366 {
367 	kcf_ntfy_elem_t *nep = (kcf_ntfy_elem_t *)hndl;
368 
369 	if (hndl == NULL)
370 		return;
371 
372 retry:
373 	mutex_enter(&ntfy_list_lock);
374 	mutex_enter(&nep->kn_lock);
375 
376 	if (nep->kn_state == NTFY_WAITING) {
377 		kcf_ntfy_elem_t *nextp = nep->kn_next;
378 		kcf_ntfy_elem_t *prevp = nep->kn_prev;
379 
380 		if (nextp != NULL)
381 			nextp->kn_prev = prevp;
382 		else
383 			ntfy_list_tail = prevp;
384 
385 		if (prevp != NULL)
386 			prevp->kn_next = nextp;
387 		else
388 			ntfy_list_head = nextp;
389 	} else {
390 		ASSERT(nep->kn_state == NTFY_RUNNING);
391 
392 		/*
393 		 * We have to drop this lock as the client might call
394 		 * crypto_notify_events() in the callback routine resulting
395 		 * in a deadlock.
396 		 */
397 		mutex_exit(&ntfy_list_lock);
398 
399 		/*
400 		 * Another thread is working on this element. We will wait
401 		 * for that thread to signal us when done. No other thread
402 		 * will free this element. So, we can be sure it stays valid
403 		 * after the wait.
404 		 */
405 		while (nep->kn_state == NTFY_RUNNING)
406 			cv_wait(&nep->kn_cv, &nep->kn_lock);
407 		mutex_exit(&nep->kn_lock);
408 
409 		/*
410 		 * We have to remove the element from the notification list.
411 		 * So, start over and do the work (acquire locks etc.). This is
412 		 * safe (i.e. We won't be in this routine forever) as the
413 		 * CRYPTO_EVENT_PROVIDERS_CHANGE event does not happen
414 		 * frequently. We have to revisit this code if we
415 		 * add a new event that happens often.
416 		 */
417 		goto retry;
418 	}
419 
420 	mutex_exit(&nep->kn_lock);
421 
422 	/* Free the element */
423 	mutex_destroy(&nep->kn_lock);
424 	cv_destroy(&nep->kn_cv);
425 	kmem_free(nep, sizeof (kcf_ntfy_elem_t));
426 
427 	mutex_exit(&ntfy_list_lock);
428 }
429 
430 /*
431  * This routine is called from crypto_register_provider() and
432  * crypto_unregister_provider() with the CRYPTO_EVENT_PROVIDERS_CHANGE event.
433  *
434  * We walk the notification list and do the callbacks.
435  */
436 void
437 kcf_walk_ntfylist(uint32_t event, void *event_arg)
438 {
439 	kcf_ntfy_elem_t *nep;
440 	int nelem = 0;
441 
442 	mutex_enter(&ntfy_list_lock);
443 
444 	/*
445 	 * Count how many clients are on the notification list. We need
446 	 * this count to ensure that clients which joined the list after we
447 	 * have started this walk, are not wrongly notified.
448 	 */
449 	for (nep = ntfy_list_head; nep != NULL; nep = nep->kn_next)
450 		nelem++;
451 
452 	for (nep = ntfy_list_head; (nep != NULL && nelem); nep = nep->kn_next) {
453 		nelem--;
454 
455 		/*
456 		 * Check if this client is interested in the
457 		 * event.
458 		 */
459 		if (!(nep->kn_event_mask & event))
460 			continue;
461 
462 		mutex_enter(&nep->kn_lock);
463 		nep->kn_state = NTFY_RUNNING;
464 		mutex_exit(&nep->kn_lock);
465 		mutex_exit(&ntfy_list_lock);
466 
467 		/*
468 		 * We invoke the callback routine with no locks held. Another
469 		 * client could have joined the list meanwhile. This is fine
470 		 * as we maintain nelem as stated above. The NULL check in the
471 		 * for loop guards against shrinkage. Also, any callers of
472 		 * crypto_unnotify_events() at this point cv_wait till kn_state
473 		 * changes to NTFY_WAITING. Hence, nep is assured to be valid.
474 		 */
475 		(*nep->kn_func)(event, event_arg);
476 
477 		mutex_enter(&nep->kn_lock);
478 		nep->kn_state = NTFY_WAITING;
479 		cv_broadcast(&nep->kn_cv);
480 		mutex_exit(&nep->kn_lock);
481 
482 		mutex_enter(&ntfy_list_lock);
483 	}
484 
485 	mutex_exit(&ntfy_list_lock);
486 }
487 
488 /*
489  * crypto_key_check()
490  *
491  * Arguments:
492  *	. mech: the mechanism to check the key with.
493  *	. key: the key to check for validity and weakness.
494  *
495  * Description:
496  *	Checks the validity and strength of the key for the mechanism.
497  *	CRYPTO_KEY_REFERENCE is not supported for this routine.
498  *	If more than one provider is capable of key checking for the mechanism,
499  *	then run the key through them all.
500  *	A conservative approach is adopted here: New weak keys may be
501  *	discovered with more recent providers. If at least one provider is
502  *	not happy with a key, then it is no good.
503  *
504  * Context:
505  *	Process and interruption.
506  */
507 int
508 crypto_key_check(crypto_mechanism_t *mech, crypto_key_t *key)
509 {
510 	int error;
511 	kcf_mech_entry_t *me;
512 	kcf_provider_desc_t *pd;
513 	kcf_prov_mech_desc_t *prov_chain;
514 
515 	/* when mech is a valid mechanism, me will be its mech_entry */
516 	if ((mech == NULL) || (key == NULL) ||
517 	    (key->ck_format == CRYPTO_KEY_REFERENCE))
518 		return (CRYPTO_ARGUMENTS_BAD);
519 
520 	if ((error = kcf_get_mech_entry(mech->cm_type, &me)) != KCF_SUCCESS) {
521 		/* error is one of the KCF_INVALID_MECH_XXX's */
522 		return (CRYPTO_MECHANISM_INVALID);
523 	}
524 
525 	mutex_enter(&me->me_mutex);
526 
527 	/* First let the software provider check this key */
528 	if (me->me_sw_prov != NULL) {
529 		pd = me->me_sw_prov->pm_prov_desc;
530 		KCF_PROV_REFHOLD(pd);
531 
532 		if ((KCF_PROV_KEY_OPS(pd) != NULL) &&
533 		    (KCF_PROV_KEY_OPS(pd)->key_check != NULL)) {
534 			crypto_mechanism_t lmech;
535 
536 			mutex_exit(&me->me_mutex);
537 			lmech = *mech;
538 			KCF_SET_PROVIDER_MECHNUM(mech->cm_type, pd, &lmech);
539 			error = KCF_PROV_KEY_CHECK(pd, &lmech, key);
540 
541 			if (error != CRYPTO_SUCCESS) {
542 				KCF_PROV_REFRELE(pd);
543 				return (error);
544 			}
545 
546 			mutex_enter(&me->me_mutex);
547 		}
548 		KCF_PROV_REFRELE(pd);
549 	}
550 
551 	prov_chain = me->me_hw_prov_chain;
552 	while (prov_chain != NULL) {
553 		pd = prov_chain->pm_prov_desc;
554 		KCF_PROV_REFHOLD(pd);
555 
556 		if ((KCF_PROV_KEY_OPS(pd) != NULL) &&
557 		    (KCF_PROV_KEY_OPS(pd)->key_check != NULL)) {
558 			crypto_mechanism_t lmech;
559 
560 			mutex_exit(&me->me_mutex);
561 			lmech = *mech;
562 			KCF_SET_PROVIDER_MECHNUM(mech->cm_type, pd,
563 			    &lmech);
564 			error = KCF_PROV_KEY_CHECK(pd, &lmech, key);
565 
566 			if (error != CRYPTO_SUCCESS) {
567 				KCF_PROV_REFRELE(pd);
568 				return (error);
569 			}
570 			mutex_enter(&me->me_mutex);
571 		}
572 		KCF_PROV_REFRELE(pd);
573 		prov_chain = prov_chain->pm_next;
574 	}
575 
576 	mutex_exit(&me->me_mutex);
577 
578 	/* All are happy with this key */
579 	return (CRYPTO_SUCCESS);
580 }
581 
582 int
583 crypto_key_check_prov(crypto_provider_t provider, crypto_mechanism_t *mech,
584     crypto_key_t *key)
585 {
586 	kcf_provider_desc_t *pd = provider;
587 	kcf_provider_desc_t *real_provider = pd;
588 	crypto_mechanism_t lmech;
589 	int rv;
590 
591 	ASSERT(KCF_PROV_REFHELD(pd));
592 
593 	if ((mech == NULL) || (key == NULL) ||
594 	    (key->ck_format == CRYPTO_KEY_REFERENCE))
595 		return (CRYPTO_ARGUMENTS_BAD);
596 
597 	/* no logical providers currently support the key check */
598 	if (pd->pd_prov_type == CRYPTO_LOGICAL_PROVIDER) {
599 		return (CRYPTO_NOT_SUPPORTED);
600 	}
601 
602 	lmech = *mech;
603 	KCF_SET_PROVIDER_MECHNUM(mech->cm_type, real_provider, &lmech);
604 	rv = KCF_PROV_KEY_CHECK(real_provider, &lmech, key);
605 	if (pd->pd_prov_type == CRYPTO_LOGICAL_PROVIDER)
606 		KCF_PROV_REFRELE(real_provider);
607 
608 	return (rv);
609 }
610 
611 /*
612  * Initialize the specified crypto_mechanism_info_t structure for
613  * the specified mechanism provider descriptor. Used by
614  * crypto_get_all_mech_info().
615  */
616 static void
617 init_mechanism_info(crypto_mechanism_info_t *mech_info,
618     kcf_prov_mech_desc_t *pmd)
619 {
620 	crypto_func_group_t fg = pmd->pm_mech_info.cm_func_group_mask;
621 
622 	/* min/max key sizes */
623 	mech_info->mi_keysize_unit =
624 	    pmd->pm_mech_info.cm_keysize_unit;
625 	mech_info->mi_min_key_size =
626 	    (size_t)pmd->pm_mech_info.cm_min_key_length;
627 	mech_info->mi_max_key_size =
628 	    (size_t)pmd->pm_mech_info.cm_max_key_length;
629 
630 	/* usage flag */
631 	mech_info->mi_usage = 0;
632 	if (fg & (CRYPTO_FG_ENCRYPT | CRYPTO_FG_ENCRYPT_ATOMIC))
633 		mech_info->mi_usage |= CRYPTO_MECH_USAGE_ENCRYPT;
634 	if (fg & (CRYPTO_FG_DECRYPT | CRYPTO_FG_DECRYPT_ATOMIC))
635 		mech_info->mi_usage |= CRYPTO_MECH_USAGE_DECRYPT;
636 	if (fg & (CRYPTO_FG_MAC | CRYPTO_FG_MAC_ATOMIC))
637 		mech_info->mi_usage |= CRYPTO_MECH_USAGE_MAC;
638 }
639 
640 /*
641  * Return the mechanism info for the specified mechanism.
642  */
643 int
644 crypto_get_all_mech_info(crypto_mech_type_t mech_type,
645     crypto_mechanism_info_t **mech_infos, uint_t *num_mech_infos,
646     int km_flag)
647 {
648 	uint_t ninfos, cur_info;
649 	kcf_mech_entry_t *me;
650 	int rv;
651 	kcf_prov_mech_desc_t *hwp;
652 	crypto_mechanism_info_t *infos;
653 	size_t infos_size;
654 
655 	/* get to the mech entry corresponding to the specified mech type */
656 	if ((rv = kcf_get_mech_entry(mech_type, &me)) != CRYPTO_SUCCESS) {
657 		return (rv);
658 	}
659 
660 	/* compute the number of key size ranges to return */
661 	mutex_enter(&me->me_mutex);
662 again:
663 	ninfos = PROV_COUNT(me);
664 	mutex_exit(&me->me_mutex);
665 
666 	if (ninfos == 0) {
667 		infos = NULL;
668 		rv = CRYPTO_SUCCESS;
669 		goto bail;
670 	}
671 	infos_size = ninfos * sizeof (crypto_mechanism_info_t);
672 	infos = kmem_alloc(infos_size, km_flag);
673 	if (infos == NULL) {
674 		rv = CRYPTO_HOST_MEMORY;
675 		goto bail;
676 	}
677 
678 	mutex_enter(&me->me_mutex);
679 	if (ninfos != PROV_COUNT(me)) {
680 		kmem_free(infos, infos_size);
681 		goto again;
682 	}
683 
684 	/* populate array of crypto mechanism infos */
685 	cur_info = 0;
686 
687 	/* software provider, if present */
688 	if (me->me_sw_prov != NULL)
689 		init_mechanism_info(&infos[cur_info++], me->me_sw_prov);
690 
691 	/* hardware providers */
692 	for (hwp = me->me_hw_prov_chain; hwp != NULL; hwp = hwp->pm_next)
693 		init_mechanism_info(&infos[cur_info++], hwp);
694 
695 	mutex_exit(&me->me_mutex);
696 	ASSERT(cur_info == ninfos);
697 bail:
698 	*mech_infos = infos;
699 	*num_mech_infos = ninfos;
700 	return (rv);
701 }
702 
703 /*
704  * memcmp_pad_max() is a specialized version of memcmp() which
705  * compares two pieces of data up to a maximum length.  If the
706  * the two data match up the maximum length, they are considered
707  * matching.  Trailing blanks do not cause the match to fail if
708  * one of the data is shorter.
709  *
710  * Examples of matches:
711  *	"one"           |
712  *	"one      "     |
713  *	                ^maximum length
714  *
715  *	"Number One     |  X"	(X is beyond maximum length)
716  *	"Number One   " |
717  *	                ^maximum length
718  *
719  * Examples of mismatches:
720  *	" one"
721  *	"one"
722  *
723  *	"Number One    X|"
724  *	"Number One     |"
725  *	                ^maximum length
726  */
727 static int
728 memcmp_pad_max(void *d1, uint_t d1_len, void *d2, uint_t d2_len, uint_t max_sz)
729 {
730 	uint_t		len, extra_len;
731 	char		*marker;
732 
733 	/* No point in comparing anything beyond max_sz */
734 	if (d1_len > max_sz)
735 		d1_len = max_sz;
736 	if (d2_len > max_sz)
737 		d2_len = max_sz;
738 
739 	/* Find shorter of the two data. */
740 	if (d1_len <= d2_len) {
741 		len = d1_len;
742 		extra_len = d2_len;
743 		marker = d2;
744 	} else {	/* d1_len > d2_len */
745 		len = d2_len;
746 		extra_len = d1_len;
747 		marker = d1;
748 	}
749 
750 	/* Have a match in the shortest length of data? */
751 	if (memcmp(d1, d2, len) != 0)
752 		/* CONSTCOND */
753 		return (!0);
754 
755 	/* If the rest of longer data is nulls or blanks, call it a match. */
756 	while (len < extra_len)
757 		if (!isspace(marker[len++]))
758 			/* CONSTCOND */
759 			return (!0);
760 	return (0);
761 }
762 
763 /*
764  * Obtain ext info for specified provider and see if it matches.
765  */
766 static boolean_t
767 match_ext_info(kcf_provider_desc_t *pd, char *label, char *manuf, char *serial,
768     crypto_provider_ext_info_t *ext_info)
769 {
770 	kcf_provider_desc_t *real_provider;
771 	int rv;
772 	kcf_req_params_t params;
773 
774 	(void) kcf_get_hardware_provider_nomech(
775 	    CRYPTO_OPS_OFFSET(provider_ops), CRYPTO_PROVIDER_OFFSET(ext_info),
776 	    CHECK_RESTRICT_FALSE, pd, &real_provider);
777 
778 	if (real_provider != NULL) {
779 		ASSERT(real_provider == pd ||
780 		    pd->pd_prov_type == CRYPTO_LOGICAL_PROVIDER);
781 		KCF_WRAP_PROVMGMT_OPS_PARAMS(&params, KCF_OP_MGMT_EXTINFO,
782 		    0, NULL, 0, NULL, 0, NULL, ext_info, pd);
783 		rv = kcf_submit_request(real_provider, NULL, NULL, &params,
784 		    B_FALSE);
785 		ASSERT(rv != CRYPTO_NOT_SUPPORTED);
786 		KCF_PROV_REFRELE(real_provider);
787 	}
788 
789 	if (rv != CRYPTO_SUCCESS)
790 		return (B_FALSE);
791 
792 	if (memcmp_pad_max(ext_info->ei_label, CRYPTO_EXT_SIZE_LABEL,
793 	    label, strlen(label), CRYPTO_EXT_SIZE_LABEL))
794 		return (B_FALSE);
795 
796 	if (manuf != NULL) {
797 		if (memcmp_pad_max(ext_info->ei_manufacturerID,
798 		    CRYPTO_EXT_SIZE_MANUF, manuf, strlen(manuf),
799 		    CRYPTO_EXT_SIZE_MANUF))
800 			return (B_FALSE);
801 	}
802 
803 	if (serial != NULL) {
804 		if (memcmp_pad_max(ext_info->ei_serial_number,
805 		    CRYPTO_EXT_SIZE_SERIAL, label, strlen(label),
806 		    CRYPTO_EXT_SIZE_SERIAL))
807 			return (B_FALSE);
808 	}
809 	return (B_TRUE);
810 }
811 
812 /*
813  * Find a provider based on its label, manufacturer ID, and serial number.
814  */
815 crypto_provider_t
816 crypto_get_provider(char *label, char *manuf, char *serial)
817 {
818 	kcf_provider_desc_t **provider_array, *pd;
819 	crypto_provider_ext_info_t *ext_info;
820 	uint_t count;
821 	int i;
822 
823 	/* manuf and serial are optional */
824 	if (label == NULL)
825 		return (NULL);
826 
827 	if (kcf_get_slot_list(&count, &provider_array, B_FALSE)
828 	    != CRYPTO_SUCCESS)
829 		return (NULL);
830 
831 	if (count == 0)
832 		return (NULL);
833 
834 	ext_info = kmem_zalloc(sizeof (crypto_provider_ext_info_t), KM_SLEEP);
835 
836 	for (i = 0; i < count; i++) {
837 		pd = provider_array[i];
838 		if (match_ext_info(pd, label, manuf, serial, ext_info)) {
839 			KCF_PROV_REFHOLD(pd);
840 			break;
841 		}
842 	}
843 	if (i == count)
844 		pd = NULL;
845 
846 	kcf_free_provider_tab(count, provider_array);
847 	kmem_free(ext_info, sizeof (crypto_provider_ext_info_t));
848 	return (pd);
849 }
850 
851 void
852 crypto_release_provider(crypto_provider_t provider)
853 {
854 	KCF_PROV_REFRELE((kcf_provider_desc_t *)provider);
855 }
856