Anonymous avatar Anonymous committed 26b948a Draft

7039910 move OpenSSL from SFW to Userland gate

Comments (0)

Files changed (59)

components/meta-packages/history/SUNWopenssl-fips-140.p5m

+#
+# CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+#
+
+#
+# Legacy package information for renamed SUNWopenssl-fips-140 package
+#
+
+set name=pkg.fmri value=pkg:/SUNWopenssl-fips-140@1.2,5.11-0.133
+set name=pkg.renamed value=true
+
+set name=org.opensolaris.consolidation value=$(CONSOLIDATION)
+
+depend fmri=library/security/openssl/openssl-fips-140@1.2-0.133 type=require

components/meta-packages/history/SUNWopenssl.p5m

+#
+# CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+#
+
+#
+# Legacy package information for renamed SUNWopenssl package
+#
+
+set name=pkg.fmri value=pkg:/SUNWopenssl@0.9.8.12,5.11-0.133
+set name=pkg.renamed value=true
+
+set name=org.opensolaris.consolidation value=$(CONSOLIDATION)
+
+depend fmri=library/security/openssl@0.9.8.12-0.133 type=require

components/openssl/README

+#
+# CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+# Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+#
+
+Build Layout
+---
+
+OpenSSL build is run three times. Once for 1.0.0 non-fips, once for 0.9.8
+fips-140, and once for 0.9.8 FIPS-140 canister (in the openssl-fips component)
+needed to build 0.9.8 FIPS-140 certified libraries. All builds are done for 32
+and 64 bits. So, in total, OpenSSL is built six times.
+
+See also comments in all three Makefiles for more information.
+
+The non-fips Build.
+---
+
+The non-fips build is the main build of OpenSSL and includes the regular
+binaries, libraries, man pages, and header files.
+
+Patches
+---
+
+08-6193522.patch
+Give CA.pl better defaults. See 6193522 for more information.
+
+11-6546806.patch
+Make sure the HMAC_CTX_init(3) man page gets delivered. See 6546806 for
+more information.
+
+14-manpage_openssl.patch
+Force openssl to install man pages into man[1357]openssl instead of man[1357].
+
+15-pkcs11_engine-0.9.8a.patch
+Patch which adds the pkcs11 engine. See also the pkcs11-engine/
+sub-directory. 
+
+18-compiler_opts.patch
+Adds four Solaris specific configurations (both 32bit and 64bit for both sparc
+and x86) to Configure which are then explicitly used by the Makefiles.
+
+Care should be taken if modifying this patch as changes to compile-time options
+can change the ABI. One example of this is the use of RC4_INT vs RC4_CHAR.
+
+20-remove_rpath.patch
+Prevent build binaries having an unnecessary runpath (/lib).
+
+23-noexstack.patch
+Build with non-executable stacks and non-executable data (x86).
+
+27-6978791.patch
+Modifies Makefile.shared so that libssl is built with -znodelete.
+
+28-enginesdir.patch
+Adds a new "enginesdir" option to the Configure script which allows a user to
+specify the engines directory.
+
+29-devcrypto_engine.patch
+Modifies engines/Makefile so that the devcrypto engine will be built in the
+"engines" directory. 
+
+opensslconf.patch
+Modifies opensslconf.h so that it is suitable for both 32bit and 64bit installs.
+OpenSSL either builds for 32bit or 64bit - it doesn't allow for combined 32bit
+and 64bit builds.
+
+The fips Build
+---
+
+FIPS-140 certified libraries for Solaris private use. We wait for OpenSSL 1.0.0
+to be FIPS-140 certified in which time we can ship only 1.0.0 with S11 and make
+it a public interface.
+
+Patches
+---
+
+All the patches from 1.0.0 are used in 0.9.8 as well aside from
+14-manpage_openssl.patch which is not needed since we do not deliver 0.9.8 man
+pages. Additional patches:
+
+01-7009105.patch
+Fixing a bug introduces in 0.9.8q and fixed in 0.9.8r.
+
+sparc-01-ccwrap.patch
+Workaround so that fingerprinting the canister during runtime and comparing it
+with the saved fingerprint works correctly.

components/openssl/openssl-0.9.8-fips-140/Makefile

