xref: /titanic_50/usr/src/uts/common/crypto/api/kcf_miscapi.c (revision c5c4113dfcabb1eed3d4bdf7609de5170027a794)
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 2007 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 	/* Check the input */
322 	if (nf == NULL || !(event_mask & (CRYPTO_EVENT_MECHS_CHANGED |
323 	    CRYPTO_EVENT_PROVIDER_REGISTERED |
324 	    CRYPTO_EVENT_PROVIDER_UNREGISTERED))) {
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 		 * events do not happen frequently. We have to revisit this
414 		 * code if we add a new event that happens often.
415 		 */
416 		goto retry;
417 	}
418 
419 	mutex_exit(&nep->kn_lock);
420 
421 	/* Free the element */
422 	mutex_destroy(&nep->kn_lock);
423 	cv_destroy(&nep->kn_cv);
424 	kmem_free(nep, sizeof (kcf_ntfy_elem_t));
425 
426 	mutex_exit(&ntfy_list_lock);
427 }
428 
429 /*
430  * We walk the notification list and do the callbacks.
431  */
432 void
433 kcf_walk_ntfylist(uint32_t event, void *event_arg)
434 {
435 	kcf_ntfy_elem_t *nep;
436 	int nelem = 0;
437 
438 	mutex_enter(&ntfy_list_lock);
439 
440 	/*
441 	 * Count how many clients are on the notification list. We need
442 	 * this count to ensure that clients which joined the list after we
443 	 * have started this walk, are not wrongly notified.
444 	 */
445 	for (nep = ntfy_list_head; nep != NULL; nep = nep->kn_next)
446 		nelem++;
447 
448 	for (nep = ntfy_list_head; (nep != NULL && nelem); nep = nep->kn_next) {
449 		nelem--;
450 
451 		/*
452 		 * Check if this client is interested in the
453 		 * event.
454 		 */
455 		if (!(nep->kn_event_mask & event))
456 			continue;
457 
458 		mutex_enter(&nep->kn_lock);
459 		nep->kn_state = NTFY_RUNNING;
460 		mutex_exit(&nep->kn_lock);
461 		mutex_exit(&ntfy_list_lock);
462 
463 		/*
464 		 * We invoke the callback routine with no locks held. Another
465 		 * client could have joined the list meanwhile. This is fine
466 		 * as we maintain nelem as stated above. The NULL check in the
467 		 * for loop guards against shrinkage. Also, any callers of
468 		 * crypto_unnotify_events() at this point cv_wait till kn_state
469 		 * changes to NTFY_WAITING. Hence, nep is assured to be valid.
470 		 */
471 		(*nep->kn_func)(event, event_arg);
472 
473 		mutex_enter(&nep->kn_lock);
474 		nep->kn_state = NTFY_WAITING;
475 		cv_broadcast(&nep->kn_cv);
476 		mutex_exit(&nep->kn_lock);
477 
478 		mutex_enter(&ntfy_list_lock);
479 	}
480 
481 	mutex_exit(&ntfy_list_lock);
482 }
483 
484 /*
485  * crypto_key_check()
486  *
487  * Arguments:
488  *	. mech: the mechanism to check the key with.
489  *	. key: the key to check for validity and weakness.
490  *
491  * Description:
492  *	Checks the validity and strength of the key for the mechanism.
493  *	CRYPTO_KEY_REFERENCE is not supported for this routine.
494  *	If more than one provider is capable of key checking for the mechanism,
495  *	then run the key through them all.
496  *	A conservative approach is adopted here: New weak keys may be
497  *	discovered with more recent providers. If at least one provider is
498  *	not happy with a key, then it is no good.
499  *
500  * Context:
501  *	Process and interruption.
502  */
503 int
504 crypto_key_check(crypto_mechanism_t *mech, crypto_key_t *key)
505 {
506 	int error;
507 	kcf_mech_entry_t *me;
508 	kcf_provider_desc_t *pd;
509 	kcf_prov_mech_desc_t *prov_chain;
510 
511 	/* when mech is a valid mechanism, me will be its mech_entry */
512 	if ((mech == NULL) || (key == NULL) ||
513 	    (key->ck_format == CRYPTO_KEY_REFERENCE))
514 		return (CRYPTO_ARGUMENTS_BAD);
515 
516 	if ((error = kcf_get_mech_entry(mech->cm_type, &me)) != KCF_SUCCESS) {
517 		/* error is one of the KCF_INVALID_MECH_XXX's */
518 		return (CRYPTO_MECHANISM_INVALID);
519 	}
520 
521 	mutex_enter(&me->me_mutex);
522 
523 	/* First let the software provider check this key */
524 	if (me->me_sw_prov != NULL) {
525 		pd = me->me_sw_prov->pm_prov_desc;
526 		KCF_PROV_REFHOLD(pd);
527 
528 		if ((KCF_PROV_KEY_OPS(pd) != NULL) &&
529 		    (KCF_PROV_KEY_OPS(pd)->key_check != NULL)) {
530 			crypto_mechanism_t lmech;
531 
532 			mutex_exit(&me->me_mutex);
533 			lmech = *mech;
534 			KCF_SET_PROVIDER_MECHNUM(mech->cm_type, pd, &lmech);
535 			error = KCF_PROV_KEY_CHECK(pd, &lmech, key);
536 
537 			if (error != CRYPTO_SUCCESS) {
538 				KCF_PROV_REFRELE(pd);
539 				return (error);
540 			}
541 
542 			mutex_enter(&me->me_mutex);
543 		}
544 		KCF_PROV_REFRELE(pd);
545 	}
546 
547 	prov_chain = me->me_hw_prov_chain;
548 	while (prov_chain != NULL) {
549 		pd = prov_chain->pm_prov_desc;
550 		KCF_PROV_REFHOLD(pd);
551 
552 		if ((KCF_PROV_KEY_OPS(pd) != NULL) &&
553 		    (KCF_PROV_KEY_OPS(pd)->key_check != NULL)) {
554 			crypto_mechanism_t lmech;
555 
556 			mutex_exit(&me->me_mutex);
557 			lmech = *mech;
558 			KCF_SET_PROVIDER_MECHNUM(mech->cm_type, pd,
559 			    &lmech);
560 			error = KCF_PROV_KEY_CHECK(pd, &lmech, key);
561 
562 			if (error != CRYPTO_SUCCESS) {
563 				KCF_PROV_REFRELE(pd);
564 				return (error);
565 			}
566 			mutex_enter(&me->me_mutex);
567 		}
568 		KCF_PROV_REFRELE(pd);
569 		prov_chain = prov_chain->pm_next;
570 	}
571 
572 	mutex_exit(&me->me_mutex);
573 
574 	/* All are happy with this key */
575 	return (CRYPTO_SUCCESS);
576 }
577 
578 int
579 crypto_key_check_prov(crypto_provider_t provider, crypto_mechanism_t *mech,
580     crypto_key_t *key)
581 {
582 	kcf_provider_desc_t *pd = provider;
583 	kcf_provider_desc_t *real_provider = pd;
584 	crypto_mechanism_t lmech;
585 	int rv;
586 
587 	ASSERT(KCF_PROV_REFHELD(pd));
588 
589 	if ((mech == NULL) || (key == NULL) ||
590 	    (key->ck_format == CRYPTO_KEY_REFERENCE))
591 		return (CRYPTO_ARGUMENTS_BAD);
592 
593 	/* no logical providers currently support the key check */
594 	if (pd->pd_prov_type == CRYPTO_LOGICAL_PROVIDER) {
595 		return (CRYPTO_NOT_SUPPORTED);
596 	}
597 
598 	lmech = *mech;
599 	KCF_SET_PROVIDER_MECHNUM(mech->cm_type, real_provider, &lmech);
600 	rv = KCF_PROV_KEY_CHECK(real_provider, &lmech, key);
601 	if (pd->pd_prov_type == CRYPTO_LOGICAL_PROVIDER)
602 		KCF_PROV_REFRELE(real_provider);
603 
604 	return (rv);
605 }
606 
607 /*
608  * Initialize the specified crypto_mechanism_info_t structure for
609  * the specified mechanism provider descriptor. Used by
610  * crypto_get_all_mech_info().
611  */
612 static void
613 init_mechanism_info(crypto_mechanism_info_t *mech_info,
614     kcf_prov_mech_desc_t *pmd)
615 {
616 	crypto_func_group_t fg = pmd->pm_mech_info.cm_func_group_mask;
617 
618 	/* min/max key sizes */
619 	mech_info->mi_keysize_unit = pmd->pm_mech_info.cm_mech_flags &
620 	    (CRYPTO_KEYSIZE_UNIT_IN_BITS | CRYPTO_KEYSIZE_UNIT_IN_BYTES);
621 	mech_info->mi_min_key_size =
622 	    (size_t)pmd->pm_mech_info.cm_min_key_length;
623 	mech_info->mi_max_key_size =
624 	    (size_t)pmd->pm_mech_info.cm_max_key_length;
625 
626 	/* usage flag */
627 	mech_info->mi_usage = 0;
628 	if (fg & (CRYPTO_FG_ENCRYPT | CRYPTO_FG_ENCRYPT_ATOMIC))
629 		mech_info->mi_usage |= CRYPTO_MECH_USAGE_ENCRYPT;
630 	if (fg & (CRYPTO_FG_DECRYPT | CRYPTO_FG_DECRYPT_ATOMIC))
631 		mech_info->mi_usage |= CRYPTO_MECH_USAGE_DECRYPT;
632 	if (fg & (CRYPTO_FG_MAC | CRYPTO_FG_MAC_ATOMIC))
633 		mech_info->mi_usage |= CRYPTO_MECH_USAGE_MAC;
634 }
635 
636 /*
637  * Return the mechanism info for the specified mechanism.
638  */
639 int
640 crypto_get_all_mech_info(crypto_mech_type_t mech_type,
641     crypto_mechanism_info_t **mech_infos, uint_t *num_mech_infos,
642     int km_flag)
643 {
644 	uint_t ninfos, cur_info;
645 	kcf_mech_entry_t *me;
646 	int rv;
647 	kcf_prov_mech_desc_t *hwp;
648 	crypto_mechanism_info_t *infos;
649 	size_t infos_size;
650 
651 	/* get to the mech entry corresponding to the specified mech type */
652 	if ((rv = kcf_get_mech_entry(mech_type, &me)) != CRYPTO_SUCCESS) {
653 		return (rv);
654 	}
655 
656 	/* compute the number of key size ranges to return */
657 	mutex_enter(&me->me_mutex);
658 again:
659 	ninfos = PROV_COUNT(me);
660 	mutex_exit(&me->me_mutex);
661 
662 	if (ninfos == 0) {
663 		infos = NULL;
664 		rv = CRYPTO_SUCCESS;
665 		goto bail;
666 	}
667 	infos_size = ninfos * sizeof (crypto_mechanism_info_t);
668 	infos = kmem_alloc(infos_size, km_flag);
669 	if (infos == NULL) {
670 		rv = CRYPTO_HOST_MEMORY;
671 		goto bail;
672 	}
673 
674 	mutex_enter(&me->me_mutex);
675 	if (ninfos != PROV_COUNT(me)) {
676 		kmem_free(infos, infos_size);
677 		goto again;
678 	}
679 
680 	/* populate array of crypto mechanism infos */
681 	cur_info = 0;
682 
683 	/* software provider, if present */
684 	if (me->me_sw_prov != NULL)
685 		init_mechanism_info(&infos[cur_info++], me->me_sw_prov);
686 
687 	/* hardware providers */
688 	for (hwp = me->me_hw_prov_chain; hwp != NULL; hwp = hwp->pm_next)
689 		init_mechanism_info(&infos[cur_info++], hwp);
690 
691 	mutex_exit(&me->me_mutex);
692 	ASSERT(cur_info == ninfos);
693 bail:
694 	*mech_infos = infos;
695 	*num_mech_infos = ninfos;
696 	return (rv);
697 }
698 
699 /*
700  * memcmp_pad_max() is a specialized version of memcmp() which
701  * compares two pieces of data up to a maximum length.  If the
702  * the two data match up the maximum length, they are considered
703  * matching.  Trailing blanks do not cause the match to fail if
704  * one of the data is shorter.
705  *
706  * Examples of matches:
707  *	"one"           |
708  *	"one      "     |
709  *	                ^maximum length
710  *
711  *	"Number One     |  X"	(X is beyond maximum length)
712  *	"Number One   " |
713  *	                ^maximum length
714  *
715  * Examples of mismatches:
716  *	" one"
717  *	"one"
718  *
719  *	"Number One    X|"
720  *	"Number One     |"
721  *	                ^maximum length
722  */
723 static int
724 memcmp_pad_max(void *d1, uint_t d1_len, void *d2, uint_t d2_len, uint_t max_sz)
725 {
726 	uint_t		len, extra_len;
727 	char		*marker;
728 
729 	/* No point in comparing anything beyond max_sz */
730 	if (d1_len > max_sz)
731 		d1_len = max_sz;
732 	if (d2_len > max_sz)
733 		d2_len = max_sz;
734 
735 	/* Find shorter of the two data. */
736 	if (d1_len <= d2_len) {
737 		len = d1_len;
738 		extra_len = d2_len;
739 		marker = d2;
740 	} else {	/* d1_len > d2_len */
741 		len = d2_len;
742 		extra_len = d1_len;
743 		marker = d1;
744 	}
745 
746 	/* Have a match in the shortest length of data? */
747 	if (memcmp(d1, d2, len) != 0)
748 		/* CONSTCOND */
749 		return (!0);
750 
751 	/* If the rest of longer data is nulls or blanks, call it a match. */
752 	while (len < extra_len)
753 		if (!isspace(marker[len++]))
754 			/* CONSTCOND */
755 			return (!0);
756 	return (0);
757 }
758 
759 /*
760  * Obtain ext info for specified provider and see if it matches.
761  */
762 static boolean_t
763 match_ext_info(kcf_provider_desc_t *pd, char *label, char *manuf, char *serial,
764     crypto_provider_ext_info_t *ext_info)
765 {
766 	int rv;
767 
768 	rv = crypto_get_provinfo(pd, ext_info);
769 	ASSERT(rv != CRYPTO_NOT_SUPPORTED);
770 	if (rv != CRYPTO_SUCCESS)
771 		return (B_FALSE);
772 
773 	if (memcmp_pad_max(ext_info->ei_label, CRYPTO_EXT_SIZE_LABEL,
774 	    label, strlen(label), CRYPTO_EXT_SIZE_LABEL))
775 		return (B_FALSE);
776 
777 	if (manuf != NULL) {
778 		if (memcmp_pad_max(ext_info->ei_manufacturerID,
779 		    CRYPTO_EXT_SIZE_MANUF, manuf, strlen(manuf),
780 		    CRYPTO_EXT_SIZE_MANUF))
781 			return (B_FALSE);
782 	}
783 
784 	if (serial != NULL) {
785 		if (memcmp_pad_max(ext_info->ei_serial_number,
786 		    CRYPTO_EXT_SIZE_SERIAL, serial, strlen(serial),
787 		    CRYPTO_EXT_SIZE_SERIAL))
788 			return (B_FALSE);
789 	}
790 	return (B_TRUE);
791 }
792 
793 /*
794  * Find a provider based on its label, manufacturer ID, and serial number.
795  */
796 crypto_provider_t
797 crypto_get_provider(char *label, char *manuf, char *serial)
798 {
799 	kcf_provider_desc_t **provider_array, *pd;
800 	crypto_provider_ext_info_t *ext_info;
801 	uint_t count;
802 	int i;
803 
804 	/* manuf and serial are optional */
805 	if (label == NULL)
806 		return (NULL);
807 
808 	if (kcf_get_slot_list(&count, &provider_array, B_FALSE)
809 	    != CRYPTO_SUCCESS)
810 		return (NULL);
811 
812 	if (count == 0)
813 		return (NULL);
814 
815 	ext_info = kmem_zalloc(sizeof (crypto_provider_ext_info_t), KM_SLEEP);
816 
817 	for (i = 0; i < count; i++) {
818 		pd = provider_array[i];
819 		if (match_ext_info(pd, label, manuf, serial, ext_info)) {
820 			KCF_PROV_REFHOLD(pd);
821 			break;
822 		}
823 	}
824 	if (i == count)
825 		pd = NULL;
826 
827 	kcf_free_provider_tab(count, provider_array);
828 	kmem_free(ext_info, sizeof (crypto_provider_ext_info_t));
829 	return (pd);
830 }
831 
832 /*
833  * Get the provider information given a provider handle. The caller
834  * needs to allocate the space for the argument, info.
835  */
836 int
837 crypto_get_provinfo(crypto_provider_t hndl, crypto_provider_ext_info_t *info)
838 {
839 	int rv;
840 	kcf_req_params_t params;
841 	kcf_provider_desc_t *pd;
842 	kcf_provider_desc_t *real_provider;
843 
844 	pd = (kcf_provider_desc_t *)hndl;
845 	rv = kcf_get_hardware_provider_nomech(
846 	    CRYPTO_OPS_OFFSET(provider_ops), CRYPTO_PROVIDER_OFFSET(ext_info),
847 	    CHECK_RESTRICT_FALSE, pd, &real_provider);
848 
849 	if (rv == CRYPTO_SUCCESS && real_provider != NULL) {
850 		ASSERT(real_provider == pd ||
851 		    pd->pd_prov_type == CRYPTO_LOGICAL_PROVIDER);
852 		KCF_WRAP_PROVMGMT_OPS_PARAMS(&params, KCF_OP_MGMT_EXTINFO,
853 		    0, NULL, 0, NULL, 0, NULL, info, pd);
854 		rv = kcf_submit_request(real_provider, NULL, NULL, &params,
855 		    B_FALSE);
856 		KCF_PROV_REFRELE(real_provider);
857 	}
858 
859 	return (rv);
860 }
861 
862 void
863 crypto_release_provider(crypto_provider_t provider)
864 {
865 	KCF_PROV_REFRELE((kcf_provider_desc_t *)provider);
866 }
867