components/openssl/openssl-1.0.1/engines/pkcs11/hw_pk11_uri.c
changeset 1489 bad87e4131b9
parent 1488 04528ffd139d
child 1490 709dae0743cb
equal deleted inserted replaced
1488:04528ffd139d 1489:bad87e4131b9
     1 /*
       
     2  * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
       
     3  */
       
     4 
       
     5 /*
       
     6  * Redistribution and use in source and binary forms, with or without
       
     7  * modification, are permitted provided that the following conditions
       
     8  * are met:
       
     9  *
       
    10  * 1. Redistributions of source code must retain the above copyright
       
    11  *    notice, this list of conditions and the following disclaimer.
       
    12  *
       
    13  * 2. Redistributions in binary form must reproduce the above copyright
       
    14  *    notice, this list of conditions and the following disclaimer in
       
    15  *    the documentation and/or other materials provided with the
       
    16  *    distribution.
       
    17  *
       
    18  * 3. All advertising materials mentioning features or use of this
       
    19  *    software must display the following acknowledgment:
       
    20  *    "This product includes software developed by the OpenSSL Project
       
    21  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
       
    22  *
       
    23  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
       
    24  *    endorse or promote products derived from this software without
       
    25  *    prior written permission. For written permission, please contact
       
    26  *    [email protected].
       
    27  *
       
    28  * 5. Products derived from this software may not be called "OpenSSL"
       
    29  *    nor may "OpenSSL" appear in their names without prior written
       
    30  *    permission of the OpenSSL Project.
       
    31  *
       
    32  * 6. Redistributions of any form whatsoever must retain the following
       
    33  *    acknowledgment:
       
    34  *    "This product includes software developed by the OpenSSL Project
       
    35  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
       
    36  *
       
    37  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
       
    38  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
       
    39  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
       
    40  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
       
    41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
       
    42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
       
    43  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
       
    44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
       
    45  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
       
    46  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
       
    47  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
       
    48  * OF THE POSSIBILITY OF SUCH DAMAGE.
       
    49  */
       
    50 
       
    51 #include <stdio.h>
       
    52 #include <stdlib.h>
       
    53 #include <string.h>
       
    54 #include <sys/types.h>
       
    55 #include <sys/wait.h>
       
    56 #include <sys/mman.h>
       
    57 #include <unistd.h>
       
    58 #include <strings.h>
       
    59 #include <libgen.h>
       
    60 #include <pthread.h>
       
    61 #include <assert.h>
       
    62 #include <errno.h>
       
    63 
       
    64 #include <openssl/crypto.h>
       
    65 
       
    66 #ifndef OPENSSL_NO_HW
       
    67 #ifndef OPENSSL_NO_HW_PK11
       
    68 
       
    69 #include <security/cryptoki.h>
       
    70 #include <security/pkcs11.h>
       
    71 #include "hw_pk11.h"
       
    72 #include "hw_pk11_uri.h"
       
    73 
       
    74 /*
       
    75  * The keystore used is always from the pubkey slot so we need to know which one
       
    76  * was selected so that we can get the information needed for the URI
       
    77  * processing.
       
    78  */
       
    79 extern CK_SLOT_ID pubkey_SLOTID;
       
    80 extern CK_FUNCTION_LIST_PTR pFuncList;
       
    81 
       
    82 /*
       
    83  * Cached PIN so that child can use it during the re-login. Note that we do not
       
    84  * cache the PIN by default.
       
    85  */
       
    86 static char *token_pin;
       
    87 
       
    88 static int mlock_pin_in_memory(char *pin);
       
    89 static char *run_askpass(char *dialog);
       
    90 
       
    91 /*
       
    92  * Get the PIN. Either run the command and use its standard output as a PIN to
       
    93  * fill in the PKCS11 URI structure, or read the PIN from the terminal. Using
       
    94  * the external command is of higher precedence. The memory for PIN is allocated
       
    95  * in this function and the PIN is always NULL terminated. The caller must take
       
    96  * care of freeing the memory used for the PIN. The maximum PIN length accepted
       
    97  * is PK11_MAX_PIN_LEN.
       
    98  *
       
    99  * The function is used also during the re-initialization of the engine after
       
   100  * the fork.
       
   101  *
       
   102  * The function must not be called under the protection of the mutex "uri_lock"
       
   103  * because the lock is acquired in the prefork function.
       
   104  *
       
   105  * Returns:
       
   106  *	0 in case of troubles (and sets "*pin" to NULL)
       
   107  *	1 if we got the PIN
       
   108  */
       
   109 #define	EXEC_SPEC	"exec:"
       
   110 #define	BUILTIN_SPEC	"builtin"
       
   111 int
       
   112 pk11_get_pin(char *dialog, char **pin)
       
   113 	{
       
   114 	/* Initialize as an error. */
       
   115 	*pin = NULL;
       
   116 
       
   117 	if (strcmp(dialog, BUILTIN_SPEC) == 0)
       
   118 		{
       
   119 		/* The getpassphrase() function is not MT safe. */
       
   120 		(void) pthread_mutex_lock(uri_lock);
       
   121 		/* Note that OpenSSL is not localized at all. */
       
   122 		*pin = getpassphrase("Enter token PIN: ");
       
   123 		if (*pin == NULL)
       
   124 			{
       
   125 			PK11err(PK11_F_GET_PIN, PK11_R_COULD_NOT_READ_PIN);
       
   126 			(void) pthread_mutex_unlock(uri_lock);
       
   127 			goto err;
       
   128 			}
       
   129 		else
       
   130 			{
       
   131 			char *pw;
       
   132 
       
   133 			/*
       
   134 			 * getpassphrase() uses an internal  buffer to hold the
       
   135 			 * entered password. Note that it terminates the buffer
       
   136 			 * with '\0'.
       
   137 			 */
       
   138 			if ((pw = strdup(*pin)) == NULL)
       
   139 				{
       
   140 				PK11err(PK11_F_GET_PIN, PK11_R_MALLOC_FAILURE);
       
   141 				(void) pthread_mutex_unlock(uri_lock);
       
   142 				goto err;
       
   143 				}
       
   144 			/* Zero the internal buffer to get rid of the PIN. */
       
   145 			memset(*pin, 0, strlen(*pin));
       
   146 			*pin = pw;
       
   147 			(void) pthread_mutex_unlock(uri_lock);
       
   148 			}
       
   149 		}
       
   150 	else
       
   151 		{
       
   152 		/*
       
   153 		 * This is the "exec:" case. We will get the PIN from the output
       
   154 		 * of an external command.
       
   155 		 */
       
   156 		if (strncmp(dialog, EXEC_SPEC, strlen(EXEC_SPEC)) == 0)
       
   157 			{
       
   158 			dialog += strlen(EXEC_SPEC);
       
   159 			if ((*pin = run_askpass(dialog)) == NULL)
       
   160 				goto err;
       
   161 			}
       
   162 		else
       
   163 			{
       
   164 			/*
       
   165 			 * Invalid specification in the passphrasedialog
       
   166 			 * keyword.
       
   167 			 */
       
   168 			PK11err(PK11_F_GET_PIN, PK11_R_BAD_PASSPHRASE_SPEC);
       
   169 			goto err;
       
   170 			}
       
   171 		}
       
   172 
       
   173 	return (1);
       
   174 err:
       
   175 	return (0);
       
   176 	}
       
   177 
       
   178 /*
       
   179  * Process the PKCS#11 URI and get the PIN. It uses information from the
       
   180  * passphrasedialog keyword to get the PIN. If passphrasedialog is not present
       
   181  * it is not considered an error since it depends on the token attributes
       
   182  * whether C_Login() is required. The function expects an allocated 'uri_struct'
       
   183  * structure.
       
   184  *
       
   185  * Returns:
       
   186  *	0 if URI is not valid at all, or if we could not get the PIN
       
   187  * 	1 if all is OK
       
   188  *	2 if the URI is not the PKCS#11 URI. In that case, put the string
       
   189  *	pointer to the filename to "*file". Note that the pointer just points
       
   190  *	inside of the "uristr", possibly skipping the file:// prefix if present.
       
   191  */
       
   192 int
       
   193 pk11_process_pkcs11_uri(const char *uristr, pkcs11_uri *uri_struct,
       
   194 	const char **file)
       
   195 	{
       
   196 	char *uristr2, *l1, *l2, *tok, *name;
       
   197 
       
   198 	/* Check the "file://" case. */
       
   199 	if (strncmp(uristr, FILE_URI_PREFIX, strlen(FILE_URI_PREFIX)) == 0)
       
   200 		{
       
   201 		*file = uristr + strlen(FILE_URI_PREFIX);
       
   202 		return (2);
       
   203 		}
       
   204 
       
   205 	/*  This is the "pkcs11:" case. */
       
   206 	if (strncmp(uristr, PK11_URI_PREFIX, strlen(PK11_URI_PREFIX)) != 0)
       
   207 		{
       
   208 		/* Not PKCS#11 URI at all, could be a filename. */
       
   209 		*file = (const char *)uristr;
       
   210 		return (2);
       
   211 		}
       
   212 	else
       
   213 		{
       
   214 		/* Dup the string and skip over the pkcs11: prefix then. */
       
   215 		uristr2 = strdup(uristr + strlen(PK11_URI_PREFIX));
       
   216 		if (uristr2 == NULL)
       
   217 			{
       
   218 			PK11err(PK11_F_CHECK_TOKEN_ATTRS,
       
   219 			    PK11_R_MALLOC_FAILURE);
       
   220 			goto err;
       
   221 			}
       
   222 		}
       
   223 
       
   224 	/* Initialize the structure. */
       
   225 	memset(uri_struct, 0, sizeof (*uri_struct));
       
   226 
       
   227 	/*
       
   228 	 * Using strtok_r() would silently skip over multiple semicolons. We
       
   229 	 * must check that before moving on. We must also avoid ';' as the first
       
   230 	 * and the last character in the URI.
       
   231 	 */
       
   232 	if (strstr(uristr2, ";;") != NULL || uristr2[0] == ';' ||
       
   233 	    (strlen(uristr2) > 0 && uristr2[strlen(uristr2) - 1] == ';'))
       
   234 		goto bad_uri;
       
   235 
       
   236 	tok = strtok_r(uristr2, ";", &l1);
       
   237 	for (; tok != NULL; tok = strtok_r(NULL, ";", &l1))
       
   238 		{
       
   239 		/* "tok" is not empty so there will be something in "name". */
       
   240 		name = strtok_r(tok, "=", &l2);
       
   241 		/* Check whether there is '=' at all. */
       
   242 		if (l2 == NULL)
       
   243 			goto bad_uri;
       
   244 
       
   245 		/*
       
   246 		 * Fill out the URI structure. We do not accept duplicit
       
   247 		 * attributes.
       
   248 		 */
       
   249 		if (strcmp(name, PK11_TOKEN) == 0)
       
   250 			if (uri_struct->token == NULL)
       
   251 				{
       
   252 				if ((uri_struct->token = strdup(l2)) == NULL)
       
   253 					goto no_mem;
       
   254 				}
       
   255 			else
       
   256 				goto bad_uri;
       
   257 		else if (strcmp(name, PK11_MANUF) == 0)
       
   258 			if (uri_struct->manuf == NULL)
       
   259 				{
       
   260 				if ((uri_struct->manuf = strdup(l2)) == NULL)
       
   261 					goto no_mem;
       
   262 				}
       
   263 			else
       
   264 				goto bad_uri;
       
   265 		else if (strcmp(name, PK11_SERIAL) == 0)
       
   266 			if (uri_struct->serial == NULL)
       
   267 				{
       
   268 				if ((uri_struct->serial = strdup(l2)) == NULL)
       
   269 					goto no_mem;
       
   270 				}
       
   271 			else
       
   272 				goto bad_uri;
       
   273 		else if (strcmp(name, PK11_MODEL) == 0)
       
   274 			if (uri_struct->model == NULL)
       
   275 				{
       
   276 				if ((uri_struct->model = strdup(l2)) == NULL)
       
   277 					goto no_mem;
       
   278 				}
       
   279 			else
       
   280 				goto bad_uri;
       
   281 		else if (strcmp(name, PK11_OBJECT) == 0)
       
   282 			if (uri_struct->object == NULL)
       
   283 				{
       
   284 				if ((uri_struct->object = strdup(l2)) == NULL)
       
   285 					goto no_mem;
       
   286 				}
       
   287 			else
       
   288 				goto bad_uri;
       
   289 		else if (strcmp(name, PK11_OBJECTTYPE) == 0)
       
   290 			if (uri_struct->objecttype == NULL)
       
   291 				{
       
   292 				uri_struct->objecttype = strdup(l2);
       
   293 				if (uri_struct->objecttype == NULL)
       
   294 					goto no_mem;
       
   295 				}
       
   296 			else
       
   297 				goto bad_uri;
       
   298 		else if (strcmp(name, PK11_ASKPASS) == 0)
       
   299 			if (uri_struct->askpass == NULL)
       
   300 				{
       
   301 				if ((uri_struct->askpass = strdup(l2)) == NULL)
       
   302 					goto no_mem;
       
   303 				}
       
   304 			else
       
   305 				goto bad_uri;
       
   306 		else
       
   307 			goto bad_uri;
       
   308 		}
       
   309 
       
   310 	/* The "object" token is mandatory in the PKCS#11 URI. */
       
   311 	if (uri_struct->object == NULL)
       
   312 		{
       
   313 		PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_MISSING_OBJECT_LABEL);
       
   314 		goto err;
       
   315 		}
       
   316 
       
   317 	free(uristr2);
       
   318 	return (1);
       
   319 bad_uri:
       
   320 	PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_INVALID_PKCS11_URI);
       
   321 	if (uristr2 != NULL)
       
   322 		free(uristr2);
       
   323 	return (0);
       
   324 no_mem:
       
   325 	PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_MALLOC_FAILURE);
       
   326 err:
       
   327 	pk11_free_pkcs11_uri(uri_struct, CK_FALSE);
       
   328 	if (uristr2 != NULL)
       
   329 		free(uristr2);
       
   330 	return (0);
       
   331 	}
       
   332 
       
   333 /*
       
   334  * Free the PKCS11 URI structure and anything that might be inside.
       
   335  */
       
   336 void
       
   337 pk11_free_pkcs11_uri(pkcs11_uri *uri_struct, CK_BBOOL free_uri_itself)
       
   338 	{
       
   339 	if (uri_struct->token != NULL)
       
   340 		free(uri_struct->token);
       
   341 	if (uri_struct->manuf != NULL)
       
   342 		free(uri_struct->manuf);
       
   343 	if (uri_struct->serial != NULL)
       
   344 		free(uri_struct->serial);
       
   345 	if (uri_struct->model != NULL)
       
   346 		free(uri_struct->model);
       
   347 	if (uri_struct->object != NULL)
       
   348 		free(uri_struct->object);
       
   349 	if (uri_struct->objecttype != NULL)
       
   350 		free(uri_struct->objecttype);
       
   351 	if (uri_struct->askpass != NULL)
       
   352 		free(uri_struct->askpass);
       
   353 
       
   354 	if (free_uri_itself == CK_TRUE)
       
   355 		OPENSSL_free(uri_struct);
       
   356 	}
       
   357 
       
   358 /*
       
   359  * While our keystore is always the one used by the pubkey slot (which is
       
   360  * usually the Metaslot) we must make sure that those URI attributes that
       
   361  * specify the keystore match the real attributes of our slot keystore. Note
       
   362  * that one can use the METASLOT_OBJECTSTORE_TOKEN environment variable to
       
   363  * change the Metaslot's keystore from the softtoken to something else (see
       
   364  * libpkcs11(3LIB)). The user might want to use such attributes in the PKCS#11
       
   365  * URI to make sure that the intended keystore is used.
       
   366  *
       
   367  * Returns:
       
   368  *	1 on success
       
   369  *	0 on failure
       
   370  */
       
   371 int
       
   372 pk11_check_token_attrs(pkcs11_uri *uri_struct)
       
   373 	{
       
   374 	CK_RV rv;
       
   375 	static CK_TOKEN_INFO_PTR token_info = NULL;
       
   376 
       
   377 	(void) pthread_mutex_lock(uri_lock);
       
   378 	if (token_info == NULL)
       
   379 		{
       
   380 		token_info = OPENSSL_malloc(sizeof (CK_TOKEN_INFO));
       
   381 		if (token_info == NULL)
       
   382 			{
       
   383 			PK11err(PK11_F_CHECK_TOKEN_ATTRS,
       
   384 			    PK11_R_MALLOC_FAILURE);
       
   385 			goto err;
       
   386 			}
       
   387 
       
   388 		rv = pFuncList->C_GetTokenInfo(pubkey_SLOTID, token_info);
       
   389 		if (rv != CKR_OK)
       
   390 			{
       
   391 			PK11err_add_data(PK11_F_CHECK_TOKEN_ATTRS,
       
   392 			    PK11_R_GETTOKENINFO, rv);
       
   393 			goto err;
       
   394 			}
       
   395 		}
       
   396 
       
   397 	if (uri_struct->token != NULL)
       
   398 		if (strncmp(uri_struct->token, (char *)token_info->label,
       
   399 		    strlen(uri_struct->token) > 32 ? 32 :
       
   400 		    strlen(uri_struct->token)) != 0)
       
   401 			{
       
   402 			goto urierr;
       
   403 			}
       
   404 
       
   405 	if (uri_struct->manuf != NULL)
       
   406 		if (strncmp(uri_struct->manuf,
       
   407 		    (char *)token_info->manufacturerID,
       
   408 		    strlen(uri_struct->manuf) > 32 ? 32 :
       
   409 		    strlen(uri_struct->manuf)) != 0)
       
   410 			goto urierr;
       
   411 
       
   412 	if (uri_struct->model != NULL)
       
   413 		if (strncmp(uri_struct->model, (char *)token_info->model,
       
   414 		    strlen(uri_struct->model) > 16 ? 16 :
       
   415 		    strlen(uri_struct->model)) != 0)
       
   416 			goto urierr;
       
   417 
       
   418 	if (uri_struct->serial != NULL)
       
   419 		if (strncmp(uri_struct->serial,
       
   420 		    (char *)token_info->serialNumber,
       
   421 		    strlen(uri_struct->serial) > 16 ? 16 :
       
   422 		    strlen(uri_struct->serial)) != 0)
       
   423 			goto urierr;
       
   424 
       
   425 	(void) pthread_mutex_unlock(uri_lock);
       
   426 	return (1);
       
   427 
       
   428 urierr:
       
   429 	PK11err(PK11_F_CHECK_TOKEN_ATTRS, PK11_R_TOKEN_ATTRS_DO_NOT_MATCH);
       
   430 	/* Correct error already set above for the "err" label. */
       
   431 err:
       
   432 	(void) pthread_mutex_unlock(uri_lock);
       
   433 	return (0);
       
   434 	}
       
   435 
       
   436 /*
       
   437  * Return the process PIN caching policy. We initialize it just once so if the
       
   438  * process change OPENSSL_PKCS11_PIN_CACHING_POLICY during the operation it will
       
   439  * not have any affect on the policy.
       
   440  *
       
   441  * We assume that the "uri_lock" mutex is already locked.
       
   442  *
       
   443  * Returns the caching policy number.
       
   444  */
       
   445 int
       
   446 pk11_get_pin_caching_policy(void)
       
   447 	{
       
   448 	char *value = NULL;
       
   449 	static int policy = POLICY_NOT_INITIALIZED;
       
   450 
       
   451 	if (policy != POLICY_NOT_INITIALIZED)
       
   452 		return (policy);
       
   453 
       
   454 	value = getenv("OPENSSL_PKCS11_PIN_CACHING_POLICY");
       
   455 
       
   456 	if (value == NULL || strcmp(value, "none") == 0)
       
   457 		{
       
   458 		policy = POLICY_NONE;
       
   459 		goto done;
       
   460 		}
       
   461 
       
   462 	if (strcmp(value, "memory") == 0)
       
   463 		{
       
   464 		policy = POLICY_MEMORY;
       
   465 		goto done;
       
   466 		}
       
   467 
       
   468 	if (strcmp(value, "mlocked-memory") == 0)
       
   469 		{
       
   470 		policy = POLICY_MLOCKED_MEMORY;
       
   471 		goto done;
       
   472 		}
       
   473 
       
   474 	return (POLICY_WRONG_VALUE);
       
   475 done:
       
   476 	return (policy);
       
   477 	}
       
   478 
       
   479 /*
       
   480  * Cache the PIN in memory once. We already know that we have either "memory" or
       
   481  * "mlocked-memory" keyword correctly set.
       
   482  *
       
   483  * Returns:
       
   484  *	1 on success
       
   485  *	0 on failure
       
   486  */
       
   487 int
       
   488 pk11_cache_pin(char *pin)
       
   489 	{
       
   490 	(void) pthread_mutex_lock(uri_lock);
       
   491 	/* We set the PIN only once since all URIs must have it the same. */
       
   492 	if (token_pin != NULL)
       
   493 		goto ok;
       
   494 
       
   495 	if (pk11_get_pin_caching_policy() == POLICY_MEMORY)
       
   496 		if ((token_pin = strdup(pin)) == NULL)
       
   497 			{
       
   498 			PK11err(PK11_F_CACHE_PIN, PK11_R_MALLOC_FAILURE);
       
   499 			goto err;
       
   500 			}
       
   501 	else
       
   502 		if (pk11_get_pin_caching_policy() == POLICY_MLOCKED_MEMORY)
       
   503 			{
       
   504 			if (mlock_pin_in_memory(pin) == 0)
       
   505 				goto err;
       
   506 			}
       
   507 
       
   508 ok:
       
   509 	(void) pthread_mutex_unlock(uri_lock);
       
   510 	return (1);
       
   511 err:
       
   512 	(void) pthread_mutex_unlock(uri_lock);
       
   513 	return (0);
       
   514 	}
       
   515 
       
   516 /*
       
   517  * Cache the PIN in mlock(3C)ed memory. If mlock(3C) fails we will not resort to
       
   518  * the normal memory caching.
       
   519  *
       
   520  * Note that this function must be called under the protection of the "uri_lock"
       
   521  * mutex.
       
   522  *
       
   523  * Returns:
       
   524  *	1 on success
       
   525  *	0 on failure
       
   526  */
       
   527 static int
       
   528 mlock_pin_in_memory(char *pin)
       
   529 	{
       
   530 	void *addr = NULL;
       
   531 	long pagesize = 0;
       
   532 
       
   533 	/* mlock(3C) locks pages so we need one whole page for the PIN. */
       
   534 	if ((pagesize = sysconf(_SC_PAGESIZE)) == -1)
       
   535 		{
       
   536 		PK11err(PK11_F_MLOCK_PIN_IN_MEMORY, PK11_R_SYSCONF_FAILED);
       
   537 		goto err;
       
   538 		}
       
   539 
       
   540 	/* This will ensure we have a page aligned pointer... */
       
   541 	if ((addr = mmap(0, pagesize, PROT_READ | PROT_WRITE,
       
   542 	    MAP_PRIVATE | MAP_ANON, -1, 0)) == MAP_FAILED)
       
   543 		{
       
   544 		PK11err(PK11_F_MLOCK_PIN_IN_MEMORY, PK11_R_MMAP_FAILED);
       
   545 		goto err;
       
   546 		}
       
   547 
       
   548 	/* ...because "addr" must be page aligned here. */
       
   549 	if (mlock(addr, pagesize) == -1)
       
   550 		{
       
   551 		/*
       
   552 		 * Missing the PRIV_PROC_LOCK_MEMORY privilege might be a common
       
   553 		 * problem so distinguish this situation from other issues.
       
   554 		 */
       
   555 		if (errno == EPERM)
       
   556 			PK11err(PK11_F_MLOCK_PIN_IN_MEMORY,
       
   557 			    PK11_R_PRIV_PROC_LOCK_MEMORY_MISSING);
       
   558 		else
       
   559 			PK11err(PK11_F_MLOCK_PIN_IN_MEMORY,
       
   560 			    PK11_R_MLOCK_FAILED);
       
   561 
       
   562 		/*
       
   563 		 * We already have a problem here so there is no need to check
       
   564 		 * that we could unmap the page. The PIN is not there yet
       
   565 		 * anyway.
       
   566 		 */
       
   567 		(void) munmap(addr, pagesize);
       
   568 		goto err;
       
   569 		}
       
   570 
       
   571 	/* Copy the PIN to the mlocked memory. */
       
   572 	token_pin = (char *)addr;
       
   573 	strlcpy(token_pin, pin, PK11_MAX_PIN_LEN + 1);
       
   574 	return (1);
       
   575 err:
       
   576 	return (0);
       
   577 	}
       
   578 
       
   579 /*
       
   580  * Log in to the keystore if we are supposed to do that at all. Take care of
       
   581  * reading and caching the PIN etc. Log in only once even when called from
       
   582  * multiple threads.
       
   583  *
       
   584  * Returns:
       
   585  *	1 on success
       
   586  *	0 on failure
       
   587  */
       
   588 int
       
   589 pk11_token_login(CK_SESSION_HANDLE session, CK_BBOOL *login_done,
       
   590     pkcs11_uri *uri_struct, CK_BBOOL is_private)
       
   591 	{
       
   592 	CK_RV rv;
       
   593 
       
   594 	if ((pubkey_token_flags & CKF_TOKEN_INITIALIZED) == 0)
       
   595 		{
       
   596 		PK11err(PK11_F_TOKEN_LOGIN,
       
   597 		    PK11_R_TOKEN_NOT_INITIALIZED);
       
   598 		goto err;
       
   599 		}
       
   600 
       
   601 	/*
       
   602 	 * If login is required or needed but the PIN has not been even
       
   603 	 * initialized we can bail out right now. Note that we are supposed to
       
   604 	 * always log in if we are going to access private keys. However, we may
       
   605 	 * need to log in even for accessing public keys in case that the
       
   606 	 * CKF_LOGIN_REQUIRED flag is set.
       
   607 	 */
       
   608 	if ((pubkey_token_flags & CKF_LOGIN_REQUIRED ||
       
   609 	    is_private == CK_TRUE) && ~pubkey_token_flags &
       
   610 	    CKF_USER_PIN_INITIALIZED)
       
   611 		{
       
   612 		PK11err(PK11_F_TOKEN_LOGIN, PK11_R_TOKEN_PIN_NOT_SET);
       
   613 		goto err;
       
   614 		}
       
   615 
       
   616 	/*
       
   617 	 * Note on locking: it is possible that more than one thread gets into
       
   618 	 * pk11_get_pin() so we must deal with that. We cannot avoid it since we
       
   619 	 * cannot guard fork() in there with a lock because we could end up in
       
   620 	 * a dead lock in the child. Why? Remember we are in a multithreaded
       
   621 	 * environment so we must lock all mutexes in the prefork function to
       
   622 	 * avoid a situation in which a thread that did not call fork() held a
       
   623 	 * lock, making future unlocking impossible. We lock right before
       
   624 	 * C_Login().
       
   625 	 */
       
   626 	if (pubkey_token_flags & CKF_LOGIN_REQUIRED || is_private == CK_TRUE)
       
   627 		{
       
   628 		if (*login_done == CK_FALSE &&
       
   629 		    uri_struct->askpass == NULL)
       
   630 			{
       
   631 			PK11err(PK11_F_TOKEN_LOGIN,
       
   632 			    PK11_R_TOKEN_PIN_NOT_PROVIDED);
       
   633 			goto err;
       
   634 			}
       
   635 
       
   636 		if (*login_done == CK_FALSE &&
       
   637 		    uri_struct->askpass != NULL)
       
   638 			{
       
   639 			if (pk11_get_pin(uri_struct->askpass,
       
   640 			    &uri_struct->pin) == 0)
       
   641 				{
       
   642 				PK11err(PK11_F_TOKEN_LOGIN,
       
   643 				    PK11_R_TOKEN_PIN_NOT_PROVIDED);
       
   644 				goto err;
       
   645 				}
       
   646 			}
       
   647 
       
   648 		/*
       
   649 		 * Note that what we are logging into is the keystore from
       
   650 		 * pubkey_SLOTID because we work with OP_RSA session type here.
       
   651 		 * That also means that we can work with only one keystore in
       
   652 		 * the engine.
       
   653 		 *
       
   654 		 * We must make sure we do not try to login more than once.
       
   655 		 * Also, see the comment above on locking strategy.
       
   656 		 */
       
   657 		(void) pthread_mutex_lock(uri_lock);
       
   658 		if (*login_done == CK_FALSE)
       
   659 			{
       
   660 			if ((rv = pFuncList->C_Login(session,
       
   661 			    CKU_USER, (CK_UTF8CHAR*)uri_struct->pin,
       
   662 			    strlen(uri_struct->pin))) != CKR_OK)
       
   663 				{
       
   664 				PK11err_add_data(PK11_F_TOKEN_LOGIN,
       
   665 				    PK11_R_TOKEN_LOGIN_FAILED, rv);
       
   666 				goto err_locked;
       
   667 				}
       
   668 
       
   669 			*login_done = CK_TRUE;
       
   670 
       
   671 			/*
       
   672 			 * Cache the passphrasedialog for possible child (which
       
   673 			 * would need to relogin).
       
   674 			 */
       
   675 			if (passphrasedialog == NULL &&
       
   676 			    uri_struct->askpass != NULL)
       
   677 				{
       
   678 				passphrasedialog =
       
   679 				    strdup(uri_struct->askpass);
       
   680 
       
   681 				if (passphrasedialog == NULL)
       
   682 					{
       
   683 					PK11err_add_data(PK11_F_TOKEN_LOGIN,
       
   684 					    PK11_R_MALLOC_FAILURE, rv);
       
   685 					goto err_locked;
       
   686 					}
       
   687 				}
       
   688 
       
   689 			/*
       
   690 			 * Check the PIN caching policy. Note that user might
       
   691 			 * have provided a PIN even when no PIN was required -
       
   692 			 * in that case we always remove the PIN from memory.
       
   693 			 */
       
   694 			if (pk11_get_pin_caching_policy() ==
       
   695 			    POLICY_WRONG_VALUE)
       
   696 				{
       
   697 				PK11err(PK11_F_TOKEN_LOGIN,
       
   698 				    PK11_R_PIN_CACHING_POLICY_INVALID);
       
   699 				goto err_locked;
       
   700 				}
       
   701 
       
   702 			if (pk11_get_pin_caching_policy() != POLICY_NONE)
       
   703 				if (pk11_cache_pin(uri_struct->pin) == 0)
       
   704 					goto err_locked;
       
   705 			}
       
   706 		(void) pthread_mutex_unlock(uri_lock);
       
   707 		}
       
   708 	else
       
   709 		{
       
   710 			/*
       
   711 			 * If token does not require login we take it as the
       
   712 			 * login was done.
       
   713 			 */
       
   714 			*login_done = CK_TRUE;
       
   715 		}
       
   716 
       
   717 	/*
       
   718 	 * If we raced at pk11_get_pin() we must make sure that all threads that
       
   719 	 * called pk11_get_pin() will erase the PIN from memory, not just the
       
   720 	 * one that called C_Login(). Note that if we were supposed to cache the
       
   721 	 * PIN it was already cached by now so filling "uri_struct.pin" with
       
   722 	 * zero bytes is always OK since pk11_cache_pin() makes a copy of it.
       
   723 	 */
       
   724 	if (uri_struct->pin != NULL)
       
   725 		memset(uri_struct->pin, 0, strlen(uri_struct->pin));
       
   726 
       
   727 	return (1);
       
   728 
       
   729 err_locked:
       
   730 	(void) pthread_mutex_unlock(uri_lock);
       
   731 err:
       
   732 	/* Always get rid of the PIN. */
       
   733 	if (uri_struct->pin != NULL)
       
   734 		memset(uri_struct->pin, 0, strlen(uri_struct->pin));
       
   735 	return (0);
       
   736 	}
       
   737 
       
   738 /*
       
   739  * Log in to the keystore in the child if we were logged in in the parent. There
       
   740  * are similarities in the code with pk11_token_login() but still it is quite
       
   741  * different so we need a separate function for this.
       
   742  *
       
   743  * Note that this function is called under the locked session mutex when fork is
       
   744  * detected. That means that C_Login() will be called from the child just once.
       
   745  *
       
   746  * Returns:
       
   747  *	1 on success
       
   748  *	0 on failure
       
   749  */
       
   750 int
       
   751 pk11_token_relogin(CK_SESSION_HANDLE session)
       
   752 	{
       
   753 	CK_RV rv;
       
   754 
       
   755 	/*
       
   756 	 * We are in the child so check if we should login to the token again.
       
   757 	 * Note that it is enough to log in to the token through one session
       
   758 	 * only, all already open and all future sessions can access the token
       
   759 	 * then.
       
   760 	 */
       
   761 	if (passphrasedialog != NULL)
       
   762 		{
       
   763 		char *pin = NULL;
       
   764 
       
   765 		/* If we cached the PIN then use it. */
       
   766 		if (token_pin != NULL)
       
   767 			pin = token_pin;
       
   768 		else if (pk11_get_pin(passphrasedialog, &pin) == 0)
       
   769 			goto err;
       
   770 
       
   771 		(void) pthread_mutex_lock(uri_lock);
       
   772 		if ((rv = pFuncList->C_Login(session, CKU_USER,
       
   773 		    (CK_UTF8CHAR_PTR)pin, strlen(pin))) != CKR_OK)
       
   774 			{
       
   775 			PK11err_add_data(PK11_F_TOKEN_RELOGIN,
       
   776 			    PK11_R_TOKEN_LOGIN_FAILED, rv);
       
   777 			(void) pthread_mutex_unlock(uri_lock);
       
   778 			goto err;
       
   779 			}
       
   780 		(void) pthread_mutex_unlock(uri_lock);
       
   781 
       
   782 		/* Forget the PIN now if we did not cache it before. */
       
   783 		if (pin != token_pin)
       
   784 			{
       
   785 			memset(pin, 0, strlen(pin));
       
   786 			OPENSSL_free(pin);
       
   787 			}
       
   788 		}
       
   789 
       
   790 	return (1);
       
   791 err:
       
   792 	return (0);
       
   793 	}
       
   794 
       
   795 /*
       
   796  * This function forks and runs an external command. It would be nice if we
       
   797  * could use popen(3C)/pclose(3C) for that but unfortunately we need to be able
       
   798  * to get rid of the PIN from the memory. With p(open|close) function calls we
       
   799  * cannot control the stdio's memory used for buffering and our tests showed
       
   800  * that the PIN really stays there even after pclose().
       
   801  *
       
   802  * Returns:
       
   803  *	allocated buffer on success
       
   804  *	NULL on failure
       
   805  */
       
   806 static char *
       
   807 run_askpass(char *dialog)
       
   808 	{
       
   809 	pid_t pid;
       
   810 	int n, p[2];
       
   811 	char *buf = NULL;
       
   812 
       
   813 	if (pipe(p) == -1)
       
   814 		{
       
   815 		PK11err(PK11_F_RUN_ASKPASS, PK11_R_PIPE_FAILED);
       
   816 		return (NULL);
       
   817 		}
       
   818 
       
   819 	switch (pid = fork())
       
   820 		{
       
   821 		case -1:
       
   822 			PK11err(PK11_F_RUN_ASKPASS, PK11_R_FORK_FAILED);
       
   823 			return (NULL);
       
   824 		/* child */
       
   825 		case 0:
       
   826 			/*
       
   827 			 * This should make sure that dup2() will not fail on
       
   828 			 * file descriptor shortage.
       
   829 			 */
       
   830 			close(p[0]);
       
   831 			(void) dup2(p[1], 1);
       
   832 			close(p[1]);
       
   833 			/*
       
   834 			 * Note that we cannot use PK11err() here since we are
       
   835 			 * in the child. However, parent will get read() error
       
   836 			 * so do not worry.
       
   837 			 */
       
   838 			(void) execl(dialog, basename(dialog), NULL);
       
   839 			exit(1);
       
   840 		/* parent */
       
   841 		default:
       
   842 			/* +1 is for the terminating '\0' */
       
   843 			buf = (char *)OPENSSL_malloc(PK11_MAX_PIN_LEN + 1);
       
   844 			if (buf == NULL)
       
   845 				{
       
   846 				PK11err(PK11_F_RUN_ASKPASS,
       
   847 				    PK11_R_MALLOC_FAILURE);
       
   848 				return (NULL);
       
   849 				}
       
   850 
       
   851 			close(p[1]);
       
   852 			n = read(p[0], buf, PK11_MAX_PIN_LEN);
       
   853 			if (n == -1 || n == 0)
       
   854 				{
       
   855 				PK11err(PK11_F_RUN_ASKPASS,
       
   856 				    PK11_R_PIN_NOT_READ_FROM_COMMAND);
       
   857 				OPENSSL_free(buf);
       
   858 				return (NULL);
       
   859 				}
       
   860 			buf[n] = '\0';
       
   861 
       
   862 			(void) waitpid(pid, NULL, 0);
       
   863 		}
       
   864 
       
   865 	return (buf);
       
   866 	}
       
   867 
       
   868 #endif	/* OPENSSL_NO_HW_PK11 */
       
   869 #endif	/* OPENSSL_NO_HW */