+#
+# CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+#
+include $(WS_TOP)/make-rules/shared-macros.mk
+
+COMPONENT_NAME =	openssl
+# Note that this is the OpenSSL version that is used to build FIPS-140 certified
+# libraries. However, we use the FIPS canister version for the IPS package.
+COMPONENT_VERSION =	0.9.8q
+IPS_COMPONENT_VERSION = 1.2
+COMPONENT_SRC =		$(COMPONENT_NAME)-$(COMPONENT_VERSION)
+COMPONENT_ARCHIVE =	$(COMPONENT_SRC).tar.gz
+COMPONENT_ARCHIVE_HASH=	sha1:12b6859698ca299fa0cba594686c25d5c01e410d
+COMPONENT_ARCHIVE_URL =	http://www.openssl.org/source/$(COMPONENT_ARCHIVE)
+
+# Apply the patch on SPARC only. Must put this before including prep.mk as
+# mentioned in there.
+PATCH_sparc = patches/sparc-01-ccwrap.patch
+EXTRA_PATCHES = $(PATCH_$(MACH))
+# Note that the SPARC patch above does not fit this pattern. That is intentional
+# and a reason why we can add it to the EXTRA_PATCHES variable so that we use it
+# only on SPARC.
+PATCH_PATTERN = [0-9][0-9]*.patch
+
+include $(WS_TOP)/make-rules/prep.mk
+include $(WS_TOP)/make-rules/configure.mk
+include $(WS_TOP)/make-rules/ips.mk
+include $(WS_TOP)/make-rules/lint-libraries.mk
+
+# OpenSSL does not use autoconf but its own configure system.
+CONFIGURE_SCRIPT = $(SOURCE_DIR)/Configure
+
+# Used in the configure options below.
+PKCS11_LIB32 = /usr/lib/libpkcs11.so.1
+PKCS11_LIB64 = /usr/lib/64/libpkcs11.so.1
+ENGINESDIR_32 = /lib/openssl/engines
+ENGINESDIR_64 = /lib/openssl/engines/64
+
+# Built openssl/openssl-fips component is used when building FIPS-140 libraries.
+# What we do here follows the OpenSSL FIPS-140 User Guide instructions.
+FIPS_BUILD_DIR_32 = $(shell echo $(BUILD_DIR_32) | \
+    sed -e 's/openssl-0.9.8-fips-140/openssl-fips/g' )
+FIPS_BUILD_DIR_64 = $(shell echo $(BUILD_DIR_64) | \
+    sed -e 's/openssl-0.9.8-fips-140/openssl-fips/g' )
+
+CONFIGURE_OPTIONS =  -DSOLARIS_OPENSSL -DNO_WINDOWS_BRAINDEATH
+CONFIGURE_OPTIONS += --openssldir=/etc/openssl
+CONFIGURE_OPTIONS += --prefix=/usr
+# We use OpenSSL install code for installing only manual pages and we do that
+# for 32-bit version only.
+CONFIGURE_OPTIONS += --install_prefix=$(PROTO_DIR)
+CONFIGURE_OPTIONS += no-ec
+CONFIGURE_OPTIONS += no-ecdh
+CONFIGURE_OPTIONS += no-ecdsa
+CONFIGURE_OPTIONS += no-rc3
+CONFIGURE_OPTIONS += no-rc5
+CONFIGURE_OPTIONS += no-mdc2
+CONFIGURE_OPTIONS += no-idea
+CONFIGURE_OPTIONS += no-hw_4758_cca
+CONFIGURE_OPTIONS += no-hw_aep
+CONFIGURE_OPTIONS += no-hw_atalla
+CONFIGURE_OPTIONS += no-hw_chil
+CONFIGURE_OPTIONS += no-hw_gmp
+CONFIGURE_OPTIONS += no-hw_ncipher
+CONFIGURE_OPTIONS += no-hw_nuron
+CONFIGURE_OPTIONS += no-hw_padlock
+CONFIGURE_OPTIONS += no-hw_sureware
+CONFIGURE_OPTIONS += no-hw_ubsec
+CONFIGURE_OPTIONS += no-hw_cswift
+CONFIGURE_OPTIONS += threads
+CONFIGURE_OPTIONS += shared
+CONFIGURE_OPTIONS += fips --with-fipslibdir="$(FIPS_BUILD_DIR_$(BITS))/fips"
+
+# We define our own compiler and linker option sets for Solaris. See Configure
+# for more information.
+CONFIGURE_OPTIONS32_i386 =	solaris-x86-cc-sunw
+CONFIGURE_OPTIONS32_sparc =	solaris-sparcv8-cc-sunw
+CONFIGURE_OPTIONS64_i386 =	solaris64-x86_64-cc-sunw
+CONFIGURE_OPTIONS64_sparc =	solaris64-sparcv9-cc-sunw
+
+# Some additional options needed for our engines.
+CONFIGURE_OPTIONS += --pk11-libname=$(PKCS11_LIB$(BITS))
+CONFIGURE_OPTIONS += --enginesdir=$(ENGINESDIR_$(BITS))
+CONFIGURE_OPTIONS += $(CONFIGURE_OPTIONS$(BITS)_$(MACH))
+
+# OpenSSL has its own configure system which must be run from the fully
+# populated source code directory. However, the Userland configuration phase is
+# run from the build directory. The easiest way to workaround it is to copy all
+# the source files there.
+COMPONENT_PRE_CONFIGURE_ACTION = \
+    ( $(CLONEY) $(SOURCE_DIR) $(BUILD_DIR)/$(MACH$(BITS)); )
+
+# We deliver only one opensslconf.h file which must be suitable for both 32 and
+# 64 bits. Depending on the configuration option, OpenSSL's Configure script
+# creates opensslconf.h for either 32 or 64 bits. A patch makes the resulting
+# header file usable on both architectures. The patch was generated against the
+# opensslconf.h version from the 32 bit build.
+COMPONENT_POST_CONFIGURE_ACTION = \
+    ( [ $(BITS) -eq 32 ] && $(GPATCH) -p1 $(@D)/crypto/opensslconf.h \
+      patches-post-config/opensslconf.patch; cd $(@D); $(MAKE) depend; )
+
+# We must make sure that openssl-fips component is built before this 0.9.8
+# component since in order to build FIPS-140 certified libraries, the canister
+# is needed. Note that we must unset BITS that would override the same variable
+# used in openssl-fips' Makefile, and we would end up up with both canisters
+# built in 64 (or 32) bits.
+$(COMPONENT_DIR)/../openssl-fips/build/$(MACH32)/.installed \
+$(COMPONENT_DIR)/../openssl-fips/build/$(MACH64)/.installed:
+	( unset BITS; \
+	$(MAKE) -C $(COMPONENT_DIR)/../openssl-fips install; )
+
+# We do not ship our engines as patches since it would be more difficult to
+# update the files which have been under continuous development. We rather copy
+# the files to the right directories and let OpenSSL makefiles build it.
+COMPONENT_PRE_BUILD_ACTION = \
+    ( $(CP) -fp engines/pkcs11/* $(@D)/crypto/engine; ) 
+
+# OpenSSL does not install into <dir>/$(MACH64) for 64-bit install so no such
+# directory is created and Userland install code would fail when installing lint
+# libraries.
+COMPONENT_PRE_INSTALL_ACTION = ( $(MKDIR) $(PROTO_DIR)/usr/lib/$(MACH64); )
+
+# For ccwrap on SPARC. This is to workaround a problem with the cc compiler on
+# SPARC. We must modify PATH so that the wrapper can be found when run from
+# fips/fipsld.
+COMPONENT_BUILD_ENV += PATH=$(COMPONENT_DIR):$(PATH)
+COMPONENT_INSTALL_ENV += PATH=$(COMPONENT_DIR):$(PATH)
+
+$(SOURCE_DIR)/.prep: $(COMPONENT_DIR)/../openssl-fips/build/$(MACH32)/.installed \
+		     $(COMPONENT_DIR)/../openssl-fips/build/$(MACH64)/.installed
+
+# We need ccwrap for building the libraries.
+$(BUILD_32_and_64):	ccwrap
+build:			$(BUILD_32_and_64)
+
+# We follow what we do for install in openssl/openssl-1.0.0 component. Please
+# see the comment in Makefile in there for more information.
+install:	$(INSTALL_32_and_64)
+
+# We need to modify the default lint flags to include patched opensslconf.h from
+# the build directory. If we do not do that, lint will complain about md2.h
+# which is not enabled by default but it is in our opensslconf.h.
+LFLAGS_32 := -I$(BUILD_DIR_32)/include $(LINT_FLAGS)
+LFLAGS_64 := -I$(BUILD_DIR_64)/include $(LINT_FLAGS)
+
+# Set modified lint flags for our lint library targets.
+$(BUILD_DIR_32)/llib-lcrypto.ln: LINT_FLAGS=$(LFLAGS_32)
+$(BUILD_DIR_32)/llib-lssl.ln: LINT_FLAGS=$(LFLAGS_32)
+$(BUILD_DIR_64)/llib-lcrypto.ln: LINT_FLAGS=$(LFLAGS_64)
+$(BUILD_DIR_64)/llib-lssl.ln: LINT_FLAGS=$(LFLAGS_64)
+
+test:		$(NO_TESTS)
+
+BUILD_PKG_DEPENDENCIES =	$(BUILD_TOOLS)
+
+include $(WS_TOP)/make-rules/depend.mk

components/openssl/openssl-0.9.8-fips-140/ccwrap.sh

+#!/bin/sh
+#
+# CDDL HEADER START
+#
+# The contents of this file are subject to the terms of the
+# Common Development and Distribution License (the "License").
+# You may not use this file except in compliance with the License.
+#
+# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+# or http://www.opensolaris.org/os/licensing.
+# See the License for the specific language governing permissions
+# and limitations under the License.
+#
+# When distributing Covered Code, include this CDDL HEADER in each
+# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+# If applicable, add the following below this CDDL HEADER, with the
+# fields enclosed by brackets "[]" replaced with your own identifying
+# information: Portions Copyright [yyyy] [name of copyright owner]
+#
+# CDDL HEADER END
+#
+
+#
+# Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+#
+
+# Very simple cc wrapper whose only purpose is to ensure that cc behaves as
+# desired when linking the fipscanister.o object. Currently that means removing
+# "-g" and adding "-W2,-Rfully_unroll" from/to the compiler options.
+#
+# This wrapper is called from fipsld. See fips/fipsld and
+# patches/sparc-01-ccwrap.patch for more information.
+
+CC_CMD=""
+while [ $# -ne 0 ]; do
+	if [ "$1" != "-g" ]; then
+		CC_CMD="$CC_CMD '$1'"
+	fi
+	shift;
+done
+
+eval $CC_CMD -W2,-Rfully_unroll

components/openssl/openssl-0.9.8-fips-140/engines/pkcs11/hw_pk11.c

+/*
+ * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
+ *
+ */
+
+/* crypto/engine/hw_pk11.c */
+/*
+ * This product includes software developed by the OpenSSL Project for
+ * use in the OpenSSL Toolkit (http://www.openssl.org/).
+ *
+ * This project also referenced hw_pkcs11-0.9.7b.patch written by
+ * Afchine Madjlessi.
+ */
+/*
+ * ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ *    software must display the following acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
+ *
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ *    endorse or promote products derived from this software without
+ *    prior written permission. For written permission, please contact
+ *    licensing@OpenSSL.org.
+ *
+ * 5. Products derived from this software may not be called "OpenSSL"
+ *    nor may "OpenSSL" appear in their names without prior written
+ *    permission of the OpenSSL Project.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ *    acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com).  This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <strings.h>
+
+#include <openssl/e_os2.h>
+#include <openssl/crypto.h>
+#include <openssl/engine.h>
+#include <openssl/dso.h>
+#include <openssl/err.h>
+#include <openssl/bn.h>
+#include <openssl/md5.h>
+#include <openssl/pem.h>
+#ifndef OPENSSL_NO_RSA
+#include <openssl/rsa.h>
+#endif
+#ifndef OPENSSL_NO_DSA
+#include <openssl/dsa.h>
+#endif
+#ifndef OPENSSL_NO_DH
+#include <openssl/dh.h>
+#endif
+#include <openssl/rand.h>
+#include <openssl/objects.h>
+#include <openssl/x509.h>
+#include <openssl/aes.h>
+#include <cryptlib.h>
+#include <dlfcn.h>
+#include <pthread.h>
+
+#ifndef OPENSSL_NO_HW
+#ifndef OPENSSL_NO_HW_PK11
+
+/* label for debug messages printed on stderr */
+#define	PK11_DBG	"PKCS#11 ENGINE DEBUG"
+/* prints a lot of debug messages on stderr about slot selection process */
+#undef	DEBUG_SLOT_SELECTION
+/*
+ * Solaris specific code. See comment at check_hw_mechanisms() for more
+ * information.
+ */
+#if defined(__SVR4) && defined(__sun)
+#define	SOLARIS_HW_SLOT_SELECTION
+#endif
+
+/*
+ * AES counter mode is not supported in the OpenSSL EVP API yet and neither
+ * there are official OIDs for mechanisms based on this mode. With our changes,
+ * an application can define its own EVP calls for AES counter mode and then
+ * it can make use of hardware acceleration through this engine. However, it's
+ * better if we keep AES CTR support code under ifdef's.
+ */
+#define	SOLARIS_AES_CTR
+
+#include <security/cryptoki.h>
+#include <security/pkcs11.h>
+#include "hw_pk11.h"
+#include "hw_pk11_uri.h"
+
+#define	PK11_ENGINE_LIB_NAME "PKCS#11 engine"
+#include "hw_pk11_err.c"
+
+#ifdef	SOLARIS_AES_CTR
+/*
+ * NIDs for AES counter mode that will be defined during the engine
+ * initialization.
+ */
+int NID_aes_128_ctr = NID_undef;
+int NID_aes_192_ctr = NID_undef;
+int NID_aes_256_ctr = NID_undef;
+#endif	/* SOLARIS_AES_CTR */
+
+/*
+ * We use this lock to prevent multiple C_Login()s, guard getpassphrase(),
+ * uri_struct manipulation, and static token info. All of that is used by the
+ * RSA keys by reference feature.
+ */
+pthread_mutex_t *uri_lock;
+
+#ifdef	SOLARIS_HW_SLOT_SELECTION
+/*
+ * Tables for symmetric ciphers and digest mechs found in the pkcs11_kernel
+ * library. See comment at check_hw_mechanisms() for more information.
+ */
+int *hw_cnids;
+int *hw_dnids;
+#endif	/* SOLARIS_HW_SLOT_SELECTION */
+
+/* PKCS#11 session caches and their locks for all operation types */
+static PK11_CACHE session_cache[OP_MAX];
+
+/*
+ * We cache the flags so that we do not have to run C_GetTokenInfo() again when
+ * logging into the token.
+ */
+CK_FLAGS pubkey_token_flags;
+
+/*
+ * As stated in v2.20, 11.7 Object Management Function, in section for
+ * C_FindObjectsInit(), at most one search operation may be active at a given
+ * time in a given session. Therefore, C_Find{,Init,Final}Objects() should be
+ * grouped together to form one atomic search operation. This is already
+ * ensured by the property of unique PKCS#11 session handle used for each
+ * PK11_SESSION object.
+ *
+ * This is however not the biggest concern - maintaining consistency of the
+ * underlying object store is more important. The same section of the spec also
+ * says that one thread can be in the middle of a search operation while another
+ * thread destroys the object matching the search template which would result in
+ * invalid handle returned from the search operation.
+ *
+ * Hence, the following locks are used for both protection of the object stores.
+ * They are also used for active list protection.
+ */
+pthread_mutex_t *find_lock[OP_MAX] = { NULL };
+
+/*
+ * lists of asymmetric key handles which are active (referenced by at least one
+ * PK11_SESSION structure, either held by a thread or present in free_session
+ * list) for given algorithm type
+ */
+PK11_active *active_list[OP_MAX] = { NULL };
+
+/*
+ * Create all secret key objects in a global session so that they are available
+ * to use for other sessions. These other sessions may be opened or closed
+ * without losing the secret key objects.
+ */
+static CK_SESSION_HANDLE	global_session = CK_INVALID_HANDLE;
+
+/* ENGINE level stuff */
+static int pk11_init(ENGINE *e);
+static int pk11_library_init(ENGINE *e);
+static int pk11_finish(ENGINE *e);
+static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
+static int pk11_destroy(ENGINE *e);
+
+/* RAND stuff */
+static void pk11_rand_seed(const void *buf, int num);
+static void pk11_rand_add(const void *buf, int num, double add_entropy);
+static void pk11_rand_cleanup(void);
+static int pk11_rand_bytes(unsigned char *buf, int num);
+static int pk11_rand_status(void);
+
+/* These functions are also used in other files */
+PK11_SESSION *pk11_get_session(PK11_OPTYPE optype);
+void pk11_return_session(PK11_SESSION *sp, PK11_OPTYPE optype);
+
+/* active list manipulation functions used in this file */
+extern int pk11_active_delete(CK_OBJECT_HANDLE h, PK11_OPTYPE type);
+extern void pk11_free_active_list(PK11_OPTYPE type);
+
+#ifndef OPENSSL_NO_RSA
+int pk11_destroy_rsa_key_objects(PK11_SESSION *session);
+int pk11_destroy_rsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
+int pk11_destroy_rsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
+#endif
+#ifndef OPENSSL_NO_DSA
+int pk11_destroy_dsa_key_objects(PK11_SESSION *session);
+int pk11_destroy_dsa_object_pub(PK11_SESSION *sp, CK_BBOOL uselock);
+int pk11_destroy_dsa_object_priv(PK11_SESSION *sp, CK_BBOOL uselock);
+#endif
+#ifndef OPENSSL_NO_DH
+int pk11_destroy_dh_key_objects(PK11_SESSION *session);
+int pk11_destroy_dh_object(PK11_SESSION *session, CK_BBOOL uselock);
+#endif
+
+/* Local helper functions */
+static int pk11_free_all_sessions(void);
+static int pk11_free_session_list(PK11_OPTYPE optype);
+static int pk11_setup_session(PK11_SESSION *sp, PK11_OPTYPE optype);
+static int pk11_destroy_cipher_key_objects(PK11_SESSION *session);
+static int pk11_destroy_object(CK_SESSION_HANDLE handle, CK_OBJECT_HANDLE oh,
+    CK_BBOOL persistent);
+static const char *get_PK11_LIBNAME(void);
+static void free_PK11_LIBNAME(void);
+static long set_PK11_LIBNAME(const char *name);
+
+/* Symmetric cipher and digest support functions */
+static int cipher_nid_to_pk11(int nid);
+#ifdef	SOLARIS_AES_CTR
+static int pk11_add_NID(char *sn, char *ln);
+static int pk11_add_aes_ctr_NIDs(void);
+#endif	/* SOLARIS_AES_CTR */
+static int pk11_usable_ciphers(const int **nids);
+static int pk11_usable_digests(const int **nids);
+static int pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
+	const unsigned char *iv, int enc);
+static int pk11_cipher_final(PK11_SESSION *sp);
+static int pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
+	const unsigned char *in, unsigned int inl);
+static int pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx);
+static int pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
+	const int **nids, int nid);
+static int pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
+	const int **nids, int nid);
+static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx,
+	const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp);
+static int check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key,
+	int key_len);
+static int md_nid_to_pk11(int nid);
+static int pk11_digest_init(EVP_MD_CTX *ctx);
+static int pk11_digest_update(EVP_MD_CTX *ctx, const void *data,
+	size_t count);
+static int pk11_digest_final(EVP_MD_CTX *ctx, unsigned char *md);
+static int pk11_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from);
+static int pk11_digest_cleanup(EVP_MD_CTX *ctx);
+
+static int pk11_choose_slots(int *any_slot_found);
+static void pk11_find_symmetric_ciphers(CK_FUNCTION_LIST_PTR pflist,
+    CK_SLOT_ID current_slot, int *current_slot_n_cipher,
+    int *local_cipher_nids);
+static void pk11_find_digests(CK_FUNCTION_LIST_PTR pflist,
+    CK_SLOT_ID current_slot, int *current_slot_n_digest,
+    int *local_digest_nids);
+static void pk11_get_symmetric_cipher(CK_FUNCTION_LIST_PTR, int slot_id,
+    CK_MECHANISM_TYPE mech, int *current_slot_n_cipher, int *local_cipher_nids,
+    int id);
+static void pk11_get_digest(CK_FUNCTION_LIST_PTR pflist, int slot_id,
+    CK_MECHANISM_TYPE mech, int *current_slot_n_digest, int *local_digest_nids,
+    int id);
+
+static int pk11_init_all_locks(void);
+static void pk11_free_all_locks(void);
+
+#ifdef	SOLARIS_HW_SLOT_SELECTION
+static int check_hw_mechanisms(void);
+static int nid_in_table(int nid, int *nid_table);
+#endif	/* SOLARIS_HW_SLOT_SELECTION */
+
+/* Index for the supported ciphers */
+enum pk11_cipher_id {
+	PK11_DES_CBC,
+	PK11_DES3_CBC,
+	PK11_DES_ECB,
+	PK11_DES3_ECB,
+	PK11_RC4,
+	PK11_AES_128_CBC,
+	PK11_AES_192_CBC,
+	PK11_AES_256_CBC,
+	PK11_AES_128_ECB,
+	PK11_AES_192_ECB,
+	PK11_AES_256_ECB,
+	PK11_BLOWFISH_CBC,
+#ifdef	SOLARIS_AES_CTR
+	PK11_AES_128_CTR,
+	PK11_AES_192_CTR,
+	PK11_AES_256_CTR,
+#endif	/* SOLARIS_AES_CTR */
+	PK11_CIPHER_MAX
+};
+
+/* Index for the supported digests */
+enum pk11_digest_id {
+	PK11_MD5,
+	PK11_SHA1,
+	PK11_SHA224,
+	PK11_SHA256,
+	PK11_SHA384,
+	PK11_SHA512,
+	PK11_DIGEST_MAX
+};
+
+#define	TRY_OBJ_DESTROY(sp, obj_hdl, retval, uselock, alg_type)	\
+	{								\
+	if (uselock)							\
+		LOCK_OBJSTORE(alg_type);				\
+	if (pk11_active_delete(obj_hdl, alg_type) == 1)			\
+		{							\
+		retval = pk11_destroy_object(sp->session, obj_hdl,	\
+		    sp->persistent);					\
+		}							\
+	if (uselock)							\
+		UNLOCK_OBJSTORE(alg_type);				\
+	}
+
+static int cipher_nids[PK11_CIPHER_MAX];
+static int digest_nids[PK11_DIGEST_MAX];
+static int cipher_count		= 0;
+static int digest_count		= 0;
+static CK_BBOOL pk11_have_rsa	= CK_FALSE;
+static CK_BBOOL pk11_have_dsa	= CK_FALSE;
+static CK_BBOOL pk11_have_dh	= CK_FALSE;
+static CK_BBOOL pk11_have_random = CK_FALSE;
+
+typedef struct PK11_CIPHER_st
+	{
+	enum pk11_cipher_id	id;
+	int			nid;
+	int			iv_len;
+	int			min_key_len;
+	int			max_key_len;
+	CK_KEY_TYPE		key_type;
+	CK_MECHANISM_TYPE	mech_type;
+	} PK11_CIPHER;
+
+static PK11_CIPHER ciphers[] =
+	{
+	{ PK11_DES_CBC,		NID_des_cbc,		8,	 8,   8,
+		CKK_DES,	CKM_DES_CBC, },
+	{ PK11_DES3_CBC,	NID_des_ede3_cbc,	8,	24,  24,
+		CKK_DES3,	CKM_DES3_CBC, },
+	{ PK11_DES_ECB,		NID_des_ecb,		0,	 8,   8,
+		CKK_DES,	CKM_DES_ECB, },
+	{ PK11_DES3_ECB,	NID_des_ede3_ecb,	0,	24,  24,
+		CKK_DES3,	CKM_DES3_ECB, },
+	{ PK11_RC4,		NID_rc4,		0,	16, 256,
+		CKK_RC4,	CKM_RC4, },
+	{ PK11_AES_128_CBC,	NID_aes_128_cbc,	16,	16,  16,
+		CKK_AES,	CKM_AES_CBC, },
+	{ PK11_AES_192_CBC,	NID_aes_192_cbc,	16,	24,  24,
+		CKK_AES,	CKM_AES_CBC, },
+	{ PK11_AES_256_CBC,	NID_aes_256_cbc,	16,	32,  32,
+		CKK_AES,	CKM_AES_CBC, },
+	{ PK11_AES_128_ECB,	NID_aes_128_ecb,	0,	16,  16,
+		CKK_AES,	CKM_AES_ECB, },
+	{ PK11_AES_192_ECB,	NID_aes_192_ecb,	0,	24,  24,
+		CKK_AES,	CKM_AES_ECB, },
+	{ PK11_AES_256_ECB,	NID_aes_256_ecb,	0,	32,  32,
+		CKK_AES,	CKM_AES_ECB, },
+	{ PK11_BLOWFISH_CBC,	NID_bf_cbc,		8,	16,  16,
+		CKK_BLOWFISH,	CKM_BLOWFISH_CBC, },
+#ifdef	SOLARIS_AES_CTR
+	/* we don't know the correct NIDs until the engine is initialized */
+	{ PK11_AES_128_CTR,	NID_undef,		16,	16,  16,
+		CKK_AES,	CKM_AES_CTR, },
+	{ PK11_AES_192_CTR,	NID_undef,		16,	24,  24,
+		CKK_AES,	CKM_AES_CTR, },
+	{ PK11_AES_256_CTR,	NID_undef,		16,	32,  32,
+		CKK_AES,	CKM_AES_CTR, },
+#endif	/* SOLARIS_AES_CTR */
+	};
+
+typedef struct PK11_DIGEST_st
+	{
+	enum pk11_digest_id	id;
+	int			nid;
+	CK_MECHANISM_TYPE	mech_type;
+	} PK11_DIGEST;
+
+static PK11_DIGEST digests[] =
+	{
+	{PK11_MD5,	NID_md5,	CKM_MD5, },
+	{PK11_SHA1,	NID_sha1,	CKM_SHA_1, },
+	{PK11_SHA224,	NID_sha224,	CKM_SHA224, },
+	{PK11_SHA256,	NID_sha256,	CKM_SHA256, },
+	{PK11_SHA384,	NID_sha384,	CKM_SHA384, },
+	{PK11_SHA512,	NID_sha512,	CKM_SHA512, },
+	{0,		NID_undef,	0xFFFF, },
+	};
+
+/*
+ * Structure to be used for the cipher_data/md_data in
+ * EVP_CIPHER_CTX/EVP_MD_CTX structures in order to use the same pk11
+ * session in multiple cipher_update calls
+ */
+typedef struct PK11_CIPHER_STATE_st
+	{
+	PK11_SESSION	*sp;
+	} PK11_CIPHER_STATE;
+
+
+/*
+ * libcrypto EVP stuff - this is how we get wired to EVP so the engine gets
+ * called when libcrypto requests a cipher NID.
+ *
+ * Note how the PK11_CIPHER_STATE is used here.
+ */
+
+/* DES CBC EVP */
+static const EVP_CIPHER pk11_des_cbc =
+	{
+	NID_des_cbc,
+	8, 8, 8,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+/* 3DES CBC EVP */
+static const EVP_CIPHER pk11_3des_cbc =
+	{
+	NID_des_ede3_cbc,
+	8, 24, 8,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+/*
+ * ECB modes don't use an Initial Vector so that's why set_asn1_parameters and
+ * get_asn1_parameters fields are set to NULL.
+ */
+static const EVP_CIPHER pk11_des_ecb =
+	{
+	NID_des_ecb,
+	8, 8, 8,
+	EVP_CIPH_ECB_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	NULL,
+	NULL,
+	NULL
+	};
+
+static const EVP_CIPHER pk11_3des_ecb =
+	{
+	NID_des_ede3_ecb,
+	8, 24, 8,
+	EVP_CIPH_ECB_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	NULL,
+	NULL,
+	NULL
+	};
+
+
+static const EVP_CIPHER pk11_aes_128_cbc =
+	{
+	NID_aes_128_cbc,
+	16, 16, 16,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+static const EVP_CIPHER pk11_aes_192_cbc =
+	{
+	NID_aes_192_cbc,
+	16, 24, 16,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+static const EVP_CIPHER pk11_aes_256_cbc =
+	{
+	NID_aes_256_cbc,
+	16, 32, 16,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+/*
+ * ECB modes don't use IV so that's why set_asn1_parameters and
+ * get_asn1_parameters are set to NULL.
+ */
+static const EVP_CIPHER pk11_aes_128_ecb =
+	{
+	NID_aes_128_ecb,
+	16, 16, 0,
+	EVP_CIPH_ECB_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	NULL,
+	NULL,
+	NULL
+	};
+
+static const EVP_CIPHER pk11_aes_192_ecb =
+	{
+	NID_aes_192_ecb,
+	16, 24, 0,
+	EVP_CIPH_ECB_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	NULL,
+	NULL,
+	NULL
+	};
+
+static const EVP_CIPHER pk11_aes_256_ecb =
+	{
+	NID_aes_256_ecb,
+	16, 32, 0,
+	EVP_CIPH_ECB_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	NULL,
+	NULL,
+	NULL
+	};
+
+#ifdef	SOLARIS_AES_CTR
+/*
+ * NID_undef's will be changed to the AES counter mode NIDs as soon they are
+ * created in pk11_library_init(). Note that the need to change these structures
+ * is the reason why we don't define them with the const keyword.
+ */
+static EVP_CIPHER pk11_aes_128_ctr =
+	{
+	NID_undef,
+	16, 16, 16,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+static EVP_CIPHER pk11_aes_192_ctr =
+	{
+	NID_undef,
+	16, 24, 16,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+static EVP_CIPHER pk11_aes_256_ctr =
+	{
+	NID_undef,
+	16, 32, 16,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+#endif	/* SOLARIS_AES_CTR */
+
+static const EVP_CIPHER pk11_bf_cbc =
+	{
+	NID_bf_cbc,
+	8, 16, 8,
+	EVP_CIPH_VARIABLE_LENGTH,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+static const EVP_CIPHER pk11_rc4 =
+	{
+	NID_rc4,
+	1, 16, 0,
+	EVP_CIPH_VARIABLE_LENGTH,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof (PK11_CIPHER_STATE),
+	NULL,
+	NULL,
+	NULL
+	};
+
+static const EVP_MD pk11_md5 =
+	{
+	NID_md5,
+	NID_md5WithRSAEncryption,
+	MD5_DIGEST_LENGTH,
+	0,
+	pk11_digest_init,
+	pk11_digest_update,
+	pk11_digest_final,
+	pk11_digest_copy,
+	pk11_digest_cleanup,
+	EVP_PKEY_RSA_method,
+	MD5_CBLOCK,
+	sizeof (PK11_CIPHER_STATE),
+	};
+
+static const EVP_MD pk11_sha1 =
+	{
+	NID_sha1,
+	NID_sha1WithRSAEncryption,
+	SHA_DIGEST_LENGTH,
+	0,
+	pk11_digest_init,
+	pk11_digest_update,
+	pk11_digest_final,
+	pk11_digest_copy,
+	pk11_digest_cleanup,
+	EVP_PKEY_RSA_method,
+	SHA_CBLOCK,
+	sizeof (PK11_CIPHER_STATE),
+	};
+
+static const EVP_MD pk11_sha224 =
+	{
+	NID_sha224,
+	NID_sha224WithRSAEncryption,
+	SHA224_DIGEST_LENGTH,
+	0,
+	pk11_digest_init,
+	pk11_digest_update,
+	pk11_digest_final,
+	pk11_digest_copy,
+	pk11_digest_cleanup,
+	EVP_PKEY_RSA_method,
+	/* SHA-224 uses the same cblock size as SHA-256 */
+	SHA256_CBLOCK,
+	sizeof (PK11_CIPHER_STATE),
+	};
+
+static const EVP_MD pk11_sha256 =
+	{
+	NID_sha256,
+	NID_sha256WithRSAEncryption,
+	SHA256_DIGEST_LENGTH,
+	0,
+	pk11_digest_init,
+	pk11_digest_update,
+	pk11_digest_final,
+	pk11_digest_copy,
+	pk11_digest_cleanup,
+	EVP_PKEY_RSA_method,
+	SHA256_CBLOCK,
+	sizeof (PK11_CIPHER_STATE),
+	};
+
+static const EVP_MD pk11_sha384 =
+	{
+	NID_sha384,
+	NID_sha384WithRSAEncryption,
+	SHA384_DIGEST_LENGTH,
+	0,
+	pk11_digest_init,
+	pk11_digest_update,
+	pk11_digest_final,
+	pk11_digest_copy,
+	pk11_digest_cleanup,
+	EVP_PKEY_RSA_method,
+	/* SHA-384 uses the same cblock size as SHA-512 */
+	SHA512_CBLOCK,
+	sizeof (PK11_CIPHER_STATE),
+	};
+
+static const EVP_MD pk11_sha512 =
+	{
+	NID_sha512,
+	NID_sha512WithRSAEncryption,
+	SHA512_DIGEST_LENGTH,
+	0,
+	pk11_digest_init,
+	pk11_digest_update,
+	pk11_digest_final,
+	pk11_digest_copy,
+	pk11_digest_cleanup,
+	EVP_PKEY_RSA_method,
+	SHA512_CBLOCK,
+	sizeof (PK11_CIPHER_STATE),
+	};
+
+/*
+ * Initialization function. Sets up various PKCS#11 library components.
+ * The definitions for control commands specific to this engine
+ */
+#define	PK11_CMD_SO_PATH		ENGINE_CMD_BASE
+static const ENGINE_CMD_DEFN pk11_cmd_defns[] =
+	{
+		{
+		PK11_CMD_SO_PATH,
+		"SO_PATH",
+		"Specifies the path to the 'pkcs#11' shared library",
+		ENGINE_CMD_FLAG_STRING
+		},
+		{0, NULL, NULL, 0}
+	};
+
+
+static RAND_METHOD pk11_random =
+	{
+	pk11_rand_seed,
+	pk11_rand_bytes,
+	pk11_rand_cleanup,
+	pk11_rand_add,
+	pk11_rand_bytes,
+	pk11_rand_status
+	};
+
+
+/* Constants used when creating the ENGINE */
+static const char *engine_pk11_id = "pkcs11";
+static const char *engine_pk11_name = "PKCS #11 engine support";
+
+CK_FUNCTION_LIST_PTR pFuncList = NULL;
+static const char PK11_GET_FUNCTION_LIST[] = "C_GetFunctionList";
+
+/*
+ * This is a static string constant for the DSO file name and the function
+ * symbol names to bind to. We set it in the Configure script based on whether
+ * this is 32 or 64 bit build.
+ */
+static const char def_PK11_LIBNAME[] = PK11_LIB_LOCATION;
+
+static CK_BBOOL pk11_true = CK_TRUE;
+static CK_BBOOL pk11_false = CK_FALSE;
+/* Needed in hw_pk11_pub.c as well so that's why it is not static. */
+CK_SLOT_ID pubkey_SLOTID = 0;
+static CK_SLOT_ID rand_SLOTID = 0;
+static CK_SLOT_ID SLOTID = 0;
+static CK_BBOOL pk11_library_initialized = CK_FALSE;
+static CK_BBOOL pk11_atfork_initialized = CK_FALSE;
+static int pk11_pid = 0;
+
+static DSO *pk11_dso = NULL;
+
+/* allocate and initialize all locks used by the engine itself */
+static int pk11_init_all_locks(void)
+	{
+	int type;
+
+#ifndef OPENSSL_NO_RSA
+	find_lock[OP_RSA] = OPENSSL_malloc(sizeof (pthread_mutex_t));
+	if (find_lock[OP_RSA] == NULL)
+		goto malloc_err;
+	(void) pthread_mutex_init(find_lock[OP_RSA], NULL);
+#endif /* OPENSSL_NO_RSA */
+
+	if ((uri_lock = OPENSSL_malloc(sizeof (pthread_mutex_t))) == NULL)
+		goto malloc_err;
+	(void) pthread_mutex_init(uri_lock, NULL);
+
+#ifndef OPENSSL_NO_DSA
+	find_lock[OP_DSA] = OPENSSL_malloc(sizeof (pthread_mutex_t));
+	if (find_lock[OP_DSA] == NULL)
+		goto malloc_err;
+	(void) pthread_mutex_init(find_lock[OP_DSA], NULL);
+#endif /* OPENSSL_NO_DSA */
+
+#ifndef OPENSSL_NO_DH
+	find_lock[OP_DH] = OPENSSL_malloc(sizeof (pthread_mutex_t));
+	if (find_lock[OP_DH] == NULL)
+		goto malloc_err;
+	(void) pthread_mutex_init(find_lock[OP_DH], NULL);
+#endif /* OPENSSL_NO_DH */
+
+	for (type = 0; type < OP_MAX; type++)
+		{
+		session_cache[type].lock =
+		    OPENSSL_malloc(sizeof (pthread_mutex_t));
+		if (session_cache[type].lock == NULL)
+			goto malloc_err;
+		(void) pthread_mutex_init(session_cache[type].lock, NULL);
+		}
+
+	return (1);
+
+malloc_err:
+	pk11_free_all_locks();
+	PK11err(PK11_F_INIT_ALL_LOCKS, PK11_R_MALLOC_FAILURE);
+	return (0);
+	}
+
+static void pk11_free_all_locks(void)
+	{
+	int type;
+
+#ifndef OPENSSL_NO_RSA
+	if (find_lock[OP_RSA] != NULL)
+		{
+		(void) pthread_mutex_destroy(find_lock[OP_RSA]);
+		OPENSSL_free(find_lock[OP_RSA]);
+		find_lock[OP_RSA] = NULL;
+		}
+#endif /* OPENSSL_NO_RSA */
+#ifndef OPENSSL_NO_DSA
+	if (find_lock[OP_DSA] != NULL)
+		{
+		(void) pthread_mutex_destroy(find_lock[OP_DSA]);
+		OPENSSL_free(find_lock[OP_DSA]);
+		find_lock[OP_DSA] = NULL;
+		}
+#endif /* OPENSSL_NO_DSA */
+#ifndef OPENSSL_NO_DH
+	if (find_lock[OP_DH] != NULL)
+		{
+		(void) pthread_mutex_destroy(find_lock[OP_DH]);
+		OPENSSL_free(find_lock[OP_DH]);
+		find_lock[OP_DH] = NULL;
+		}
+#endif /* OPENSSL_NO_DH */
+
+	for (type = 0; type < OP_MAX; type++)
+		{
+		if (session_cache[type].lock != NULL)
+			{
+			(void) pthread_mutex_destroy(session_cache[type].lock);
+			OPENSSL_free(session_cache[type].lock);
+			session_cache[type].lock = NULL;
+			}
+		}
+	}
+
+/*
+ * This internal function is used by ENGINE_pk11() and "dynamic" ENGINE support.
+ */
+static int bind_pk11(ENGINE *e)
+	{
+#ifndef OPENSSL_NO_RSA
+	const RSA_METHOD *rsa = NULL;
+	RSA_METHOD *pk11_rsa = PK11_RSA();
+#endif	/* OPENSSL_NO_RSA */
+	if (!pk11_library_initialized)
+		if (!pk11_library_init(e))
+			return (0);
+
+	if (!ENGINE_set_id(e, engine_pk11_id) ||
+	    !ENGINE_set_name(e, engine_pk11_name) ||
+	    !ENGINE_set_ciphers(e, pk11_engine_ciphers) ||
+	    !ENGINE_set_digests(e, pk11_engine_digests))
+		return (0);
+#ifndef OPENSSL_NO_RSA
+	if (pk11_have_rsa == CK_TRUE)
+		{
+		if (!ENGINE_set_RSA(e, PK11_RSA()) ||
+		    !ENGINE_set_load_privkey_function(e, pk11_load_privkey) ||
+		    !ENGINE_set_load_pubkey_function(e, pk11_load_pubkey))
+			return (0);
+#ifdef	DEBUG_SLOT_SELECTION
+		fprintf(stderr, "%s: registered RSA\n", PK11_DBG);
+#endif	/* DEBUG_SLOT_SELECTION */
+		}
+#endif	/* OPENSSL_NO_RSA */
+#ifndef OPENSSL_NO_DSA
+	if (pk11_have_dsa == CK_TRUE)
+		{
+		if (!ENGINE_set_DSA(e, PK11_DSA()))
+			return (0);
+#ifdef	DEBUG_SLOT_SELECTION
+		fprintf(stderr, "%s: registered DSA\n", PK11_DBG);
+#endif	/* DEBUG_SLOT_SELECTION */
+		}
+#endif	/* OPENSSL_NO_DSA */
+#ifndef OPENSSL_NO_DH
+	if (pk11_have_dh == CK_TRUE)
+		{
+		if (!ENGINE_set_DH(e, PK11_DH()))
+			return (0);
+#ifdef	DEBUG_SLOT_SELECTION
+		fprintf(stderr, "%s: registered DH\n", PK11_DBG);
+#endif	/* DEBUG_SLOT_SELECTION */
+		}
+#endif	/* OPENSSL_NO_DH */
+	if (pk11_have_random)
+		{
+		if (!ENGINE_set_RAND(e, &pk11_random))
+			return (0);
+#ifdef	DEBUG_SLOT_SELECTION
+		fprintf(stderr, "%s: registered random\n", PK11_DBG);
+#endif	/* DEBUG_SLOT_SELECTION */
+		}
+	if (!ENGINE_set_init_function(e, pk11_init) ||
+	    !ENGINE_set_destroy_function(e, pk11_destroy) ||
+	    !ENGINE_set_finish_function(e, pk11_finish) ||
+	    !ENGINE_set_ctrl_function(e, pk11_ctrl) ||
+	    !ENGINE_set_cmd_defns(e, pk11_cmd_defns))
+		return (0);
+
+/*
+ * Apache calls OpenSSL function RSA_blinding_on() once during startup
+ * which in turn calls bn_mod_exp. Since we do not implement bn_mod_exp
+ * here, we wire it back to the OpenSSL software implementation.
+ * Since it is used only once, performance is not a concern.
+ */
+#ifndef OPENSSL_NO_RSA
+	rsa = RSA_PKCS1_SSLeay();
+	pk11_rsa->rsa_mod_exp = rsa->rsa_mod_exp;
+	pk11_rsa->bn_mod_exp = rsa->bn_mod_exp;
+#endif	/* OPENSSL_NO_RSA */
+
+	/* Ensure the pk11 error handling is set up */
+	ERR_load_pk11_strings();
+
+	return (1);
+	}
+
+/* Dynamic engine support is disabled at a higher level for Solaris */
+#ifdef	ENGINE_DYNAMIC_SUPPORT
+static int bind_helper(ENGINE *e, const char *id)
+	{
+	if (id && (strcmp(id, engine_pk11_id) != 0))
+		return (0);
+
+	if (!bind_pk11(e))
+		return (0);
+
+	return (1);
+	}
+
+IMPLEMENT_DYNAMIC_CHECK_FN()
+IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
+
+#else
+static ENGINE *engine_pk11(void)
+	{
+	ENGINE *ret = ENGINE_new();
+
+	if (!ret)
+		return (NULL);
+
+	if (!bind_pk11(ret))
+		{
+		ENGINE_free(ret);
+		return (NULL);
+		}
+
+	return (ret);
+	}
+
+void
+ENGINE_load_pk11(void)
+	{
+	ENGINE *e_pk11 = NULL;
+
+	/*
+	 * Do not use dynamic PKCS#11 library on Solaris due to
+	 * security reasons. We will link it in statically.
+	 */
+	/* Attempt to load PKCS#11 library */
+	if (!pk11_dso)
+		pk11_dso = DSO_load(NULL, get_PK11_LIBNAME(), NULL, 0);
+
+	if (pk11_dso == NULL)
+		{
+		PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
+		return;
+		}
+
+	e_pk11 = engine_pk11();
+	if (!e_pk11)
+		{
+		DSO_free(pk11_dso);
+		pk11_dso = NULL;
+		return;
+		}
+
+	/*
+	 * At this point, the pk11 shared library is either dynamically
+	 * loaded or statically linked in. So, initialize the pk11
+	 * library before calling ENGINE_set_default since the latter
+	 * needs cipher and digest algorithm information
+	 */
+	if (!pk11_library_init(e_pk11))
+		{
+		DSO_free(pk11_dso);
+		pk11_dso = NULL;
+		ENGINE_free(e_pk11);
+		return;
+		}
+
+	ENGINE_add(e_pk11);
+
+	ENGINE_free(e_pk11);
+	ERR_clear_error();
+	}
+#endif	/* ENGINE_DYNAMIC_SUPPORT */
+
+/*
+ * These are the static string constants for the DSO file name and
+ * the function symbol names to bind to.
+ */
+static const char *PK11_LIBNAME = NULL;
+
+static const char *get_PK11_LIBNAME(void)
+	{
+	if (PK11_LIBNAME)
+		return (PK11_LIBNAME);
+
+	return (def_PK11_LIBNAME);
+	}
+
+static void free_PK11_LIBNAME(void)
+	{
+	if (PK11_LIBNAME)
+		OPENSSL_free((void*)PK11_LIBNAME);
+
+	PK11_LIBNAME = NULL;
+	}
+
+static long set_PK11_LIBNAME(const char *name)
+	{
+	free_PK11_LIBNAME();
+
+	return ((PK11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
+	}
+
+/* acquire all engine specific mutexes before fork */
+static void pk11_fork_prepare(void)
+	{
+	int i;
+
+	if (!pk11_library_initialized)
+		return;
+
+	LOCK_OBJSTORE(OP_RSA);
+	LOCK_OBJSTORE(OP_DSA);
+	LOCK_OBJSTORE(OP_DH);
+	(void) pthread_mutex_lock(uri_lock);
+	for (i = 0; i < OP_MAX; i++)
+		{
+		(void) pthread_mutex_lock(session_cache[i].lock);
+		}
+	}
+
+/* release all engine specific mutexes */
+static void pk11_fork_parent(void)
+	{
+	int i;
+
+	if (!pk11_library_initialized)
+		return;
+
+	for (i = OP_MAX - 1; i >= 0; i--)
+		{
+		(void) pthread_mutex_unlock(session_cache[i].lock);
+		}
+	UNLOCK_OBJSTORE(OP_DH);
+	UNLOCK_OBJSTORE(OP_DSA);
+	UNLOCK_OBJSTORE(OP_RSA);
+	(void) pthread_mutex_unlock(uri_lock);
+	}
+
+/*
+ * same situation as in parent - we need to unlock all locks to make them
+ * accessible to all threads.
+ */
+static void pk11_fork_child(void)
+	{
+	int i;
+
+	if (!pk11_library_initialized)
+		return;
+
+	for (i = OP_MAX - 1; i >= 0; i--)
+		{
+		(void) pthread_mutex_unlock(session_cache[i].lock);
+		}
+	UNLOCK_OBJSTORE(OP_DH);
+	UNLOCK_OBJSTORE(OP_DSA);
+	UNLOCK_OBJSTORE(OP_RSA);
+	(void) pthread_mutex_unlock(uri_lock);
+	}
+
+/* Initialization function for the pk11 engine */
+static int pk11_init(ENGINE *e)
+{
+	return (pk11_library_init(e));
+}
+
+/*
+ * Initialization function. Sets up various PKCS#11 library components.
+ * It selects a slot based on predefined critiera. In the process, it also
+ * count how many ciphers and digests to support. Since the cipher and
+ * digest information is needed when setting default engine, this function
+ * needs to be called before calling ENGINE_set_default.
+ */
+/* ARGSUSED */
+static int pk11_library_init(ENGINE *e)
+	{
+	CK_C_GetFunctionList p;
+	CK_RV rv = CKR_OK;
+	CK_INFO info;
+	CK_ULONG ul_state_len;
+	int any_slot_found;
+	int i;
+
+	/*
+	 * pk11_library_initialized is set to 0 in pk11_finish() which is called
+	 * from ENGINE_finish(). However, if there is still at least one
+	 * existing functional reference to the engine (see engine(3) for more
+	 * information), pk11_finish() is skipped. For example, this can happen
+	 * if an application forgets to clear one cipher context. In case of a
+	 * fork() when the application is finishing the engine so that it can be
+	 * reinitialized in the child, forgotten functional reference causes
+	 * pk11_library_initialized to stay 1. In that case we need the PID
+	 * check so that we properly initialize the engine again.
+	 */
+	if (pk11_library_initialized)
+		{
+		if (pk11_pid == getpid())
+			{
+			return (1);
+			}
+		else
+			{
+			global_session = CK_INVALID_HANDLE;
+			/*
+			 * free the locks first to prevent memory leak in case
+			 * the application calls fork() without finishing the
+			 * engine first.
+			 */
+			pk11_free_all_locks();
+			}
+		}
+
+	if (pk11_dso == NULL)
+		{
+		PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
+		goto err;
+		}
+
+#ifdef	SOLARIS_AES_CTR
+	/*
+	 * We must do this before we start working with slots since we need all
+	 * NIDs there.
+	 */
+	if (pk11_add_aes_ctr_NIDs() == 0)
+		goto err;
+#endif	/* SOLARIS_AES_CTR */
+
+#ifdef	SOLARIS_HW_SLOT_SELECTION
+	if (check_hw_mechanisms() == 0)
+		goto err;
+#endif	/* SOLARIS_HW_SLOT_SELECTION */
+
+	/* get the C_GetFunctionList function from the loaded library */
+	p = (CK_C_GetFunctionList)DSO_bind_func(pk11_dso,
+		PK11_GET_FUNCTION_LIST);
+	if (!p)
+		{
+		PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
+		goto err;
+		}
+
+	/* get the full function list from the loaded library */
+	rv = p(&pFuncList);
+	if (rv != CKR_OK)
+		{
+		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE, rv);
+		goto err;
+		}
+
+	rv = pFuncList->C_Initialize(NULL_PTR);
+	if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
+		{
+		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_INITIALIZE, rv);
+		goto err;
+		}
+
+	rv = pFuncList->C_GetInfo(&info);
+	if (rv != CKR_OK)
+		{
+		PK11err_add_data(PK11_F_LIBRARY_INIT, PK11_R_GETINFO, rv);
+		goto err;
+		}
+
+	if (pk11_choose_slots(&any_slot_found) == 0)
+		goto err;
+
+	/*
+	 * The library we use, set in def_PK11_LIBNAME, may not offer any
+	 * slot(s). In that case, we must not proceed but we must not return an
+	 * error. The reason is that applications that try to set up the PKCS#11
+	 * engine don't exit on error during the engine initialization just
+	 * because no slot was present.
+	 */
+	if (any_slot_found == 0)
+		return (1);
+
+	if (global_session == CK_INVALID_HANDLE)
+		{
+		/* Open the global_session for the new process */
+		rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+			NULL_PTR, NULL_PTR, &global_session);
+		if (rv != CKR_OK)
+			{
+			PK11err_add_data(PK11_F_LIBRARY_INIT,
+			    PK11_R_OPENSESSION, rv);
+			goto err;
+			}
+		}
+
+	/*
+	 * Disable digest if C_GetOperationState is not supported since
+	 * this function is required by OpenSSL digest copy function
+	 */
+	if (pFuncList->C_GetOperationState(global_session, NULL, &ul_state_len)
+			== CKR_FUNCTION_NOT_SUPPORTED) {
+#ifdef	DEBUG_SLOT_SELECTION
+		fprintf(stderr, "%s: C_GetOperationState() not supported, "
+		    "setting digest_count to 0\n", PK11_DBG);
+#endif	/* DEBUG_SLOT_SELECTION */
+		digest_count = 0;
+	}
+
+	pk11_library_initialized = CK_TRUE;
+	pk11_pid = getpid();
+	/*
+	 * if initialization of the locks fails pk11_init_all_locks()
+	 * will do the cleanup.
+	 */
+	if (!pk11_init_all_locks())
+		goto err;
+	for (i = 0; i < OP_MAX; i++)
+		session_cache[i].head = NULL;
+	/*
+	 * initialize active lists. We only use active lists
+	 * for asymmetric ciphers.
+	 */
+	for (i = 0; i < OP_MAX; i++)
+		active_list[i] = NULL;
+
+	if (!pk11_atfork_initialized)
+		{
+		if (pthread_atfork(pk11_fork_prepare, pk11_fork_parent,
+		    pk11_fork_child) != 0)
+			{
+			PK11err(PK11_F_LIBRARY_INIT, PK11_R_ATFORK_FAILED);
+			goto err;
+			}
+		pk11_atfork_initialized = CK_TRUE;
+		}
+
+	return (1);
+
+err:
+	return (0);
+	}
+
+/* Destructor (complements the "ENGINE_pk11()" constructor) */
+/* ARGSUSED */
+static int pk11_destroy(ENGINE *e)
+	{
+	free_PK11_LIBNAME();
+	ERR_unload_pk11_strings();
+	return (1);
+	}
+
+/*
+ * Termination function to clean up the session, the token, and the pk11
+ * library.
+ */
+/* ARGSUSED */
+static int pk11_finish(ENGINE *e)
+	{
+	int i;
+
+	if (pk11_dso == NULL)
+		{
+		PK11err(PK11_F_FINISH, PK11_R_NOT_LOADED);
+		goto err;
+		}
+
+	OPENSSL_assert(pFuncList != NULL);
+
+	if (pk11_free_all_sessions() == 0)
+		goto err;
+
+	/* free all active lists */
+	for (i = 0; i < OP_MAX; i++)
+		pk11_free_active_list(i);
+
+	pFuncList->C_CloseSession(global_session);
+	global_session = CK_INVALID_HANDLE;
+
+	/*
+	 * Since we are part of a library (libcrypto.so), calling this function
+	 * may have side-effects.
+	 */
+#if 0
+	pFuncList->C_Finalize(NULL);
+#endif
+#ifdef	SOLARIS_AES_CTR
+	{
+		ASN1_OBJECT *ob = NULL;
+		if (NID_aes_128_ctr != NID_undef) {
+			ob = OBJ_nid2obj(NID_aes_128_ctr);
+			if (ob != NULL)
+				ASN1_OBJECT_free(ob);
+		}
+		if (NID_aes_192_ctr != NID_undef) {
+			ob = OBJ_nid2obj(NID_aes_192_ctr);
+			if (ob != NULL)
+				ASN1_OBJECT_free(ob);
+		}
+		if (NID_aes_256_ctr != NID_undef) {
+			ob = OBJ_nid2obj(NID_aes_256_ctr);
+			if (ob != NULL)
+				ASN1_OBJECT_free(ob);
+		}
+	}
+#endif
+
+	if (!DSO_free(pk11_dso))
+		{
+		PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
+		goto err;
+		}
+	pk11_dso = NULL;
+	pFuncList = NULL;
+	pk11_library_initialized = CK_FALSE;
+	pk11_pid = 0;
+	/*
+	 * There is no way how to unregister atfork handlers (other than
+	 * unloading the library) so we just free the locks. For this reason
+	 * the atfork handlers check if the engine is initialized and bail out
+	 * immediately if not. This is necessary in case a process finishes
+	 * the engine before calling fork().
+	 */
+	pk11_free_all_locks();
+
+	return (1);
+
+err:
+	return (0);
+	}
+
+/* Standard engine interface function to set the dynamic library path */
+/* ARGSUSED */
+static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
+	{
+	int initialized = ((pk11_dso == NULL) ? 0 : 1);
+
+	switch (cmd)
+		{
+	case PK11_CMD_SO_PATH:
+		if (p == NULL)
+			{
+			PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
+			return (0);
+			}
+
+		if (initialized)
+			{
+			PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
+			return (0);
+			}
+
+		return (set_PK11_LIBNAME((const char *)p));
+	default:
+		break;
+		}
+
+	PK11err(PK11_F_CTRL, PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
+
+	return (0);
+	}
+
+
+/* Required function by the engine random interface. It does nothing here */
+static void pk11_rand_cleanup(void)
+	{
+	return;
+	}
+
+/* ARGSUSED */
+static void pk11_rand_add(const void *buf, int num, double add)
+	{
+	PK11_SESSION *sp;
+
+	if ((sp = pk11_get_session(OP_RAND)) == NULL)
+		return;
+
+	/*
+	 * Ignore any errors (e.g. CKR_RANDOM_SEED_NOT_SUPPORTED) since
+	 * the calling functions do not care anyway
+	 */
+	pFuncList->C_SeedRandom(sp->session, (unsigned char *) buf, num);
+	pk11_return_session(sp, OP_RAND);
+
+	return;
+	}
+