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